ShtukbaseStandard
包文件→ .shtukbase/packages/keer-ui/tools/catalog.ts

tools/catalog.ts

131 行, 7.3 KB.

文件按包中的原样显示:代码及其注释不做翻译。

  1. // Builds keer-ui/pages/design/keer-ui/catalog.html from keer-ui/library (names, levels, descriptions, states).
  2. // Usage: bun catalog.ts <keer-ui package dir>
  3. import { readFileSync, readdirSync, writeFileSync, mkdirSync } from 'node:fs';
  4. import { join } from 'node:path';
  5. const pkg = process.argv[2];
  6. const lib = join(pkg, 'library');
  7. const esc = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  8. type C = { file: string; name: string; level: string; doc: string; states: string[]; na: string[]; exports: string[] };
  9. const all: C[] = [];
  10. const DESC: Record<string, string> = {
  11. AlertDialog: 'Confirmation dialog for an irreversible action.', Alert: 'Message strip: info, warning, error.',
  12. Attachment: 'Attached file strip: name, size, remove.', Avatar: 'Avatar: picture or initials.',
  13. Badge: 'Badge: shadcn variants and soft state tones.', Breadcrumb: 'Breadcrumb trail.', Bubble: 'A speech bubble in a conversation.',
  14. Button: 'Button: primary graphite, outline, secondary, ghost, destructive, link.', Card: 'Card: header, content, footer.',
  15. Checkbox: 'Checkbox.', Collapsible: 'Collapsible block.', Dialog: 'Dialog over the page.', DropdownMenu: 'Dropdown menu.',
  16. Field: 'Form field: label, input, hint, error.', InputGroup: 'Input with buttons and icons inside.', Input: 'Single-line input.',
  17. Label: 'Field label.', Marker: 'Marker in the margin of a text.', Message: 'Conversation message: author, text, actions.',
  18. Progress: 'Progress bar.', RadioGroup: 'Choice of one of several.', ScrollArea: 'Area with a thin scroll bar.',
  19. Select: 'Select list.', Separator: 'Separator.', Sheet: 'Side sheet.', Sidebar: 'Application side panel that collapses.',
  20. Skeleton: 'Loading skeleton of the same shape as the data.', Sonner: 'Pop-up notifications (sonner).', Tabs: 'Tabs.',
  21. Textarea: 'Multi-line input.', Tooltip: 'Tooltip on hover.',
  22. };
  23. function topKeys(block: string): string[] {
  24. const keys: string[] = [];
  25. let depth = 0, expect = false, i = 0;
  26. while (i < block.length) {
  27. const rest = block.slice(i);
  28. const ws = rest.match(/^(\s+|\/\*[\s\S]*?\*\/|\/\/[^\n]*)/);
  29. if (ws) { i += ws[0].length; continue; }
  30. if (expect && depth === 1) {
  31. const m = rest.match(/^("[^"]+"|[A-Za-z][\w-]*)\s*:/);
  32. expect = false;
  33. if (m) { keys.push(m[1].replace(/"/g, '')); i += m[0].length; continue; }
  34. }
  35. const s = rest.match(/^("(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`)/);
  36. if (s) { i += s[0].length; continue; }
  37. const c = block[i];
  38. if ('{[('.includes(c)) { depth++; if (depth === 1) expect = true; }
  39. else if ('}])'.includes(c)) depth--;
  40. else if (c === ',' && depth === 1) expect = true;
  41. i++;
  42. }
  43. return keys;
  44. }
  45. for (const dir of ['primitives', 'composites']) {
  46. for (const f of readdirSync(join(lib, dir)).filter((x) => x.endsWith('.states.tsx')).sort()) {
  47. const st = readFileSync(join(lib, dir, f), 'utf8');
  48. const src = readFileSync(join(lib, dir, f.replace('.states.tsx', '.tsx')), 'utf8');
  49. const name = st.match(/name:\s*"([^"]+)"/)?.[1] ?? f;
  50. const level = st.match(/level:\s*"([^"]+)"/)?.[1] ?? dir;
  51. const at = st.indexOf('defineStates');
  52. const open = st.indexOf('{', st.indexOf('meta,', at));
  53. let depth = 0, end = open;
  54. for (; end < st.length; end++) { if (st[end] === '{') depth++; if (st[end] === '}') { depth--; if (!depth) break; } }
  55. const body = st.slice(open, end + 1);
  56. const keys = topKeys(body);
  57. const naAt = body.indexOf('notApplicable');
  58. let na: string[] = [];
  59. if (naAt >= 0) {
  60. const o = body.indexOf('{', naAt);
  61. let d = 0, e = o;
  62. for (; e < body.length; e++) { if (body[e] === '{') d++; if (body[e] === '}') { d--; if (!d) break; } }
  63. na = topKeys(body.slice(o, e + 1));
  64. }
  65. const docM = src.match(new RegExp(`/\\*\\*((?:(?!\\*/)[\\s\\S])*)\\*/\\s*(?:export\\s+)?(?:function|const)\\s+${name}\\b`));
  66. const doc = docM ? docM[1].replace(/^\s*\*\s?/gm, '').replace(/\s+/g, ' ').trim() : (DESC[name] ?? '');
  67. const exports = [...src.matchAll(/^export\s+(?:function|const)\s+([A-Z]\w*)/gm)].map((m) => m[1]);
  68. const ex2 = [...src.matchAll(/^export\s*\{([^}]*)\}/gm)].flatMap((m) => m[1].split(',').map((s) => s.trim().split(/\s+as\s+/).pop()!.trim()).filter((s) => /^[A-Z]/.test(s)));
  69. all.push({ file: `${dir}/${f.replace('.states.tsx', '.tsx')}`, name, level, doc, states: keys.filter((k) => k !== 'notApplicable'), na, exports: [...new Set([...exports, ...ex2])] });
  70. }
  71. }
  72. const section = (lvl: string, title: string, note: string) => {
  73. const list = all.filter((c) => c.level === lvl);
  74. return `
  75. <section class="ks-section" id="${lvl}">
  76. <h2 class="ks-section-title">${title} <span class="ks-caption">${list.length}</span></h2>
  77. <p class="ks-muted">${note}</p>
  78. <div class="ks-table-wrap">
  79. <table class="ks-table">
  80. <thead><tr><th>Component</th><th>File</th><th>States</th><th>Not applicable</th></tr></thead>
  81. <tbody>${list.map((c) => `
  82. <tr>
  83. <td><strong>${c.name}</strong>${c.doc ? `<div class="ks-caption">${esc(c.doc)}</div>` : ''}${c.exports.length > 1 ? `<div class="ks-caption ks-mono">${esc(c.exports.join(', '))}</div>` : ''}</td>
  84. <td class="ks-mono">${c.file}</td>
  85. <td><div class="ks-row">${c.states.map((s) => `<span class="ks-badge">${esc(s)}</span>`).join('')}</div></td>
  86. <td><div class="ks-row">${c.na.map((s) => `<span class="ks-badge ks-badge--warning">${esc(s)}</span>`).join('')}</div></td>
  87. </tr>`).join('')}
  88. </tbody>
  89. </table>
  90. </div>
  91. </section>`;
  92. };
  93. const total = all.reduce((n, c) => n + c.states.length, 0);
  94. const html = `<!doctype html>
  95. <html lang="en">
  96. <head>
  97. <meta charset="utf-8">
  98. <meta name="viewport" content="width=device-width, initial-scale=1">
  99. <title>keer-ui — component catalog</title>
  100. <link rel="stylesheet" href="../keer-style/tokens.css">
  101. <link rel="stylesheet" href="../keer-style/elements.css">
  102. <style>
  103. .ks-table td { height: auto; padding-top: var(--ds-space-2); padding-bottom: var(--ds-space-2); vertical-align: top; }
  104. .ks-table td .ks-caption { max-width: 34em; }
  105. </style>
  106. </head>
  107. <body class="ks-page">
  108. <main class="ks-layout">
  109. <header class="ks-page-header">
  110. <div>
  111. <div class="ks-overline">keer-ui · catalog</div>
  112. <h1 class="ks-page-title">Components</h1>
  113. <p>${all.length} components and ${total} states. The code lives in the project (the folder from the target: field of the page design/keer-ui.md); the look comes from the keer-style tokens.</p>
  114. </div>
  115. </header>
  116. ${section('primitive', 'Primitives', 'The shadcn base on Base UI: button, input, card, table, menu, dialog. They know nothing about the product.')}
  117. ${section('composite', 'Composites', 'Built from primitives: page header, layout, state view, lists, badges. They know nothing about the product.')}
  118. <p class="ks-caption">The catalog is built from the *.states.tsx files of the library. "Not applicable" lists the states a component does not have, with the reason in its states file.</p>
  119. </main>
  120. </body>
  121. </html>
  122. `;
  123. mkdirSync(join(pkg, 'pages/design/keer-ui'), { recursive: true });
  124. writeFileSync(join(pkg, 'pages/design/keer-ui/catalog.html'), html);
  125. console.log(all.length, 'components', total, 'states');
  126. for (const c of all) if (!c.states.length || !c.doc) console.log('check:', c.name, c.states.length, c.doc ? '' : 'no doc');