ShtukbaseStandard
файл пакета→ .shtukbase/packages/design-base/lib/markup.ts

lib/markup.ts

129 строк, 5.5 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // Markup for the design checks: elements in HTML and JSX/TSX (opening tag, attributes, inner text), class tokens
  2. // from string literals. A scanner, not a parser: it skips braces and quotes inside tags, which is enough for
  3. // the questions the checks ask (is there an alt, a label, a name).
  4. export type El = {
  5. name: string;
  6. attrs: string; // raw text between the name and the end of the opening tag
  7. flat: string; // attrs with the inside of {...} blanked, so regexps see only attribute names and literal values
  8. spread: boolean; // has {...rest}: the attribute may come from outside
  9. selfClosing: boolean;
  10. start: number;
  11. openEnd: number; // offset just after '>' of the opening tag
  12. inner: string | null; // text up to the matching closing tag (null: self-closing or not found)
  13. inAttr: boolean; // written inside another tag's attribute (`render={<Button />}`): a template, not a child
  14. };
  15. /** Comments out of the way (JSX {/* *\/}, //, /* *\/ and <!-- -->), lengths and newlines kept. */
  16. export function blankComments(text: string, html: boolean): string {
  17. const blank = (m: string) => m.replace(/[^\n]/g, ' ');
  18. let t = text.replace(/<!--[\s\S]*?-->/g, blank);
  19. if (!html) t = t.replace(/\/\*[\s\S]*?\*\//g, blank).replace(/(^|[^:"'`\\])\/\/[^\n]*/g, (m, p) => p + blank(m.slice(p.length)));
  20. return t;
  21. }
  22. /** End of an opening tag that starts at `i` (at '<'): offset of its '>' or -1. Skips {...} and quoted values. */
  23. function tagEnd(text: string, i: number): number {
  24. let depth = 0;
  25. let quote = '';
  26. for (let k = i + 1; k < text.length; k++) {
  27. const c = text[k];
  28. if (quote) { if (c === quote) quote = ''; continue; }
  29. if (depth === 0 && (c === '"' || c === "'")) { quote = c; continue; }
  30. if (depth > 0 && (c === '"' || c === "'" || c === '`')) { quote = c; continue; }
  31. if (c === '{') depth++;
  32. else if (c === '}') depth--;
  33. else if (c === '>' && depth === 0) return k;
  34. else if (c === '<' && depth === 0 && /[A-Za-z]/.test(text[k + 1] ?? '')) return -1;
  35. }
  36. return -1;
  37. }
  38. function flatten(attrs: string): { flat: string; spread: boolean } {
  39. let out = '';
  40. let depth = 0;
  41. let spread = false;
  42. for (let k = 0; k < attrs.length; k++) {
  43. const c = attrs[k];
  44. if (c === '{') {
  45. if (depth === 0 && /^\{\s*\.\.\./.test(attrs.slice(k)) && !/=\s*$/.test(out)) spread = true;
  46. depth++;
  47. out += depth === 1 ? '{' : ' ';
  48. continue;
  49. }
  50. if (c === '}') { depth--; out += depth === 0 ? '}' : ' '; continue; }
  51. out += depth > 0 ? (c === '\n' ? '\n' : ' ') : c;
  52. }
  53. return { flat: out, spread };
  54. }
  55. /** Every element whose tag name matches `names` (anchored), in document order. */
  56. export function elements(text: string, names: RegExp): El[] {
  57. const out: El[] = [];
  58. const re = /<([A-Za-z][\w.:-]*)(?=[\s/>])/g;
  59. const want = new RegExp(`^(?:${names.source})$`);
  60. let reach = -1; // the furthest end of an opening tag seen so far
  61. let m: RegExpExecArray | null;
  62. while ((m = re.exec(text))) {
  63. const name = m[1];
  64. const end = tagEnd(text, m.index);
  65. const inAttr = m.index < reach;
  66. if (end > reach) reach = end;
  67. if (!want.test(name) || end < 0) continue;
  68. const raw = text.slice(m.index + 1 + name.length, end);
  69. const selfClosing = raw.trimEnd().endsWith('/');
  70. const attrs = selfClosing ? raw.trimEnd().slice(0, -1) : raw;
  71. const { flat, spread } = flatten(attrs);
  72. out.push({ name, attrs, flat, spread, selfClosing, start: m.index, openEnd: end + 1, inner: selfClosing ? null : innerOf(text, name, end + 1), inAttr });
  73. }
  74. return out;
  75. }
  76. function innerOf(text: string, name: string, from: number): string | null {
  77. const esc = name.replace(/[.]/g, '\\.');
  78. const re = new RegExp(`<${esc}(?=[\\s/>])|</${esc}\\s*>`, 'g');
  79. re.lastIndex = from;
  80. let depth = 1;
  81. let m: RegExpExecArray | null;
  82. while ((m = re.exec(text))) {
  83. if (m[0].startsWith('</')) { depth--; if (depth === 0) return text.slice(from, m.index); }
  84. else {
  85. const e = tagEnd(text, m.index);
  86. if (e > 0 && text[e - 1] !== '/') depth++;
  87. }
  88. }
  89. return null;
  90. }
  91. /** Value of an attribute: the literal string, '{…}' for an expression, '' for a bare attribute, null when absent. */
  92. export function attr(el: El, name: string): string | null {
  93. const re = new RegExp(`(?:^|\\s)${name.replace(/[-]/g, '\\-')}(?:\\s*=\\s*("([^"]*)"|'([^']*)'|\\{))?(?=[\\s/>]|$)`);
  94. const m = re.exec(el.flat);
  95. if (!m) {
  96. const m2 = new RegExp(`(?:^|\\s)${name.replace(/[-]/g, '\\-')}\\s*=\\s*\\{`).exec(el.flat);
  97. return m2 ? '{…}' : null;
  98. }
  99. if (m[1] === undefined) return '';
  100. if (m[1] === '{') return '{…}';
  101. return m[2] ?? m[3] ?? '';
  102. }
  103. /** Text a person would hear inside an element: tags dropped; null when an expression ({…}) may give text. */
  104. export function innerText(inner: string): string | null {
  105. if (/\{(?!\s*\})/.test(inner)) return null;
  106. return inner.replace(/<[^>]*>/g, ' ').replace(/&nbsp;|&#160;/g, ' ').replace(/\s+/g, ' ').trim();
  107. }
  108. /** Every string literal in a script (".." '..' `..` without ${}), with its offset. Class names live there. */
  109. export function strings(text: string): { value: string; at: number }[] {
  110. const out: { value: string; at: number }[] = [];
  111. const re = /"((?:[^"\\\n]|\\.)*)"|'((?:[^'\\\n]|\\.)*)'|`((?:[^`\\$]|\\.|\$(?!\{))*)`/g;
  112. let m: RegExpExecArray | null;
  113. while ((m = re.exec(text))) out.push({ value: m[1] ?? m[2] ?? m[3] ?? '', at: m.index });
  114. return out;
  115. }
  116. /** Class-like tokens of a string (split on whitespace). */
  117. export function tokens(s: string): string[] {
  118. return s.split(/\s+/).filter(Boolean);
  119. }