@usableapp/cardds 0.7.166 → 0.7.168

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/bin/cardds.mjs +4 -3
  3. package/cardds.css +1 -1
  4. package/css/choice.css +1 -1
  5. package/css/fonts.css +53 -24
  6. package/css/lists.css +14 -7
  7. package/css/parts.css +8 -5
  8. package/css/stack.css +1 -1
  9. package/css/theme.template.css +2 -2
  10. package/css/tokens.css +5 -4
  11. package/dist/cardds.css +83 -43
  12. package/dist/cards/Card.js +2 -1
  13. package/dist/cards/CardFeed.js +1 -2
  14. package/dist/catalog.json +1 -1
  15. package/dist/lists/Bubble.d.ts +29 -5
  16. package/dist/lists/Bubble.js +70 -9
  17. package/dist/parts/Head.d.ts +57 -13
  18. package/dist/parts/Head.js +72 -31
  19. package/dist/parts/Words.d.ts +2 -2
  20. package/dist/parts/Words.js +2 -2
  21. package/dist/parts/endRoom.d.ts +2 -0
  22. package/dist/parts/endRoom.js +1 -1
  23. package/dist/parts/headCtx.d.ts +3 -0
  24. package/dist/parts/headCtx.js +3 -0
  25. package/dist/sheets/Modal.d.ts +1 -1
  26. package/dist/sheets/Modal.js +4 -2
  27. package/dist/sheets/Sheet.d.ts +3 -2
  28. package/dist/sheets/Sheet.js +4 -1
  29. package/dist/sheets/StackBack.d.ts +1 -1
  30. package/dist/sheets/StackBack.js +1 -1
  31. package/dist/sheets/StackSheet.js +4 -6
  32. package/dist/sheets/sheetMeasure.js +1 -1
  33. package/dist/templates/CallSheet.js +2 -3
  34. package/dist/templates/Walkthrough.js +1 -2
  35. package/dist/type/icons.d.ts +1 -1
  36. package/dist/type/icons.js +2 -2
  37. package/dist/words.d.ts +1 -1
  38. package/dist/words.js +2 -2
  39. package/docs/reference.md +56 -33
  40. package/fonts/LICENSES.md +94 -32
  41. package/fonts/noto-sans/cyrillic.woff2 +0 -0
  42. package/fonts/noto-sans/greek.woff2 +0 -0
  43. package/fonts/noto-sans/latin-ext.woff2 +0 -0
  44. package/fonts/noto-sans/latin.woff2 +0 -0
  45. package/fonts/noto-sans/vietnamese.woff2 +0 -0
  46. package/fonts/noto-sans-thai-looped/thai.woff2 +0 -0
  47. package/icons.svg +2 -1
  48. package/lib/guide.mjs +6 -5
  49. package/lint/headSlots.d.mts +2 -0
  50. package/lint/headSlots.mjs +15 -0
  51. package/lint/rules.mjs +42 -1
  52. package/package.json +2 -1
  53. package/scripts/codemod-head.mjs +306 -0
  54. package/scripts/codemod-parts.mjs +2 -1
  55. package/fonts/fc-pride-medium.otf +0 -0
  56. package/fonts/pk-nonthaburi-demo.ttf +0 -0
Binary file
package/icons.svg CHANGED
@@ -23,7 +23,8 @@
23
23
  <symbol id="store" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m2 7 4.41-4.41A2 2 0 0 1 7.83 2h8.34a2 2 0 0 1 1.42.59L22 7" /> <path d="M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8" /> <path d="M15 22v-4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4" /> <path d="M2 7h20" /> <path d="M22 7v3a2 2 0 0 1-2 2a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 16 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 12 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 8 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 4 12a2 2 0 0 1-2-2V7" /></symbol>
24
24
 
25
25
  <symbol id="check" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></symbol>
26
- <symbol id="arrow-up" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m5 12 7-7 7 7"/><path d="M12 19V5"/></symbol>
26
+ <symbol id="arrow-down" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14"/><path d="m19 12-7 7-7-7"/></symbol>
27
+ <symbol id="arrow-up"viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m5 12 7-7 7 7"/><path d="M12 19V5"/></symbol>
27
28
  <symbol id="arrow-right" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></symbol>
28
29
  <symbol id="chevron-left" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m15 18-6-6 6-6"/></symbol>
29
30
  <symbol id="chevron-right" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6"/></symbol>
package/lib/guide.mjs CHANGED
@@ -4,14 +4,15 @@
4
4
  // not here — they are in its JSDoc (get_component) and in lint/rules.mjs.
