файл пакета→ .shtukbase/packages/shtukbase-ui-react/test/lib.ts
test/lib.ts
221 строка, 10.9 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // Helpers of the render tests: load a component of the library and its states, render it to static HTML, read the
- // templates of the HTML library, and compare the two markups as trees (not as strings).
- import { existsSync, readFileSync } from 'node:fs';
- import { join } from 'node:path';
- import * as React from 'react';
- import { renderToStaticMarkup } from 'react-dom/server';
- import { LEVEL_DIRS, files } from '../actions/kitlib.ts';
- import { parseHeader, type Header } from '../../design-components/lib/header.ts';
- export const PKG = join(import.meta.dir, '..');
- export const LIBRARY = join(PKG, 'library');
- export const HTML_PACKAGE = join(PKG, '..', 'shtukbase-ui-html');
- /** The HTML library as it lies in its package: pages/design/shtukbase-ui-html/components/<level>/<id>/<id>.html. */
- export const HTML_COMPONENTS = process.env.SB_UI_HTML_COMPONENTS ?? join(HTML_PACKAGE, 'pages', 'design', 'shtukbase-ui-html', 'components');
- // ---- the React library ----
- export type Loaded = {
- id: string;
- dir: string;
- file: string;
- header: Header;
- // biome-ignore lint/suspicious/noExplicitAny: components have different props
- component: React.ComponentType<any>;
- // biome-ignore lint/suspicious/noExplicitAny: the same
- states: { names: readonly string[]; entries: Record<string, any> };
- };
- /** The library files of every component: library/<level dir>/<id>.tsx. */
- export function libraryComponents(): { id: string; dir: string; path: string }[] {
- return files(LIBRARY)
- .filter((rel) => /^(primitives|composites|blocks|shell|pages)\/[^/]+\.tsx$/.test(rel) && !/\.(states|test|spec|stories)\.tsx$/.test(rel))
- .map((rel) => ({ id: rel.split('/')[1].replace(/\.tsx$/, ''), dir: rel.split('/')[0], path: join(LIBRARY, rel) }));
- }
- const pascal = (id: string) => id.split('-').map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join('');
- /** Imports a component and its states file. The React export is the PascalCase of the id. */
- export async function load(id: string): Promise<Loaded> {
- const found = libraryComponents().find((c) => c.id === id);
- if (!found) throw new Error(`no component "${id}" in the library`);
- const parsed = parseHeader(readFileSync(found.path, 'utf8'), found.path);
- if (!parsed.header) throw new Error(parsed.problems.join('\n') || `${found.path}: no header`);
- const mod = await import(found.path);
- const component = mod[pascal(id)];
- if (!component) throw new Error(`${found.path} does not export ${pascal(id)}`);
- const statesFile = found.path.replace(/\.tsx$/, '.states.tsx');
- if (!existsSync(statesFile)) throw new Error(`no states file ${statesFile}`);
- const st = await import(statesFile);
- return { id, dir: found.dir, file: found.path, header: parsed.header, component, states: st.states };
- }
- export function render(component: React.ComponentType<any>, props: Record<string, unknown>): string {
- return renderToStaticMarkup(React.createElement(component, props));
- }
- /** Draws one state of a loaded component: its entry is the props, or a function that draws the state. */
- export function renderState(c: Loaded, name: string): string {
- const entry = c.states.entries[name];
- if (entry === undefined) throw new Error(`${c.id}: no state "${name}" in ${c.file.replace(/\.tsx$/, '.states.tsx')}`);
- return typeof entry === 'function' ? renderToStaticMarkup(entry()) : render(c.component, entry);
- }
- // ---- the HTML library ----
- export type HtmlComponent = { id: string; level: string; path: string; header: Header; templates: Record<string, string> };
- /** The `<template data-state="…">` / `<template data-status="…">` blocks of an HTML component file: name -> inner markup. */
- export function templatesOf(text: string): Record<string, string> {
- const out: Record<string, string> = {};
- for (const m of text.matchAll(/<template\b([^>]*)>([\s\S]*?)<\/template>/g)) {
- const a = /data-(?:state|status)\s*=\s*"([^"]*)"/.exec(m[1]);
- if (a) out[a[1]] = m[2].trim();
- }
- return out;
- }
- /** Every component of the HTML library (empty when the package has not landed yet). */
- export function htmlComponents(): HtmlComponent[] {
- if (!existsSync(HTML_COMPONENTS)) return [];
- const out: HtmlComponent[] = [];
- for (const rel of files(HTML_COMPONENTS)) {
- const m = /^([^/]+)\/([^/]+)\/\2\.html$/.exec(rel);
- if (!m) continue;
- const path = join(HTML_COMPONENTS, rel);
- const text = readFileSync(path, 'utf8');
- const p = parseHeader(text, path);
- if (!p.header) throw new Error(p.problems.join('\n') || `${path}: no header`);
- out.push({ id: m[2], level: m[1], path, header: p.header, templates: templatesOf(text) });
- }
- return out;
- }
- export { LEVEL_DIRS };
- // ---- a small HTML tree ----
- export type El = { tag: string; attrs: Record<string, string>; children: (El | string)[] };
- const VOID = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
- const RAW = new Set(['script', 'style']);
- const unescape = (s: string) =>
- s.replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi, (_, e: string) => {
- const k = e.toLowerCase();
- if (k === 'amp') return '&';
- if (k === 'lt') return '<';
- if (k === 'gt') return '>';
- if (k === 'quot') return '"';
- if (k === 'apos') return "'";
- if (k === 'nbsp') return ' ';
- return String.fromCodePoint(k.startsWith('#x') ? parseInt(k.slice(2), 16) : parseInt(k.slice(1), 10));
- });
- /** Parses a fragment of HTML (what a template or `renderToStaticMarkup` gives) into elements and text. Tolerant, not a browser. */
- export function parseHtml(html: string): (El | string)[] {
- const root: El = { tag: '#root', attrs: {}, children: [] };
- const stack: El[] = [root];
- const re = /<!--[\s\S]*?-->|<\/([a-zA-Z][\w:-]*)\s*>|<([a-zA-Z][\w:-]*)((?:\s+[^\s"'<>\/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'=<>`]+))?)*)\s*(\/?)>|([^<]+|<)/g;
- let m: RegExpExecArray | null;
- while ((m = re.exec(html))) {
- const top = stack[stack.length - 1];
- if (m[0].startsWith('<!--')) continue;
- if (m[1]) {
- const at = stack.map((e) => e.tag).lastIndexOf(m[1].toLowerCase());
- if (at > 0) stack.length = at;
- } else if (m[2]) {
- const el: El = { tag: m[2].toLowerCase(), attrs: {}, children: [] };
- for (const a of m[3].matchAll(/([^\s"'<>\/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g))
- el.attrs[a[1].toLowerCase()] = unescape(a[2] ?? a[3] ?? a[4] ?? '');
- top.children.push(el);
- if (!VOID.has(el.tag) && !m[4]) {
- if (RAW.has(el.tag)) {
- const end = html.indexOf(`</${el.tag}`, re.lastIndex);
- el.children.push(html.slice(re.lastIndex, end < 0 ? html.length : end));
- re.lastIndex = end < 0 ? html.length : html.indexOf('>', end) + 1;
- } else stack.push(el);
- }
- } else if (m[5] !== undefined) top.children.push(unescape(m[5]));
- }
- return root.children;
- }
- const collapse = (s: string) => s.replace(/\s+/g, ' ').trim();
- /** The children without blank text, adjacent text joined and whitespace collapsed. */
- function kids(e: El | { children: (El | string)[] }): (El | string)[] {
- const out: (El | string)[] = [];
- for (const c of e.children) {
- if (typeof c === 'string') {
- const t = collapse(c);
- if (!t) continue;
- if (typeof out[out.length - 1] === 'string') out[out.length - 1] = `${out[out.length - 1]} ${t}`;
- else out.push(t);
- } else out.push(c);
- }
- return out;
- }
- const styleMap = (s: string): Record<string, string> => {
- const out: Record<string, string> = {};
- for (const part of s.split(';')) {
- const i = part.indexOf(':');
- if (i > 0) out[part.slice(0, i).trim().toLowerCase()] = part.slice(i + 1).trim().replace(/\s+/g, ' ');
- }
- return out;
- };
- /** What the comparison leaves out by default: the hidden checkbox Radix draws next to a switch on the server. */
- export const DEFAULTS: CompareOptions = {
- dropReact: (el) => el.tag === 'input' && el.attrs.type === 'checkbox' && el.attrs['aria-hidden'] === 'true',
- };
- /** Compares two fragments of markup (a template may hold several root elements). */
- export function compareFragment(html: string, react: string, opt: CompareOptions = DEFAULTS): string[] {
- const wrap = (nodes: (El | string)[]): El => ({ tag: '#fragment', attrs: {}, children: nodes });
- return compare(wrap(parseHtml(html)), wrap(parseHtml(react)), '', opt);
- }
- export type CompareOptions = {
- /** Attributes only the React side has and the HTML side does not need (compared in the other direction: never reported). */
- ignoreAttrs?: string[];
- /** Tags of the HTML template that React draws differently: skipped with their children. */
- skipTags?: string[];
- /** 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). */
- dropReact?: (el: El) => boolean;
- };
- /**
- * The HTML markup is the standard; the React markup must carry all of it: the same tags and text in the same order, every
- * attribute of the HTML side with the same value, every class of the HTML side (shadcn adds its own Tailwind classes), every
- * custom property of the inline style. What only React has (`type`, `aria-*`, Tailwind classes, Radix `data-state`) is not a difference.
- */
- export function compare(html: El | string, react: El | string, path = '', opt: CompareOptions = {}): string[] {
- if (typeof html === 'string' || typeof react === 'string') {
- const a = typeof html === 'string' ? html : `<${html.tag}>`;
- const b = typeof react === 'string' ? react : `<${react.tag}>`;
- return a === b ? [] : [`${path}: HTML has ${JSON.stringify(a)}, React has ${JSON.stringify(b)}`];
- }
- const here = `${path}/${html.tag}${html.attrs['data-slot'] ? `[${html.attrs['data-slot']}]` : ''}`;
- const out: string[] = [];
- if (html.tag !== react.tag) return [`${here}: the HTML tag is <${html.tag}>, React draws <${react.tag}>`];
- for (const [k, v] of Object.entries(html.attrs)) {
- if (opt.ignoreAttrs?.includes(k)) continue;
- if (k === 'class') {
- const have = new Set((react.attrs.class ?? '').split(/\s+/).filter(Boolean));
- const lack = v.split(/\s+/).filter((c) => c && !have.has(c));
- if (lack.length) out.push(`${here}: class lacks ${lack.join(', ')}`);
- } else if (k === 'style') {
- const mine = styleMap(react.attrs.style ?? '');
- 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)}`);
- } else if (react.attrs[k] !== v) out.push(`${here}: attribute ${k} is ${JSON.stringify(react.attrs[k])}, the HTML has ${JSON.stringify(v)}`);
- }
- if (opt.skipTags?.includes(html.tag)) return out;
- const a = kids(html);
- const b = kids(react).filter((c) => typeof c === 'string' || !opt.dropReact?.(c));
- if (a.length !== b.length) {
- 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(' ')})`);
- return out;
- }
- a.forEach((c, i) => out.push(...compare(c, b[i], here, opt)));
- return out;
- }