#!/usr/bin/env tsx /** * gen-page-cards — switch built-in tools onto the record page drawn as cards. * * pnpm gen:page-cards todo event write a hand (or a strip) for these tables * pnpm gen:page-cards --all for every built-in tool * pnpm gen:page-cards --check list the built-in tools not on cards yet * * A record page is a title, a facts line, a hand of field cards, the tray and * what is tagged to it (owner, 12 Oct 2026). The page's words are `parts.cards` * (the hand) and `parts.strip` (small cards over a page whose content comes * first); cotton-core's `parts.rs` says what they hold and refuses what they * cannot. A table with either is drawn as cards, so writing them IS the * switch, tool by tool (todo first). * * The cards come from TUNED — the tables tuned by hand to the approved mocks — * or else from the order the page draws its fields today: the facts, the state * tag, the link chips, the body, then the page's remaining sections. A page * whose content comes first (a `desk`, or a conversation, edition or script * page) gets a strip and keeps its body; every other page gets a hand, a long * text taking its own row. Only the `parts` member of a file is rewritten, the * rest keeps its formatting. The kit's file is the one definition; the app * bundles no copy. */ import { dealtActs } from "./gen-cards/dealt-acts"; import { actLabelFault, cardTextFault, NAMED_ACTS, type Theme } from "./gen-cards/card-label"; import { readdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; const ROOT = join(dirname(fileURLToPath(import.meta.url)), ".."); const KITS = join(ROOT, "crates/cotton-core/kits"); /** Every table the kit defines: the shell's (`kits/shell/tables`) and the personal kit's (`kits/personal/tables`, one definition per table, the one the object serves) where the shell defines none of that id. */ const TABLE_FILES: { file: string; path: string }[] = ((): { file: string; path: string }[] => { const of = (kit: string) => readdirSync(join(KITS, kit, "tables")).filter((name) => name.endsWith(".json")).map((file) => ({ file, path: join(KITS, kit, "tables", file) })); const shell = of("shell"); return [...of("personal").filter(({ file }) => !shell.some((own) => own.file === file)), ...shell].sort((a, b) => a.file.localeCompare(b.file)); })(); type Column = { key: string; type: string; secret?: boolean; name?: string }; type Section = { commands?: string[]; columns?: string[]; list?: { table: string; link?: string } | null; heading?: string | null; actions?: Array<{ label?: string; object?: string; delete?: boolean }>; }; type Command = { id: string; sheet?: string; kind: string; label?: string; object?: string; does?: string; destructive?: boolean; pick?: unknown; pick_table?: string; }; type Card = { column?: string; act?: string; row?: boolean; object?: string; label?: string; until?: string }; type Parts = { shape: "sheet" | "desk"; head: { facts: string[]; state: string | null }; links: string[]; body: string | null; lists: Array>; acts: { main: string | null; more: string[]; away: string | null }; cards?: Card[]; strip?: Card[]; }; type Definition = { id: string; on_open?: string | null; title: string; columns: Column[]; page?: Section[]; page_parts?: string[]; commands?: Command[] | null; parts?: Parts; tool?: unknown; }; /** Tables tuned by hand to the approved mocks (12 Oct 2026): their cards, the faces of their lists, their facts. */ const TUNED: Record; facts?: string[] }> = { todo: { cards: cards("due_at", "project", "people", "repeats@ring", "priority@flag", "notes!") }, // The event's hand is when, where, who, repeats and its calendar; its notes are the content slip (architect, 13 Oct 2026). event: { cards: cards("starts_at>ends_at=when", "location=where", "people=who", "rrule@ring=repeats", "calendar_name=calendar"), strip: cards("project", "my_response"), facts: [], }, // A goal's hand is by when, its project and when it was met; why is the content slip. How it // stands is its acts (Achieved ⇄ Reopen, Pause, Set aside), never a status card (acts ruling). goal: { cards: cards("target_date=by when", "project", "achieved_at=achieved"), strip: [] }, transaction: { cards: cards("amount_minor", "occurred_on", "counterparty_person_id", "category_account_id", "money_account_id", "notes!"), strip: cards("to_account_id", "status", "due_date", "gst_amount_minor", "payee_text", "statement_id"), }, person: { cards: cards("org", "city", "timezone", "birthday", "balance"), strip: [], faces: { person_note: "notes", photo: "photos" }, facts: ["role_title", "org"] }, // A thread is laid out as every record page (architect, r7): title, facts, the grid (its fields, then its acts), then its mail. email_thread: { cards: cards("marks", "transaction_id", "event_id"), strip: [], facts: ["sender", "email_count", "record_on"] }, thread: { strip: [] }, session: { strip: cards("state", "project_id", "machine", "branch", "model", "todo_id", "hold_reason", "error") }, }; /** Cards by column key: a trailing `!` gives the card its row, `@object` names its object, `>column` the date that ends its span, `=label` its name. */ function cards(...keys: string[]): Card[] { return keys.map((whole) => { const [spanned, label] = whole.split("="); const [spec, until] = spanned.split(">"); const [held, object] = spec.split("@"); const row = held.endsWith("!"); return { column: row ? held.slice(0, -1) : held, ...(row ? { row: true } : {}), ...(object ? { object } : {}), ...(label ? { label } : {}), ...(until ? { until } : {}), }; }); } /** cotton-core's `parts::STAMPS`: said on the facts line, never a card. */ const STAMPS = ["created_at", "updated_at", "trashed_at"]; /** cotton-core's `parts::HAND`: the most cards a hand holds. */ const HAND = 6; /** cotton-core's FACT_TYPES: the column types a fact is said from. */ const FACT_TYPES = ["text", "date", "time", "number", "amount", "choice", "bool", "url"]; /** Page styles whose content comes first. */ const CONTENT_PARTS = ["messages", "content", "script"]; /** cotton-core's `resolved_parts`, for a definition that has no `parts` of its own. */ function resolvedParts(table: Definition): Parts { if (table.parts) { const { cards: _cards, strip: _strip, ...drawn } = table.parts; return drawn; } const sections = table.page ?? []; const drawn = (key: string) => sections.some((section) => (section.columns ?? []).includes(key)); const facts = table.columns .filter((column) => column.key !== table.title && FACT_TYPES.includes(column.type)) .filter((column) => column.secret !== true && drawn(column.key)) .slice(0, 2) .map((column) => column.key); const body = table.columns.find((column) => column.type === "longtext")?.key ?? null; const lists = sections.flatMap((section) => section.list?.link ? [{ table: section.list.table, relation: section.list.link, ...(section.heading ? { heading: section.heading } : {}) }] : [], ); const commands = table.commands ?? []; const away = commands.find((command) => !command.sheet && command.kind === "delete")?.id ?? null; return { shape: body ? "desk" : "sheet", head: { facts, state: null }, links: table.columns.filter((column) => column.type === "link").map((column) => column.key), body, lists, // The command the page runs on opening is no act. acts: { main: null, more: commands.filter((command) => !command.sheet && command.id !== away && command.id !== table.on_open).map((command) => command.id), away }, }; } /** The fields in the order the page draws them today, the title never among them. */ function fieldOrder(table: Definition, parts: Parts): string[] { const order = [ ...parts.head.facts, ...(parts.head.state ? [parts.head.state] : []), ...parts.links, ...(parts.body ? [parts.body] : []), ...(table.page ?? []).flatMap((section) => section.columns ?? []), ]; const known = new Set(table.columns.map((column) => column.key)); // The stamps are the facts line's, never a card (cotton-core `parts::STAMPS`). return [...new Set(order)].filter((key) => key !== table.title && known.has(key) && !STAMPS.includes(key)); } function cardsFor(table: Definition): Parts { const parts = resolvedParts(table); const tuned = TUNED[table.id]; if (tuned) { const lists = parts.lists.map((list) => { const face = tuned.faces?.[String(list.table)]; return face ? { ...list, face } : list; }); const head = tuned.facts ? { ...parts.head, facts: tuned.facts } : parts.head; const { cards: _cards, strip: _strip, ...rest } = parts; return { ...rest, head, lists, ...(tuned.cards ? { cards: tuned.cards } : {}), ...(tuned.strip || !tuned.cards ? { strip: tuned.strip ?? [] } : {}) }; } const content = parts.shape === "desk" || (table.page_parts ?? []).some((part) => CONTENT_PARTS.includes(part)); const type = (key: string) => table.columns.find((column) => column.key === key)?.type; const fields = fieldOrder(table, parts); if (content) { return { ...parts, strip: fields.filter((key) => key !== parts.body).map((column) => ({ column })) }; } // A hand holds at most six cards; the rest are a strip under it (cotton-core `parts::HAND`). const hand = fields.slice(0, HAND).map((column) => (type(column) === "longtext" ? { column, row: true } : { column })); const under = fields.slice(HAND).map((column) => ({ column })); return { ...parts, cards: hand, ...(under.length ? { strip: under } : {}) }; } /** The span of a top-level member's value in a JSON object's text, or null. */ function memberSpan(text: string, key: string): { start: number; end: number } | null { let depth = 0; let i = 0; let pending: string | null = null; while (i < text.length) { const ch = text[i]; if (ch === '"') { let j = i + 1; while (text[j] !== '"') j += text[j] === "\\" ? 2 : 1; if (depth === 1) { const rest = text.slice(j + 1).trimStart(); if (rest.startsWith(":")) pending = JSON.parse(text.slice(i, j + 1)); } i = j + 1; continue; } if (ch === ":" && depth === 1 && pending !== null) { const name: string = pending; pending = null; let start = i + 1; while (/\s/.test(text[start])) start++; let end = start; let inner = 0; while (end < text.length) { const c = text[end]; if (c === '"') { let j = end + 1; while (text[j] !== '"') j += text[j] === "\\" ? 2 : 1; end = j + 1; continue; } if (c === "{" || c === "[") inner++; if (c === "}" || c === "]") { if (inner === 0) break; inner--; } if (c === "," && inner === 0) break; end++; } while (/\s/.test(text[end - 1])) end--; if (name === key) return { start, end }; i = end; continue; } if (ch === "{" || ch === "[") depth++; if (ch === "}" || ch === "]") depth--; i++; } return null; } /** Two-space JSON one level in, each card on a line of its own. */ function indented(value: unknown): string { // An absent word, never a null: a reader is told only what the page says. return JSON.stringify(value, (_, held) => (held === null ? undefined : held), 2) .replace(/\{\n\s+("(?:column|act)": "[^"]+")(,\n\s+"row": true)?(,\n\s+"object": "[^"]+")?(,\n\s+"label": "[^"]+")?(,\n\s+"until": "[^"]+")?\n\s+\}/g, (_, card, row, object, label, until) => `{${card}${row ? ', "row": true' : ""}${[object, label, until].filter(Boolean).map((key) => `, ${key.replace(/^,\s+/, "")}`).join("")}}`) .replace(/\n/g, "\n "); } /** The file's text with its `parts` set to `parts`, everything else as it was. */ function withParts(text: string, parts: Parts): string { const span = memberSpan(text, "parts"); if (span) return text.slice(0, span.start) + indented(parts) + text.slice(span.end); const tool = memberSpan(text, "tool"); if (!tool) { // Supporting tables share the tool's home; they still declare their own record page. const at = text.lastIndexOf("}"); return `${text.slice(0, at).trimEnd()},\n "parts": ${indented(parts)}\n${text.slice(at)}`; } const at = text.lastIndexOf('"tool"', tool.start); return `${text.slice(0, at)}"parts": ${indented(parts)},\n ${text.slice(at)}`; } const args = process.argv.slice(2); const check = args.includes("--check"); const all = args.includes("--all"); const named = new Set(args.filter((arg) => !arg.startsWith("--"))); if (!check && !all && named.size === 0) { console.error("name the tables to switch onto cards, or --all, or --check"); process.exit(2); } const SHELL_THEMES = join(ROOT, "crates/cotton-core/kits/shell/themes"); const THEMES: Theme[] = readdirSync(SHELL_THEMES) .filter((file) => file.endsWith(".json")) .map((file) => JSON.parse(readFileSync(join(SHELL_THEMES, file), "utf8"))); function labelFault(label: string, act?: string): string | null { if (act !== undefined && act in NAMED_ACTS) namedSeen.add(act); return actLabelFault(label, THEMES, act); } const namedSeen = new Set(); function cardNameFault(name: string): string | null { return cardTextFault(name, "key", THEMES); } /** * The objects an act stands beneath an opened card: the closed vocabulary the * core declares (`ACT_OBJECTS`, 7a34399ae, 1 Nov 2026), each drawn by the fan * as `Media.xcassets/act-`. */ const OBJECTS = new Set( readdirSync(join(ROOT, "apps/loom/Sources/CottonPaper/Media.xcassets")) .filter((name) => name.startsWith("act-") && name.endsWith(".imageset")) .map((name) => name.slice("act-".length, -".imageset".length)), ); /** An act names one of them or none: no object is a typed row under More, never an inferred picture. */ function actObjectFault(object: string | undefined): string | null { if (object === undefined) return null; return OBJECTS.has(object) ? null : `names the object "${object}", which the app does not draw`; } /** The enamel objects a section's own act card draws (`Media.xcassets/object-`). */ const SECTION_OBJECTS = new Set( readdirSync(join(ROOT, "apps/loom/Sources/CottonPaper/Media.xcassets")) .filter((name) => name.startsWith("object-") && name.endsWith(".imageset")) .map((name) => name.slice("object-".length, -".imageset".length)), ); // A gauge is drawn natively by CardObjectView rather than an imageset. SECTION_OBJECTS.add("gauge"); /** * A section act's card stands an object that means it: the one it names, or * the bin when it deletes. The pencil is no fallback (architect, 13 Oct 2026). */ function sectionObjectFault(object: string | undefined, deletes: boolean): string | null { if (object !== undefined) return SECTION_OBJECTS.has(object) ? null : `names the object "${object}", which the app does not draw`; return deletes ? null : "names no object, and nothing it does or is says one — give it an `object`"; } const waiting: string[] = []; const faults: string[] = []; for (const { file, path } of TABLE_FILES) { const text = readFileSync(path, "utf8"); const table = JSON.parse(text) as Definition; if (!Array.isArray(table.columns)) continue; const onCards = Boolean(table.parts?.cards || table.parts?.strip); if (check) { if (table.tool && !onCards) waiting.push(table.id); // Only the acts dealt as cards: a field's picker/sheet commands are slips. const parts = table.parts ?? resolvedParts(table); for (const command of dealtActs(table.commands ?? [], parts, table.page ?? [])) { if (command.id === table.on_open) continue; const fault = labelFault(command.label ?? "", `${table.id}.${command.id}`); if (fault) faults.push(`${table.id}.${command.id}: ${fault}`); const objectFault = actObjectFault(command.object); if (objectFault) faults.push(`${table.id}.${command.id}: ${objectFault}`); } // A section's own writes ("Urgent", "Drop") are act cards as well. for (const action of (table.page ?? []).flatMap((section) => section.actions ?? [])) { const fault = labelFault(action.label ?? ""); if (fault) faults.push(`${table.id} section act: ${fault}`); const objectFault = sectionObjectFault(action.object, Boolean(action.delete)); if (objectFault) faults.push(`${table.id} section act "${action.label}": ${objectFault}`); } // Every field card's name fits it. for (const card of [...(table.parts?.cards ?? []), ...(table.parts?.strip ?? [])]) { const column = card.column ? table.columns.find((each) => each.key === card.column) : undefined; if (!column || card.row) continue; const fault = cardNameFault(card.label ?? column.name ?? column.key); if (fault) faults.push(`${table.id}.${column.key} card: ${fault}`); } continue; } if (!(named.has(table.id) || (all && table.tool))) continue; named.delete(table.id); const parts = cardsFor(table); const written = withParts(text, parts); if (JSON.stringify(JSON.parse(written).parts) !== JSON.stringify(parts, (_, held) => (held === null ? undefined : held))) { throw new Error(`${file}: parts did not land whole`); } writeFileSync(path, written); console.log(`${table.id}: ${parts.cards ? `hand of ${parts.cards.length}` : `strip of ${parts.strip?.length}`}`); } if (named.size > 0) { console.error(`no built-in table named: ${[...named].join(", ")}`); process.exit(1); } if (check) for (const act of Object.keys(NAMED_ACTS)) if (!namedSeen.has(act)) faults.push(`${act}: NAMED_ACTS (gen-cards/card-label.ts) excuses an act no table deals — remove its entry`); if (check) console.log(waiting.length ? `not on cards yet: ${waiting.join(", ")}` : "every built-in tool is on cards"); if (faults.length > 0) { console.error(`cards a definition cannot deal:\n ${faults.join("\n ")}`); process.exit(1); }