5
5
  export const GUIDE = `cardds — BEFORE drawing any phone-width / mobile screen in a project with @usableapp/cardds, or that Lh asks to build "with cardds": load these tools (ToolSearch "cardds" if deferred) and call find_components. Even when the request only says prototype, poc, mock-up, sketch, "show me a design", หน้า, หน้าจอ, ขึ้นหน้า, ขอดู prototype — a screen, card, bottom sheet, sheet stack, form step, sticky note / post-it, chat of notes, stamp, postcard, home. Never hand-write HTML, CSS or emoji for what it has.
6
6
  ORDER: find → scaffold or get → write. First question: has cardds drawn this screen already? find BOTH ways: by the axes (represents · shape · interact) and by the task's English noun ("sticky", "stamp", "chat").
7
- TOOLS: find_components · scaffold_screen · get_component · list_components. No MCP: npx cardds find|scaffold|get|list (all take --json). check / check_source: a person's tool, never a session's step.
7
+ TOOLS: find_components · scaffold_screen · get_component · list_components. No MCP: npx cardds find|scaffold|get|list --json. check / check_source: a person's tool, never a session's step.
8
8
  What no checker sees:
9
- 1. cardds is a framework you take from outside. Never edit, commit to or release cardds from a consumer project, never node_modules. What cannot be set from outside is a framework gap: STOP, tell the user what you needed.
10
- 2. Adjust from outside only, widest first: theme.css bases → knobs (--<component>-<what>) → props/slots. Theme values are the user's call, never yours. cardGrounds() names a card the member cannot see on that theme; inkGrounds() a word or glyph they cannot read (docs/reference.md).
9
+ 1. cardds is a framework you take from outside. Never edit or release cardds, or node_modules, from a consumer project. What cannot be set from outside is a framework gap: STOP, tell the user what you needed.
10
+ 2. Adjust from outside only, widest first: theme.css bases → knobs (--<component>-<what>) → props/slots. Theme values are the user's call, never yours. cardGrounds() / inkGrounds() name a card or a word the member cannot see (docs/reference.md).
11
11
  3. Every component is controlled like an input (state/open/value + its on…, or default…) and none knows another: the app owns state and wires them.
12
- 4. Import components, never copy their markup or classes: a component is the look AND the behaviour.
12
+ 4. Import components, never copy their markup or classes: a component is look AND behaviour.
13
13
  5. Mobile only, big targets, never adapted to desktop.
14
14
  6. Option row: title = the answer; meta = only the deciding difference, all or none (docs/reference.md).
15
- An HTML prototype (scaffold --html) is a still picture, never a screen; when it warns, write the tsx.
15
+ 7. Head = variant + slots, never children; variant="sheet" draws the close (onClose).
16
+ scaffold --html is a still picture, never a screen; when it warns, write the tsx.
16
17
  A component's own rules: get_component.
17
18
  `;
@@ -0,0 +1,2 @@
1
+ export const HEAD_SLOTS: Record<'plain' | 'lead' | 'date' | 'status' | 'centre' | 'sheet' | 'stack', readonly string[]>;
2
+ export function headSlotsText(): string;
@@ -0,0 +1,15 @@
1
+ // lint/headSlots.mjs — the ONE table of which slots each `Head` variant takes beside title · meta · level. Plain JS, shipped in lint/: src/parts/Head.tsx
2
+ // imports it (dist/parts/Head.js reaches it as ../../lint/headSlots.mjs) and lint/rules.mjs reads it, so the component, `cardds check` and the warning
3
+ // text cannot disagree.
4
+ export const HEAD_SLOTS = {
5
+ plain: ['over', 'end'],
6
+ lead: ['lead', 'over', 'end'],
7
+ date: ['lead', 'chips', 'over', 'end'],
8
+ status: ['tag', 'end'],
9
+ centre: ['lead', 'end'],
10
+ sheet: ['lead', 'actions', 'onClose', 'closeLabel'],
11
+ stack: ['back', 'backLabel', 'end'],
12
+ };
13
+
14
+ /** the table as one line: `plain over·end · lead lead·over·end · …` */
15
+ export const headSlotsText = () => Object.entries(HEAD_SLOTS).map(([v, s]) => `${v} ${s.join('·')}`).join(' · ');
package/lint/rules.mjs CHANGED
@@ -5,13 +5,27 @@
5
5
  import { readFileSync, readdirSync } from 'node:fs';
6
6
  import { dirname, join } from 'node:path';
7
7
  import { fileURLToPath } from 'node:url';
8
+ import { HEAD_SLOTS, headSlotsText } from './headSlots.mjs';
8
9
 
9
10
  const CSS_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', 'css');
10
11
 
11
12
  /** the props whose default is cardds's own word (src/words.ts), per component — a `label` that is a control's required accessible name (a round Btn, Fab, Pin…) is not here */
