файл пакета→ .shtukbase/packages/design-base/lib/markup.ts
lib/markup.ts
129 строк, 5.5 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // Markup for the design checks: elements in HTML and JSX/TSX (opening tag, attributes, inner text), class tokens
- // from string literals. A scanner, not a parser: it skips braces and quotes inside tags, which is enough for
- // the questions the checks ask (is there an alt, a label, a name).
- export type El = {
- name: string;
- attrs: string; // raw text between the name and the end of the opening tag
- flat: string; // attrs with the inside of {...} blanked, so regexps see only attribute names and literal values
- spread: boolean; // has {...rest}: the attribute may come from outside
- selfClosing: boolean;
- start: number;
- openEnd: number; // offset just after '>' of the opening tag
- inner: string | null; // text up to the matching closing tag (null: self-closing or not found)
- inAttr: boolean; // written inside another tag's attribute (`render={<Button />}`): a template, not a child
- };
- /** Comments out of the way (JSX {/* *\/}, //, /* *\/ and <!-- -->), lengths and newlines kept. */
- export function blankComments(text: string, html: boolean): string {
- const blank = (m: string) => m.replace(/[^\n]/g, ' ');
- let t = text.replace(/<!--[\s\S]*?-->/g, blank);
- if (!html) t = t.replace(/\/\*[\s\S]*?\*\//g, blank).replace(/(^|[^:"'`\\])\/\/[^\n]*/g, (m, p) => p + blank(m.slice(p.length)));
- return t;
- }
- /** End of an opening tag that starts at `i` (at '<'): offset of its '>' or -1. Skips {...} and quoted values. */
- function tagEnd(text: string, i: number): number {
- let depth = 0;
- let quote = '';
- for (let k = i + 1; k < text.length; k++) {
- const c = text[k];
- if (quote) { if (c === quote) quote = ''; continue; }
- if (depth === 0 && (c === '"' || c === "'")) { quote = c; continue; }
- if (depth > 0 && (c === '"' || c === "'" || c === '`')) { quote = c; continue; }
- if (c === '{') depth++;
- else if (c === '}') depth--;
- else if (c === '>' && depth === 0) return k;
- else if (c === '<' && depth === 0 && /[A-Za-z]/.test(text[k + 1] ?? '')) return -1;
- }
- return -1;
- }
- function flatten(attrs: string): { flat: string; spread: boolean } {
- let out = '';
- let depth = 0;
- let spread = false;
- for (let k = 0; k < attrs.length; k++) {
- const c = attrs[k];
- if (c === '{') {
- if (depth === 0 && /^\{\s*\.\.\./.test(attrs.slice(k)) && !/=\s*$/.test(out)) spread = true;
- depth++;
- out += depth === 1 ? '{' : ' ';
- continue;
- }
- if (c === '}') { depth--; out += depth === 0 ? '}' : ' '; continue; }
- out += depth > 0 ? (c === '\n' ? '\n' : ' ') : c;
- }
- return { flat: out, spread };
- }
- /** Every element whose tag name matches `names` (anchored), in document order. */
- export function elements(text: string, names: RegExp): El[] {
- const out: El[] = [];
- const re = /<([A-Za-z][\w.:-]*)(?=[\s/>])/g;
- const want = new RegExp(`^(?:${names.source})$`);
- let reach = -1; // the furthest end of an opening tag seen so far
- let m: RegExpExecArray | null;
- while ((m = re.exec(text))) {
- const name = m[1];
- const end = tagEnd(text, m.index);
- const inAttr = m.index < reach;
- if (end > reach) reach = end;
- if (!want.test(name) || end < 0) continue;
- const raw = text.slice(m.index + 1 + name.length, end);
- const selfClosing = raw.trimEnd().endsWith('/');
- const attrs = selfClosing ? raw.trimEnd().slice(0, -1) : raw;
- const { flat, spread } = flatten(attrs);
- out.push({ name, attrs, flat, spread, selfClosing, start: m.index, openEnd: end + 1, inner: selfClosing ? null : innerOf(text, name, end + 1), inAttr });
- }
- return out;
- }
- function innerOf(text: string, name: string, from: number): string | null {
- const esc = name.replace(/[.]/g, '\\.');
- const re = new RegExp(`<${esc}(?=[\\s/>])|</${esc}\\s*>`, 'g');
- re.lastIndex = from;
- let depth = 1;
- let m: RegExpExecArray | null;
- while ((m = re.exec(text))) {
- if (m[0].startsWith('</')) { depth--; if (depth === 0) return text.slice(from, m.index); }
- else {
- const e = tagEnd(text, m.index);
- if (e > 0 && text[e - 1] !== '/') depth++;
- }
- }
- return null;
- }
- /** Value of an attribute: the literal string, '{…}' for an expression, '' for a bare attribute, null when absent. */
- export function attr(el: El, name: string): string | null {
- const re = new RegExp(`(?:^|\\s)${name.replace(/[-]/g, '\\-')}(?:\\s*=\\s*("([^"]*)"|'([^']*)'|\\{))?(?=[\\s/>]|$)`);
- const m = re.exec(el.flat);
- if (!m) {
- const m2 = new RegExp(`(?:^|\\s)${name.replace(/[-]/g, '\\-')}\\s*=\\s*\\{`).exec(el.flat);
- return m2 ? '{…}' : null;
- }
- if (m[1] === undefined) return '';
- if (m[1] === '{') return '{…}';
- return m[2] ?? m[3] ?? '';
- }
- /** Text a person would hear inside an element: tags dropped; null when an expression ({…}) may give text. */
- export function innerText(inner: string): string | null {
- if (/\{(?!\s*\})/.test(inner)) return null;
- return inner.replace(/<[^>]*>/g, ' ').replace(/ | /g, ' ').replace(/\s+/g, ' ').trim();
- }
- /** Every string literal in a script (".." '..' `..` without ${}), with its offset. Class names live there. */
- export function strings(text: string): { value: string; at: number }[] {
- const out: { value: string; at: number }[] = [];
- const re = /"((?:[^"\\\n]|\\.)*)"|'((?:[^'\\\n]|\\.)*)'|`((?:[^`\\$]|\\.|\$(?!\{))*)`/g;
- let m: RegExpExecArray | null;
- while ((m = re.exec(text))) out.push({ value: m[1] ?? m[2] ?? m[3] ?? '', at: m.index });
- return out;
- }
- /** Class-like tokens of a string (split on whitespace). */
- export function tokens(s: string): string[] {
- return s.split(/\s+/).filter(Boolean);
- }