ShtukbaseStandard
файл пакета→ .shtukbase/packages/shtukbase-ui-react/test/lib.ts

test/lib.ts

221 строка, 10.9 КБ.

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

  1. // Helpers of the render tests: load a component of the library and its states, render it to static HTML, read the
  2. // templates of the HTML library, and compare the two markups as trees (not as strings).
  3. import { existsSync, readFileSync } from 'node:fs';
  4. import { join } from 'node:path';
  5. import * as React from 'react';
  6. import { renderToStaticMarkup } from 'react-dom/server';
  7. import { LEVEL_DIRS, files } from '../actions/kitlib.ts';
  8. import { parseHeader, type Header } from '../../design-components/lib/header.ts';
  9. export const PKG = join(import.meta.dir, '..');
  10. export const LIBRARY = join(PKG, 'library');
  11. export const HTML_PACKAGE = join(PKG, '..', 'shtukbase-ui-html');
  12. /** The HTML library as it lies in its package: pages/design/shtukbase-ui-html/components/<level>/<id>/<id>.html. */
  13. export const HTML_COMPONENTS = process.env.SB_UI_HTML_COMPONENTS ?? join(HTML_PACKAGE, 'pages', 'design', 'shtukbase-ui-html', 'components');
  14. // ---- the React library ----
  15. export type Loaded = {
  16. id: string;
  17. dir: string;
  18. file: string;
  19. header: Header;
  20. // biome-ignore lint/suspicious/noExplicitAny: components have different props
  21. component: React.ComponentType<any>;
  22. // biome-ignore lint/suspicious/noExplicitAny: the same
  23. states: { names: readonly string[]; entries: Record<string, any> };
  24. };
  25. /** The library files of every component: library/<level dir>/<id>.tsx. */
  26. export function libraryComponents(): { id: string; dir: string; path: string }[] {
  27. return files(LIBRARY)
  28. .filter((rel) => /^(primitives|composites|blocks|shell|pages)\/[^/]+\.tsx$/.test(rel) && !/\.(states|test|spec|stories)\.tsx$/.test(rel))
  29. .map((rel) => ({ id: rel.split('/')[1].replace(/\.tsx$/, ''), dir: rel.split('/')[0], path: join(LIBRARY, rel) }));
  30. }
  31. const pascal = (id: string) => id.split('-').map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('');
  32. /** Imports a component and its states file. The React export is the PascalCase of the id. */
  33. export async function load(id: string): Promise<Loaded> {
  34. const found = libraryComponents().find((c) => c.id === id);
  35. if (!found) throw new Error(`no component "${id}" in the library`);
  36. const parsed = parseHeader(readFileSync(found.path, 'utf8'), found.path);
  37. if (!parsed.header) throw new Error(parsed.problems.join('\n') || `${found.path}: no header`);
  38. const mod = await import(found.path);
  39. const component = mod[pascal(id)];
  40. if (!component) throw new Error(`${found.path} does not export ${pascal(id)}`);
  41. const statesFile = found.path.replace(/\.tsx$/, '.states.tsx');
  42. if (!existsSync(statesFile)) throw new Error(`no states file ${statesFile}`);
  43. const st = await import(statesFile);
  44. return { id, dir: found.dir, file: found.path, header: parsed.header, component, states: st.states };
  45. }
  46. export function render(component: React.ComponentType<any>, props: Record<string, unknown>): string {
  47. return renderToStaticMarkup(React.createElement(component, props));
  48. }
  49. /** Draws one state of a loaded component: its entry is the props, or a function that draws the state. */
  50. export function renderState(c: Loaded, name: string): string {
  51. const entry = c.states.entries[name];
  52. if (entry === undefined) throw new Error(`${c.id}: no state "${name}" in ${c.file.replace(/\.tsx$/, '.states.tsx')}`);
  53. return typeof entry === 'function' ? renderToStaticMarkup(entry()) : render(c.component, entry);
  54. }
  55. // ---- the HTML library ----
  56. export type HtmlComponent = { id: string; level: string; path: string; header: Header; templates: Record<string, string> };
  57. /** The `<template data-state="…">` / `<template data-status="…">` blocks of an HTML component file: name -> inner markup. */
  58. export function templatesOf(text: string): Record<string, string> {
  59. const out: Record<string, string> = {};
  60. for (const m of text.matchAll(/<template\b([^>]*)>([\s\S]*?)<\/template>/g)) {
  61. const a = /data-(?:state|status)\s*=\s*"([^"]*)"/.exec(m[1]);
  62. if (a) out[a[1]] = m[2].trim();
  63. }
  64. return out;
  65. }
  66. /** Every component of the HTML library (empty when the package has not landed yet). */
  67. export function htmlComponents(): HtmlComponent[] {
  68. if (!existsSync(HTML_COMPONENTS)) return [];
  69. const out: HtmlComponent[] = [];
  70. for (const rel of files(HTML_COMPONENTS)) {
  71. const m = /^([^/]+)\/([^/]+)\/\2\.html$/.exec(rel);
  72. if (!m) continue;
  73. const path = join(HTML_COMPONENTS, rel);
  74. const text = readFileSync(path, 'utf8');
  75. const p = parseHeader(text, path);
  76. if (!p.header) throw new Error(p.problems.join('\n') || `${path}: no header`);
  77. out.push({ id: m[2], level: m[1], path, header: p.header, templates: templatesOf(text) });
  78. }
  79. return out;
  80. }
  81. export { LEVEL_DIRS };
  82. // ---- a small HTML tree ----
  83. export type El = { tag: string; attrs: Record<string, string>; children: (El | string)[] };
  84. const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
  85. const RAW = new Set(['script', 'style']);
  86. const unescape = (s: string) =>
  87. s.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi, (_, e: string) => {
  88. const k = e.toLowerCase();
  89. if (k === 'amp') return '&';
  90. if (k === 'lt') return '<';
  91. if (k === 'gt') return '>';
  92. if (k === 'quot') return '"';
  93. if (k === 'apos') return "'";
  94. if (k === 'nbsp') return ' ';
  95. return String.fromCodePoint(k.startsWith('#x') ? parseInt(k.slice(2), 16) : parseInt(k.slice(1), 10));
  96. });
  97. /** Parses a fragment of HTML (what a template or `renderToStaticMarkup` gives) into elements and text. Tolerant, not a browser. */
  98. export function parseHtml(html: string): (El | string)[] {
  99. const root: El = { tag: '#root', attrs: {}, children: [] };
  100. const stack: El[] = [root];
  101. const re = /<!--[\s\S]*?-->|<\/([a-zA-Z][\w:-]*)\s*>|<([a-zA-Z][\w:-]*)((?:\s+[^\s"'<>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>|([^<]+|<)/g;
  102. let m: RegExpExecArray | null;
  103. while ((m = re.exec(html))) {
  104. const top = stack[stack.length - 1];
  105. if (m[0].startsWith('<!--')) continue;
  106. if (m[1]) {
  107. const at = stack.map((e) => e.tag).lastIndexOf(m[1].toLowerCase());
  108. if (at > 0) stack.length = at;
  109. } else if (m[2]) {
  110. const el: El = { tag: m[2].toLowerCase(), attrs: {}, children: [] };
  111. for (const a of m[3].matchAll(/([^\s"'<>\/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g))
  112. el.attrs[a[1].toLowerCase()] = unescape(a[2] ?? a[3] ?? a[4] ?? '');
  113. top.children.push(el);
  114. if (!VOID.has(el.tag) && !m[4]) {
  115. if (RAW.has(el.tag)) {
  116. const end = html.indexOf(`</${el.tag}`, re.lastIndex);
  117. el.children.push(html.slice(re.lastIndex, end < 0 ? html.length : end));
  118. re.lastIndex = end < 0 ? html.length : html.indexOf('>', end) + 1;
  119. } else stack.push(el);
  120. }
  121. } else if (m[5] !== undefined) top.children.push(unescape(m[5]));
  122. }
  123. return root.children;
  124. }
  125. const collapse = (s: string) => s.replace(/\s+/g, ' ').trim();
  126. /** The children without blank text, adjacent text joined and whitespace collapsed. */
  127. function kids(e: El | { children: (El | string)[] }): (El | string)[] {
  128. const out: (El | string)[] = [];
  129. for (const c of e.children) {
  130. if (typeof c === 'string') {
  131. const t = collapse(c);
  132. if (!t) continue;
  133. if (typeof out[out.length - 1] === 'string') out[out.length - 1] = `${out[out.length - 1]} ${t}`;
  134. else out.push(t);
  135. } else out.push(c);
  136. }
  137. return out;
  138. }
  139. const styleMap = (s: string): Record<string, string> => {
  140. const out: Record<string, string> = {};
  141. for (const part of s.split(';')) {
  142. const i = part.indexOf(':');
  143. if (i > 0) out[part.slice(0, i).trim().toLowerCase()] = part.slice(i + 1).trim().replace(/\s+/g, ' ');
  144. }
  145. return out;
  146. };
  147. /** What the comparison leaves out by default: the hidden checkbox Radix draws next to a switch on the server. */
  148. export const DEFAULTS: CompareOptions = {
  149. dropReact: (el) => el.tag === 'input' && el.attrs.type === 'checkbox' && el.attrs['aria-hidden'] === 'true',
  150. };
  151. /** Compares two fragments of markup (a template may hold several root elements). */
  152. export function compareFragment(html: string, react: string, opt: CompareOptions = DEFAULTS): string[] {
  153. const wrap = (nodes: (El | string)[]): El => ({ tag: '#fragment', attrs: {}, children: nodes });
  154. return compare(wrap(parseHtml(html)), wrap(parseHtml(react)), '', opt);
  155. }
  156. export type CompareOptions = {
  157. /** Attributes only the React side has and the HTML side does not need (compared in the other direction: never reported). */
  158. ignoreAttrs?: string[];
  159. /** Tags of the HTML template that React draws differently: skipped with their children. */
  160. skipTags?: string[];
  161. /** Elements of the React side that are not part of the comparison (Radix draws a hidden checkbox next to a switch when it renders on the server). */
  162. dropReact?: (el: El) => boolean;
  163. };
  164. /**
  165. * The HTML markup is the standard; the React markup must carry all of it: the same tags and text in the same order, every
  166. * attribute of the HTML side with the same value, every class of the HTML side (shadcn adds its own Tailwind classes), every
  167. * custom property of the inline style. What only React has (`type`, `aria-*`, Tailwind classes, Radix `data-state`) is not a difference.
  168. */
  169. export function compare(html: El | string, react: El | string, path = '', opt: CompareOptions = {}): string[] {
  170. if (typeof html === 'string' || typeof react === 'string') {
  171. const a = typeof html === 'string' ? html : `<${html.tag}>`;
  172. const b = typeof react === 'string' ? react : `<${react.tag}>`;
  173. return a === b ? [] : [`${path}: HTML has ${JSON.stringify(a)}, React has ${JSON.stringify(b)}`];
  174. }
  175. const here = `${path}/${html.tag}${html.attrs['data-slot'] ? `[${html.attrs['data-slot']}]` : ''}`;
  176. const out: string[] = [];
  177. if (html.tag !== react.tag) return [`${here}: the HTML tag is <${html.tag}>, React draws <${react.tag}>`];
  178. for (const [k, v] of Object.entries(html.attrs)) {
  179. if (opt.ignoreAttrs?.includes(k)) continue;
  180. if (k === 'class') {
  181. const have = new Set((react.attrs.class ?? '').split(/\s+/).filter(Boolean));
  182. const lack = v.split(/\s+/).filter((c) => c && !have.has(c));
  183. if (lack.length) out.push(`${here}: class lacks ${lack.join(', ')}`);
  184. } else if (k === 'style') {
  185. const mine = styleMap(react.attrs.style ?? '');
  186. for (const [p, val] of Object.entries(styleMap(v))) if (mine[p] !== val) out.push(`${here}: style ${p} is ${JSON.stringify(mine[p])}, the HTML has ${JSON.stringify(val)}`);
  187. } else if (react.attrs[k] !== v) out.push(`${here}: attribute ${k} is ${JSON.stringify(react.attrs[k])}, the HTML has ${JSON.stringify(v)}`);
  188. }
  189. if (opt.skipTags?.includes(html.tag)) return out;
  190. const a = kids(html);
  191. const b = kids(react).filter((c) => typeof c === 'string' || !opt.dropReact?.(c));
  192. if (a.length !== b.length) {
  193. out.push(`${here}: the HTML has ${a.length} child nodes, React draws ${b.length} (${b.map((c) => (typeof c === 'string' ? JSON.stringify(c) : `<${c.tag}>`)).join(' ')})`);
  194. return out;
  195. }
  196. a.forEach((c, i) => out.push(...compare(c, b[i], here, opt)));
  197. return out;
  198. }