12
13
  export const CONTROL_NAMES = {
13
14
  Sheet: ['handle'], CallSheet: ['handle'], StackSheet: ['backLabel'], Home: ['backLabel'], Walkthrough: ['backLabel', 'nextLabel'],
14
- Calendar: ['prevLabel', 'nextLabel'], SheetStep: ['skipLabel'], Sticky: ['unreadLabel'], StampOn: ['removeLabel'], Card: ['removeLabel', 'toBackLabel', 'toFrontLabel'], PostLetter: ['backLabel', 'pictureLabel', 'playLabel', 'pauseLabel', 'toLabel'],
15
+ Calendar: ['prevLabel', 'nextLabel'], SheetStep: ['skipLabel'], Head: ['closeLabel', 'backLabel'], Sticky: ['unreadLabel'], StampOn: ['removeLabel'], Card: ['removeLabel', 'toBackLabel', 'toFrontLabel'], PostLetter: ['backLabel', 'pictureLabel', 'playLabel', 'pauseLabel', 'toLabel'],
16
+ };
17
+
18
+ export { HEAD_SLOTS };
19
+
20
+ /** an opening tag with every `{…}` emptied, so only its own attributes are read; the length and the places stay */
21
+ const ownAttrs = (tag) => {
22
+ let depth = 0, out = '';
23
+ for (const c of tag) {
24
+ if (c === '}') depth--;
25
+ out += depth > 0 ? ' ' : c;
26
+ if (c === '{') depth++;
27
+ }
28
+ return out;
15
29
  };
16
30
 
17
31
  export const lineOf = (text, idx) => text.slice(0, idx).split('\n').length;
@@ -308,6 +322,33 @@ export function checkSource(source, file, { classes = carddsClasses() } = {}) {
308
322
  add('map-bleed-without-inline', 'warn', m.index, '<MapArea bleed> without inline: bleed is read only with inline (the map in flow), so the map stays in its inset. Add inline, or drop bleed.');
309
323
  }
310
324
 
325
+ // 13 · a Head is one of a closed set (`variant`), filled through the slots that variant takes: a slot it does not take, or a child, is left out at runtime
326
+ for (const m of text.matchAll(/<Head\b(?![\w.])/g)) {
327
+ const tag = tagAt(text, m.index);
328
+ if (!tag.endsWith('/>') && elementAt(text, m.index).slice(tag.length).replace(/<\/Head>$/, '').trim()) add('head-slot', 'error', m.index, '<Head> with children: a head takes none — it is its variant and its slots (title · meta · lead · end · actions…), laid out by the variant. `npx cardds codemod-head <files>` rewrites it.');
329
+ if (/\scentre\b(?!\s*=\s*\{\s*false)/.test(tag)) { add('head-slot', 'error', m.index, '<Head centre> is renamed: <Head variant="centre" title=… lead={<Btn shape="round" …/>} end={<Btn shape="round" …/>} />.'); continue; }
330
+ const own = ownAttrs(tag); // the Head's own attributes: an element inside a slot (`end={<ChipRow lead=…>}`) keeps its own
331
+ const at = own.search(/\svariant\s*=/);
332
+ const variant = at < 0 ? 'plain' : tag.slice(at).match(/^\s*variant\s*=\s*\{?\s*["']([\w-]+)["']/)?.[1];
333
+ if (!variant) continue; // a variant the code picks at runtime: the component warns
334
+ const takes = HEAD_SLOTS[variant];
335
+ if (!takes) { add('head-slot', 'error', m.index, `<Head variant="${variant}">: no such head — the variants are ${Object.keys(HEAD_SLOTS).join(' · ')}.`); continue; }
336
+ for (const s of own.matchAll(/\s(tag|lead|chips|over|end|actions|onClose|closeLabel|back|backLabel)\s*=/g)) {
337
+ if (!takes.includes(s[1])) add('head-slot', 'error', m.index + s.index + 1, `${s[1]} on <Head variant="${variant}">: that head takes no ${s[1]} (it is left out). The slots beside title · meta · level: ${headSlotsText()}.`);
338
+ }
339
+ }
340
+
341
+ // 14 · a sheet's or a modal's close written by hand in its Head: Head variant="sheet" draws it, names it in the page's language and wires it
342
+ const sheets = span(/<(?:Sheet|Modal)\b(?![\w.])/g);
343
+ for (const h of heads) {
344
+ if (!sheets.some((s) => within(h.at, s))) continue;
345
+ const el = text.slice(h.at, h.end);
346
+ for (const b of el.matchAll(/<Btn\b(?![\w.])/g)) {
347
+ if (/\sicon\s*=\s*\{?\s*["']x["']/.test(tagAt(el, b.index)))
348
+ add('head-close-by-hand', 'warn', h.at + b.index, 'a close Btn written by hand in a sheet\'s or a modal\'s Head: <Head variant="sheet" title=… onClose={…} /> draws the close, names it in the page\'s language (closeLabel for other words) and wires it — in a Sheet given no onClose it asks the sheet to go away. Other round buttons beside it go in `actions` (two at most).');
349
+ }
350
+ }
351
+
311
352
  return findings.sort((a, b) => a.line - b.line);
312
353
  }
313
354
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usableapp/cardds",
3
- "version": "0.7.166",
3
+ "version": "0.7.168",
4
4
  "license": "UNLICENSED",
5
5
  "type": "module",
6
6
  "description": "card-first mobile design system, React-first: the components in src/ are thin wrappers over the CSS contract (css/*.css stays the only truth); gallery/ shows every story live (npm run dev).",
@@ -52,6 +52,7 @@
52
52
  "lib",
53
53
  "bin",
54
54
  "scripts/codemod-parts.mjs",
55
+ "scripts/codemod-head.mjs",
55
56
  "css",
56
57
  "fonts",
57
58
  "cardds.css",
@@ -0,0 +1,306 @@
1
+ // A `Head` is one of a closed set of heads (`variant`), filled through named slots; the composed head — a `Words` and loose children laid out by
2
+ // their order — is gone (Lh 2026-10-29). This rewrites a file's composed heads to a variant and its slots, through the TypeScript AST, never by
3
+ // the text of a name. A consumer runs it on its screens after the release; the previews were migrated by it.
4
+ // npx cardds codemod-head <files or folders…> rewrite each composed head in place; a head it cannot rewrite safely is printed and left
5
+ // npx cardds codemod-head --check <files or folders…> exit 1 naming every head still written with children
6
+ // (in this repo also `node scripts/codemod-head.mjs …`; it reads `typescript` from the project that runs it). Run `codemod-parts` first on a
7
+ // screen older than the parts (it writes composed heads), then this.
8
+ // What it decides, and nothing else (a head it is unsure of is left as it is and named, never guessed):
9
+ // the title: a `Words` (title · meta · over · level) or a hand-written `Text level="h1|h2|display"` / bare h1-h3 with words only in it
10
+ // before the title: nothing → plain · a `Lead` / `Avatar` / `AvatarStack` → lead · a `JourneyBadge` (+ a `ChipRow`) → date ·
11
+ // a `StackBack` → stack (back="start") · one element in a `Head centre` / `variant="centre"` → centre's `lead`
12
+ // after the title: everything → `end` (a fragment for two or more) · a `StackBack end` → stack (back="end") ·
13
+ // a round `Btn icon="x"` in a `Sheet` or a `Modal` (the close, last) → sheet: its `onClick` → `onClose`, its `label` → `closeLabel`
14
+ // (dropped when it is cardds's own word, "Close"), the round `Btn`s before it → `actions` (two at most)
15
+ // The `cardds` imports a rewrite left unused (`Words`, `Text`, `StackBack`, `Btn`) are taken out.
16
+ import { readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs';
17
+ import { join } from 'node:path';
18
+ import { fileURLToPath } from 'node:url';
19
+ import ts from 'typescript';
20
+
21
+ const LEADS = ['Lead', 'Avatar', 'AvatarStack'];
22
+ const TITLE_LEVELS = { h1: 'h1', h2: null, display: 'display' };
23
+ const WORDS_PROPS = ['title', 'meta', 'over', 'level'];
24
+ const CLOSE_PROPS = ['shape', 'size', 'icon', 'label', 'onClick'];
25
+ const ACTIONS_MAX = 2;
26
+ const LINE = 140;
27
+ const MAYBE_UNUSED = ['Words', 'Text', 'StackBack', 'Btn'];
28
+
29
+ const parse = (source, file) => ts.createSourceFile(file, source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
30
+ const openingOf = (n) => (ts.isJsxElement(n) ? n.openingElement : n);
31
+ const tagOf = (n) => {
32
+ if (!ts.isJsxElement(n) && !ts.isJsxSelfClosingElement(n)) return null;
33
+ const t = openingOf(n).tagName;
34
+ return ts.isIdentifier(t) ? t.text : null;
35
+ };
36
+ const attrsOf = (n) => openingOf(n).attributes.properties;
37
+ const attrName = (a) => (ts.isJsxAttribute(a) && ts.isIdentifier(a.name) ? a.name.text : null);
38
+ const attr = (n, name) => attrsOf(n).find((a) => attrName(a) === name);
39
+ /** a prop's literal string (`icon="x"`, `icon={'x'}`), `true` for a bare prop, or undefined */
40
+ const literal = (n, name) => {
41
+ const a = attr(n, name);
42
+ if (!a) return undefined;
43
+ if (!a.initializer) return true;
44
+ if (ts.isStringLiteral(a.initializer)) return a.initializer.text;
45
+ const e = ts.isJsxExpression(a.initializer) ? a.initializer.expression : null;
46
+ if (e && (ts.isStringLiteral(e) || ts.isNoSubstitutionTemplateLiteral(e))) return e.text;
47
+ if (e && e.kind === ts.SyntaxKind.TrueKeyword) return true;
48
+ if (e && e.kind === ts.SyntaxKind.FalseKeyword) return false;
49
+ return null; // an expression: not known here
50
+ };
51
+ /** only these props (and no spread) on the element */
52
+ const only = (n, names) => attrsOf(n).every((a) => names.includes(attrName(a)));
53
+ const line = (sf, n) => sf.getLineAndCharacterOfPosition(n.getStart(sf)).line + 1;
54
+ const lineIndent = (source, pos) => /^[ \t]*/.exec(source.slice(source.lastIndexOf('\n', pos - 1) + 1))[0];
55
+ const blank = (c) => ts.isJsxText(c) && !c.text.trim();
56
+
57
+ /** the element round the head that gives its close a way to go: `Sheet` (no onClick needed), `Modal` (onClick needed), or null. A `Card` on the way is
58
+ * the head's own outer (a card standing in a sheet's body never closes the sheet) */
59
+ function sheetOf(head) {
60
+ for (let n = head.parent; n && !ts.isSourceFile(n); n = n.parent) {
61
+ const t = tagOf(n);
62
+ if (t === 'Card') return null;
63
+ if (t === 'Sheet' || t === 'Modal') return t;
64
+ }
65
+ return null;
66
+ }
67
+
68
+ /** what one child of a composed head is */
69
+ function kindOf(c, sheet) {
70
+ if (ts.isJsxText(c)) return { kind: 'text' };
71
+ if (ts.isJsxExpression(c)) return c.expression ? { kind: 'end', node: c } : { kind: 'comment' };
72
+ const t = tagOf(c);
73
+ if (!t) return { kind: 'end', node: c }; // a fragment, an element with a dotted name: it stands where the ends stand
74
+ if (t === 'Words') return { kind: 'words', node: c };
75
+ if (t === 'Text' && literal(c, 'level') in TITLE_LEVELS) return { kind: 'title', node: c, level: TITLE_LEVELS[literal(c, 'level')] };
76
+ if (/^h[1-3]$/.test(t)) return { kind: 'title', node: c, level: t === 'h1' ? 'h1' : null };
77
+ if (LEADS.includes(t)) return { kind: 'lead', node: c };
78
+ if (t === 'JourneyBadge') return { kind: 'date', node: c };
79
+ if (t === 'ChipRow') return { kind: 'chips', node: c };
80
+ if (t === 'StackBack') return { kind: 'back', node: c };
81
+ if (t === 'Btn' && literal(c, 'shape') === 'round') return sheet && literal(c, 'icon') === 'x' ? { kind: 'close', node: c } : { kind: 'round', node: c };
82
+ return { kind: 'end', node: c };
83
+ }
84
+
85
+ /** JSX text as an attribute value: its lines trimmed and joined by a space, as JSX reads it */
86
+ const textValue = (raw) => {
87
+ const words = raw.split('\n').map((l) => l.trim()).filter(Boolean).join(' ');
88
+ return /["{}<>]/.test(words) ? `{${JSON.stringify(words)}}` : `"${words}"`;
89
+ };
90
+ /** an element's children as one prop value, or null when there is nothing in it */
91
+ function childrenValue(el, sf) {
92
+ if (!ts.isJsxElement(el)) return null;
93
+ const kids = el.children.filter((c) => !blank(c));
94
+ if (!kids.length) return null;
95
+ if (kids.length === 1 && ts.isJsxText(kids[0])) return textValue(kids[0].getText(sf));
96
+ if (kids.length === 1 && ts.isJsxExpression(kids[0]) && kids[0].expression) return `{${kids[0].expression.getText(sf)}}`;
97
+ if (kids.length === 1 && (ts.isJsxElement(kids[0]) || ts.isJsxSelfClosingElement(kids[0]))) return `{${kids[0].getText(sf)}}`;
98
+ return `{<>${el.children.map((c) => c.getText(sf)).join('').trim()}</>}`;
99
+ }
100
+ /** a prop's value as written (`"x"`, `{x}`), or `{true}` for a bare prop */
101
+ const valueText = (a, sf) => (a.initializer ? a.initializer.getText(sf) : '{true}');
102
+ /** children as one slot value: an element as it is, an expression unwrapped, two or more in a fragment */
103
+ function slotValue(nodes, sf) {
104
+ if (nodes.length === 1) {
105
+ const n = nodes[0];
106
+ return ts.isJsxExpression(n) ? `{${n.expression.getText(sf)}}` : `{${n.getText(sf)}}`;
107
+ }
108
+ return `{<>${nodes.map((n) => n.getText(sf)).join('')}</>}`;
109
+ }
110
+
111
+ /** the slot form of one composed head, `{ text }`, or `{ why }` when it cannot be decided safely */
112
+ function convert(head, sf) {
113
+ const sheet = sheetOf(head);
114
+ const kids = head.children.filter((c) => !blank(c)).map((c) => kindOf(c, sheet));
115
+ const why = (w) => ({ why: w });
116
+ if (kids.some((k) => k.kind === 'text')) return why('words written straight in the head (no Words or heading round them)');
117
+ if (kids.some((k) => k.kind === 'comment')) return why('a comment among its children: move it by hand');
118
+ const at = kids.findIndex((k) => k.kind === 'words' || k.kind === 'title');
119
+ if (at < 0) {
120
+ // a head of a lead alone, or of a date and its chips alone (the title in the card's middle): the same head with no title
121
+ const shape = kids.map((k) => k.kind).join(' ');
122
+ const variant = { lead: 'lead', date: 'date', 'date chips': 'date' }[shape];
123
+ if (!variant || head.openingElement.attributes.properties.some((a) => ['centre', 'variant'].includes(attrName(a)))) return why('no title (a Words, or a Text h1 / h2 / display) and not a lead or a date alone: pick the variant by hand');
124
+ const slots = [['lead', slotValue([kids[0].node], sf)], ...(kids[1] ? [['chips', slotValue([kids[1].node], sf)]] : [])];
125
+ return lay(head, sf, variant, slots);
126
+ }
127
+ if (kids.slice(at + 1).some((k) => k.kind === 'words' || k.kind === 'title')) return why('two titles');
128
+ const t = kids[at];
129
+ const props = [];
130
+ if (t.kind === 'words') {
131
+ if (ts.isJsxElement(t.node) && t.node.children.some((c) => !blank(c))) return why('a Words with children (a Wave, words of its own): not a title and a meta');
132
+ if (!only(t.node, WORDS_PROPS)) return why(`a Words with props a head has no slot for (${attrsOf(t.node).map((a) => attrName(a) ?? '{…spread}').filter((n) => !WORDS_PROPS.includes(n)).join(', ')}): they went on the title`);
133
+ for (const p of WORDS_PROPS) { const a = attr(t.node, p); if (a) props.push([p, valueText(a, sf)]); }
134
+ } else if (only(t.node, ['level'])) {
135
+ const value = childrenValue(t.node, sf);
136
+ if (!value) return why('an empty title');
137
+ props.push(['title', value]);
138
+ if (t.level) props.push(['level', `"${t.level}"`]);
139
+ } else {
140
+ // a hand-written Text title with props of its own (caps, an id): it stays, as a span inside the head's title, so it reads as it read
141
+ if (tagOf(t.node) !== 'Text' || attr(t.node, 'as')) return why(`a hand-written title with props the head's title does not take (${attrsOf(t.node).map((a) => attrName(a) ?? '{…spread}').filter((n) => n !== 'level').join(', ')})`);
142
+ const text = t.node.getText(sf);
143
+ props.push(['title', `{${text.replace(/^<Text\b/, '<Text as="span"')}}`]);
144
+ if (t.level) props.push(['level', `"${t.level}"`]);
145
+ }
146
+ const before = kids.slice(0, at), after = kids.slice(at + 1);
147
+ const centre = literal(head, 'variant') === 'centre' || literal(head, 'centre') === true;
148
+ const hasOver = props.some(([p]) => p === 'over');
149
+ const backs = kids.filter((k) => k.kind === 'back');
150
+ const closes = after.filter((k) => k.kind === 'close');
151
+ let variant;
152
+ const slots = [];
153
+
154
+ if (literal(head, 'variant') !== undefined && !centre) return why('a variant written with children');
155
+ if (backs.length) {
156
+ variant = 'stack';
157
+ if (closes.length || centre || hasOver) return why('a StackBack beside a close, a centre or an over');
158
+ if (backs.length > 1) return why('two StackBacks');
159
+ const b = backs[0];
160
+ if (!only(b.node, ['end', 'label'])) return why('a StackBack with props the head has no slot for');
161
+ const atEnd = literal(b.node, 'end') === true;
162
+ if (atEnd ? after.at(-1) !== b : before.length !== 1 || before[0] !== b) return why(atEnd ? 'a StackBack end that is not the last child' : 'a StackBack that is not the first child');
163
+ if (!atEnd && literal(b.node, 'end') !== undefined) return why('a StackBack whose end is an expression');
164
+ const ends = after.filter((k) => k !== b);
165
+ if (ends.some((k) => k.kind !== 'end' && k.kind !== 'round' && k.kind !== 'chips')) return why('a lead or a date after the title of a stack head');
166
+ slots.push(['back', atEnd ? '"end"' : '"start"']);
167
+ const label = attr(b.node, 'label');
168
+ if (label) slots.push(['backLabel', valueText(label, sf)]);
169
+ if (ends.length) slots.push(['end', slotValue(ends.map((k) => k.node), sf)]);
170
+ } else if (closes.length) {
171
+ variant = 'sheet';
172
+ const close = closes[0];
173
+ if (closes.length > 1 || after.at(-1) !== close) return why('a close Btn that is not the last child');
174
+ if (centre || hasOver) return why('a close beside a centre or an over');
175
+ if (before.length > 1 || (before.length === 1 && before[0].kind !== 'lead')) return why('something before the title of a sheet head other than a Lead, an Avatar or an AvatarStack');
176
+ if (!only(close.node, CLOSE_PROPS)) return why(`a close Btn with props the close does not take (${attrsOf(close.node).map((a) => attrName(a) ?? '{…spread}').filter((n) => !CLOSE_PROPS.includes(n)).join(', ')})`);
177
+ const acts = after.slice(0, -1);
178
+ if (acts.some((k) => k.kind !== 'round')) return why('a sheet head with a close and something that is not a round Btn beside it (a sheet head takes `actions` only)');
179
+ if (acts.length > ACTIONS_MAX) return why(`${acts.length} round Btns beside the close (a sheet head takes ${ACTIONS_MAX})`);
180
+ const onClick = attr(close.node, 'onClick');
181
+ if (!onClick && sheet === 'Modal') return why('a close Btn in a Modal with no onClick: the modal has nothing to ask — wire onClose by hand');
182
+ if (before.length) slots.push(['lead', slotValue([before[0].node], sf)]);
183
+ if (acts.length) slots.push(['actions', slotValue(acts.map((k) => k.node), sf)]);
184
+ if (onClick) slots.push(['onClose', valueText(onClick, sf)]);
185
+ const label = attr(close.node, 'label');
186
+ if (label && literal(close.node, 'label') !== 'Close') slots.push(['closeLabel', valueText(label, sf)]);
187
+ } else if (centre) {
188
+ variant = 'centre';
189
+ if (hasOver) return why('an over in a centre head');
190
+ if (before.length > 1 || after.length > 1) return why('more than one thing either side of a centre head\'s title');
191
+ if (before.length) slots.push(['lead', slotValue([before[0].node], sf)]);
192
+ if (after.length) slots.push(['end', slotValue([after[0].node], sf)]);
193
+ } else {
194
+ const shape = before.map((k) => k.kind).join(' ');
195
+ variant = { '': 'plain', lead: 'lead', date: 'date', 'date chips': 'date' }[shape];
196
+ if (!variant) return why(`${before.map((k) => tagOf(k.node) ?? 'an expression').join(', ')} before the title: no variant leads that way`);
197
+ if (before.length) slots.push(['lead', slotValue([before[0].node], sf)]);
198
+ if (before.length > 1) slots.push(['chips', slotValue([before[1].node], sf)]);
199
+ if (after.length) slots.push(['end', slotValue(after.map((k) => k.node), sf)]);
200
+ }
201
+
202
+ return lay(head, sf, variant, [...props, ...slots]);
203
+ }
204
+
205
+ /** the self-closing head: its own props (but `centre` and `variant`, which the variant writes), the variant, then the slots — on one line
206
+ * when it fits, else the words on the first line and each slot holding an element on a line of its own */
207
+ function lay(head, sf, variant, slots) {
208
+ const own = head.openingElement.attributes.properties.filter((a) => !['centre', 'variant'].includes(attrName(a))).map((a) => a.getText(sf));
209
+ const all = [...(variant === 'plain' ? [] : [`variant="${variant}"`]), ...own, ...slots.map(([p, v]) => `${p}=${v}`)];
210
+ const indent = lineIndent(sf.text, head.getStart(sf));
211
+ const one = `<Head ${all.join(' ')} />`;
212
+ if (one.length + indent.length <= LINE && !one.includes('\n')) return { text: one };
213
+ const first = all.filter((p) => !/=\{</.test(p)), rest = all.filter((p) => /=\{</.test(p));
214
+ return { text: `<Head ${first.join(' ')}${rest.map((p) => `\n${indent} ${p}`).join('')} />` };
215
+ }
216
+
217
+ /** a `cardds` import's names the rewrite left unused, taken out (the comma beside each with it) */
218
+ function dropUnused(source, file, names) {
219
+ const sf = parse(source, file);
220
+ const used = new Set();
221
+ const walk = (n) => {
222
+ if (ts.isImportDeclaration(n)) return;
223
+ if (ts.isIdentifier(n)) used.add(n.text);
224
+ ts.forEachChild(n, walk);
225
+ };
226
+ walk(sf);
227
+ const cuts = [];
228
+ for (const imp of sf.statements.filter(ts.isImportDeclaration)) {
229
+ const nb = imp.importClause?.namedBindings;
230
+ if (!/^(cardds|@usableapp\/cardds)$/.test(imp.moduleSpecifier.text) || !nb || !ts.isNamedImports(nb)) continue;
231
+ const els = nb.elements;
232
+ els.forEach((e, i) => {
233
+ if (!names.includes(e.name.text) || used.has(e.name.text) || els.length === 1) return;
234
+ const from = e.getStart(sf), to = e.end;
235
+ cuts.push(i < els.length - 1 ? [from, els[i + 1].getStart(sf)] : [els[i - 1].end, to]);
236
+ });
237
+ }
238
+ let out = source;
239
+ for (const [from, to] of cuts.sort((a, b) => b[0] - a[0])) out = out.slice(0, from) + out.slice(to);
240
+ return out;
241
+ }
242
+
243
+ /** every composed head of a file: `{ source, done, left: [{ line, why }] }` */
244
+ export function rewrite(source, file = 'x.tsx') {
245
+ const sf = parse(source, file);
246
+ const edits = [], left = [];
247
+ const walk = (n) => {
248
+ if (ts.isJsxElement(n) && tagOf(n) === 'Head' && n.children.some((c) => !blank(c))) {
249
+ const r = convert(n, sf);
250
+ if (r.text) edits.push([n.getStart(sf), n.end, r.text]);
251
+ else left.push({ line: line(sf, n), why: r.why });
252
+ return; // a head inside a head's child is that head's business
253
+ }
254
+ ts.forEachChild(n, walk);
255
+ };
256
+ walk(sf);
257
+ let out = source;
258
+ for (const [from, to, text] of edits.sort((a, b) => b[0] - a[0])) out = out.slice(0, from) + text + out.slice(to);
259
+ if (edits.length) out = dropUnused(out, file, MAYBE_UNUSED);
260
+ return { source: out, done: edits.length, left: left.sort((a, b) => a.line - b.line) };
261
+ }
262
+
263
+ /** every head of a file still written with children: `[{ line }]` */
264
+ export function check(source, file = 'x.tsx') {
265
+ const sf = parse(source, file);
266
+ const out = [];
267
+ const walk = (n) => {
268
+ if (ts.isJsxElement(n) && tagOf(n) === 'Head' && n.children.some((c) => !blank(c))) out.push({ line: line(sf, n) });
269
+ ts.forEachChild(n, walk);
270
+ };
271
+ walk(sf);
272
+ return out;
273
+ }
274
+
275
+ /** the .tsx / .jsx files of the paths given (a folder is read through, node_modules and dist left out) */
276
+ function filesOf(paths) {
277
+ const out = [];
278
+ const visit = (p) => {
279
+ if (statSync(p).isDirectory()) {
280
+ for (const name of readdirSync(p)) if (!['node_modules', 'dist', '.git'].includes(name)) visit(join(p, name));
281
+ } else if (/\.[jt]sx$/.test(p)) out.push(p);
282
+ };
283
+ paths.forEach(visit);
284
+ return out;
285
+ }
286
+
287
+ export function main(args) {
288
+ const checking = args.includes('--check');
289
+ const paths = args.filter((a) => a !== '--check');
290
+ if (!paths.length) { console.error('usage: npx cardds codemod-head [--check] <files or folders…>'); return 2; }
291
+ let failed = false, done = 0;
292
+ for (const file of filesOf(paths)) {
293
+ const source = readFileSync(file, 'utf8');
294
+ if (checking) {
295
+ for (const { line: at } of check(source, file)) { failed = true; console.log(`${file}:${at}: a Head written with children — write its variant and slots (npx cardds codemod-head ${file})`); }
296
+ continue;
297
+ }
298
+ const r = rewrite(source, file);
299
+ if (r.source !== source) { writeFileSync(file, r.source); done += r.done; console.log(`${file}: ${r.done} head${r.done === 1 ? '' : 's'}`); }
300
+ for (const { line: at, why } of r.left) { failed = true; console.log(`${file}:${at}: TODO <Head> left as it is — ${why}`); }
301
+ }
302
+ if (!checking) console.log(`${done} head${done === 1 ? '' : 's'} rewritten${failed ? '; each TODO above is a head to write by hand' : ''}`);
303
+ return failed ? 1 : 0;
304
+ }
305
+
306
+ if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) process.exit(main(process.argv.slice(2)));
@@ -5,6 +5,7 @@
5
5
  // npx cardds codemod-parts <files…> rewrite each file in place; a tag it cannot rewrite is printed and left
6
6
  // npx cardds codemod-parts --check <files…> exit 1 naming every tag, prop, import and type that still writes a retired name
7
7
  // (in this repo also `node scripts/codemod-parts.mjs …`; it reads `typescript` from the project that runs it)
8
+ // The heads it writes take children, which a Head no longer takes (2026-10-29): run `npx cardds codemod-head <files>` after it.
8
9
  // A part a tag now needs is imported once, on the file's value import (`import type { … }` only has its type names renamed, `CardFootProps` → `FootProps`).
9
10
  // A Card's `foot={cond ? x : undefined}` (or `: null`, or `cond && x`) keeps its condition, `{cond ? <Foot>{x}</Foot> : null}`, so no empty foot is drawn;
10
11
  // a `foot={value}` is written `<Foot>{value}</Foot>` as it is: the script cannot know whether `value` may be undefined, and the consumer reads that line.
@@ -29,7 +30,7 @@ export const RENAMES = {
29
30
  * a `Row` keeps its own too, and the props that drew its line (ROW_PROPS) go */
30
31
  export const RESHAPES = {
31
32
  CardHead: { to: 'Head', words: { heading: 'title', caption: 'meta', level: 'level' }, end: 'end' },
32
- SheetHead: { to: 'Head', adds: 'centre', words: { title: 'title', sub: 'meta' }, lead: 'lead', end: 'trail' },
33
+ SheetHead: { to: 'Head', adds: 'variant="centre"', words: { title: 'title', sub: 'meta' }, lead: 'lead', end: 'trail' },
33
34
  Card: { words: { heading: 'title', caption: 'meta', level: 'level' }, end: 'end', head: true },
34
35
  Row: { line: true },
35
36
  };
Binary file
Binary file