@ai-matrx/records-ui 0.116.49 → 0.116.51
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.
- package/CHANGELOG.md +17 -1
- package/dist/{SaveToTable-G7Y4H7SB.js → SaveToTable-EM2JT3OS.js} +3 -3
- package/dist/{chunk-P4P4IFM4.js → chunk-7LELV7UI.js} +7 -3
- package/dist/chunk-7LELV7UI.js.map +1 -0
- package/dist/{chunk-KDD2FZZR.js → chunk-BZ6PLCAR.js} +2 -2
- package/dist/{chunk-6TDTSMLU.js → chunk-HA7RICYJ.js} +11 -7
- package/dist/chunk-HA7RICYJ.js.map +1 -0
- package/dist/{chunk-FMJ2ULGP.js → chunk-O5K6Y3N3.js} +1 -1
- package/dist/chunk-O5K6Y3N3.js.map +1 -0
- package/dist/helpers.cjs +5 -1
- package/dist/helpers.cjs.map +1 -1
- package/dist/helpers.js +5 -1
- package/dist/helpers.js.map +1 -1
- package/dist/html-frame.cjs.map +1 -1
- package/dist/html-frame.js +1 -1
- package/dist/index.cjs +13 -5
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +4 -4
- package/dist/pickers.cjs +13 -5
- package/dist/pickers.cjs.map +1 -1
- package/dist/pickers.js +3 -3
- package/package.json +2 -2
- package/dist/chunk-6TDTSMLU.js.map +0 -1
- package/dist/chunk-FMJ2ULGP.js.map +0 -1
- package/dist/chunk-P4P4IFM4.js.map +0 -1
- /package/dist/{SaveToTable-G7Y4H7SB.js.map → SaveToTable-EM2JT3OS.js.map} +0 -0
- /package/dist/{chunk-KDD2FZZR.js.map → chunk-BZ6PLCAR.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/personZone.ts","../src/personTime.ts","../src/signature.tsx","../src/looks/designLooks.tsx","../src/looks/htmlLook.tsx","../src/looks/jsonLook.tsx","../src/looks/registry.ts","../src/looks/tableTokens.tsx","../src/askOnce.ts","../src/labels.tsx","../src/PersonPicker.tsx","../src/ReferenceBuilder.tsx","../src/ChoiceListEditor.tsx","../src/AddChoicesInline.tsx","../src/editors.tsx","../src/newerKindValues.tsx","../src/RelationPicker.tsx","../src/tellApart.ts","../src/readableLink.ts","../src/buttonCell.tsx","../src/gridOpen.tsx","../src/columnName.ts","../src/FieldEditor.tsx","../src/WatchFieldsPicker.tsx","../src/FormulaTextEditor.tsx","../src/EntityReferenceKindPicker.tsx","../src/SourceArchivedNotice.tsx","../src/leadingBlank.ts","../src/values.tsx","../src/withheldNotice.ts","../src/withheld.tsx","../src/EntityReferenceControl.tsx","../src/WholeValue.tsx","../src/formattedValue.tsx","../src/LinkPreviewCard.tsx","../src/gridAttachments.tsx","../src/ReferenceChips.tsx","../src/ClampedChips.tsx","../src/formulaNames.ts","../src/userIds.ts","../src/personNames.ts","../src/cellMarks.tsx","../src/RetiredValues.tsx","../src/memberNames.ts","../src/structuredValue.tsx","../src/Condition.tsx","../src/FieldRetype.tsx","../src/personRetype.ts","../src/FieldRulePreview.tsx","../src/ColumnLook.tsx","../src/NewerKindQuestions.tsx","../src/FieldFormatPicker.tsx","../src/archiveWords.ts","../src/reversePrefix.ts","../src/gridPage.ts","../src/tableJson.ts","../src/gridLook.ts","../src/gridMenus.ts","../src/ButtonSettings.tsx","../src/AccentSwatches.tsx","../src/AddRowSettings.tsx","../src/standardFieldChoices.ts","../src/FloatingRefusal.tsx","../src/formatControls.tsx","../src/typedDateHelper.tsx","../src/dataSource.ts","../src/RecordsMount.tsx","../src/PersonNamesBridge.tsx","../src/TablePickers.tsx","../src/DataBindingPicker.tsx","../src/PickedSummaries.tsx","../src/HeldChangeDecision.tsx"],"sourcesContent":["// The person's time zone, as the app saved it (userPreferences.display.timeZone).\n//\n// The host app tells this package once (`setPersonTimeZone(\"America/Los_Angeles\")`); every \"today\" and\n// \"now\" a screen draws (the calendar's today marker and now-line, a timeline's today, a date picker's\n// today) is read in that zone instead of the device's. With nothing set the device zone applies, as before.\n// Nothing here stores a zone: the host's saved preference is the one place, this is its mirror.\n\nimport { setColorRuleTimeZone } from \"@ai-matrx/design-system/data-table/table-style\";\nimport { globalSlot } from \"@ai-matrx/kit/global-slot\";\n\n// No React here: `@ai-matrx/records-ui/helpers` serves this file alone (the host sets the zone at\n// boot), and the root entry carries its own copy — so the zone lives in ONE realm-wide slot that\n// both copies read, never a module `let` that would split in two. The hook is `./personTime`.\nconst state = globalSlot(\"ai-matrx.records-ui.person-time-zone\", () => ({\n zone: null as string | null,\n listeners: new Set<() => void>(),\n}));\n\nfunction valid(z: unknown): z is string {\n if (typeof z !== \"string\" || !z.trim()) return false;\n try {\n new Intl.DateTimeFormat(\"en-US\", { timeZone: z });\n return true;\n } catch {\n return false;\n }\n}\n\n/** The host app's saved zone (IANA). `null` / junk clears it: the device zone applies. */\nexport function setPersonTimeZone(next: string | null | undefined): void {\n const clean = valid(next) ? next : null;\n if (clean === state.zone) return;\n state.zone = clean;\n // \"Today\" in a color rule is the person's day, not the device's (lane NOTION-SMALL-2).\n setColorRuleTimeZone(clean);\n state.listeners.forEach((l) => l());\n}\n\nexport function getPersonTimeZone(): string | null {\n return state.zone;\n}\n\n/** Calls `listener` whenever the zone changes; returns the unsubscribe. */\nexport function subscribePersonTimeZone(listener: () => void): () => void {\n state.listeners.add(listener);\n return () => {\n state.listeners.delete(listener);\n };\n}\n\n/**\n * `at` as a Date whose LOCAL fields (getFullYear, getHours, ...) read the wall clock in the person's zone.\n * For day / hour math only: never compare it with a stored instant.\n */\nexport function personWallNow(at: Date = new Date()): Date {\n const zone = state.zone;\n if (!zone) return at;\n const parts = new Intl.DateTimeFormat(\"en-US\", {\n timeZone: zone,\n year: \"numeric\",\n month: \"2-digit\",\n day: \"2-digit\",\n hour: \"2-digit\",\n minute: \"2-digit\",\n second: \"2-digit\",\n hourCycle: \"h23\",\n }).formatToParts(at);\n const n = (t: string) => Number(parts.find((p) => p.type === t)?.value ?? 0);\n return new Date(n(\"year\"), n(\"month\") - 1, n(\"day\"), n(\"hour\"), n(\"minute\"), n(\"second\"));\n}\n","// The person's time zone as a React value. The zone itself (set, read, the wall clock) is\n// `./personZone` — pure, so the host's boot code sets it through `@ai-matrx/records-ui/helpers`.\n\nimport { useSyncExternalStore } from \"react\";\nimport { getPersonTimeZone, subscribePersonTimeZone } from \"./personZone\";\n\nexport { setPersonTimeZone, getPersonTimeZone, personWallNow, subscribePersonTimeZone } from \"./personZone\";\n\n/** Re-renders the caller when the zone changes; returns it. */\nexport function usePersonTimeZone(): string | null {\n return useSyncExternalStore(\n subscribePersonTimeZone,\n getPersonTimeZone,\n () => null,\n );\n}\n","\"use client\";\n\n// src/signature.tsx — @ai-matrx/records-ui · lane 10 VIEWS-AND-FIELDS W1-A\n//\n// A SIGNATURE IS DRAWN, AND IT IS SEEN AS A DRAWING.\n//\n// The store keeps a Signature column as `type: text, format: signature`\n// (`custom.doc_signature_field_ok`). Through a form, the value it takes is a string, and the\n// drawing travels as the same `data:image/(png|jpeg);base64,…` URL `custom.sign_request_sign`\n// already validates for its drawn mark — one image format for every signature on the platform.\n// A signature the document door sealed (`custom.doc_sign`) is the signer's NAME instead; both\n// read back here: a drawing as an image, a name as the name.\n//\n// THE PAD was lifted from matrx-frontend's `/sign/[token]` DrawPad (canvas + pointer events, no\n// library, `touch-none` so a phone draws instead of scrolling) so there is one pad, here, that\n// every host and every form shares. Ink is always dark on a white sheet (a stored image must read in\n// both themes — cells invert it in dark mode).\n//\n// 🚨 SIZE. A drawing's encoded size depends on what is drawn, not on the canvas: a dense signature\n// measured ~310 kB as a 600-px PNG (verifier, 2026-10-02) against the store's `value_max_bytes`\n// default of 100,000 — and over the ceiling the store keeps a cell's first 1,000 characters, which\n// is a broken image. So `fitDrawing` re-encodes down a ladder (smaller PNGs, then JPEG on white)\n// until the value is under `SIGNATURE_BUDGET_BYTES`; when nothing fits the pad sends nothing and\n// says so, so a form can never submit a signature the store would cut.\n//\n// WHERE THE DRAWING GOES is decided in ONE place, `fitDrawing`'s caller (`end` below) handing a data\n// URL to `onChange`. A form sends that data URL as the answer, and `custom.form_submit` (CHAIR-DOORS-1,\n// live 2026-10-02) turns it into a File record: the record keeps the word \"Signed\" and its value's\n// source names the File (`{kind: 'signature', mark: 'drawn', signature_file_id, signed_at, via:\n// 'form', form_id}`). The ladder still guards a FORM too: the File keeps the drawing inline as its\n// `content`, and one value is capped at 100,000 bytes there as anywhere (measured on the clone,\n// 2026-10-02: a 312,024-byte drawing was refused by `custom._value_envelope`).\n//\n// READING IT BACK. A drawing kept inline (every value written before the File door, a sign-link,\n// an offline capture) is drawn as it is. \"Signed\" whose source names a File is drawn from that File\n// (`SignatureDrawing`): the source through `recordValuesVersioned` (the read doors give the value\n// without its envelope), then the File record's `content`; a File the host keeps elsewhere draws\n// through the host's `fileImage` port, the gallery's picture renderer. Until it is read, and when it\n// cannot be, the cell says \"Signed\" — never a broken image.\n\nimport { useEffect, useRef, useState } from \"react\";\nimport { Button, ErrorBox, cn } from \"@ai-matrx/design-system\";\nimport type { RecordDocument, Uuid } from \"@ai-matrx/records\";\nimport type { RecordsClient } from \"@ai-matrx/records/core\";\nimport { useOptionalRecordsClient } from \"@ai-matrx/records/react\";\nimport { isSignatureField } from \"./docs\";\nimport { useRecordsUi } from \"./host\";\n\n/** The exact shape `custom.sign_request_sign` accepts for a drawn mark. */\nconst DRAWN = /^data:image\\/(png|jpeg);base64,[A-Za-z0-9+/=]{64,}$/;\n\n/** Whether this column is a Signature column — the one test, `docs.ts` (VAL-10). */\nexport { isSignatureField };\n\n/** The drawing a signature value holds, or null when it holds none (empty, or a signer's name). */\nexport function drawnSignatureOf(value: unknown): string | null {\n return typeof value === \"string\" && DRAWN.test(value) ? value : null;\n}\n\n/** The word a text-only place (a card title, a sentence, an export) writes for a drawn signature. */\nexport const SIGNED_WORD = \"Signed\";\n\n/** A signature value in words: a drawing is \"Signed\"; a sealed name stays the name. */\nexport function signatureWords(value: unknown): string | null {\n if (value === null || value === undefined || value === \"\") return null;\n return drawnSignatureOf(value) ? SIGNED_WORD : String(value);\n}\n\n/** The File a signature value's source names (`custom.form_submit`, `custom.sign_request_sign`). */\nexport function signatureFileOf(source: unknown): string | null {\n if (!source || typeof source !== \"object\") return null;\n const src = source as Record<string, unknown>;\n const id = src[\"signature_file_id\"];\n return src[\"kind\"] === \"signature\" && typeof id === \"string\" && id !== \"\" ? id : null;\n}\n\n/**\n * The File a stored document's envelope names for one key, when the document carries its envelope\n * (`_values.<key>.src`, inline or a pointer into `_sources`). The read doors strip both, so a\n * screen usually has to ask (`SignatureDrawing`); a document that has them is answered here.\n */\nexport function signatureFileIn(document: RecordDocument | null | undefined, key: string): string | null {\n const values = document?.[\"_values\"] as Record<string, { src?: unknown }> | undefined;\n const src = values?.[key]?.src;\n if (typeof src === \"string\") {\n const sources = document?.[\"_sources\"] as Record<string, unknown> | undefined;\n return signatureFileOf(sources?.[src]);\n }\n return signatureFileOf(src);\n}\n\n/** What one record's signature File holds, as a picture: an inline drawing, or a host file id. */\ntype Drawing = { src: string | null; hostFileId: string | null };\n\nconst SOURCES = new WeakMap<RecordsClient, Map<string, Promise<Record<string, string | null>>>>();\nconst FILES = new WeakMap<RecordsClient, Map<string, Promise<Drawing>>>();\n\n/** Every signature File one record's values name, by field key — one read per record. */\nfunction signatureFilesOf(client: RecordsClient, recordId: string): Promise<Record<string, string | null>> {\n let held = SOURCES.get(client);\n if (!held) SOURCES.set(client, (held = new Map()));\n let asked = held.get(recordId);\n if (!asked) {\n asked = client.recordValuesVersioned({ record_id: recordId as Uuid }).then((answered) => {\n if (!answered.ok) return {};\n return Object.fromEntries(answered.data.map((v) => [v.field_key, signatureFileOf(v.source)]));\n });\n held.set(recordId, asked);\n }\n return asked;\n}\n\n/** The picture a signature File holds — one read per File. */\nfunction drawingOf(client: RecordsClient, fileId: string): Promise<Drawing> {\n let held = FILES.get(client);\n if (!held) FILES.set(client, (held = new Map()));\n let asked = held.get(fileId);\n if (!asked) {\n asked = client.recordRead({ record_id: fileId as Uuid }).then((answered) => {\n if (!answered.ok) return { src: null, hostFileId: null };\n const doc = (answered.data.document ?? {}) as RecordDocument;\n const content = drawnSignatureOf(doc[\"content\"]);\n const hostFileId = typeof doc[\"file_id\"] === \"string\" && doc[\"file_id\"] !== \"\" ? (doc[\"file_id\"] as string) : null;\n return { src: content, hostFileId };\n });\n held.set(fileId, asked);\n }\n return asked;\n}\n\nfunction DrawnImage({ src, inCell }: { src: string; inCell?: boolean | undefined }) {\n return (\n <img\n src={src}\n alt={SIGNED_WORD}\n data-records-signature=\"\"\n className={cn(\"max-w-[12rem] object-contain object-left dark:invert\", inCell ? \"h-7\" : \"h-12\")}\n />\n );\n}\n\n/** \"Signed\" whose drawing is a File: read the File, draw it; say \"Signed\" until then. */\nfunction SignatureDrawing({\n recordId,\n fieldKey,\n fileId: knownFile,\n value,\n inCell,\n}: {\n recordId: string | null;\n fieldKey: string | null;\n fileId: string | null;\n value: unknown;\n inCell?: boolean | undefined;\n}) {\n const client = useOptionalRecordsClient();\n const host = useRecordsUi();\n const [drawing, setDrawing] = useState<Drawing | null>(null);\n useEffect(() => {\n let cancelled = false;\n setDrawing(null);\n if (!client) return;\n void (async () => {\n const fileId = knownFile ?? (recordId && fieldKey ? (await signatureFilesOf(client, recordId))[fieldKey] ?? null : null);\n if (!fileId || cancelled) return;\n const read = await drawingOf(client, fileId);\n if (!cancelled) setDrawing(read);\n })();\n return () => {\n cancelled = true;\n };\n }, [client, recordId, fieldKey, knownFile]);\n if (drawing?.src) return <DrawnImage src={drawing.src} inCell={inCell} />;\n if (drawing?.hostFileId && host.fileImage) {\n return (\n <span className={cn(\"inline-block max-w-[12rem] dark:invert\", inCell ? \"h-7\" : \"h-12\")} data-records-signature=\"\">\n {host.fileImage({ fileId: drawing.hostFileId as Uuid, alt: SIGNED_WORD })}\n </span>\n );\n }\n return <span className=\"font-serif italic\">{String(value)}</span>;\n}\n\n/**\n * A signature as it reads anywhere a value is shown: the drawing, or the signer's name. A drawing\n * kept as a File (a form's, `custom.form_submit`) needs to know whose value this is: `recordId` and\n * `fieldKey`, or the `document` when it carries its envelope.\n */\nexport function SignatureValue({\n value,\n inCell,\n recordId,\n fieldKey,\n document,\n}: {\n value: unknown;\n inCell?: boolean | undefined;\n recordId?: string | null | undefined;\n fieldKey?: string | null | undefined;\n document?: RecordDocument | null | undefined;\n}) {\n const drawn = drawnSignatureOf(value);\n if (drawn) return <DrawnImage src={drawn} inCell={inCell} />;\n const fileId = fieldKey ? signatureFileIn(document, fieldKey) : null;\n if (value === SIGNED_WORD && (fileId || (recordId && fieldKey))) {\n return <SignatureDrawing recordId={recordId ?? null} fieldKey={fieldKey ?? null} fileId={fileId} value={value} inCell={inCell} />;\n }\n return <span className=\"font-serif italic\">{String(value)}</span>;\n}\n\nconst INK = \"#111827\";\n\n/** The most a drawn signature may weigh as a value — well under the store's 100,000-byte default. */\nexport const SIGNATURE_BUDGET_BYTES = 60_000;\n\n/** Said on the pad when even the smallest encoding of a drawing is over the budget. */\nexport const SIGNATURE_TOO_DETAILED = \"Too detailed to save — clear and sign again.\";\n\n/**\n * THE ONE SIGNATURE PAD. Draw with a finger, a pen or a mouse; Clear starts again. `onChange`\n * receives the drawing as a PNG data URL when a stroke ends, and `null` when cleared.\n */\nexport function SignaturePad({\n value,\n onChange,\n disabled,\n id,\n className,\n}: {\n value: unknown;\n onChange: (value: string | null) => void;\n disabled?: boolean | undefined;\n id?: string | undefined;\n className?: string | undefined;\n}) {\n const kept = drawnSignatureOf(value);\n const named = !kept && typeof value === \"string\" && value !== \"\" ? value : null;\n // A value already there when the control opens is shown as itself until somebody chooses to\n // sign again; once the pad is open it stays open while they draw (their own strokes come back\n // as `value` and must not swap the pad for a picture mid-signature).\n const [showPad, setShowPad] = useState(() => !kept && !named);\n\n const canvasRef = useRef<HTMLCanvasElement | null>(null);\n const drawing = useRef(false);\n const [dirty, setDirty] = useState(false);\n const [tooBig, setTooBig] = useState(false);\n\n useEffect(() => {\n if (!showPad) return;\n const canvas = canvasRef.current;\n if (!canvas) return;\n // Backed at device resolution so the strokes are not blurred squares on the phone.\n const ratio = window.devicePixelRatio || 1;\n const rect = canvas.getBoundingClientRect();\n canvas.width = Math.round(rect.width * ratio);\n canvas.height = Math.round(rect.height * ratio);\n const context = canvas.getContext(\"2d\");\n if (!context) return;\n context.scale(ratio, ratio);\n context.lineWidth = 2.2;\n context.lineCap = \"round\";\n context.lineJoin = \"round\";\n context.strokeStyle = INK;\n }, [showPad]);\n\n const point = (event: React.PointerEvent<HTMLCanvasElement>) => {\n const rect = event.currentTarget.getBoundingClientRect();\n return { x: event.clientX - rect.left, y: event.clientY - rect.top };\n };\n\n const start = (event: React.PointerEvent<HTMLCanvasElement>) => {\n if (disabled) return;\n event.currentTarget.setPointerCapture?.(event.pointerId);\n const context = canvasRef.current?.getContext(\"2d\");\n if (!context) return;\n const { x, y } = point(event);\n context.beginPath();\n context.moveTo(x, y);\n drawing.current = true;\n };\n\n const move = (event: React.PointerEvent<HTMLCanvasElement>) => {\n if (!drawing.current) return;\n const context = canvasRef.current?.getContext(\"2d\");\n if (!context) return;\n const { x, y } = point(event);\n context.lineTo(x, y);\n context.stroke();\n if (!dirty) setDirty(true);\n };\n\n const end = () => {\n if (!drawing.current) return;\n drawing.current = false;\n const canvas = canvasRef.current;\n if (!canvas) return;\n // THE ONE PLACE the drawing becomes a value (see the header: CHAIR-DOORS-1 changes this line).\n const fitted = fitDrawing(canvas);\n setTooBig(fitted === null);\n onChange(fitted);\n setDirty(true);\n };\n\n const clear = () => {\n const canvas = canvasRef.current;\n const context = canvas?.getContext(\"2d\");\n if (canvas && context) {\n context.save();\n context.setTransform(1, 0, 0, 1, 0, 0);\n context.clearRect(0, 0, canvas.width, canvas.height);\n context.restore();\n }\n setDirty(false);\n setTooBig(false);\n setShowPad(true);\n onChange(null);\n };\n\n if (!showPad) {\n return (\n <div id={id} className={cn(\"flex items-center justify-between gap-2 rounded-md border px-3 py-2\", className)}>\n <SignatureValue value={value} />\n {!disabled ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" onClick={clear}>\n Sign again\n </Button>\n ) : null}\n </div>\n );\n }\n\n return (\n <div className={cn(\"flex w-full flex-col gap-1\", className)}>\n <div className=\"relative\">\n <canvas\n id={id}\n ref={canvasRef}\n role=\"img\"\n aria-label=\"Signature pad\"\n data-records-signature-pad=\"\"\n onPointerDown={start}\n onPointerMove={move}\n onPointerUp={end}\n onPointerLeave={end}\n onPointerCancel={end}\n // `touch-none` or a phone scrolls the page instead of drawing.\n className={cn(\n \"block h-36 w-full touch-none rounded-md border border-border bg-white\",\n disabled ? \"cursor-not-allowed opacity-60\" : \"cursor-crosshair\",\n )}\n />\n {!dirty ? (\n <span className=\"pointer-events-none absolute inset-x-0 bottom-3 text-center text-xs text-neutral-400\">\n Sign here\n </span>\n ) : null}\n </div>\n <div className=\"flex items-center justify-end gap-2\">\n {tooBig ? (\n <ErrorBox\n as=\"span\"\n className=\"mr-auto text-xs text-destructive\"\n message={SIGNATURE_TOO_DETAILED}\n operation=\"Save a signature\"\n origin=\"records-ui/signature\"\n />\n ) : null}\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" onClick={clear} disabled={disabled || !dirty}>\n Clear\n </Button>\n </div>\n </div>\n );\n}\n\n/** The encodings tried in order, smallest-loss first: [format, max width, JPEG quality]. */\nconst LADDER: Array<[\"image/png\" | \"image/jpeg\", number, number]> = [\n [\"image/png\", 600, 1],\n [\"image/png\", 400, 1],\n [\"image/jpeg\", 600, 0.7],\n [\"image/jpeg\", 400, 0.6],\n [\"image/jpeg\", 300, 0.5],\n];\n\n/**\n * The drawing as the smallest-loss data URL under `SIGNATURE_BUDGET_BYTES`, or null when none\n * fits. JPEG has no transparency, so it is drawn on white (the pad's own sheet).\n */\nexport function fitDrawing(canvas: HTMLCanvasElement): string | null {\n for (const [type, maxWidth, quality] of LADDER) {\n const encoded = encodeAt(canvas, type, maxWidth, quality);\n if (encoded && encoded.length <= SIGNATURE_BUDGET_BYTES) return encoded;\n }\n return null;\n}\n\nfunction encodeAt(canvas: HTMLCanvasElement, type: \"image/png\" | \"image/jpeg\", maxWidth: number, quality: number): string | null {\n const width = Math.min(maxWidth, canvas.width || maxWidth);\n const scale = canvas.width > 0 ? width / canvas.width : 1;\n const out = document.createElement(\"canvas\");\n out.width = width;\n out.height = Math.max(1, Math.round((canvas.height || 1) * scale));\n const context = out.getContext(\"2d\");\n if (!context) return null;\n if (type === \"image/jpeg\") {\n context.fillStyle = \"#ffffff\";\n context.fillRect(0, 0, out.width, out.height);\n }\n context.drawImage(canvas, 0, 0, out.width, out.height);\n return out.toDataURL(type, quality);\n}\n","\"use client\";\n\n// src/looks/designLooks.tsx — @ai-matrx/records-ui · THE FOUR DESIGN-TOKEN LOOKS\n//\n// color pair · size · type style · shadow — the rows of a design system, a brand sheet, a\n// style guide. Each value is read by the design-system's pure readers (`design-tokens.ts`), so a\n// value that does not fit falls back to the format's own amber text (THE FALLBACK LAW): these\n// views draw only a value they could read.\n\nimport { useState, type ReactNode } from \"react\";\nimport { AlertTriangleIcon, CheckIcon } from \"@ai-matrx/design-system/icons\";\nimport { BasicInput, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, cn } from \"@ai-matrx/design-system\";\nimport {\n MEASURE_UNITS,\n TYPE_WEIGHTS,\n contrastLevel,\n TEXT_CONTRAST,\n contrastRatio,\n readColorPair,\n MOTION_EASINGS,\n motionText,\n readMotion,\n readOpacity,\n readShadowPair,\n readTypeStyle,\n shadowWords,\n shadowCss,\n typeStyleCss,\n typeStyleText,\n type ColorPair,\n type FieldFormatConfig,\n type Motion,\n type ShadowLayer,\n type TypeStyle,\n} from \"@ai-matrx/design-system/field-formats\";\n\nimport type { FieldLook, FieldLookCheck, FieldLookEditorProps, FieldLookViewProps, LookContext } from \"./types\";\n\nexport const TYPE_SAMPLE = \"The quick brown fox jumps over the lazy dog\";\n\nconst HEX_6 = /^#[0-9a-f]{6}$/i;\n\nfunction numberOf(value: unknown): number | null {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const n = Number(value.replace(/[a-z%\\s]+$/i, \"\"));\n return Number.isFinite(n) ? n : null;\n }\n return null;\n}\n\n// ── Color pair ───────────────────────────────────────────────────────────────\n\nexport function Swatch({ color, className }: { color: string; className?: string }) {\n return <span aria-hidden className={cn(\"inline-block h-4 w-4 shrink-0 rounded border border-border\", className)} style={{ backgroundColor: color }} />;\n}\n\n/**\n * The ground a color pair is read on: the host's per-row ground (`context.ground`, from the row\n * named in `contrastWith.readsOnField`) when the column reads per row, else the column's fixed\n * ground. A per-row column whose row names no ground has none — and is not checked.\n */\nexport function colorPairGround(\n format: FieldFormatConfig,\n context?: LookContext,\n): { light?: string; dark?: string; label: string } | null {\n const fixed = format.options?.contrastWith;\n if (fixed?.readsOnField) return context?.ground ?? null;\n if (context?.ground) return context.ground;\n if (!fixed || (!fixed.light && !fixed.dark)) return null;\n return { ...(fixed.light ? { light: fixed.light } : {}), ...(fixed.dark ? { dark: fixed.dark } : {}), label: fixed.label ?? \"its background\" };\n}\n\n/** The contrast of each side of a pair against its ground (`colorPairGround`), when it has one. */\nexport function colorPairContrast(\n pair: ColorPair,\n format: FieldFormatConfig,\n context?: LookContext,\n): { light?: number; dark?: number } {\n const ground = colorPairGround(format, context);\n if (!ground) return {};\n const out: { light?: number; dark?: number } = {};\n if (ground.light) {\n const r = contrastRatio(pair.light, ground.light);\n if (r !== null) out.light = r;\n }\n if (ground.dark) {\n const r = contrastRatio(pair.dark ?? pair.light, ground.dark);\n if (r !== null) out.dark = r;\n }\n return out;\n}\n\n/** \"17:1\" with a tick, or a warning mark under the color's minimum (its `min`, else text's 4.5:1). */\nexport function ContrastMark({ ratio, min }: { ratio: number; min?: number | undefined }) {\n const level = contrastLevel(ratio, min);\n const said = `${ratio}:1`;\n return (\n <span\n data-records-contrast={level}\n title={level === \"pass\" ? `Readable: ${said}` : level === \"large-only\" ? `Large text only: ${said}` : `Hard to read: ${said}`}\n className={cn(\"shrink-0 text-xs tabular-nums\", level === \"pass\" ? \"text-muted-foreground\" : \"text-warning-ink\")}\n >\n {level === \"pass\" ? <CheckIcon className=\"mr-0.5 inline h-3 w-3 align-[-1px]\" /> : <AlertTriangleIcon className=\"mr-0.5 inline h-3 w-3 align-[-1px]\" />}\n {said}\n </span>\n );\n}\n\nfunction ColorPairView({ value, format }: FieldLookViewProps): ReactNode {\n const pair = readColorPair(value);\n if (!pair) return null;\n const contrast = colorPairContrast(pair, format);\n return (\n <span data-records-look=\"color_pair\" className=\"inline-flex min-w-0 items-center gap-3\">\n <span className=\"inline-flex items-center gap-1.5\">\n <Swatch color={pair.light} />\n <code className=\"font-mono text-xs uppercase\">{pair.light}</code>\n {contrast.light !== undefined ? <ContrastMark ratio={contrast.light} min={pair.min} /> : null}\n </span>\n <span className=\"inline-flex items-center gap-1.5\">\n <Swatch color={pair.dark ?? pair.light} />\n <code className={cn(\"font-mono text-xs uppercase\", !pair.dark && \"text-muted-foreground\")}>{pair.dark ?? \"Inherits light\"}</code>\n {contrast.dark !== undefined ? <ContrastMark ratio={contrast.dark} min={pair.min} /> : null}\n </span>\n </span>\n );\n}\n\n/** One side of a pair: a color well and its hex, typed or picked. */\nexport function ColorWell({\n id,\n label,\n value,\n placeholder,\n onChange,\n disabled,\n}: {\n id: string;\n label: string;\n value: string | undefined;\n placeholder?: string;\n onChange: (next: string | undefined) => void;\n disabled?: boolean | undefined;\n}) {\n const [text, setText] = useState(value ?? \"\");\n const [seen, setSeen] = useState(value);\n if (seen !== value) {\n setSeen(value);\n setText(value ?? \"\");\n }\n return (\n <span className=\"flex min-w-0 items-center gap-2\">\n <BasicInput\n type=\"color\"\n aria-label={`${label}: pick a color`}\n className=\"h-7 w-8 shrink-0 p-0.5\"\n value={value && HEX_6.test(value) ? value : \"#000000\"}\n disabled={disabled}\n onChange={(e) => {\n setText(e.target.value);\n onChange(e.target.value);\n }}\n />\n <BasicInput\n id={id}\n aria-label={label}\n // A hex never shrinks below its own width (#RRGGBBAA): a narrow row wraps or scrolls, it never cuts \"#2F4…\" to \"#2\".\n className=\"h-7 shrink-0 font-mono text-xs uppercase\"\n style={{ width: \"calc(9ch + 1.25rem)\" }}\n value={text}\n placeholder={placeholder}\n disabled={disabled}\n onChange={(e) => {\n const next = e.target.value.trim();\n setText(next);\n // While typing only a whole color is written (#1f4 is on the way to #1f4fe0, not a color yet);\n // a short #abc is written when the box is left.\n if (next === \"\") onChange(undefined);\n else if (/^#(?:[0-9a-f]{6}|[0-9a-f]{8})$/i.test(next)) onChange(next.toLowerCase());\n }}\n onBlur={() => {\n if (/^#[0-9a-f]{3}$/i.test(text) && text.toLowerCase() !== (value ?? \"\")) onChange(text.toLowerCase());\n }}\n />\n </span>\n );\n}\n\nfunction ColorPairEditor({ value, onChange, disabled, id, label }: FieldLookEditorProps): ReactNode {\n const pair = readColorPair(value) ?? { light: \"\" };\n const write = (next: ColorPair) => onChange(next.light ? JSON.stringify(next) : null);\n return (\n <span className=\"grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1.5\">\n <span className=\"text-xs text-muted-foreground\">Light</span>\n <ColorWell\n id={id}\n label={`${label} light`}\n value={pair.light || undefined}\n placeholder=\"#1f4fe0\"\n disabled={disabled}\n onChange={(light) => write(light ? { ...pair, light } : { light: \"\" })}\n />\n <span className=\"text-xs text-muted-foreground\">Dark</span>\n <ColorWell\n id={`${id}-dark`}\n label={`${label} dark`}\n value={pair.dark}\n placeholder=\"Inherits light\"\n disabled={disabled || !pair.light}\n onChange={(dark) => write(dark ? { ...pair, dark } : { light: pair.light })}\n />\n </span>\n );\n}\n\nfunction ColorPairPreview({ value }: FieldLookViewProps): ReactNode {\n const pair = readColorPair(value);\n if (!pair) return null;\n return (\n <span className=\"grid h-24 w-full grid-cols-2 overflow-hidden rounded-lg border border-border\">\n <span className=\"flex items-end p-2\" style={{ backgroundColor: pair.light }}>\n <span className=\"rounded bg-background px-1.5 py-0.5 text-xs text-foreground\">Light</span>\n </span>\n <span className=\"flex items-end p-2\" style={{ backgroundColor: pair.dark ?? pair.light }}>\n <span className=\"rounded bg-background px-1.5 py-0.5 text-xs text-foreground\">Dark</span>\n </span>\n </span>\n );\n}\n\nfunction colorPairChecks(value: unknown, format: FieldFormatConfig, context?: LookContext): FieldLookCheck[] {\n const pair = readColorPair(value);\n if (!pair) return [];\n const contrast = colorPairContrast(pair, format, context);\n const ground = colorPairGround(format, context)?.label ?? \"its background\";\n const out: FieldLookCheck[] = [];\n for (const part of [\"light\", \"dark\"] as const) {\n const ratio = contrast[part];\n if (ratio === undefined || contrastLevel(ratio, pair.min) === \"pass\") continue;\n const color = part === \"light\" ? pair.light : (pair.dark ?? pair.light);\n const need = pair.min ?? TEXT_CONTRAST;\n out.push({\n part,\n message: `hard to read on ${ground}`,\n fix: {\n label: \"Fix with AI\",\n ask: `The ${part} color ${color} reads at ${ratio}:1 on ${ground}. Suggest the nearest color that reaches ${need}:1 and keeps its hue.`,\n },\n });\n }\n return out;\n}\n\n// ── A number typed as text ────────────────────────────────────────────────────\n\n/** A whole, finished number in the box (\"1.5\", \"-2\", \"0\"); \"1.\" and \"-\" are still being typed. */\nconst FINISHED_NUMBER = /^-?(?:\\d+|\\d*\\.\\d+)$/;\n\n/**\n * A number box that keeps what the person TYPES: \"1.\" stays \"1.\" until the 5 arrives, \"-\" stays\n * \"-\". Only a finished number is written; empty writes `null`. A value that changes from outside\n * (another tab, a reload) replaces the text unless it is the number just written.\n */\nfunction NumberBox({\n id,\n label,\n value,\n unit,\n onChange,\n disabled,\n className,\n}: {\n id?: string;\n label: string;\n value: number | null | undefined;\n unit: string;\n onChange: (next: number | null) => void;\n disabled?: boolean | undefined;\n className?: string;\n}) {\n const [text, setText] = useState(value === null || value === undefined ? \"\" : String(value));\n const [seen, setSeen] = useState(value);\n if (seen !== value) {\n setSeen(value);\n const typed = FINISHED_NUMBER.test(text.trim()) ? Number(text.trim()) : undefined;\n if (typed !== value) setText(value === null || value === undefined ? \"\" : String(value));\n }\n return (\n <span className={cn(\"relative flex items-center\", className)}>\n <BasicInput\n {...(id ? { id } : {})}\n aria-label={label}\n inputMode=\"decimal\"\n className={cn(\"h-7 text-xs tabular-nums\", unit ? \"pr-9\" : \"\")}\n value={text}\n disabled={disabled}\n onChange={(e) => {\n const raw = e.target.value;\n setText(raw);\n const t = raw.trim();\n if (t === \"\") onChange(null);\n else if (FINISHED_NUMBER.test(t)) onChange(Number(t));\n }}\n />\n <span aria-hidden className=\"pointer-events-none absolute right-2.5 text-xs text-muted-foreground\">\n {unit}\n </span>\n </span>\n );\n}\n\n// ── Size ──────────────────────────────────────────────────────────────────────\n\nfunction unitOf(format: FieldFormatConfig): string {\n return format.options?.unit ?? \"px\";\n}\n\n/** A measure's picture at row size: two boxes this far apart, or a corner this round. */\nfunction MeasureMini({ px, kind }: { px: number; kind: string }) {\n if (kind === \"spacing\") {\n const gap = Math.max(1, Math.min(px, 48));\n return (\n <span aria-hidden data-records-measure-mini=\"spacing\" className=\"inline-flex h-4 shrink-0 items-center\">\n <span className=\"h-4 w-2.5 rounded-sm border border-border bg-muted\" />\n <span style={{ width: gap }} />\n <span className=\"h-4 w-2.5 rounded-sm border border-border bg-muted\" />\n </span>\n );\n }\n if (kind === \"border\") {\n return (\n <span aria-hidden data-records-measure-mini=\"border\" className=\"inline-block h-5 w-5 shrink-0 rounded-sm bg-card\" style={{ boxShadow: `inset 0 0 0 ${Math.max(0.5, Math.min(px, 6))}px hsl(var(--foreground))` }} />\n );\n }\n if (kind === \"radius\") {\n return (\n <span\n aria-hidden\n data-records-measure-mini=\"radius\"\n className=\"inline-block h-5 w-5 shrink-0 border-2 border-foreground bg-card\"\n style={{ borderRadius: Math.min(px, 10) }}\n />\n );\n }\n return null;\n}\n\nfunction MeasureView({ value, format }: FieldLookViewProps): ReactNode {\n const n = numberOf(value);\n if (n === null) return null;\n const px = pixels(n, unitOf(format));\n const kind = format.options?.measurePreview ?? \"none\";\n return (\n <span data-records-look=\"measure\" className=\"inline-flex items-center gap-2 tabular-nums\">\n {px !== null && (kind === \"spacing\" || kind === \"radius\" || kind === \"border\") ? <MeasureMini px={px} kind={kind} /> : null}\n <span>\n {n} <span className=\"text-muted-foreground\">{unitOf(format)}</span>\n </span>\n </span>\n );\n}\n\nfunction MeasureEditor({ value, format, onChange, disabled, id, label }: FieldLookEditorProps): ReactNode {\n const n = numberOf(value);\n const px = n === null ? null : pixels(n, unitOf(format));\n const kind = format.options?.measurePreview ?? \"none\";\n return (\n <span className=\"flex items-center gap-2\">\n <NumberBox id={id} label={label} value={n} unit={unitOf(format)} disabled={disabled} className=\"w-full max-w-40\" onChange={onChange} />\n {px !== null && (kind === \"spacing\" || kind === \"radius\" || kind === \"border\") ? <MeasureMini px={px} kind={kind} /> : null}\n </span>\n );\n}\n\n/** Pixels a measure draws at: px as is, rem/em at 16, other units have no picture. */\nfunction pixels(n: number, unit: string): number | null {\n if (unit === \"px\" || unit === \"pt\") return n;\n if (unit === \"rem\" || unit === \"em\") return n * 16;\n return null;\n}\n\nfunction MeasurePreview({ value, format }: FieldLookViewProps): ReactNode {\n const n = numberOf(value);\n const kind = format.options?.measurePreview ?? \"none\";\n if (n === null || kind === \"none\") return null;\n const px = pixels(n, unitOf(format));\n if (px === null) return null;\n const clamped = Math.max(0, Math.min(px, 160));\n const dotted = \"flex h-24 w-full items-center justify-center rounded-lg border border-border bg-muted bg-[radial-gradient(hsl(var(--border))_1px,transparent_1px)] [background-size:12px_12px]\";\n if (kind === \"spacing\") {\n return (\n <span className={dotted} data-records-measure-preview=\"spacing\">\n <span className=\"h-14 w-11 rounded-md border border-border bg-card\" />\n <span style={{ width: clamped }} />\n <span className=\"h-14 w-11 rounded-md border border-border bg-card\" />\n </span>\n );\n }\n if (kind === \"radius\") {\n return (\n <span className={dotted} data-records-measure-preview=\"radius\">\n <span className=\"h-16 w-16 border-2 border-foreground bg-card\" style={{ borderRadius: Math.min(px, 32) }} />\n </span>\n );\n }\n return (\n <span className={dotted} data-records-measure-preview=\"size\">\n <span className=\"h-3 rounded-full bg-primary\" style={{ width: Math.max(2, clamped) }} />\n </span>\n );\n}\n\n// ── Type style ────────────────────────────────────────────────────────────────\n\nfunction TypeStyleView({ value }: FieldLookViewProps): ReactNode {\n const style = readTypeStyle(value);\n if (!style) return null;\n return (\n <span data-records-look=\"type_style\" className=\"flex min-w-0 flex-col items-start gap-1\">\n <span className=\"block max-w-full truncate text-foreground\" style={typeStyleCss(style)}>\n {TYPE_SAMPLE}\n </span>\n <span className=\"rounded-md border border-border bg-muted px-1.5 py-0.5 text-xs text-muted-foreground\">{typeStyleText(style)}</span>\n </span>\n );\n}\n\nconst FIELD = \"grid grid-cols-[6rem_1fr] items-center gap-2\";\n\nfunction TypeStyleEditor({ value, onChange, disabled, id, label }: FieldLookEditorProps): ReactNode {\n const style: TypeStyle = readTypeStyle(value) ?? { font: \"\", weight: 400, size: 13, lineHeight: 20, letterSpacing: 0 };\n const write = (next: { [K in keyof TypeStyle]?: TypeStyle[K] | undefined }) => {\n const merged: Record<string, unknown> = { ...style };\n for (const [k, v] of Object.entries(next)) {\n if (v === undefined) delete merged[k];\n else merged[k] = v;\n }\n // A style without a font is not a style yet: nothing is written until the font has a name.\n if (String(merged[\"font\"] ?? \"\").trim() === \"\") return;\n onChange(JSON.stringify(merged));\n };\n /** Weight 100–900 in hundreds; size above 0 and at most 512 px. */\n const clampWeight = (w: number) => Math.min(900, Math.max(100, Math.round(w / 100) * 100));\n const clampSize = (n: number) => Math.min(512, Math.max(1, n));\n const [font, setFont] = useState(style.font);\n return (\n <span className=\"flex w-full flex-col gap-1.5\">\n <span className={FIELD}>\n <span className=\"text-xs text-muted-foreground\">Font</span>\n <BasicInput id={id} aria-label={`${label} font`} value={font} placeholder=\"Geist\" disabled={disabled} onChange={(e) => {\n setFont(e.target.value);\n write({ font: e.target.value });\n }} />\n </span>\n <span className={FIELD}>\n <span className=\"text-xs text-muted-foreground\">Weight</span>\n <span className=\"grid grid-cols-[1fr_6rem] gap-2\">\n <Select value={String(clampWeight(style.weight))} disabled={disabled ?? false} onValueChange={(v) => write({ weight: clampWeight(Number(v)) })}>\n <SelectTrigger aria-label={`${label} weight`}>\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {TYPE_WEIGHTS.map((w) => (\n <SelectItem key={w.value} value={String(w.value)}>\n {w.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <UnitInput label={`${label} size`} unit=\"px\" value={style.size} disabled={disabled} onChange={(n) => n !== null && write({ size: clampSize(n) })} />\n </span>\n </span>\n <span className={FIELD}>\n <span className=\"text-xs text-muted-foreground\">Line height</span>\n <span className=\"grid grid-cols-2 gap-2\">\n <UnitInput label={`${label} line height`} unit=\"px\" value={style.lineHeight} disabled={disabled} onChange={(n) => write({ lineHeight: n !== null && n > 0 ? n : undefined })} />\n <UnitInput label={`${label} letter spacing`} unit=\"em\" value={style.letterSpacing} disabled={disabled} onChange={(n) => write({ letterSpacing: n ?? undefined })} />\n </span>\n </span>\n </span>\n );\n}\n\nfunction UnitInput({\n label,\n unit,\n value,\n onChange,\n disabled,\n}: {\n label: string;\n unit: string;\n value: number | undefined;\n onChange: (next: number | null) => void;\n disabled?: boolean | undefined;\n}) {\n return <NumberBox label={label} unit={unit} value={value} disabled={disabled} onChange={onChange} />;\n}\n\nfunction TypeStylePreview({ value }: FieldLookViewProps): ReactNode {\n const style = readTypeStyle(value);\n return (\n <span className=\"flex h-28 w-full items-center justify-center overflow-hidden rounded-lg border border-border bg-muted px-4\">\n <span className=\"truncate text-foreground\" style={style ? typeStyleCss(style) : undefined}>\n {style ? TYPE_SAMPLE : \"Aa\"}\n </span>\n </span>\n );\n}\n\n// ── Shadow ────────────────────────────────────────────────────────────────────\n\n/** The grounds a shadow is previewed on, per theme — data colors (a preview of a theme), not UI chrome. */\nexport const THEME_GROUNDS = { light: { ground: \"#f4f4f5\", card: \"#ffffff\" }, dark: { ground: \"#0b0c0e\", card: \"#18191c\" } } as const;\n\n/** One theme's shadow on that theme's own ground. */\nexport function ShadowSwatch({ layers, theme, size = \"sm\" }: { layers: readonly ShadowLayer[]; theme: \"light\" | \"dark\"; size?: \"sm\" | \"lg\" }) {\n const g = THEME_GROUNDS[theme];\n return (\n <span\n aria-hidden\n data-records-shadow-swatch={theme}\n className={cn(\"flex shrink-0 items-center justify-center rounded-md\", size === \"lg\" ? \"h-24 w-full\" : \"h-7 w-11\")}\n style={{ backgroundColor: g.ground }}\n >\n <span className={cn(\"rounded\", size === \"lg\" ? \"h-12 w-20\" : \"h-3.5 w-6\")} style={{ backgroundColor: g.card, boxShadow: shadowCss(layers) }} />\n </span>\n );\n}\n\nconst layersWords = shadowWords;\n\nfunction ShadowView({ value }: FieldLookViewProps): ReactNode {\n const pair = readShadowPair(value);\n if (!pair) return null;\n return (\n <span data-records-look=\"shadow\" className=\"inline-flex min-w-0 items-center gap-2\">\n <ShadowSwatch layers={pair.light} theme=\"light\" />\n <ShadowSwatch layers={pair.dark} theme=\"dark\" />\n <span className=\"truncate text-xs text-muted-foreground\">{layersWords(pair.light)}</span>\n </span>\n );\n}\n\nconst NEW_LAYER: ShadowLayer = { x: 0, y: 4, blur: 12, spread: 0, color: \"#0000001f\" };\n\n/** The layers of ONE shadow: x, y, blur, spread and color per layer; add or remove a layer. */\nexport function ShadowLayersEditor({\n layers,\n onChange,\n disabled,\n id,\n label,\n}: {\n layers: readonly ShadowLayer[];\n onChange: (next: ShadowLayer[]) => void;\n disabled?: boolean | undefined;\n id: string;\n label: string;\n}) {\n const set = (i: number, patch: Partial<ShadowLayer>) => onChange(layers.map((l, j) => (j === i ? { ...l, ...patch } : l)));\n return (\n <span className=\"flex w-full flex-col gap-2\">\n {layers.map((layer, i) => (\n <span key={i} className=\"grid grid-cols-4 gap-1.5\">\n {([\"x\", \"y\", \"blur\", \"spread\"] as const).map((k) => (\n <UnitInput\n key={k}\n label={`${label} layer ${i + 1} ${k}`}\n unit={k === \"x\" || k === \"y\" ? k : k === \"blur\" ? \"B\" : \"S\"}\n value={layer[k]}\n disabled={disabled}\n onChange={(n) => set(i, { [k]: k === \"blur\" ? Math.max(0, n ?? 0) : (n ?? 0) })}\n />\n ))}\n <span className=\"col-span-3\">\n <ColorWell id={i === 0 ? id : `${id}-${i}`} label={`${label} layer ${i + 1} color`} value={layer.color} disabled={disabled} onChange={(c) => c && set(i, { color: c })} />\n </span>\n <span className=\"flex items-center justify-end\">\n {layers.length > 1 ? (\n <button type=\"button\" disabled={disabled} className=\"text-xs text-muted-foreground hover:text-foreground\" onClick={() => onChange(layers.filter((_, j) => j !== i))}>\n Remove\n </button>\n ) : null}\n </span>\n </span>\n ))}\n <button type=\"button\" disabled={disabled} className=\"self-start text-xs text-muted-foreground hover:text-foreground\" onClick={() => onChange([...layers, NEW_LAYER])}>\n + Layer\n </button>\n </span>\n );\n}\n\n/** A shadow per theme: Light, and Dark (the same as light until it is given its own). */\nfunction ShadowEditor({ value, onChange, disabled, id, label }: FieldLookEditorProps): ReactNode {\n const pair = readShadowPair(value) ?? { light: [NEW_LAYER], dark: [NEW_LAYER] };\n const own = (() => {\n const raw = typeof value === \"string\" && value.trim().startsWith(\"{\") ? value : null;\n return raw !== null && raw.includes('\"dark\"');\n })();\n const [theme, setTheme] = useState<\"light\" | \"dark\">(\"light\");\n const pack = (l: readonly ShadowLayer[]) => (l.length === 1 ? l[0] : { layers: l });\n const write = (next: { light: readonly ShadowLayer[]; dark: readonly ShadowLayer[] | null }) =>\n onChange(JSON.stringify(next.dark ? { light: pack(next.light), dark: pack(next.dark) } : pack(next.light)));\n return (\n <span className=\"flex w-full flex-col gap-2\">\n <span className=\"flex items-center gap-1\" role=\"tablist\" aria-label={`${label} theme`}>\n {([\"light\", \"dark\"] as const).map((t) => (\n <button\n key={t}\n type=\"button\"\n role=\"tab\"\n aria-selected={theme === t}\n className={cn(\"rounded-md px-2 py-0.5 text-xs\", theme === t ? \"bg-muted text-foreground\" : \"text-muted-foreground hover:text-foreground\")}\n onClick={() => setTheme(t)}\n >\n {t === \"light\" ? \"Light\" : \"Dark\"}\n </button>\n ))}\n {theme === \"dark\" && own ? (\n <button type=\"button\" className=\"ml-auto text-xs text-muted-foreground hover:text-foreground\" onClick={() => write({ light: pair.light, dark: null })}>\n Same as light\n </button>\n ) : null}\n </span>\n <ShadowLayersEditor\n layers={theme === \"light\" ? pair.light : pair.dark}\n id={id}\n label={`${label} ${theme}`}\n disabled={disabled}\n onChange={(next) => write(theme === \"light\" ? { light: next, dark: own ? pair.dark : null } : { light: pair.light, dark: next })}\n />\n </span>\n );\n}\n\nfunction ShadowPreview({ value }: FieldLookViewProps): ReactNode {\n const pair = readShadowPair(value) ?? { light: [NEW_LAYER], dark: [NEW_LAYER] };\n return (\n <span className=\"grid w-full grid-cols-2 gap-2\">\n <ShadowSwatch layers={pair.light} theme=\"light\" size=\"lg\" />\n <ShadowSwatch layers={pair.dark} theme=\"dark\" size=\"lg\" />\n </span>\n );\n}\n\n// ── Opacity ───────────────────────────────────────────────────────────────────\n\nconst CHECKER = \"repeating-conic-gradient(#d4d4d8 0% 25%, #ffffff 0% 50%) 50% / 8px 8px\";\n\nfunction OpacitySwatch({ opacity, size = \"sm\" }: { opacity: number; size?: \"sm\" | \"lg\" }) {\n return (\n <span aria-hidden className={cn(\"relative inline-block shrink-0 overflow-hidden rounded border border-border\", size === \"lg\" ? \"h-24 w-full\" : \"h-5 w-5\")} style={{ background: CHECKER }}>\n <span className=\"absolute inset-0 bg-foreground\" style={{ opacity }} />\n </span>\n );\n}\n\nfunction OpacityView({ value }: FieldLookViewProps): ReactNode {\n const o = readOpacity(value);\n if (o === null) return null;\n return (\n <span data-records-look=\"opacity\" className=\"inline-flex items-center gap-2 tabular-nums\">\n <OpacitySwatch opacity={o} />\n {Math.round(o * 1000) / 10}%\n </span>\n );\n}\n\nfunction OpacityEditor({ value, onChange, disabled, id, label }: FieldLookEditorProps): ReactNode {\n const o = readOpacity(value);\n return (\n <span className=\"flex items-center gap-2\">\n <NumberBox id={id} label={label} value={o} unit=\"\" disabled={disabled} className=\"w-full max-w-28\" onChange={(n) => onChange(n === null ? null : Math.min(1, Math.max(0, n)))} />\n {o !== null ? <OpacitySwatch opacity={o} /> : null}\n {o !== null ? <span className=\"text-xs tabular-nums text-muted-foreground\">{Math.round(o * 1000) / 10}%</span> : null}\n </span>\n );\n}\n\nfunction OpacityPreview({ value }: FieldLookViewProps): ReactNode {\n return <OpacitySwatch opacity={readOpacity(value) ?? 0.5} size=\"lg\" />;\n}\n\n// ── Motion ────────────────────────────────────────────────────────────────────\n\n/** A dot crossing a track at the motion's own duration and easing; still when the person asks for less motion. */\nfunction MotionTrack({ motion, size = \"sm\" }: { motion: Motion; size?: \"sm\" | \"lg\" }) {\n const id = `m${Math.round(motion.duration)}-${motion.easing.replace(/[^a-z0-9]/gi, \"\")}`;\n return (\n <span aria-hidden className={cn(\"relative inline-block shrink-0 rounded-full bg-muted\", size === \"lg\" ? \"h-3 w-full\" : \"h-2 w-12\")}>\n <style>{`@keyframes records-motion-${id}{0%{left:0}50%{left:calc(100% - var(--d))}100%{left:0}}@media (prefers-reduced-motion: reduce){[data-records-motion-dot]{animation:none!important}}`}</style>\n <span\n data-records-motion-dot=\"\"\n className=\"absolute top-0 rounded-full bg-primary\"\n style={{\n [\"--d\" as string]: size === \"lg\" ? \"12px\" : \"8px\",\n width: \"var(--d)\",\n height: \"var(--d)\",\n animation: `records-motion-${id} ${Math.max(motion.duration, 50) * 2 + 600}ms ${motion.easing} infinite`,\n }}\n />\n </span>\n );\n}\n\nfunction MotionView({ value }: FieldLookViewProps): ReactNode {\n const m = readMotion(value);\n if (!m) return null;\n return (\n <span data-records-look=\"motion\" className=\"inline-flex items-center gap-2\">\n <MotionTrack motion={m} />\n <span className=\"tabular-nums\">{motionText(m)}</span>\n </span>\n );\n}\n\nfunction MotionEditor({ value, onChange, disabled, id, label }: FieldLookEditorProps): ReactNode {\n const m = readMotion(value) ?? { duration: 200, easing: \"ease-out\" };\n const write = (next: Partial<Motion>) => onChange(JSON.stringify({ ...m, ...next }));\n return (\n <span className=\"flex flex-wrap items-center gap-2\">\n <NumberBox id={id} label={`${label} duration`} value={m.duration} unit=\"ms\" disabled={disabled} className=\"w-24\" onChange={(n) => n !== null && n >= 0 && write({ duration: n })} />\n <Select value={m.easing} disabled={disabled ?? false} onValueChange={(v) => write({ easing: v })}>\n <SelectTrigger aria-label={`${label} easing`} className=\"h-7 w-36 text-xs\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {MOTION_EASINGS.map((e) => (\n <SelectItem key={e.value} value={e.value}>\n {e.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n <MotionTrack motion={m} />\n </span>\n );\n}\n\nfunction MotionPreview({ value }: FieldLookViewProps): ReactNode {\n const m = readMotion(value) ?? { duration: 200, easing: \"ease-out\" };\n return (\n <span className=\"flex h-24 w-full items-center rounded-lg border border-border bg-muted px-4\">\n <MotionTrack motion={m} size=\"lg\" />\n </span>\n );\n}\n\n// ── The built-in looks ──────────────────────────────────────────────────────\n// A plain list, never a registration side effect: this package is `\"sideEffects\": false`, so a\n// bundler may drop a module imported only for what it does on load. The registry seeds itself\n// from this list (`registry.ts`), so every reader that asks for a look gets these.\n\nexport const DESIGN_LOOKS: readonly FieldLook[] = [\n {\n id: \"color_pair\",\n View: ColorPairView,\n Editor: ColorPairEditor,\n Preview: ColorPairPreview,\n checks: colorPairChecks,\n starter: () => JSON.stringify({ light: \"#1f4fe0\" }),\n },\n { id: \"measure\", View: MeasureView, Editor: MeasureEditor, Preview: MeasurePreview, starter: () => 16 },\n {\n id: \"type_style\",\n View: TypeStyleView,\n Editor: TypeStyleEditor,\n Preview: TypeStylePreview,\n starter: () => JSON.stringify({ font: \"Geist\", weight: 400, size: 13, lineHeight: 20, letterSpacing: 0 }),\n },\n { id: \"shadow\", View: ShadowView, Editor: ShadowEditor, Preview: ShadowPreview, starter: () => JSON.stringify(NEW_LAYER) },\n { id: \"opacity\", View: OpacityView, Editor: OpacityEditor, Preview: OpacityPreview, starter: () => 0.5 },\n { id: \"motion\", View: MotionView, Editor: MotionEditor, Preview: MotionPreview, starter: () => JSON.stringify({ duration: 200, easing: \"ease-out\" }) },\n];\n\nexport const DESIGN_LOOK_IDS = DESIGN_LOOKS.map((look) => look.id);\n\nexport { MEASURE_UNITS };\n","\"use client\";\n\n// src/looks/htmlLook.tsx — @ai-matrx/records-ui · THE HTML SAMPLE LOOK\n//\n// A design system's Components table holds one component family per row, drawn from a piece of\n// HTML (`format: html_sample`). The sample is drawn AS IT LOOKS, in a frame that:\n// • is sandboxed with NO `allow-scripts`: the HTML is markup and CSS only, so nothing in it can\n// run, reach the app, submit a form, open a window or navigate the page. `allow-same-origin` is\n// there only so the HOST can read the sample's height and hand it the theme — with no script in\n// the frame, nothing on the inside can use that origin. Never add `allow-scripts` beside it.\n// • carries a Content-Security-Policy that loads nothing but inline styles and images/fonts\n// (`connect-src` and `script-src` are `none`).\n// • is SEAMLESS: no border, transparent, the card's own color scheme (a frame whose scheme\n// differs from its host paints an opaque backdrop), and AUTO-HEIGHT: it grows to its content\n// and never scrolls inside.\n// • gives the sample the design system's tokens as CSS variables (`--background`, `--primary`,\n// `--radius`… SAMPLE_TOKEN_NAMES): the host page's own values by default, the host's chosen\n// values when it provides them (`HtmlSampleTokensProvider` — a board can pass its Colors /\n// Spacing / Radius / Shadow tables). The theme follows the host live, with no reload.\n//\n// `HtmlSampleFrame` (htmlFrame.tsx, also `@ai-matrx/records-ui/html-frame`) is the frame on its own,\n// for any host that draws agent- or person-written HTML seamlessly (the board's Cover hero).\n\nimport { useEffect, useRef, useState, type ReactNode } from \"react\";\nimport { BasicTextarea, Button } from \"@ai-matrx/design-system\";\nimport type { FieldFormatConfig } from \"@ai-matrx/design-system/field-formats\";\n\nimport { HtmlSampleFrame } from \"./htmlFrame\";\nimport type { FieldLook, FieldLookCheck, FieldLookEditorProps, FieldLookViewProps } from \"./types\";\n\nexport * from \"./htmlFrame\";\n\nexport const HTML_SAMPLE_LOOK_ID = \"html_sample\";\n\n// ── The look ─────────────────────────────────────────────────────────────────\n\nfunction htmlOf(value: unknown): string {\n return typeof value === \"string\" ? value : value === null || value === undefined ? \"\" : String(value);\n}\n\nfunction HtmlSampleView({ value }: FieldLookViewProps): ReactNode {\n const html = htmlOf(value).trim();\n if (!html) return null;\n return <HtmlSampleFrame html={html} title=\"Component sample\" />;\n}\n\nconst PREVIEW_AFTER_MS = 250;\n\n/**\n * The sample first; a press (or Enter) opens its HTML in a code box with the sample drawn live\n * beneath it. Done or Escape returns to the sample. Every change is written as it is typed: the\n * host saves it (a section card saves after a pause).\n */\nfunction HtmlSampleEditor({ value, onChange, disabled, id, label }: FieldLookEditorProps): ReactNode {\n const stored = htmlOf(value);\n const [editing, setEditing] = useState(false);\n const [text, setText] = useState(stored);\n const [shown, setShown] = useState(stored);\n const box = useRef<HTMLTextAreaElement | null>(null);\n\n // A value changed from outside (an assistant, another tab) while not being edited is shown.\n useEffect(() => {\n if (!editing) {\n setText(stored);\n setShown(stored);\n }\n }, [stored, editing]);\n\n useEffect(() => {\n if (!editing) return;\n const timer = setTimeout(() => setShown(text), PREVIEW_AFTER_MS);\n return () => clearTimeout(timer);\n }, [text, editing]);\n\n useEffect(() => {\n if (editing) box.current?.focus();\n }, [editing]);\n\n if (!editing) {\n return (\n <div className=\"group relative min-w-0\" data-records-look=\"html_sample\">\n {stored.trim() ? (\n <HtmlSampleFrame html={stored} title={label} />\n ) : (\n <span className=\"block py-1 text-sm text-muted-foreground\">No sample</span>\n )}\n {disabled ? null : (\n <button\n type=\"button\"\n id={id}\n aria-label={`Edit ${label} HTML`}\n onClick={() => setEditing(true)}\n className=\"absolute right-0 top-0 inline-flex h-6 items-center rounded-md border border-border bg-card px-2 font-mono text-[11px] text-muted-foreground opacity-0 shadow-sm transition-opacity hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-focus-within:opacity-100 group-hover:opacity-100\"\n >\n {\"</>\"}\n </button>\n )}\n </div>\n );\n }\n\n const done = () => {\n setShown(text);\n setEditing(false);\n };\n\n return (\n <div className=\"flex min-w-0 flex-col gap-2\" data-records-look=\"html_sample\" data-records-editing=\"\">\n {/* ui-exception: raw HTML source, a code value */}\n <BasicTextarea\n ref={box}\n id={id}\n aria-label={`${label} HTML`}\n rows={Math.min(18, Math.max(6, text.split(\"\\n\").length + 1))}\n spellCheck={false}\n className=\"font-mono text-xs\"\n value={text}\n disabled={disabled}\n onChange={(e) => {\n setText(e.target.value);\n onChange(e.target.value === \"\" ? null : e.target.value);\n }}\n onKeyDown={(e) => {\n if (e.key === \"Escape\") {\n e.preventDefault();\n e.stopPropagation();\n done();\n }\n }}\n />\n {shown.trim() ? <HtmlSampleFrame html={shown} title={`${label} preview`} /> : null}\n <div className=\"flex justify-end\">\n <Button type=\"button\" variant=\"outline\" onClick={done}>\n Done\n </Button>\n </div>\n </div>\n );\n}\n\n/** A color written as a value (`#1f4fe0`, `rgb(…)`) instead of a token: the sample will not follow the theme. */\nconst FIXED_COLOUR = /#[0-9a-f]{3,8}\\b|\\brgba?\\(|\\bhsla?\\(/i;\n\nfunction htmlSampleChecks(value: unknown, _format: FieldFormatConfig): FieldLookCheck[] {\n const html = htmlOf(value);\n if (!html.trim()) return [];\n const out: FieldLookCheck[] = [];\n const styles = [...html.matchAll(/<style[^>]*>([\\s\\S]*?)<\\/style>|style\\s*=\\s*\"([^\"]*)\"/gi)].map((m) => m[1] ?? m[2] ?? \"\").join(\"\\n\");\n // A color inside a var() fallback is fine: `var(--primary, #1f4fe0)`.\n const outsideFallbacks = styles.replace(/var\\([^()]*(\\([^()]*\\))?[^()]*\\)/g, \"\");\n if (FIXED_COLOUR.test(outsideFallbacks)) {\n out.push({\n message: \"fixed colors, not the theme's\",\n fix: {\n label: \"Use tokens\",\n // bare-hsl-ok: prose naming the frame's variables, not a colour\n ask: \"Rewrite this HTML sample so every color is one of the design system's CSS variables (var(--background), var(--foreground), var(--primary), var(--border)…), keeping the markup and the look the same, so it follows light and dark.\",\n },\n });\n }\n if (/<script\\b/i.test(html)) out.push({ message: \"scripts do not run in a sample\" });\n return out;\n}\n\n/** Seeded into the registry's starting list (registry.ts), never registered as an import side effect. */\nexport const HTML_SAMPLE_LOOK: FieldLook = {\n id: HTML_SAMPLE_LOOK_ID,\n View: HtmlSampleView,\n Editor: HtmlSampleEditor,\n Preview: HtmlSampleView,\n checks: htmlSampleChecks,\n starter: () =>\n // bare-hsl-ok: sample HTML for the frame, whose :root holds full colours\n '<style>.b{font:inherit;padding:6px 12px;border-radius:var(--radius);border:1px solid transparent;background:var(--primary);color:var(--primary-foreground)}</style>\\n<button class=\"b\">Button</button>',\n};\n","// src/looks/jsonLook.tsx — @ai-matrx/records-ui\n//\n// W2-A 1 (AIRTABLE-PARITY row 100): A JSON COLUMN SHOWS COLLAPSED. The store keeps any JSON value (`format: json`);\n// a cell shows one line — `{ 3 keys }`, `[ 2 items ]`, or a short scalar — with the whole value on hover. It is\n// edited in the kind's own code box (`JsonControl`), so this look draws only.\nimport type { FieldLook, FieldLookViewProps } from \"./types\";\n\n/** The one-line, collapsed words for a JSON value. */\nexport function jsonCollapsed(value: unknown): string {\n if (value === null || value === undefined) return \"\";\n let v: unknown = value;\n if (typeof v === \"string\") {\n try {\n v = JSON.parse(v);\n } catch {\n return v as string;\n }\n }\n if (Array.isArray(v)) return `[ ${v.length} ${v.length === 1 ? \"item\" : \"items\"} ]`;\n if (v && typeof v === \"object\") {\n const n = Object.keys(v).length;\n return `{ ${n} ${n === 1 ? \"key\" : \"keys\"} }`;\n }\n return JSON.stringify(v);\n}\n\nfunction JsonView({ value }: FieldLookViewProps) {\n if (value === null || value === undefined) return null;\n const whole = typeof value === \"string\" ? value : JSON.stringify(value, null, 2);\n return (\n <span className=\"truncate font-mono text-xs\" title={whole} data-records-json-collapsed=\"\">\n {jsonCollapsed(value)}\n </span>\n );\n}\n\n/** Seeded into the registry's starting list (registry.ts), never registered as an import side effect. */\nexport const JSON_LOOK: FieldLook = { id: \"json\", View: JsonView };\nexport const JSON_LOOK_ID = JSON_LOOK.id;\n","// src/looks/registry.ts — @ai-matrx/records-ui · PLUG-IN FIELD LOOKS\n//\n// A LOOK IS EVERYTHING A COLUMN'S \"SHOWS AS\" BRINGS WITH IT: how one value reads in a cell, the\n// editor that changes it, the big picture a dialog or a section card draws, and the checks it\n// offers (never blocks). The pure half — the format id, its text and its parse — lives in\n// `@ai-matrx/design-system/field-formats`; this is the drawn half.\n//\n// One registry, consulted FIRST by `FormattedValue` (the read view everywhere) and `formatControl`\n// (the editor everywhere), so a look registered here is drawn by the grid, the record form, the\n// record panel, the section card and the public page with no second wiring. The design-token\n// looks are the registry's starting list (`designLooks.tsx` `DESIGN_LOOKS`); a host registers its own with `registerFieldLook`\n// — a law firm's deadline countdown, a clinic's vital sign — and every table that wears it gets it.\n\nimport type { FieldFormatConfig } from \"@ai-matrx/design-system/field-formats\";\n\nimport { DESIGN_LOOKS } from \"./designLooks\";\nimport { HTML_SAMPLE_LOOK } from \"./htmlLook\";\nimport { JSON_LOOK } from \"./jsonLook\";\nimport type { FieldLook, FieldLookCheck, LookContext } from \"./types\";\n\nexport type { FieldLook, FieldLookCheck, FieldLookEditorProps, FieldLookViewProps, LookContext } from \"./types\";\n\n// Seeded with the built-in looks, so no reader depends on a module having been loaded for its side\n// effects (the package is `\"sideEffects\": false`).\nconst LOOKS = new Map<string, FieldLook>([...DESIGN_LOOKS, JSON_LOOK, HTML_SAMPLE_LOOK].map((look) => [look.id, look]));\n\n/** Register (or replace) the look for a format id. Returns the id. */\nexport function registerFieldLook(look: FieldLook): string {\n LOOKS.set(look.id, look);\n return look.id;\n}\n\n/** The look drawn for this format, or undefined: the format's own drawing. */\nexport function fieldLookFor(formatId: string | null | undefined): FieldLook | undefined {\n return formatId ? LOOKS.get(formatId) : undefined;\n}\n\n/** Every registered look id, in registration order. */\nexport function fieldLookIds(): string[] {\n return [...LOOKS.keys()];\n}\n\n/** The checks a look makes of one value; none when the format has no look or no checks. */\nexport function lookChecks(value: unknown, format: FieldFormatConfig | undefined, context?: LookContext): FieldLookCheck[] {\n if (!format) return [];\n const look = LOOKS.get(format.id);\n return look?.checks ? look.checks(value, format, context) : [];\n}\n\n/**\n * The look a value is drawn in, from the column's own \"Shows as\" format — or undefined. Callers\n * hand over the format (`shownAsOf(field)`), so this file reads no Field.\n */\nexport function registeredLook(format: FieldFormatConfig | undefined): FieldFormatConfig | undefined {\n return format && LOOKS.has(format.id) ? format : undefined;\n}\n","\"use client\";\n\n// src/looks/tableTokens.tsx — @ai-matrx/records-ui · A DESIGN-TOKEN TABLE IS A SET OF CSS VARIABLES\n//\n// A design system's own tables (Colors, Spacing, Corner radius, Shadows, Opacity, Motion) become the\n// variables its component samples draw with (`html_sample`, `HtmlSampleTokensProvider`), so a button\n// sample on a brand's board is that brand's button — never the app's. Every row whose value wears a\n// design look becomes `--<row name>`: a color pair per theme, a size as `16px`, a shadow per theme as\n// its CSS, an opacity as its number, a motion as `200ms ease-out`. `radius` is filled from a row named\n// `radius` or `radius-md` when no row is called that already.\n//\n// Read through the same store door as the section card (`useRecordPage`), so a table the viewer\n// cannot read adds nothing.\n\nimport { useEffect, useState, type ReactNode } from \"react\";\nimport { useFields, useRecordPage, useTable, type Field, type ReadRow, type Uuid } from \"@ai-matrx/records/react\";\nimport {\n readColorPair,\n readMotion,\n readOpacity,\n readShadowPair,\n readTypeStyle,\n shadowCss,\n typeStyleCss,\n type FieldFormatConfig,\n} from \"@ai-matrx/design-system/field-formats\";\n\nimport { formatForField } from \"../presentation\";\nimport { HtmlSampleTokensProvider, type SampleTokenSet } from \"./htmlFrame\";\n\nconst NAME_KEYS = [\"name\", \"title\", \"token\", \"label\"];\n\n/** A row name as a CSS variable name: \"Card Foreground\" → \"card-foreground\". */\nexport function tokenName(raw: string): string {\n return raw\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9-]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n}\n\nfunction numberOf(value: unknown): number | null {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const n = Number(value.trim());\n return Number.isFinite(n) ? n : null;\n }\n return null;\n}\n\n/** The variables one table holds, per theme. Pure: rows + their fields in, variables out. */\nexport function tokensFromRows(rows: readonly ReadRow[], fields: readonly Field[], titleField?: string | null): SampleTokenSet {\n const light: Record<string, string> = {};\n const dark: Record<string, string> = {};\n const fonts: string[] = [];\n const nameKey = (titleField && fields.some((f) => f.key === titleField) ? titleField : NAME_KEYS.find((k) => fields.some((f) => f.key === k))) ?? null;\n if (!nameKey) return {};\n const looked = fields\n .map((f) => ({ field: f, format: formatForField(f) }))\n .filter((x): x is { field: Field; format: FieldFormatConfig } => Boolean(x.format));\n for (const row of rows) {\n const name = tokenName(String((row.document ?? {})[nameKey] ?? \"\"));\n if (!name) continue;\n for (const { field, format } of looked) {\n const value = (row.document ?? {})[field.key];\n if (value === null || value === undefined || value === \"\") continue;\n switch (format.id) {\n case \"color_pair\": {\n const pair = readColorPair(value);\n if (pair) {\n light[name] = pair.light;\n dark[name] = pair.dark ?? pair.light;\n }\n break;\n }\n case \"measure\": {\n const n = numberOf(value);\n if (n !== null) light[name] = dark[name] = `${n}${format.options?.unit ?? \"px\"}`;\n break;\n }\n case \"shadow\": {\n const pair = readShadowPair(value);\n if (pair) {\n light[name] = shadowCss(pair.light);\n dark[name] = shadowCss(pair.dark);\n }\n break;\n }\n case \"opacity\": {\n const o = readOpacity(value);\n if (o !== null) light[name] = dark[name] = String(o);\n break;\n }\n case \"type_style\": {\n // A type style is five variables: --font-<name>, --text-<name>, --leading-<name>, --weight-<name>, --tracking-<name> (em).\n const style = readTypeStyle(value);\n if (style) {\n const css = typeStyleCss(style);\n light[`font-${name}`] = dark[`font-${name}`] = String(css.fontFamily);\n light[`text-${name}`] = dark[`text-${name}`] = `${style.size}px`;\n light[`weight-${name}`] = dark[`weight-${name}`] = String(style.weight);\n if (style.lineHeight) light[`leading-${name}`] = dark[`leading-${name}`] = `${style.lineHeight}px`;\n light[`tracking-${name}`] = dark[`tracking-${name}`] = `${style.letterSpacing ?? 0}em`;\n const first = style.font.split(\",\")[0]!.replace(/[\"']/g, \"\").trim();\n if (first && !fonts.includes(first)) fonts.push(first);\n }\n break;\n }\n case \"motion\": {\n const m = readMotion(value);\n if (m) light[name] = dark[name] = `${m.duration}ms ${m.easing}`;\n break;\n }\n default:\n break;\n }\n }\n }\n if (!(\"radius\" in light)) {\n const r = light[\"radius-md\"] ?? light[\"radius-base\"];\n if (r) light.radius = dark.radius = r;\n }\n return fonts.length > 0 ? { light, dark, fonts } : { light, dark };\n}\n\n/** Merge token sets in order; a later table wins a name both hold. */\nexport function mergeTokenSets(sets: readonly SampleTokenSet[]): SampleTokenSet {\n const light: Record<string, string> = {};\n const dark: Record<string, string> = {};\n const fonts: string[] = [];\n for (const s of sets) {\n Object.assign(light, s.light ?? {});\n Object.assign(dark, s.dark ?? {});\n for (const f of s.fonts ?? []) if (!fonts.includes(f)) fonts.push(f);\n }\n return fonts.length > 0 ? { light, dark, fonts } : { light, dark };\n}\n\nfunction OneTable({ tableId, onTokens }: { tableId: Uuid; onTokens: (id: Uuid, set: SampleTokenSet) => void }) {\n const table = useTable(tableId);\n const fields = useFields(tableId);\n const page = useRecordPage(fields.data ? tableId : null, { pageSize: 500 });\n const rows = page.data?.rows;\n const titleField = table.data?.title_field ?? null;\n // The provider keeps a set only when it differs from the one it holds, so a re-run is cheap.\n useEffect(() => {\n if (!rows || !fields.data) return;\n onTokens(tableId, tokensFromRows(rows, fields.data, titleField));\n }, [rows, fields.data, titleField, tableId, onTokens]);\n return null;\n}\n\n/**\n * Every component sample under it draws with the variables these tables hold (in order; a later\n * table wins a shared name). No tables: the samples keep the host page's own tokens.\n */\nexport function TableTokensProvider({ tableIds, children }: { tableIds: readonly Uuid[]; children: ReactNode }) {\n const [byTable, setByTable] = useState<Record<string, SampleTokenSet>>({});\n const merged = tableIds.length === 0 ? null : mergeTokenSets(tableIds.map((id) => byTable[id] ?? {}));\n return (\n <>\n {tableIds.map((id) => (\n <OneTable key={id} tableId={id} onTokens={(tid, set) => setByTable((prev) => (JSON.stringify(prev[tid]) === JSON.stringify(set) ? prev : { ...prev, [tid]: set }))} />\n ))}\n <HtmlSampleTokensProvider tokens={merged}>{children}</HtmlSampleTokensProvider>\n </>\n );\n}\n","// src/askOnce.ts — @ai-matrx/records-ui · moved whole to @ai-matrx/records/versions (2026-10-08); one instance (askOnce's cache) for both packages.\nexport * from \"@ai-matrx/records/versions\";\n","\"use client\";\n\n// src/labels.tsx — @ai-matrx/records-ui\n//\n// WHAT AN ID IS CALLED, ONCE, FOR EVERY SCREEN THAT DRAWS A VALUE.\n//\n// A choice field stores the ID of an option record and a relation field stores\n// the ID of the record it points at (FLD-5 / FLD-6, REL-1) — that is the store\n// being right, and it is also why the 19 September verdict saw a bare\n// 36-character identifier in a relation cell, in a choice cell, and as the\n// HEADING OF EVERY KANBAN COLUMN. The pickers resolved those ids because each\n// one loaded its own list; the read-only surfaces never did, so the same value\n// read as a name in the form and as a machine id in the grid.\n//\n// One resolver, provided once inside the mount, so every surface gets the same\n// answer and asks the store once per Field rather than once per cell:\n//\n// · a list field → `custom.field_options`, which resolves the options Table\n// from the Field's own config, so no screen has to know which Table it is\n// · a relation field → the read door on the Field's declared target\n//\n// WHAT IT DOES WHILE IT IS LOOKING. It returns `null`, and every caller draws\n// the word \"Loading…\" rather than the id. Showing the id \"until it resolves\" is\n// how the defect got shipped in the first place: it looks like a value.\n\nimport { fieldOptionsOnce } from \"./askOnce\";\nimport { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { useRecordsClient, type Field, type Uuid } from \"@ai-matrx/records/react\";\nimport { autonumberPrefixOf, autonumberWords } from \"@ai-matrx/records\";\nimport { newerKindExportWords, optionKey, type RecordDocument, type StoredRecord } from \"@ai-matrx/records\";\nimport { UNREAD_RECORD_LABEL, WITHHELD_RECORD_LABEL, recordName } from \"./names\";\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\nimport { isSignatureField } from \"./docs\";\nimport { signatureWords } from \"./signature\";\nimport { registeredLook } from \"./looks\";\nimport { shownAsOf } from \"./presentation\";\nimport { formatFieldValue } from \"@ai-matrx/design-system/field-formats\";\n\n/**\n * Answers \"what is the record with this id called\", for one Field's values. The resolver the mount\n * provides also answers `archived` — whether a referenced record sits in Archived items (an archive\n * keeps every reference to it, chair ruling B3-21) — so a chip can draw that state.\n */\nexport type LabelLookup = ((field: Field, id: string) => string | null) & {\n archived?: (field: Field, id: string) => boolean;\n /** The linked record's own icon, and its table's icon for one that has none (same call as the words). */\n icons?: (field: Field, id: string) => { icon: string | null; tableIcon: string | null } | undefined;\n};\n\nconst LabelContext = createContext<{\n lookup: LabelLookup;\n want: (field: Field) => void;\n waiting: (field: Field) => string | null;\n}>({\n // With no provider the resolver is ABSENT, not silently empty: a caller gets\n // null and says \"Loading…\" forever, which is visible. The mount always\n // provides one, so this is only ever a bare unit test.\n lookup: () => null,\n want: () => {},\n waiting: () => null,\n});\n\n/**\n * HOW LONG A CELL MAY SAY \"Loading…\" BEFORE IT HAS TO SAY WHAT IT IS WAITING\n * FOR. One second is the span at which a person stops reading a word as \"this\n * is about to happen\" and starts reading it as \"this is stuck\" — the same line\n * Nielsen's response-time work draws and the one Linear and Stripe design to.\n */\nexport const SAY_WHAT_YOU_ARE_WAITING_FOR_AFTER_MS = 1000;\n\n/**\n * WHAT THIS COLUMN IS WAITING FOR, in a person's words.\n *\n * 🚨 WHY A CELL MAY NOT JUST SAY \"Loading…\" (lane FRONT-DOOR, 2026-09-21;\n * VERIFIER-8 MEDIUM-1). On records-ui 0.57 the whole CUSTOMER column of a\n * 40-row Jobs grid read \"Loading…\" for 10–13 seconds with the rest of the grid\n * drawn and readable behind it. The bulk resolver below has since made that ~0.1 s\n * on the same real table — but \"Loading…\" is a word with no remedy in it, and\n * the moment a target table is big, a network is slow or a reader holds fewer\n * rows than the column points at, it is back to being a dead column that tells\n * nobody anything. A stand-in announces itself: after one second this column\n * says what it went to read.\n */\nfunction waitingLineFor(field: Field, target: string | null): string {\n return field.type === \"list\"\n ? \"Reading this column’s list of choices…\"\n : `Reading the ${target ?? \"records\"} this column points at…`;\n}\n\n/** Which ids a Field's stored value refers to. */\nexport function idsOf(value: unknown): string[] {\n if (Array.isArray(value)) return value.map(String).filter(isId);\n if (typeof value === \"string\" && isId(value)) return [value];\n return [];\n}\n\n/** Where a choice's words are kept under its KEY (ids and keys never collide: a key is no uuid). */\nexport function choiceKeyName(fieldId: string, key: string): string {\n return `${fieldId}\\u0000key\\u0000${key}`;\n}\n\nexport function isId(value: unknown): boolean {\n return typeof value === \"string\" && isUuidShape(value);\n}\n\n/** Whether the grid's own cell copy resolves this column through `shownValue` rather than the raw value. */\nexport function copiesAsWords(field: Field): boolean {\n return pointsAtRecords(field) || isSignatureField(field) || autonumberPrefixOf(field) !== \"\";\n}\n\n/** True when this Field's values are ids of other records rather than values. */\nexport function pointsAtRecords(field: Field): boolean {\n return field.type === \"list\" || field.type === \"relation\";\n}\n\n/**\n * WHAT THE PERSON SEES, NOT WHAT THE STORE KEEPS (GRID-PORT finding, 2026-09-24). A relation or a\n * choice stores the ID of the record it points at; the grid draws that record's words (\"Ojeda\n * residence\", \"Scheduled\"), and the older grid's export wrote those words too. So an exported,\n * copied or Copy-for-AI cell carries the same words the grid shows: each id resolved through the one label resolver the\n * grid uses (`useRecordLabels`). An id nobody could resolve stays the id, rather than a blank that\n * would claim the cell was empty. A worked-out column already holds the store's worked-out value.\n */\nexport function shownValue(field: Field, value: unknown, labels?: LabelLookup): unknown {\n // A DRAWN SIGNATURE is \"Signed\" wherever words are copied or exported — never its image data\n // (a spreadsheet cell cannot show it, and Excel cuts a cell at 32,767 characters). A name a\n // sealed document wrote stays the name (`signature.tsx`).\n if (isSignatureField(field)) return signatureWords(value);\n // NOTION-PROPS-3: a record number is copied as it is shown, with its prefix (TASK-42).\n if (autonumberPrefixOf(field)) return autonumberWords(field, value) ?? value;\n // An address, a length of time, who made it — copied and exported in words (lane 10 P4).\n const newerWords = value === null || value === undefined ? null : newerKindExportWords(field, value);\n if (newerWords !== null) return newerWords;\n // A PLUG-IN LOOK (`looks/`) is copied and exported in its format's words (\"16 px\", \"#fff / #000\").\n const look = value === null || value === undefined ? undefined : registeredLook(shownAsOf(field));\n if (look) {\n const read = formatFieldValue(value, look);\n if (read.ok && !read.empty) return read.text;\n }\n if (!labels || !pointsAtRecords(field)) return value;\n const ids = idsOf(value);\n if (ids.length === 0) return value;\n const words = ids.map((id) => labels(field, id) ?? id);\n return Array.isArray(value) ? words : words[0];\n}\n\nexport function RecordLabelProvider({ children }: { children: ReactNode }) {\n const client = useRecordsClient();\n const [names, setNames] = useState<Record<string, string>>({});\n /** `${field.id}:${id}` of every referenced record the store says is archived. */\n const [archivedRefs, setArchivedRefs] = useState<Record<string, true>>({});\n /** id → the record's icon and its table's icon, learned with its words. */\n const [iconsOf, setIconsOf] = useState<Record<string, { icon: string | null; tableIcon: string | null }>>({});\n // Which Fields have FINISHED looking. Until a Field is in here its ids are\n // still loading; once it is in here, an id that is still missing is missing\n // for a reason, and the reason is asked for rather than waited out.\n const [settled, setSettled] = useState<Record<string, true>>({});\n /** Per Field: the sentence a cell shows once it has waited long enough to owe one. */\n const [waitingLines, setWaitingLines] = useState<Record<string, string>>({});\n const asked = useRef<Set<string>>(new Set());\n const chased = useRef<Set<string>>(new Set());\n const timers = useRef<Map<string, ReturnType<typeof setTimeout>>>(new Map());\n\n /** Start this Field's one-second clock. Cleared the moment it settles. */\n const startWaitClock = useCallback((field: Field, target: string | null) => {\n if (timers.current.has(field.id)) return;\n timers.current.set(\n field.id,\n setTimeout(() => {\n timers.current.delete(field.id);\n setWaitingLines((current) =>\n current[field.id] ? current : { ...current, [field.id]: waitingLineFor(field, target) },\n );\n }, SAY_WHAT_YOU_ARE_WAITING_FOR_AFTER_MS),\n );\n }, []);\n\n const stopWaitClock = useCallback((fieldId: string) => {\n const timer = timers.current.get(fieldId);\n if (timer) {\n clearTimeout(timer);\n timers.current.delete(fieldId);\n }\n setWaitingLines((current) => {\n if (!current[fieldId]) return current;\n const next = { ...current };\n delete next[fieldId];\n return next;\n });\n }, []);\n\n useEffect(\n () => () => {\n for (const timer of timers.current.values()) clearTimeout(timer);\n timers.current.clear();\n },\n [],\n );\n\n const want = useCallback(\n (field: Field) => {\n if (!pointsAtRecords(field)) return;\n if (asked.current.has(field.id)) return;\n asked.current.add(field.id);\n startWaitClock(field, null);\n\n void (async () => {\n if (field.type === \"list\") {\n const result = await fieldOptionsOnce(client, field.id);\n if (result.ok) {\n setNames((current) => {\n const next = { ...current };\n for (const option of result.data ?? []) {\n const words = recordName(option.data as RecordDocument | undefined, null, \"Unnamed choice\");\n next[option.id] = words;\n // A CHOICE HELD BY ITS KEY READS AS ITS WORDS TOO (DATA-V2-BASICS-2): a moved list\n // and the enum nudge's Add keep `backordered`, and the grid printed the key.\n const key = optionKey(option as unknown as StoredRecord);\n if (key) next[choiceKeyName(field.id, key)] = words;\n }\n return next;\n });\n }\n setSettled((current) => ({ ...current, [field.id]: true }));\n stopWaitClock(field.id);\n return;\n }\n // ── A RELATION'S WORDS ARE THE STORE'S ANSWER, NOT THIS FILE'S (lane\n // RELATION-DISPLAY-2, 2026-09-21). ───────────────────────────────────────────\n // This branch used to read 200 rows of the target Table plus `tableList()`, find\n // the Table's `title_field` and name every row itself. That was one of three\n // copies of the same derivation, and it had three faults nobody could fix here:\n //\n // · IT COULD NOT SEE A DISPLAY SPEC. REL-DISP lets a column say it shows\n // `first_name` + \" \" + `last_name`; this code knew only `title_field`, so\n // Rincon Plumbing's two Maria Chens stayed two identical chips no matter\n // what the column was configured to show.\n // · A 200-ROW CEILING. The 201st customer was never in the prefetch and fell\n // through to the per-id chase, so a big table quietly changed how it resolved.\n // · IT NAMED WHAT IT COULD READ. The read-access ladder runs inside the store's\n // `custom._words_for`; a name assembled out here has already been read.\n //\n // So the relation branch fetches NOTHING up front. It settles immediately, and\n // the ids the page actually draws go through the queue below into ONE\n // `relation_words_many` call per Field per tick — the store's own resolver,\n // this column's own display spec, the ladder asked before the name is read.\n if (!field.relation_target) {\n setSettled((current) => ({ ...current, [field.id]: true }));\n stopWaitClock(field.id);\n return;\n }\n setSettled((current) => ({ ...current, [field.id]: true }));\n })();\n },\n [client, startWaitClock, stopWaitClock],\n );\n\n // ── WHAT AN ID IS CALLED IS THE STORE'S QUESTION (RELATION-DECLARE 2026-09-20 ·\n // FRONT-DOOR 2026-09-21 · RELATION-DISPLAY-2 2026-09-21). ────────────────────────────\n //\n // A relation joins two records in two tables, and holding one end says nothing about\n // the other: a Job shared with you may point at a Client nobody shared. The three\n // possible answers for such a chip are the target's TITLE (a leak), a bare id (a bug\n // with a hex number in it) and a permanent \"Loading…\" (a lie with a spinner on it) —\n // and picking between them is not a decision a screen is entitled to make, because the\n // screen does not know the ladder.\n //\n // So the screen does not decide. Every id a cell draws is asked of the store's ONE\n // resolver through `relation_words_many`, which:\n // · applies THIS column's display spec — one column, or several joined by its own\n // separator, which is the whole of REL-DISP and which nothing out here could do;\n // · asks the read-access ladder BEFORE it reads a name, so a record this reader may\n // not open comes back withheld rather than named;\n // · answers a WHOLE PAGE in one round trip, with no 200-row ceiling anywhere.\n //\n // 🚨 ONE ROUND FOR THE WHOLE PAGE, NOT ONE PER CELL (FRONT-DOOR). The first version of\n // this chase fired the moment a cell asked and committed its own `setNames`, so forty\n // rows cost forty round trips AND forty re-renders of every cell on the page. The ids\n // therefore still GATHER and flush once a tick — that part was right and is kept. What\n // changes is that the flush is now ONE call per Field instead of one per id: the batch\n // door this file's own comment recorded as missing (\"there is still no batch door on\n // the store\") exists as of REL-DISP, so the per-id lane is gone entirely.\n //\n // AN ID THE DOOR GAVE NO WORDS FOR is not a missing name, it is a withheld one: the\n // door answered, and the answer was nothing. It reads the SAME SENTENCE the store\n // itself gives (`platform.relation_withheld_label()`), never the title, never the id,\n // and never a \"Loading…\" that resolves for nobody.\n const queued = useRef<Map<string, { field: Field; ids: Set<string> }>>(new Map());\n const flushing = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const flush = useCallback(() => {\n flushing.current = null;\n const batch = [...queued.current.values()];\n queued.current.clear();\n if (batch.length === 0) return;\n void (async () => {\n const learned: Record<string, string> = {};\n const archivedNow: Record<string, true> = {};\n const iconsNow: Record<string, { icon: string | null; tableIcon: string | null }> = {};\n // One call per FIELD — each one carries that field's whole page of ids. Several\n // relation columns on one grid are several calls, which is the number of distinct\n // display specs in play and cannot be fewer.\n await Promise.all(\n batch.map(async ({ field, ids }) => {\n const wanted = [...ids];\n const result = await client.relationWordsMany({\n field_id: field.id,\n record_ids: wanted as Uuid[],\n });\n for (const id of wanted) {\n const words = result.ok ? result.data[id] : undefined;\n // A FAILED read is unread, never withheld — only an answer of nothing is withheld.\n learned[id] = !result.ok\n ? UNREAD_RECORD_LABEL\n : typeof words === \"string\" && words !== \"\"\n ? words\n : WITHHELD_RECORD_LABEL;\n }\n if (result.ok) for (const id of result.archived ?? []) archivedNow[`${field.id}:${id}`] = true;\n if (result.ok) for (const [id, pair] of Object.entries(result.icons ?? {})) iconsNow[id] = pair;\n }),\n );\n // ONE commit for the whole page.\n setNames((current) => ({ ...current, ...learned }));\n if (Object.keys(archivedNow).length > 0) setArchivedRefs((current) => ({ ...current, ...archivedNow }));\n if (Object.keys(iconsNow).length > 0) setIconsOf((current) => ({ ...current, ...iconsNow }));\n for (const { field } of batch) stopWaitClock(field.id);\n })();\n }, [client, stopWaitClock]);\n\n const chase = useCallback(\n (field: Field, id: string) => {\n const key = `${field.id}:${id}`;\n if (chased.current.has(key)) return;\n chased.current.add(key);\n // Grouped BY FIELD, because the door's question is \"what does THIS column call\n // these records\" — the display spec belongs to the column, so two columns pointing\n // at the same table can legitimately give the same id two different answers. The\n // old map was keyed by id alone and would have collapsed exactly that case.\n const pending = queued.current.get(field.id);\n if (pending) pending.ids.add(id);\n else queued.current.set(field.id, { field, ids: new Set([id]) });\n startWaitClock(field, null);\n if (flushing.current === null) flushing.current = setTimeout(flush, 0);\n },\n [flush, startWaitClock],\n );\n\n useEffect(\n () => () => {\n if (flushing.current !== null) clearTimeout(flushing.current);\n },\n [],\n );\n\n /** A choice key this page has not seen yet asks the Field's options again, once per key. */\n const rereadFor = useRef<Set<string>>(new Set());\n const lookupWords = useCallback(\n (field: Field, id: string): string | null => {\n if (field.type === \"list\" && !isId(id)) {\n const named = names[choiceKeyName(field.id, id)];\n if (named !== undefined) return named;\n const once = choiceKeyName(field.id, id);\n if (settled[field.id] && !rereadFor.current.has(once)) {\n // A choice added after the options were read (the nudge's Add): read them again.\n rereadFor.current.add(once);\n asked.current.delete(field.id);\n want(field);\n }\n return null;\n }\n const known = names[id];\n if (known !== undefined) return known;\n if (settled[field.id]) chase(field, id);\n return null;\n },\n [names, settled, chase, want],\n );\n const lookup = useMemo<LabelLookup>(\n () => {\n const answer = ((field: Field, id: string) => lookupWords(field, id)) as LabelLookup;\n answer.archived = (field: Field, id: string) => archivedRefs[`${field.id}:${id}`] === true;\n answer.icons = (_field: Field, id: string) => iconsOf[id];\n return answer;\n },\n [lookupWords, archivedRefs, iconsOf],\n );\n\n const waiting = useCallback((field: Field) => waitingLines[field.id] ?? null, [waitingLines]);\n\n const value = useMemo(() => ({ lookup, want, waiting }), [lookup, want, waiting]);\n return <LabelContext.Provider value={value}>{children}</LabelContext.Provider>;\n}\n\n/**\n * The hook a surface uses: it declares the Fields it is about to draw, and gets\n * back the lookup. Declaring is what makes one request per Field instead of one\n * per cell, and it is why a grid of 200 rows asks the store twice.\n */\nexport function useRecordLabels(fields: readonly Field[] | undefined): LabelLookup {\n const { lookup, want } = useContext(LabelContext);\n useEffect(() => {\n for (const field of fields ?? []) want(field);\n }, [fields, want]);\n return lookup;\n}\n\n/**\n * WHAT THIS COLUMN IS STILL WAITING FOR, or null while \"Loading…\" is still an\n * honest word. A cell draws this INSTEAD of \"Loading…\" once the resolver has\n * been looking for a second — see `SAY_WHAT_YOU_ARE_WAITING_FOR_AFTER_MS`.\n */\nexport function useLabelWait(field: Field | undefined): string | null {\n const { waiting } = useContext(LabelContext);\n return field ? waiting(field) : null;\n}\n","\"use client\";\n\n// src/PersonPicker.tsx — @ai-matrx/records-ui · FLD-11 (`member`)\n//\n// PICKING A PERSON MEANS PICKING A PERSON.\n//\n// What it replaced, measured on the real screen (independent verdict, 19\n// September): the \"Owner\" field — which the settings panel itself calls a\n// Person field — offered \"Comments Home\", \"Saved views Home\" and \"V78 Home\".\n// Those are not people. They are the Home records this package writes into the\n// kernel Person Table so that its own Tables have somewhere to live (REC-1),\n// and the generic relation picker was listing the Table's contents, which is\n// exactly right for a relation and exactly wrong for a person.\n//\n// SO A PERSON FIELD ASKS A DIFFERENT QUESTION. The list is the ORGANIZATION'S\n// MEMBERS — who those are is the platform's answer and not the record store's,\n// so it arrives through the `members` port on the host, the same way saved\n// views and file uploads do. The record store has no door onto organization\n// membership and this package does not invent one.\n//\n// WHAT IS STORED IS STILL A RECORD ID, because a member field is a relation to\n// the kernel Person Table and the store's foreign key is real. So picking a\n// member resolves that member to their Person record — by the `user_id` the\n// record carries — and writes one when the organization has not got one yet.\n// That write is the same `record_write` everything else in this package uses;\n// there is no second storage path, and a Home (a Person record with no\n// `user_id`) is never offered and never picked.\n//\n// Unbound port: the control is ABSENT with its reason, never a dead box and\n// never a list of the wrong things.\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { Field, ReadRow, RecordsError, Uuid } from \"@ai-matrx/records\";\nimport { rankTypedMatches } from \"@ai-matrx/records\";\nimport { useOptionalRecordsClient } from \"@ai-matrx/records/react\";\nimport type { RecordsClient } from \"@ai-matrx/records/core\";\nimport { cn } from \"@ai-matrx/design-system\";\n\nimport { PickOrAdd } from \"./PickOrAdd\";\nimport { PersonChip } from \"./personChip\";\nimport { useRecordsUi, type OrganizationMember } from \"./host\";\nimport { NO_MEMBERS_REASON } from \"./host\";\nimport { fieldName } from \"./names\";\nimport { RefusalLine } from \"./Refusal\";\n\nexport interface PersonPickerProps {\n field: Field;\n value: unknown;\n onChange: (value: unknown) => void;\n disabled?: boolean | undefined;\n id?: string | undefined;\n className?: string | undefined;\n /** A grid cell's picker opens at once (`FieldEditorControlProps.autoOpen`). */\n autoOpen?: boolean | undefined;\n /** The list closed: the cell commits who is picked. */\n onClose?: (() => void) | undefined;\n /** Escape in a grid cell's list: the cell's cancel — nothing is written (`PickOrAdd.onEscape`). */\n onCancel?: (() => void) | undefined;\n /** What was typed to open a grid cell's list: its first search (`FieldEditorControlProps.initialSearch`). */\n initialSearch?: string | undefined;\n}\n\n/** A Person record in the kernel Table, as this picker needs to read it. */\nexport interface PersonRecord {\n id: Uuid;\n userId: string | null;\n name: string;\n}\n\nexport function personFromRow(row: Pick<ReadRow, \"id\" | \"document\">): PersonRecord {\n const data = (row.document ?? {}) as Record<string, unknown>;\n const userId = data[\"user_id\"];\n return {\n id: row.id,\n userId: typeof userId === \"string\" && userId !== \"\" ? userId : null,\n name: String(data[\"full_name\"] ?? data[\"name\"] ?? data[\"email\"] ?? \"\").trim(),\n };\n}\n\n/** The member's own name, as a person reads it. Never a uuid. */\nexport function memberName(member: OrganizationMember): string {\n const display = (member.name ?? \"\").trim();\n if (display !== \"\") return display;\n const email = (member.email ?? \"\").trim();\n if (email !== \"\") return email;\n return \"A member with no name set\";\n}\n\n/**\n * Find (or write) the kernel Person record for one member. Exported because\n * an agent filling a person field server-side needs exactly the same answer,\n * and two implementations of \"which record is this person\" is two answers.\n */\nexport async function personRecordForMember(\n client: RecordsClient,\n personTableId: Uuid,\n people: PersonRecord[],\n member: OrganizationMember,\n): Promise<{ ok: true; data: Uuid } | { ok: false; error: RecordsError }> {\n const held = people.find((p) => p.userId === member.userId);\n if (held) return { ok: true, data: held.id };\n const written = await client.recordWrite({\n table_id: personTableId,\n data: {\n user_id: member.userId,\n full_name: memberName(member),\n ...(member.email ? { email: member.email } : {}),\n },\n });\n return written;\n}\n\nexport function PersonPicker({ field, value, onChange, disabled, id, className, autoOpen, onClose, onCancel, initialSearch }: PersonPickerProps) {\n // NOT `useRecordsClient`. This control is drawn by `FieldControl`, and\n // `FieldControl` is drawn by the PUBLIC arm of `FormRunner`, which mounts no\n // store client at all — the hook that throws turned a stranger's form into an\n // HTTP 500 (VERIFIER-10, F1). With no client there is nobody to offer, which\n // is the same answer this control already gives an unbound `members` port.\n const client = useOptionalRecordsClient();\n const host = useRecordsUi();\n const [members, setMembers] = useState<OrganizationMember[] | null>(null);\n const [people, setPeople] = useState<PersonRecord[]>([]);\n const [error, setError] = useState<RecordsError | null>(null);\n const [search, setSearch] = useState(initialSearch ?? \"\");\n const [open, setOpenState] = useState(autoOpen === true);\n const onCloseRef = useRef(onClose);\n onCloseRef.current = onClose;\n // Closing the list — a pick, Escape, a click away — is what a grid cell commits on.\n const setOpen = useCallback((next: boolean) => {\n setOpenState(next);\n if (!next) onCloseRef.current?.();\n }, []);\n const [busy, setBusy] = useState(false);\n\n const membersPort = host.members;\n const personTable = field.relation_target;\n\n const picked = useMemo<string[]>(\n () => (Array.isArray(value) ? value.map(String) : value === null || value === undefined ? [] : [String(value)]),\n [value],\n );\n\n const load = useCallback(async () => {\n if (!membersPort || !client) return;\n const [roster, records] = await Promise.all([\n membersPort(),\n personTable ? client.list({ table_id: personTable, limit: 500 }) : Promise.resolve(null),\n ]);\n setMembers(roster);\n if (records && !records.ok) {\n setError(records.error);\n return;\n }\n setPeople(records ? records.data.rows.map(personFromRow).filter((p) => p.userId !== null) : []);\n }, [membersPort, client, personTable]);\n\n useEffect(() => {\n if (!open) return;\n void load();\n }, [open, load]);\n\n // The names of the records that are already picked, whether or not the list\n // has been opened — a chip that read `8f2c1b0a` is the defect this closes.\n useEffect(() => {\n if (picked.length === 0 || !personTable || people.length > 0 || !client) return;\n let cancelled = false;\n void client.list({ table_id: personTable, limit: 500 }).then((result) => {\n if (cancelled || !result.ok) return;\n setPeople(result.data.rows.map(personFromRow).filter((p) => p.userId !== null));\n });\n return () => {\n cancelled = true;\n };\n }, [client, personTable, picked.length, people.length]);\n\n // THE ONE RANKING (`rankTypedMatches`, grids review 3): exact, starts with, a word starts with, contains.\n const listed = rankTypedMatches(members ?? [], search, memberName);\n\n if (!membersPort || !client) {\n // ABSENT AND HONEST. A person question with nobody to offer is not a box\n // that silently does nothing — it names the port that fills it.\n return <p className={cn(\"text-xs text-muted-foreground\", className)}>{NO_MEMBERS_REASON}</p>;\n }\n\n if (!personTable) {\n return (\n <p className={cn(\"text-xs text-muted-foreground\", className)}>\n {fieldName(field)} is a person field, but it does not say which Table the people are\n records of yet, so there is nothing to pick from. A table admin sets its target in the field\n editor.\n </p>\n );\n }\n\n // ONE PERSON, ONE NAME (lane CELL-EDITORS, 2026-10-06): the chip read \"admin\" (the Person record)\n // while the list read \"admin@admin.com\" (a member with no display name). The display name is the\n // member's own, else the Person record's; the email is shown beside it, and alone only when there is\n // no name at all.\n const displayNameOf = (userId: string | null, recordName?: string): string | null => {\n const member = userId ? (members ?? []).find((m) => m.userId === userId) : undefined;\n const own = (member?.name ?? \"\").trim();\n if (own !== \"\") return own;\n const kept = (recordName ?? people.find((p) => p.userId === userId)?.name ?? \"\").trim();\n const email = (member?.email ?? \"\").trim();\n return kept !== \"\" && kept !== email ? kept : null;\n };\n const nameOfRecord = (recordId: string) => {\n const person = people.find((p) => p.id === recordId);\n if (!person) return \"Loading…\";\n const member = (members ?? []).find((m) => m.userId === person.userId);\n return displayNameOf(person.userId, person.name) ?? (member ? memberName(member) : person.name || \"A member with no name set\");\n };\n\n const pick = async (member: OrganizationMember) => {\n setBusy(true);\n setError(null);\n const resolved = await personRecordForMember(client, personTable, people, member);\n setBusy(false);\n if (!resolved.ok) {\n setError(resolved.error);\n return;\n }\n // Keep the newly written record so the chip can be named at once.\n if (!people.some((p) => p.id === resolved.data)) {\n setPeople((held) => [...held, { id: resolved.data, userId: member.userId, name: memberName(member) }]);\n }\n if (!field.multi) {\n onChange(picked[0] === resolved.data ? null : resolved.data);\n setOpen(false);\n return;\n }\n const next = new Set(picked);\n if (next.has(resolved.data)) next.delete(resolved.data);\n else next.add(resolved.data);\n onChange(next.size === 0 ? null : [...next]);\n };\n\n const drop = (recordId: string) => {\n const next = picked.filter((id) => id !== recordId);\n onChange(next.length === 0 ? null : field.multi ? next : (next[0] ?? null));\n };\n\n const visible = listed;\n const pickedUserIds = new Set(\n picked.map((recordId) => people.find((p) => p.id === recordId)?.userId).filter(Boolean),\n );\n\n const anchored = autoOpen === true;\n const cellChips = picked.map((recordId) => (\n <PersonChip key={recordId} name={nameOfRecord(recordId)} {...(disabled || anchored ? {} : { onRemove: () => drop(recordId) })} />\n ));\n\n return (\n <div className={cn(\"flex flex-wrap items-center gap-1\", className)}>\n {anchored && !disabled ? null : cellChips}\n {disabled ? null : (\n // THE ONE \"PICK OR ADD\" BUILDER (lane CELL-EDITORS, 2026-10-06): the person list used to carry\n // its own copy of the list's layout and keys; it now draws the same rows, ticks, highlight and\n // head chips as every other picker, and in a grid cell hangs from the cell.\n <PickOrAdd\n {...(anchored && onCancel ? { onEscape: onCancel } : {})}\n anchored={anchored}\n multi={field.multi}\n triggerId={id}\n triggerLabel={`Pick a person for ${fieldName(field)}`}\n triggerText={picked.length === 0 ? \"Pick a person\" : \"Change\"}\n open={open}\n onOpenChange={setOpen}\n search={search}\n onSearch={setSearch}\n chips={picked.map((recordId) => ({ id: recordId, label: nameOfRecord(recordId), person: true, onRemove: () => drop(recordId) }))}\n items={visible.map((member) => ({\n id: member.userId,\n label: displayNameOf(member.userId) ?? memberName(member),\n // A name and an email with nothing between them read as one run-on string (verdict,\n // 19 September). They are two facts, so they are drawn as two.\n detail: displayNameOf(member.userId) !== null && member.email ? member.email : null,\n picked: pickedUserIds.has(member.userId),\n person: true,\n disabled: busy,\n }))}\n onPick={(userId) => {\n const member = visible.find((m) => m.userId === userId);\n if (member && !busy) void pick(member);\n }}\n notice={\n <>\n {error ? <RefusalLine error={error} className=\"p-2\" /> : null}\n {members === null ? <p className=\"p-2 text-xs text-muted-foreground\">Reading the members…</p> : null}\n </>\n }\n empty={\n members !== null ? (\n <p className=\"p-2 text-xs text-muted-foreground\">\n {members.length === 0\n ? \"This organization has no other members yet, so there is nobody to assign.\"\n : \"Nobody in this organization matches.\"}\n </p>\n ) : null\n }\n >\n {anchored ? cellChips : null}\n </PickOrAdd>\n )}\n </div>\n );\n}\n","\"use client\";\n\n// src/ReferenceBuilder.tsx — @ai-matrx/records-ui · REL-DISP\n//\n// THE ONE PLACE A REFERENCE TO ANOTHER TABLE IS BUILT.\n//\n// The owner's ruling, 2026-09-21: *a column that offers choices from ANOTHER\n// table is a relation; the stored value is always the id; what is DISPLAYED is\n// resolved by one primitive.* This is the UI half — one component, so the\n// question \"which table, and which of its columns do I read?\" is asked once and\n// answered the same way wherever it is asked: declaring a column in the field\n// editor, changing one from the grid's column settings, referencing a relation\n// in a condition, a form, or a portal.\n//\n// WHAT IT ASKS, IN THE ORDER A PERSON THINKS OF IT\n// 1. which table its records come from;\n// 2. what a record of that table is called TODAY — its own reference column,\n// shown rather than hidden, because the honest default is a fact the person\n// should see before they decide to override it;\n// 3. only if they want it, WHICH columns to show instead, in order, and what\n// goes between them — the \"first name\" + \" \" + \"last name\" the store could\n// not express at all before REL-DISP;\n// 4. a preview built from that table's REAL first rows, so the answer is read\n// rather than imagined.\n//\n// WHY THIS EXISTS RATHER THAN A FOURTH COPY. Before this component, three\n// separate implementations of \"read tableList, find title_field, call rowName\"\n// lived in labels.tsx, RelationPicker.tsx and PortalsPanel.tsx, and the only\n// target-table picker was `TableToPointAt`, private inside FieldEditor.tsx. Four\n// places to fix, four places to forget, and not one of them could ever have\n// shown two columns joined.\n//\n// THE STORE IS THE AUTHORITY AND THIS IS A PREVIEW. `previewWords` below mirrors\n// the display arm of `custom._words_for` so the panel can show an answer for a\n// column that does not exist yet — a declaration has no field id to ask about.\n// It is deliberately NOT the resolver: once a column exists, its words come from\n// `client.relationWords` / `client.relationWordsMany`, which ask the read-access\n// ladder before they read a name. Nothing renders a real cell from this function.\n\nimport { useMemo, useState } from \"react\";\nimport type { Field, RecordsError, RelationDisplay, Uuid } from \"@ai-matrx/records\";\nimport { useFields, useRecords, useRecordsClient } from \"@ai-matrx/records/react\";\nimport { DOORS, doorReady, ensureTable } from \"@ai-matrx/records/core\";\nimport { tokenFor, type NewFieldSpec } from \"./createTable\";\nimport { RefusalNotice } from \"./Refusal\";\nimport { ShowListsToggle, tablePickerEntries, usePickerTables } from \"./tablePicking\";\nimport {\n Button,\n Checkbox,\n Label,\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n BasicInput,\n cn,\n} from \"@ai-matrx/design-system\";\nimport { looksLikeId, tableName } from \"./names\";\n\n/** What a person has chosen: the table, and optionally which of its columns to show. */\nexport interface ReferenceChoice {\n /** The Table whose records this column offers. `\"\"` until one is picked. */\n targetTableId: Uuid | \"\";\n /** Which of that Table's columns to show. `null` = the Table's own reference column. */\n display: RelationDisplay | null;\n}\n\nexport interface ReferenceBuilderProps {\n /** The Table the column being built lives on, so \"this table\" can be marked. */\n tableId: Uuid;\n value: ReferenceChoice;\n onChange: (next: ReferenceChoice) => void;\n /**\n * A Person or File column points at a kernel Table the person does not choose.\n * The target picker is then not shown — but which columns to display still is,\n * because that half is theirs either way.\n */\n lockTarget?: boolean | undefined;\n className?: string | undefined;\n}\n\nconst DEFAULT_SEPARATOR = \" \";\n\n/** The Select's own value for \"New table…\" — never a table id, so it can never be saved as one. */\nconst NEW_TABLE = \"__records_ui_new_table__\";\n\n/**\n * THE PRIMARY COLUMN A TABLE MADE FROM THE LINK PICKER IS BORN WITH (T4.3, lane 10 sublane LT).\n * Airtable's new table opens with \"Name\" as its primary field; a table a person makes in order to\n * point at it (\"Referring Physicians\") is a list of named things, so its records are titled by a\n * Name and the link's chips read as those names from the first record on.\n */\nconst LINK_TARGET_FIELDS: NewFieldSpec[] = [\n { key: \"name\", label: \"Name\", type: \"text\", sort: 10, required: false },\n];\n\n/**\n * The client mirror of `custom._words_for`'s display arm, for the PREVIEW only.\n * Same order, same blank-dropping, same refusal to print an id — a preview that\n * disagreed with the store about what a chip says would be worse than none.\n */\nexport function previewWords(\n document: Record<string, unknown> | undefined,\n display: RelationDisplay | null,\n titleField: string | null,\n): string {\n const data = document ?? {};\n const read = (key: string): string => {\n const raw = data[key];\n if (typeof raw === \"number\") return String(raw);\n if (typeof raw !== \"string\") return \"\";\n const trimmed = raw.trim();\n // An id is never a name. The store resolves one hop here; a preview cannot\n // (it holds only this table's rows) and says so rather than printing a uuid.\n if (looksLikeId(trimmed)) return \"…\";\n return trimmed;\n };\n\n if (display && display.columns.length > 0) {\n const parts = display.columns.map(read).filter((part) => part !== \"\");\n if (parts.length > 0) return parts.join(display.separator ?? DEFAULT_SEPARATOR);\n // Falls through exactly as the store does: the named columns hold nothing on\n // THIS record, so the table's own answer is shown rather than an empty chip.\n }\n for (const key of [titleField, \"title\", \"name\", \"label\", \"full_name\", \"company\", \"subject\"]) {\n if (!key) continue;\n const value = read(key);\n if (value !== \"\" && value !== \"…\") return value;\n }\n // The store's last resort, mirrored: the first words the record holds in key\n // order, skipping its own machinery and anything uuid-shaped.\n for (const key of Object.keys(data).sort()) {\n if (key.startsWith(\"_\") || key === \"id\" || key === \"table_id\") continue;\n const value = read(key);\n if (value !== \"\" && value !== \"…\") return value;\n }\n return \"an untitled record\";\n}\n\n/**\n * THE COLUMNS OF THE TABLE ON THE OTHER SIDE.\n *\n * A Table the STORE keeps itself still has columns: `custom.applicable_fields`\n * answers what a table DECLARES, and the kernels declare none — a Person column\n * points at the person kernel, which has records and zero Field rows. So when\n * the target declares nothing, one of its records is read through the ordinary\n * door and the keys it actually carries are offered. Same fact, asked the way\n * the store will ask it.\n */\nfunction useTargetColumns(target: Uuid | null): { keys: string[]; loading: boolean } {\n const declared = useFields(target);\n const usable = (declared.data ?? []).filter((f: Field) => f.type !== \"formula\");\n const needSample = usable.length === 0 && !declared.loading && target !== null;\n const sample = useRecords(needSample ? target : null, { pageSize: 1 });\n return useMemo(() => {\n if (usable.length > 0) return { keys: usable.map((f) => f.key), loading: false };\n const carried = sample.data?.rows[0]?.document ?? null;\n if (!carried) return { keys: [], loading: declared.loading || sample.loading };\n return {\n keys: Object.keys(carried).filter((k) => !k.startsWith(\"_\")),\n loading: false,\n };\n }, [usable, sample.data, declared.loading, sample.loading]);\n}\n\nexport function ReferenceBuilder({\n tableId,\n value,\n onChange,\n lockTarget,\n className,\n}: ReferenceBuilderProps) {\n const tables = usePickerTables();\n const client = useRecordsClient();\n // \"NEW TABLE…\" (T4.3). `null` = the name box is closed; a string = what she has typed so far.\n const [naming, setNaming] = useState<string | null>(null);\n const [making, setMaking] = useState(false);\n const [refused, setRefused] = useState<RecordsError | null>(null);\n // The table just made, offered at once — before the re-read of the organization's tables lands.\n const [born, setBorn] = useState<{ id: Uuid; name: string } | null>(null);\n const target = (value.targetTableId || null) as Uuid | null;\n const columns = useTargetColumns(target);\n const preview = useRecords(target, { pageSize: 3 });\n\n const targetTable = (tables.data ?? []).find((t) => t.id === target) ?? null;\n const titleField = targetTable?.title_field ?? null;\n\n // \"Show more than one column\" is OPEN when a spec already exists — a person\n // editing a column that joins two names should see that, not a closed tick.\n const [overriding, setOverriding] = useState(value.display !== null);\n\n // TABLES ONLY, unless \"Show lists\" — the choice lists every choice column keeps were 64 entries\n // here, \"Status choices\" five times (`tablePicking.ts`, the one rule every table picker uses).\n const [showLists, setShowLists] = useState(false);\n const picking = useMemo(\n () =>\n tablePickerEntries(\n [\n ...(tables.data ?? []).map((t) => ({ ...t, name: tableName(t) })),\n ...(born && !(tables.data ?? []).some((t) => t.id === born.id) ? [born] : []),\n ],\n { showLists, keep: value.targetTableId || null },\n ),\n [tables.data, showLists, value.targetTableId, born],\n );\n const offered = picking.entries;\n\n /**\n * MAKE THE TABLE, LINK THE COLUMN TO IT, STAY HERE. Through the store's own doors, in the active\n * organization (the client's — where every write goes):\n * · `tableFind` by the slug the name makes — a table of that address she can see is the one she\n * means, and it is picked as it stands (`ensureTable` would otherwise ADD a Name column to it);\n * · otherwise `ensureTable` (`custom.table_ensure`, one transaction) makes it with a Name column.\n * A refusal keeps the name box open with what she typed, and says the store's own sentence.\n */\n const makeTable = async () => {\n const name = (naming ?? \"\").trim();\n if (!name || making) return;\n setMaking(true);\n setRefused(null);\n const slug = tokenFor(name);\n const found = await client.tableFind({ slug });\n if (!found.ok) {\n setMaking(false);\n setRefused(found.error);\n return;\n }\n const existing =\n found.data && !(found.data as { kept_for?: string | null }).kept_for ? found.data : null;\n let id: Uuid;\n let bornName = name;\n if (existing) {\n id = existing.id as Uuid;\n bornName = tableName(existing);\n } else {\n const made = await ensureTable(client, {\n name,\n slug,\n titleField: \"name\",\n fields: LINK_TARGET_FIELDS,\n });\n if (!made.ok) {\n setMaking(false);\n setRefused(made.error);\n return;\n }\n id = made.data;\n }\n setMaking(false);\n setNaming(null);\n setBorn({ id, name: bornName });\n tables.reload();\n onChange({ targetTableId: id, display: null });\n };\n\n /** \"New table…\" is offered only where the store has the two doors it calls (absent before the chair's apply). */\n const mayMakeTable = doorReady(client.config, DOORS.tableFind) && doorReady(client.config, DOORS.tableEnsure);\n const newTableButton = !mayMakeTable ? null : (\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"outline\"\n className=\"self-start\"\n onClick={() => {\n setRefused(null);\n setNaming(\"\");\n }}\n >\n New table…\n </Button>\n );\n\n const display = value.display;\n const chosen = display?.columns ?? [];\n const separator = display?.separator ?? DEFAULT_SEPARATOR;\n\n const setDisplay = (next: RelationDisplay | null) => onChange({ ...value, display: next });\n\n const toggleColumn = (key: string) => {\n const next = chosen.includes(key) ? chosen.filter((k) => k !== key) : [...chosen, key];\n setDisplay(next.length === 0 ? null : { columns: next, separator });\n };\n\n const move = (key: string, by: -1 | 1) => {\n const at = chosen.indexOf(key);\n const to = at + by;\n if (at < 0 || to < 0 || to >= chosen.length) return;\n const next = chosen.slice();\n next.splice(to, 0, next.splice(at, 1)[0]!);\n setDisplay({ columns: next, separator });\n };\n\n return (\n <div className={cn(\"flex max-w-[26rem] flex-col gap-3\", className)}>\n {/* ── 1. WHICH TABLE ─────────────────────────────────────────────── */}\n {!lockTarget && (\n <div className=\"flex flex-col gap-1\">\n <div className=\"flex items-center justify-between gap-2\">\n <Label className=\"text-xs\">The table it points at</Label>\n <ShowListsToggle count={picking.listCount} on={showLists} onChange={setShowLists} />\n </div>\n {naming !== null ? (\n <div className=\"flex flex-col gap-1\" data-new-link-table=\"\">\n <div className=\"flex items-center gap-1\">\n <BasicInput\n autoFocus\n value={naming}\n placeholder=\"Table name\"\n aria-label=\"New table name\"\n disabled={making}\n onChange={(e) => setNaming(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === \"Enter\") {\n e.preventDefault();\n void makeTable();\n }\n if (e.key === \"Escape\") {\n e.stopPropagation();\n setNaming(null);\n setRefused(null);\n }\n }}\n className=\"h-7 text-xs\"\n />\n <Button\n type=\"button\"\n size=\"sm\"\n disabled={making || naming.trim() === \"\"}\n onClick={() => void makeTable()}\n >\n {making ? \"Creating…\" : \"Create\"}\n </Button>\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"ghost\"\n disabled={making}\n onClick={() => {\n setNaming(null);\n setRefused(null);\n }}\n >\n Cancel\n </Button>\n </div>\n {refused ? <RefusalNotice error={refused} /> : null}\n </div>\n ) : tables.loading && offered.length === 0 ? (\n <p className=\"text-[11px] text-muted-foreground\">Reading your tables…</p>\n ) : offered.length === 0 ? (\n <div className=\"flex items-center gap-2\">\n <p className=\"text-[11px] text-muted-foreground\">No tables yet.</p>\n {newTableButton}\n </div>\n ) : (\n <Select\n value={value.targetTableId}\n onValueChange={(next) => {\n if (next === NEW_TABLE) {\n setRefused(null);\n setNaming(\"\");\n return;\n }\n // Changing the table invalidates the columns: the store refuses a\n // spec naming a column the new target does not have, and a panel\n // that carried the old one would walk a person into that refusal.\n onChange({ targetTableId: next as Uuid, display: null });\n }}\n >\n <SelectTrigger size=\"sm\" aria-label=\"The table this column points at\">\n <SelectValue placeholder=\"Choose a table\" />\n </SelectTrigger>\n <SelectContent>\n {offered.map((t) => (\n <SelectItem key={t.id} value={t.id}>\n {t.label}\n {t.id === tableId ? \" — this table\" : \"\"}\n </SelectItem>\n ))}\n {mayMakeTable ? <SelectItem value={NEW_TABLE}>New table…</SelectItem> : null}\n </SelectContent>\n </Select>\n )}\n </div>\n )}\n\n {/* ── 2. WHAT ONE OF ITS RECORDS IS CALLED TODAY ──────────────────── */}\n {target && (\n <div className=\"flex flex-col gap-1\">\n <div className=\"flex items-center gap-2\">\n <Label className=\"text-xs\">Shown as</Label>\n <span className=\"text-[11px] text-muted-foreground\">\n {titleField\n ? `${titleField} — what ${targetTable ? tableName(targetTable) : \"that table\"} is titled by`\n : \"whatever each record is named by\"}\n </span>\n </div>\n\n <label className=\"flex items-center gap-2 text-[11px] text-muted-foreground\">\n <Checkbox\n checked={overriding}\n onCheckedChange={(next) => {\n const on = next === true;\n setOverriding(on);\n if (!on) setDisplay(null);\n }}\n aria-label=\"Show more than one column\"\n />\n Show different columns, or more than one\n </label>\n </div>\n )}\n\n {/* ── 3. WHICH COLUMNS, IN ORDER, AND WHAT JOINS THEM ─────────────── */}\n {target && overriding && (\n <div className=\"flex flex-col gap-2 rounded-md border border-border p-2\">\n {columns.loading ? (\n <p className=\"text-[11px] text-muted-foreground\">Reading that table's columns…</p>\n ) : columns.keys.length === 0 ? (\n <p className=\"text-[11px] text-muted-foreground\">\n That table has no columns to show yet. Give it one, then come back — until then this\n column shows whatever each record is named by.\n </p>\n ) : (\n <>\n <div className=\"flex flex-wrap gap-1\">\n {columns.keys.map((key) => {\n const on = chosen.includes(key);\n return (\n <Button\n key={key}\n type=\"button\"\n size=\"sm\"\n variant={on ? \"default\" : \"outline\"}\n onClick={() => toggleColumn(key)}\n aria-pressed={on}\n >\n {key}\n {on && chosen.length > 1 ? ` ${chosen.indexOf(key) + 1}` : \"\"}\n </Button>\n );\n })}\n </div>\n\n {chosen.length > 1 && (\n <div className=\"flex flex-wrap items-center gap-1\">\n <span className=\"text-[11px] text-muted-foreground\">Order</span>\n {chosen.map((key, at) => (\n <span key={key} className=\"flex items-center gap-0.5\">\n <span className=\"text-[11px]\">{key}</span>\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"ghost\"\n disabled={at === 0}\n onClick={() => move(key, -1)}\n aria-label={`Move ${key} earlier`}\n >\n ←\n </Button>\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"ghost\"\n disabled={at === chosen.length - 1}\n onClick={() => move(key, 1)}\n aria-label={`Move ${key} later`}\n >\n →\n </Button>\n </span>\n ))}\n </div>\n )}\n\n {chosen.length > 1 && (\n <div className=\"flex items-center gap-2\">\n <Label className=\"text-xs whitespace-nowrap\">Joined by</Label>\n <BasicInput\n value={separator}\n onChange={(e) => setDisplay({ columns: chosen, separator: e.target.value })}\n aria-label=\"What goes between the columns\"\n className=\"h-7 w-28 text-xs\"\n />\n <span className=\"text-[11px] text-muted-foreground\">a space by default</span>\n </div>\n )}\n </>\n )}\n </div>\n )}\n\n {/* ── 4. READ IT, RATHER THAN IMAGINE IT ──────────────────────────── */}\n {target && (\n <div className=\"flex flex-col gap-0.5\">\n <Label className=\"text-xs\">It will read</Label>\n {preview.loading ? (\n <p className=\"text-[11px] text-muted-foreground\">Reading a few of its records…</p>\n ) : (preview.data?.rows?.length ?? 0) === 0 ? (\n <p className=\"text-[11px] text-muted-foreground\">\n That table has no records yet, so there is nothing to show here — this column will\n still work, and the first record added is the first thing it offers.\n </p>\n ) : (\n <ul className=\"flex flex-col gap-0.5\">\n {(preview.data?.rows ?? []).map((row) => (\n <li key={row.id} className=\"truncate text-[11px] text-foreground\">\n {previewWords(\n row.document as Record<string, unknown> | undefined,\n display,\n titleField,\n )}\n </li>\n ))}\n </ul>\n )}\n </div>\n )}\n </div>\n );\n}\n","\"use client\";\n\n// src/ChoiceListEditor.tsx — @ai-matrx/records-ui\n//\n// THE CHOICES OF AN EXISTING CHOICE COLUMN, ONE ROW EACH (lane CHOICE-COLUMN-EDIT, 2026-09-27).\n//\n// A software team's \"Account Type\" column offers Cusor · Claude · Codex, and \"Cusor\" is a typo.\n// The panel used to hand them an empty \"one per line\" box: fixing one letter meant retyping the\n// whole list, and a re-typed word was a NEW choice, so every cell holding the old one kept the\n// typo. Here each choice is its own row, read from the store in its own order\n// (`metadata.option_position`): its words are edited IN PLACE (the choice keeps its key, so every\n// cell holding it reads the new words), a choice can be added, removed (retired, never deleted —\n// cells holding it keep it) and moved up or down. Save sends the whole list, in order, in the\n// panel's one `fieldUpdate` call: `{id, words}` for a choice that was there, plain words for a new\n// one (`FieldPatch.options`). The same list for a table that was moved and one that was not.\n//\n// ONE EDITOR, WITH ITS COLORS (lane VIEWS-AND-FIELDS W1-B, 2026-10-02 — Airtable). Add column used\n// to take choices in a one-per-line box and the colors only appeared later, in a second \"Choice\n// colours\" block of the column's settings. Each row now carries its own swatch (the color kept on\n// the Field, `display_format.options.choices`, `choiceLooks.ts`), a new choice takes the next\n// palette color by itself, and the SAME component serves a new column (no `field`: the rows live\n// in the panel) and an existing one (rows read from the store).\n\nimport { useEffect, useRef, useState, type KeyboardEvent } from \"react\";\nimport type { ChoiceRehome, ChoiceUsage, Field, FieldOptionEdit, StoredRecord } from \"@ai-matrx/records\";\nimport { optionLabel, recordsUseSentence, rehomeSentence } from \"@ai-matrx/records\";\nimport { useRecordsClient } from \"@ai-matrx/records/react\";\nimport {\n BasicInput,\n Button,\n Label,\n Popover,\n PopoverContent,\n PopoverTrigger,\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n cn,\n} from \"@ai-matrx/design-system\";\nimport { STYLE_COLORS, STYLE_COLOR_LABELS, SWATCH_CLASS, type StyleColor } from \"@ai-matrx/design-system/data-table\";\nimport { nextChoiceColor, storedChoiceColor } from \"./choiceLooks\";\nimport { inTheStoresOrder } from \"./editors\";\nimport { refusalSentence } from \"./plainWords\";\n\n/** One row of the list: a choice that was there (`id`) or one being added (`id: null`). */\nexport interface ChoiceListRow {\n /** The option record's id, or null for a choice this panel is adding. */\n id: string | null;\n /** What it reads as. */\n words: string;\n /** A stable React key for a row that has no id yet. */\n row: string;\n /** The color it wears (`display_format.options.choices`); null or absent: none. */\n color?: StyleColor | null | undefined;\n}\n\nlet rowSeed = 0;\nconst nextRow = () => `new-${(rowSeed += 1)}`;\n\n/** The rows a column's live options start as, in the store's order, each in the color its Field keeps. */\nexport function choiceRowsFrom(options: readonly StoredRecord[], field?: Field): ChoiceListRow[] {\n return inTheStoresOrder([...options]).map((option) => {\n const words = optionLabel(option);\n const key = (option.data as { key?: unknown } | null | undefined)?.key;\n const color = field ? (storedChoiceColor(field, words) ?? storedChoiceColor(field, key)) : undefined;\n return { id: option.id, words, row: option.id, color: color ?? null };\n });\n}\n\n/** A new, empty row, already wearing the next palette color the list does not wear (Airtable). */\nexport function newChoiceRow(rows: readonly ChoiceListRow[], words = \"\"): ChoiceListRow {\n return { id: null, words, row: nextRow(), color: nextChoiceColor(rows.map((r) => r.color)) };\n}\n\n/**\n * WHAT A SAVE SENDS as `options`, or `undefined` when the list is what the store already holds\n * (so a rename of the column alone does not rewrite its choices).\n */\nexport function choiceListPatch(\n start: readonly ChoiceListRow[],\n rows: readonly ChoiceListRow[],\n): Array<string | FieldOptionEdit> | undefined {\n const kept = rows.filter((r) => r.words.trim() !== \"\");\n const same =\n kept.length === start.length && kept.every((r, i) => r.id === start[i]!.id && r.words.trim() === start[i]!.words.trim());\n if (same) return undefined;\n return kept.map((r) => (r.id ? { id: r.id, words: r.words.trim() } : r.words.trim()));\n}\n\n/** Why this list cannot be saved yet, in the panel's words, or null. */\nexport function whatTheChoiceListIsMissing(rows: readonly ChoiceListRow[] | null): string | null {\n if (!rows) return null;\n const words = rows.map((r) => r.words.trim()).filter((w) => w !== \"\");\n // A choice column with no choices yet is still a choice column (lane CHOICE-COLUMN-EDIT b): its\n // first choice is added here later, or from a cell, which asks before adding what was typed.\n if (words.length === 0) return null;\n const seen = new Set<string>();\n for (const word of words) {\n const low = word.toLowerCase();\n if (seen.has(low)) return `“${word}” is in the list twice. Each choice needs its own words.`;\n seen.add(low);\n }\n return null;\n}\n\nexport function ChoiceListEditor({\n field,\n isNew = false,\n rows,\n onRows,\n onStart,\n allowOther = false,\n rehome = {},\n onRehome,\n}: {\n /** The column, when it exists. Absent: a column being made, whose rows the panel holds. */\n field?: Field | undefined;\n /** A column being made: no store read, no removal question. */\n isNew?: boolean | undefined;\n rows: ChoiceListRow[] | null;\n onRows: (next: ChoiceListRow[]) => void;\n /** The list as the store answered it, once — what a save is compared against. */\n onStart?: ((start: ChoiceListRow[]) => void) | undefined;\n /** Whether the column takes other values — the only case \"keep the words\" is offered. */\n allowOther?: boolean | undefined;\n /**\n * REMOVING A CHOICE RECORDS STILL HOLD (lane CHOICE-TAILS): where the records of each removed\n * choice go, keyed by the option's id — sent in the same save as the list. Without `onRehome`\n * a removal is immediate and its records keep the retired choice, as before.\n */\n rehome?: Record<string, ChoiceRehome> | undefined;\n onRehome?: ((next: Record<string, ChoiceRehome>) => void) | undefined;\n}) {\n const client = useRecordsClient();\n const [refused, setRefused] = useState<string | null>(null);\n const [usage, setUsage] = useState<Record<string, ChoiceUsage> | null>(null);\n const [asking, setAsking] = useState<ChoiceListRow | null>(null);\n const [moveTo, setMoveTo] = useState(\"\");\n const focusRow = useRef<string | null>(null);\n const [removed, setRemoved] = useState<Record<string, { row: ChoiceListRow; index: number }>>({});\n const fieldId = field?.id ?? null;\n useEffect(() => {\n if (rows !== null || !fieldId || !field) return;\n let live = true;\n void client.fieldOptions({ field_id: fieldId }).then((got) => {\n if (!live) return;\n if (!got.ok) {\n setRefused(refusalSentence(got.error));\n return;\n }\n const start = choiceRowsFrom(got.data ?? [], field);\n onStart?.(start);\n onRows(start);\n });\n return () => {\n live = false;\n };\n // `field` is read for its colours once, with the options; its id is what re-asks.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, fieldId, rows, onRows, onStart]);\n // HOW MANY RECORDS HOLD EACH CHOICE, read once. Unreadable, nothing is asked and a removal\n // behaves as it always has (its records keep the retired choice) — never a guessed count.\n useEffect(() => {\n if (!onRehome || !fieldId) return;\n let live = true;\n // A door that throws (not just refuses) is the same answer: unread, nothing asked.\n void client.fieldChoiceUsage({ field_id: fieldId }).then(\n (got) => {\n if (live && got.ok) setUsage(got.data);\n },\n () => undefined,\n );\n return () => {\n live = false;\n };\n }, [client, fieldId, onRehome]);\n\n if (refused) {\n return (\n <p className=\"text-[11px] text-muted-foreground\" data-records-choice-list=\"\">\n The choices could not be read, so they are left as they are: {refused}\n </p>\n );\n }\n if (rows === null) return <p className=\"text-[11px] text-muted-foreground\">Reading this column’s choices…</p>;\n\n const set = (index: number, words: string) => onRows(rows.map((r, i) => (i === index ? { ...r, words } : r)));\n const paint = (index: number, color: StyleColor | null) => onRows(rows.map((r, i) => (i === index ? { ...r, color } : r)));\n // THE BOX A PERSON ASKED FOR TAKES FOCUS, THE FIRST ONE TOO. A row the panel starts with (a new\n // column opens on one empty row) must not steal focus from the name box, so focus follows the\n // row `addRow` made — by its key — rather than a guess from the row's place in the list.\n const addRow = () => {\n const made = newChoiceRow(rows);\n focusRow.current = made.row;\n onRows([...rows, made]);\n };\n // ENTER IN THE LAST CHOICE STARTS THE NEXT ONE (Airtable): a list is typed without the mouse.\n const enterAdds = (index: number) => (e: KeyboardEvent<HTMLInputElement>) => {\n if (e.key !== \"Enter\" || e.nativeEvent.isComposing) return;\n e.preventDefault();\n if (rows[index]!.words.trim() === \"\") return;\n if (index === rows.length - 1) {\n addRow();\n return;\n }\n // A choice in the middle of the list: Enter moves on to the next box.\n const next = (e.currentTarget.closest(\"li\")?.nextElementSibling as HTMLElement | null)?.querySelector(\"input\");\n next?.focus();\n };\n const move = (index: number, by: -1 | 1) => {\n const to = index + by;\n if (to < 0 || to >= rows.length) return;\n const next = [...rows];\n [next[index], next[to]] = [next[to]!, next[index]!];\n onRows(next);\n };\n const named = (r: ChoiceListRow, i: number) => (r.words.trim() === \"\" ? `choice ${i + 1}` : `“${r.words.trim()}”`);\n const heldBy = (r: ChoiceListRow) => (r.id && onRehome ? (usage?.[r.id]?.records ?? 0) : 0);\n const remove = (i: number) => {\n const r = rows[i]!;\n if (heldBy(r) > 0) {\n setAsking(r);\n setMoveTo(\"\");\n return;\n }\n onRows(rows.filter((_, j) => j !== i));\n };\n const answer = (spec: ChoiceRehome) => {\n if (!asking?.id || !onRehome) return;\n const index = rows.findIndex((r) => r.id === asking.id);\n setRemoved({ ...removed, [asking.id]: { row: asking, index: index < 0 ? rows.length : index } });\n onRows(rows.filter((r) => r.id !== asking.id));\n onRehome({ ...rehome, [asking.id]: spec });\n setAsking(null);\n };\n const putBack = (id: string) => {\n const was = removed[id];\n if (!was || !onRehome) return;\n const next = [...rows];\n next.splice(Math.min(was.index, next.length), 0, was.row);\n onRows(next);\n const { [id]: _gone, ...rest } = rehome;\n onRehome(rest);\n const { [id]: _was, ...keep } = removed;\n setRemoved(keep);\n };\n const targets = rows.filter((r) => r.id && r.id !== asking?.id && r.words.trim() !== \"\");\n const wordsOf = (id: string) => rows.find((r) => r.id === id)?.words.trim() ?? usage?.[id]?.words ?? \"\";\n\n return (\n <div className=\"flex flex-col gap-1\" data-records-choice-list=\"\">\n <Label className=\"text-xs\">The choices</Label>\n {rows.length === 0 ? (\n <p className=\"text-xs text-muted-foreground\" data-records-choice-list-empty=\"\">\n No choices yet.\n </p>\n ) : null}\n <ul className=\"flex flex-col gap-1\">\n {rows.map((r, i) => (\n <li key={r.row} className=\"flex items-center gap-1\" data-records-choice-row=\"\">\n <ChoiceSwatch words={r.words.trim() === \"\" ? `choice ${i + 1}` : r.words.trim()} color={r.color ?? null} onColor={(c) => paint(i, c)} />\n <BasicInput\n value={r.words}\n aria-label={`Choice ${i + 1}`}\n className=\"h-7 min-w-0 flex-1 text-xs\"\n ref={(box) => {\n if (box && focusRow.current === r.row) {\n focusRow.current = null;\n box.focus();\n }\n }}\n onChange={(e) => set(i, e.target.value)}\n onKeyDown={enterAdds(i)}\n />\n <Button type=\"button\" size=\"sm\" variant=\"ghost\" className=\"h-7 px-1.5 text-xs\" aria-label={`Move ${named(r, i)} up`} disabled={i === 0} onClick={() => move(i, -1)}>\n ↑\n </Button>\n <Button type=\"button\" size=\"sm\" variant=\"ghost\" className=\"h-7 px-1.5 text-xs\" aria-label={`Move ${named(r, i)} down`} disabled={i === rows.length - 1} onClick={() => move(i, 1)}>\n ↓\n </Button>\n <Button type=\"button\" size=\"sm\" variant=\"ghost\" className=\"h-7 px-1.5 text-xs\" aria-label={`Remove ${named(r, i)}`} onClick={() => remove(i)}>\n ×\n </Button>\n </li>\n ))}\n </ul>\n {asking ? (\n // THE QUESTION, Notion-style: where do the records that hold it go?\n <div\n role=\"group\"\n aria-label={recordsUseSentence(heldBy(asking), asking.words.trim())}\n data-records-choice-removal-ask=\"\"\n className=\"flex flex-col gap-1 rounded border bg-muted/40 p-2\"\n >\n <p className=\"text-xs\">{recordsUseSentence(heldBy(asking), asking.words.trim())}</p>\n <div className=\"flex flex-wrap items-center gap-1\">\n {targets.length > 0 ? (\n <>\n <Button type=\"button\" size=\"sm\" className=\"h-7 px-2 text-xs\" disabled={moveTo === \"\"} onClick={() => answer({ then: \"move\", to: moveTo })}>\n Move them to\n </Button>\n <Select value={moveTo} onValueChange={setMoveTo}>\n <SelectTrigger size=\"sm\" className=\"h-7 w-36 text-xs\" aria-label=\"Another choice\">\n <SelectValue placeholder=\"Another choice\" />\n </SelectTrigger>\n <SelectContent>\n {targets.map((r) => (\n <SelectItem key={r.id!} value={r.id!}>\n {r.words.trim()}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </>\n ) : null}\n {allowOther ? (\n <Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"h-7 px-2 text-xs\" onClick={() => answer({ then: \"keep\" })}>\n Keep the words as other values\n </Button>\n ) : null}\n <Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"h-7 px-2 text-xs\" onClick={() => answer({ then: \"clear\" })}>\n Clear them\n </Button>\n <Button type=\"button\" size=\"sm\" variant=\"ghost\" className=\"h-7 px-2 text-xs\" onClick={() => setAsking(null)}>\n Cancel\n </Button>\n </div>\n </div>\n ) : null}\n {Object.entries(rehome).map(([id, spec]) =>\n removed[id] ? (\n <div key={id} className=\"flex items-center justify-between gap-2 text-[11px] text-muted-foreground\" data-records-choice-rehome=\"\">\n <span>{rehomeSentence(usage?.[id]?.records ?? 0, removed[id]!.row.words.trim(), spec, spec.then === \"move\" ? wordsOf(spec.to) : undefined)}</span>\n <Button type=\"button\" size=\"sm\" variant=\"ghost\" className=\"h-6 px-1.5 text-[11px]\" onClick={() => putBack(id)}>\n Put it back\n </Button>\n </div>\n ) : null,\n )}\n <Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"h-7 self-start text-xs\" onClick={addRow}>\n Add a choice\n </Button>\n {isNew ? null : (\n <p className=\"text-[11px] text-muted-foreground\">\n Changing a choice’s words changes them in every record that holds it. Removing a choice that records hold\n asks where those records go.\n </p>\n )}\n </div>\n );\n}\n\n/**\n * ONE CHOICE'S COLOR: a dot in the color it wears that opens the palette (Airtable). Every\n * color is a name from the design-system palette (`STYLE_COLORS`), never a raw hex.\n */\nfunction ChoiceSwatch({ words, color, onColor }: { words: string; color: StyleColor | null; onColor: (color: StyleColor | null) => void }) {\n const [open, setOpen] = useState(false);\n const pick = (next: StyleColor | null) => {\n onColor(next);\n setOpen(false);\n };\n return (\n <Popover open={open} onOpenChange={setOpen}>\n <PopoverTrigger asChild>\n <button\n type=\"button\"\n aria-label={`Color for ${words}: ${color ? STYLE_COLOR_LABELS[color] : \"none\"}`}\n title={color ? STYLE_COLOR_LABELS[color] : \"No color\"}\n data-records-choice-swatch={color ?? \"none\"}\n className={cn(\n \"h-4 w-4 shrink-0 rounded-full\",\n color ? SWATCH_CLASS[color] : \"border border-border bg-background\",\n )}\n />\n </PopoverTrigger>\n <PopoverContent sizing=\"content\" align=\"start\" className=\"p-2\">\n <div className=\"flex items-center gap-1\" role=\"radiogroup\" aria-label={`Color for ${words}`}>\n <button\n type=\"button\"\n role=\"radio\"\n aria-checked={color === null}\n aria-label=\"No color\"\n title=\"No color\"\n onClick={() => pick(null)}\n className={cn(\"h-5 w-5 rounded-full border border-border bg-background\", color === null && \"ring-2 ring-ring ring-offset-1\")}\n />\n {STYLE_COLORS.map((c) => (\n <button\n key={c}\n type=\"button\"\n role=\"radio\"\n aria-checked={color === c}\n aria-label={STYLE_COLOR_LABELS[c]}\n title={STYLE_COLOR_LABELS[c]}\n data-records-choice-color={`${words}:${c}`}\n onClick={() => pick(c)}\n className={cn(\"h-5 w-5 rounded-full\", SWATCH_CLASS[c], color === c && \"ring-2 ring-ring ring-offset-1\")}\n />\n ))}\n </div>\n </PopoverContent>\n </Popover>\n );\n}\n","\"use client\";\n\n// src/AddChoicesInline.tsx — @ai-matrx/records-ui\n//\n// A CHOICE COLUMN WITH NO CHOICES OFFERS TO GET THEM, WHERE THE PERSON IS (lane PICK-LISTS, 2026-10-10).\n// A Choice or Several-choices column can be made with no options; opening it in a record form, a grid\n// cell or a form then showed an empty list. This is the way out, inline: one small control that opens\n// the same choice rows the column editor draws, and adds what was typed to the column\n// (`fieldUpdate` `options_add`). It OFFERS: the picker beside it still works and nothing is blocked.\n\nimport { useState } from \"react\";\nimport type { Field, RecordsError } from \"@ai-matrx/records\";\nimport { useOptionalRecordsClient } from \"@ai-matrx/records/react\";\nimport { Button, Popover, PopoverContent, PopoverTrigger } from \"@ai-matrx/design-system\";\nimport { ChoiceListEditor, newChoiceRow, whatTheChoiceListIsMissing, type ChoiceListRow } from \"./ChoiceListEditor\";\nimport { RefusalLine } from \"./Refusal\";\n\nexport function AddChoicesInline({ field, onAdded, disabled = false }: { field: Field; onAdded: () => void; disabled?: boolean }) {\n const client = useOptionalRecordsClient();\n const [open, setOpen] = useState(false);\n const [rows, setRows] = useState<ChoiceListRow[]>(() => [newChoiceRow([])]);\n const [saving, setSaving] = useState(false);\n const [refused, setRefused] = useState<RecordsError | null>(null);\n if (!client) return null;\n const words = rows.map((r) => r.words.trim()).filter((w) => w !== \"\");\n const missing = whatTheChoiceListIsMissing(rows);\n const save = async () => {\n setSaving(true);\n setRefused(null);\n const done = await client.fieldUpdate({ field_id: field.id, patch: { options_add: words } });\n setSaving(false);\n if (!done.ok) {\n setRefused(done.error);\n return;\n }\n setOpen(false);\n setRows([newChoiceRow([])]);\n onAdded();\n };\n return (\n <Popover open={open} onOpenChange={setOpen}>\n <PopoverTrigger asChild>\n <Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"h-7 self-start text-xs\" disabled={disabled} data-records-add-choices=\"\">\n Add choices\n </Button>\n </PopoverTrigger>\n <PopoverContent className=\"w-72 space-y-2 p-3\" align=\"start\">\n <ChoiceListEditor isNew rows={rows} onRows={setRows} />\n {missing ? <p className=\"text-[11px] text-muted-foreground\">{missing}</p> : null}\n {refused ? <RefusalLine error={refused} /> : null}\n <Button type=\"button\" size=\"sm\" className=\"h-7 text-xs\" disabled={saving || words.length === 0 || missing !== null} onClick={() => void save()}>\n Save choices\n </Button>\n </PopoverContent>\n </Popover>\n );\n}\n","\"use client\";\n\n// src/editors.tsx — @ai-matrx/records-ui\n//\n// ONE EDITOR PER PARITY TYPE, and every one of them is a design-system\n// primitive. There is no bespoke input in this package and no per-feature\n// editor anywhere in the platform: a Field decides which of these is drawn,\n// from what the STORE stores about it (behavior + modifiers + format + unit +\n// relation target), never from the value it happens to hold.\n//\n// FLD-9: a Formula is worked out by the system. Its editor is not a disabled\n// text box — it is the value with the sentence the store itself would say if\n// you tried to type into it.\n\nimport { fieldOptionsOnce, forgetAsked } from \"./askOnce\";\nimport { AddChoicesInline } from \"./AddChoicesInline\";\nimport { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from \"react\";\nimport type { Field, RecordDocument, RecordsError, StoredRecord, Uuid } from \"@ai-matrx/records\";\nimport { isButtonField, allowsOtherValues, choiceValuesOf, coerceTypedAnswer, newerKindOf, decideTypedChoice, isTheChosen, optionKey, rankTypedMatches, readTypedTime, typedDateText, typedTimeText, type ChoiceNudge } from \"@ai-matrx/records\";\nimport { useOptionalRecordsClient } from \"@ai-matrx/records/react\";\nimport {\n BasicInput,\n BasicTextarea,\n Badge,\n Button,\n Checkbox,\n Label,\n Popover,\n PopoverContent,\n PopoverTrigger,\n Select,\n SelectContent,\n SelectItem,\n SelectTrigger,\n SelectValue,\n cn,\n} from \"@ai-matrx/design-system\";\nimport { carriesTimeOfDay } from \"./dates\";\nimport { newerKindControl } from \"./newerKindValues\";\nimport { editorKindFor } from \"./parity\";\nimport { fieldName, recordName } from \"./names\";\nimport { RelationPicker } from \"./RelationPicker\";\nimport { ButtonValue } from \"./buttonCell\";\nimport { prettyJsonText, structuredOf } from \"./structuredValue\";\nimport { AttachmentControl, hostTakesFiles } from \"./gridAttachments\";\nimport { useRecordsUi } from \"./host\";\nimport { EntityReferenceControl } from \"./EntityReferenceControl\";\nimport { PickOrAdd } from \"./PickOrAdd\";\nimport { PersonPicker } from \"./PersonPicker\";\nimport { RefusalLine, RefusalNotice } from \"./Refusal\";\nimport { FloatingRefusal } from \"./FloatingRefusal\";\nimport { refusalFromThrown } from \"./refusals\";\nimport { formatForField } from \"./presentation\";\nimport { formatControl, typedText } from \"./formatControls\";\nimport { TypedDateHelper, type DateHelperKind } from \"./typedDateHelper\";\nimport { FormattedValue } from \"./formattedValue\";\nimport { useChoiceNudge } from \"./choiceNudge\";\nimport { SignaturePad, isSignatureField } from \"./signature\";\nimport { choiceChipLookOf } from \"./choiceLooks\";\n\n/**\n * STORE-RULE-GAPS: the choice editor below takes words that are not a choice on a column that\n * takes other values (`config.allow_other`) — kept as typed, or added to the choices, as the\n * person (or the `custom/choice_nudge` knob) decides. The field editor offers that setting's\n * tick ONLY because this is true — the screen never offers a setting it cannot honor.\n */\nexport const CHOICE_EDITOR_ADDS_WHAT_IS_TYPED = true;\n\n/* ═══ WORDS THAT ARE NOT A CHOICE YET (lane CHOICE-COLUMN-EDIT, 2026-09-27) ═════════════════════\n *\n * A software team's \"Account Type\" column offers Cursor · Claude · Codex and somebody types\n * \"Gemini\". The cell asks: Add “Gemini” to the choices for Account Type? — Add / Keep as typed /\n * Cancel, with Keep as typed only on a column that takes other values. What it asks, or does\n * without asking, is `decideTypedChoice` (@ai-matrx/records) reading the `custom/choice_nudge`\n * knob; this file only draws the answer.\n *\n * 🚨 THE LIE THIS CLOSES. The allow-other picker offered Add “<typed>” and sent the word; the\n * store kept it as an OTHER value and never added it to the choices. Now Add really adds: in a\n * grid cell the value becomes a `ChoiceAddition`, which the grid saves through\n * `recordUpdateAddingChoices` (the new choice and the cell, one transaction); elsewhere the\n * choice is added through `fieldUpdate`'s `options_add` and the cell then takes it.\n */\n\n/** A cell value that also ADDS words to its column's choices. Only a host that declares\n * `addsChoices` (the grid) is ever handed one. */\nexport interface ChoiceAddition {\n readonly addingChoices: true;\n /** What the cell holds — the words (beside the keys of existing choices, for several). */\n readonly value: unknown;\n /** The words added to the column's choices. */\n readonly add: readonly string[];\n}\n\nexport function isChoiceAddition(value: unknown): value is ChoiceAddition {\n return typeof value === \"object\" && value !== null && (value as { addingChoices?: unknown }).addingChoices === true;\n}\n\nexport function choiceAddition(value: unknown, add: readonly string[]): ChoiceAddition {\n return { addingChoices: true, value, add: [...add] };\n}\n\n/** A value with any addition set aside. */\nexport function withoutAddition(value: unknown): { value: unknown; add: readonly string[] } {\n return isChoiceAddition(value) ? { value: value.value, add: value.add } : { value, add: [] };\n}\n\n/** The question a choice cell asks about words that are not one of its choices. */\nexport interface ChoiceAsk {\n /** The words that are not a choice. */\n readonly words: readonly string[];\n /** True only when the column takes other values. */\n readonly keepOffered: boolean;\n /** What the cell takes on Add. */\n readonly onAdd: ChoiceAddition;\n /** What the cell takes on Keep as typed. */\n readonly asTyped: unknown;\n}\n\n/** “Gemini” · “Gemini” and “Copilot” · “A”, “B” and “C”. */\nfunction quoted(words: readonly string[]): string {\n const q = words.map((w) => `“${w}”`);\n return q.length <= 1 ? (q[0] ?? \"\") : `${q.slice(0, -1).join(\", \")} and ${q[q.length - 1]}`;\n}\n\n/** Add “Gemini” to the choices for Account Type? */\nexport function choiceAskSentence(field: Field, words: readonly string[]): string {\n return `Add ${quoted(words)} to the choices for ${fieldName(field)}?`;\n}\n\n/** “Gemini” is not one of the choices for Account Type. */\nexport function notAChoiceSentence(field: Field, words: readonly string[]): string {\n return `${quoted(words)} ${words.length === 1 ? \"is\" : \"are\"} not one of the choices for ${fieldName(field)}.`;\n}\n\n/** The question's three doors, drawn once for the typed cell and the picker alike. */\nexport function ChoiceAskButtons({\n field,\n words,\n keepOffered,\n onAdd,\n onKeep,\n onCancel,\n busy,\n}: {\n field: Field;\n words: readonly string[];\n keepOffered: boolean;\n onAdd: () => void;\n onKeep: () => void;\n onCancel: () => void;\n busy?: boolean | undefined;\n}) {\n return (\n <span data-records-choice-ask=\"\" data-records-cell-note=\"\" role=\"group\" aria-label={choiceAskSentence(field, words)} className=\"flex flex-col gap-1\">\n <span className=\"text-[11px] leading-snug\">{choiceAskSentence(field, words)}</span>\n <span className=\"flex flex-wrap items-center gap-1\">\n <Button type=\"button\" size=\"sm\" className=\"h-6 px-2 text-xs\" disabled={busy ?? false} onClick={onAdd}>\n Add\n </Button>\n {keepOffered ? (\n <Button type=\"button\" size=\"sm\" variant=\"outline\" className=\"h-6 px-2 text-xs\" disabled={busy ?? false} onClick={onKeep}>\n Keep as typed\n </Button>\n ) : null}\n <Button type=\"button\" size=\"sm\" variant=\"ghost\" className=\"h-6 px-2 text-xs\" disabled={busy ?? false} onClick={onCancel}>\n Cancel\n </Button>\n </span>\n </span>\n );\n}\n\n/** Kinds whose control is the record's own (a choice, a link, a person, a file, a worked-out value). */\nconst FORMAT_BLIND_KINDS = new Set([\"formula\", \"lookup\", \"rollup\", \"json\", \"checkbox\", \"select\", \"multi_select\", \"member\", \"entity_reference\", \"relation\", \"attachment\", \"datetime\"]);\n\nexport interface FieldEditorControlProps {\n field: Field;\n value: unknown;\n onChange: (value: unknown) => void;\n disabled?: boolean | undefined;\n id?: string | undefined;\n /**\n * A GRID CELL'S PICKER OPENS AT ONCE (merged-grid review 2026-09-26, A2). One click on a selected\n * choice, multi-choice or person cell opens its list directly — no inline Save/Cancel form that\n * grows the row. Honored by the choice and person pickers; every other control ignores it.\n */\n autoOpen?: boolean | undefined;\n /** The picker's list closed (a pick, Enter, Tab, a click away): the cell commits what is chosen. Escape is `onCancel`. */\n onClose?: (() => void) | undefined;\n /**\n * WHAT THE PERSON TYPED TO OPEN A GRID CELL'S PICKER (merged-grid review 2, A2 — Airtable): a\n * letter typed on a selected choice, multi-choice or person cell opens its list with that text\n * already in the search box. Honored by the choice and person pickers.\n */\n initialSearch?: string | undefined;\n /** The control's own answer is final (a choice cell's Add / Keep as typed): commit it now. */\n onCommit?: (() => void) | undefined;\n /** The control's own Cancel: the cell goes back to what it held. */\n onCancel?: (() => void) | undefined;\n /**\n * The host saves a `ChoiceAddition` through `recordUpdateAddingChoices` (the grid). Without it\n * a choice control adds the words through `fieldUpdate`'s `options_add` and hands back words.\n */\n addsChoices?: boolean | undefined;\n /**\n * DRAWN AS A FORM QUESTION (lane VIEWS-AND-FIELDS W1-B item 3): a choice is answered from its\n * choices laid out — pills for a few, a searchable list for more (`ChoiceAnswer`) — never a\n * drop-down or a \"Choose\" button. Every other control ignores it.\n */\n asForm?: boolean | undefined;\n /** A FORM'S SINGLE CHOICE WAS PICKED (lane TYPEFORM-2): the runner may go on to the next question. */\n onChosen?: (() => void) | undefined;\n /** The record whose value this is: a link picker never offers it (walk 2026-10-08 D11). */\n recordId?: string | undefined;\n}\n\n/** The label row every editor shares: one line, the label, the unit, the required mark. */\nexport function FieldLabel({ field, htmlFor, children }: { field: Field; htmlFor: string; children?: ReactNode }) {\n return (\n <div className=\"flex items-baseline gap-1.5\">\n <Label htmlFor={htmlFor} className=\"text-xs font-medium\">\n {fieldName(field)}\n </Label>\n {field.required ? <span className=\"text-xs text-destructive\">required</span> : null}\n {/* A length of time reads as h:mm, so its stored unit (seconds) is not a word to show (P4). */}\n {field.unit && newerKindOf(field) !== \"duration\" ? <span className=\"text-xs text-muted-foreground\">{field.unit}</span> : null}\n {children}\n </div>\n );\n}\n\n\n/* ═══ A CELL OPENED BY TYPING (merged-grid cold review, 2026-09-26) ════════════════════════════════\n *\n * 🚨 THE DEFECT. A dispatcher selected a Visit date cell and typed `10/03/2026`; the store kept\n * **Jan 31, 0026**. The typed first character was DROPPED (a date was not a \"typed\" kind), the\n * editor opened on the stored value as the browser's segmented date control, and the rest of the\n * keystrokes landed in it one segment at a time — each half-typed segment a \"valid\" date. A\n * number cell had the same hazard: `-5` or `$50` dropped the first character and APPENDED the rest\n * to the value already in the box (100 → 10050). A choice cell handed the keystrokes to a closed\n * drop-down, whose type-ahead picked whatever option the SECOND letter matched.\n *\n * THE RULE (Google Sheets and Airtable): what a person types into a selected cell goes into a\n * plain TEXT box, whole; nothing is written until they commit; on commit the text is read by the\n * ONE typed-answer reader (`coerceTypedAnswer` — the same one a paste, a public form and an import\n * use), in the reader's locale; and anything it would have to guess is REFUSED with its sentence,\n * the box still holding what was typed. A kind whose value is not typed words (a linked record, a\n * person, a file, a document) and a tick box (one click or Space toggles it) are not opened by a\n * keystroke at all — Enter opens them.\n */\n\n/** A draft that is still the words a person typed, with the reader's verdict on them. */\nexport interface TypedDraft {\n readonly typedDraft: true;\n readonly text: string;\n /**\n * What the text reads as, why it is not a value, or — for a choice column — the question about\n * words that are not a choice yet. `null` while the column's choices (and the knob) load.\n */\n readonly judged: { value: unknown } | { refusal: string; why?: string; cancelOnly?: true } | { ask: ChoiceAsk } | null;\n /**\n * The words the cell OPENED with (Enter, a double-click, F2 — `draftForOpening`). Committing them\n * unchanged writes nothing: opening a cell and pressing Enter never rewrites what is stored.\n */\n readonly openedAs?: string | undefined;\n}\n\nexport function isTypedDraft(value: unknown): value is TypedDraft {\n return typeof value === \"object\" && value !== null && (value as { typedDraft?: unknown }).typedDraft === true;\n}\n\n/** Text kinds take the typed words as the value itself: a letter is a letter. */\nconst TYPED_AS_WORDS = new Set([\"text\", \"long_text\", \"phone\"]);\n/**\n * Kinds whose typed words are READ into a value on commit. A link and an email are read too\n * (review 2, A9): \"company.com\" is kept as https://company.com, and words that cannot be an email\n * say what one looks like — before anything reaches the store.\n */\nconst TYPED_AND_READ = new Set([\"number\", \"currency\", \"percent\", \"datetime\", \"select\", \"multi_select\", \"email\", \"url\"]);\n\n/**\n * What a keystroke on a selected cell does to THIS column: `\"words\"` — the text is the value;\n * `\"read\"` — the text is read on commit; `\"search\"` — the column's picker opens with the text as\n * its search (a choice, a multi-choice, a person: Airtable); `\"none\"` — typing does not open it.\n */\nexport function typingOpens(field: Field): \"words\" | \"read\" | \"search\" | \"none\" {\n if (isButtonField(field)) return \"none\";\n const kind = String(editorKindFor(field));\n if (kind === \"formula\" || kind === \"lookup\" || kind === \"rollup\") return \"none\";\n if (kind === \"select\" || kind === \"multi_select\" || kind === \"member\") return \"search\";\n const format = formatForField(field);\n if (format && format.id === \"time\") return \"read\";\n if (format && format.id === \"rating\") return \"read\";\n if (TYPED_AS_WORDS.has(kind)) return \"words\";\n if (TYPED_AND_READ.has(kind)) return \"read\";\n return \"none\";\n}\n\n/**\n * The reader's verdict on typed text for this column (choices: when they are known; `nudge`: the\n * `custom/choice_nudge` knob, `null` while it is asked, absent meaning its default `ask`).\n */\n/** The few words a cell says when what was typed cannot be an email, a link or a phone number. */\nexport const SHORT_REFUSAL = {\n email: \"Enter a valid email\",\n url: \"Enter a valid link\",\n phone: \"Enter a valid phone number\",\n time: \"Enter a time, like 2:30 PM\",\n date: \"Enter a date\",\n number: \"Enter a number\",\n value: \"Not a valid value\",\n} as const;\n\nexport function judgeTyped(field: Field, text: string, choices?: StoredRecord[] | null, nudge?: ChoiceNudge | null): TypedDraft[\"judged\"] {\n const trimmed = text.trim();\n const kind = String(editorKindFor(field));\n const format = formatForField(field);\n if (trimmed === \"\") return { value: null };\n if (format && format.id === \"time\") {\n // THE ONE TIME READER (`@ai-matrx/records` `readTypedTime`): `1200PM`, `12pm`, `9:30a`, `0930`\n // are all read; a bare `9` (morning or evening?) is refused with the way to write it.\n const read = readTypedTime(trimmed);\n return read.ok ? { value: read.value } : { refusal: SHORT_REFUSAL.time, why: `${fieldName(field)} holds a time of day, and ${read.why}` };\n }\n if (kind === \"select\" || kind === \"multi_select\") {\n if (!choices || nudge === null) return null;\n const several = field.multi || kind === \"multi_select\";\n const words = several ? trimmed.split(/\\s*[,;\\n]\\s*/).filter(Boolean) : [trimmed];\n const allowOther = allowsOtherValues(field);\n // ONE DECISION PER WORD, from the one helper every surface uses.\n const parts: string[] = [];\n const add: string[] = [];\n const ask: string[] = [];\n const notChoices: string[] = [];\n let keepOffered = allowOther;\n for (const word of words) {\n const decided = decideTypedChoice({ words: word, options: choices, allowOther, nudge });\n if (decided.decision === \"empty\") continue;\n if (decided.decision === \"chosen\") parts.push(decided.key);\n else {\n parts.push(decided.words);\n if (decided.decision === \"add\") add.push(decided.words);\n else if (decided.decision === \"ask\") {\n ask.push(decided.words);\n keepOffered = keepOffered && decided.keepOffered;\n } else if (decided.decision === \"not_a_choice\") notChoices.push(decided.words);\n }\n }\n const valueOf = (list: string[]) => (several ? list : (list[0] ?? null));\n if (notChoices.length > 0) return { refusal: notAChoiceSentence(field, notChoices), cancelOnly: true };\n if (ask.length > 0) {\n return {\n ask: { words: ask, keepOffered, onAdd: choiceAddition(valueOf(parts), [...add, ...ask]), asTyped: valueOf(parts) },\n };\n }\n if (add.length > 0) return { value: choiceAddition(valueOf(parts), add) };\n return { value: valueOf(parts) };\n }\n if (format && (format.id === \"rating\")) {\n const n = Number(trimmed);\n const max = format.options?.ratingMax ?? 5;\n return Number.isInteger(n) && n >= 0 && n <= max\n ? { value: n === 0 ? null : n }\n : { refusal: `Enter 1 to ${max}`, why: `${fieldName(field)} is a rating from 1 to ${max}.` };\n }\n // A PHONE NUMBER IS READ TOO (lane CELL-EDITORS, night walk 2026-10-06): any words used to be saved.\n // Digits with the usual marks (+, spaces, dashes, dots, brackets, an extension) and 7 to 15 digits.\n if (kind === \"phone\" || (format && format.id === \"phone\")) {\n const digits = trimmed.replace(/\\D/g, \"\");\n const usual = /^\\+?[\\d\\s().-]+(\\s*(x|ext\\.?)\\s*\\d+)?$/i.test(trimmed);\n return usual && digits.length >= 7 && digits.length <= 20 ? { value: trimmed } : { refusal: SHORT_REFUSAL.phone };\n }\n const showsAsPercent = Boolean(format && (format.id === \"percent\" || format.id === \"progress\"));\n const read = coerceTypedAnswer(field as never, text, { label: fieldName(field), showsAsPercent });\n // A CELL HAS NO ROOM FOR A PARAGRAPH (interface-text rules): an email or a link that cannot be one is\n // said in a few words, never echoing what was typed — the box beside it already shows that.\n // EVERY TYPED REFUSAL IS A SHORT LABEL (REVIEW-FIX 9, interface-text): \"Enter a date\", never the\n // reader's paragraph; the full reason rides the note's tooltip (`why`).\n if (\"refusal\" in read) {\n if (kind === \"email\" || kind === \"url\") return { refusal: SHORT_REFUSAL[kind] };\n const short =\n kind === \"datetime\" ? SHORT_REFUSAL.date : kind === \"number\" || kind === \"currency\" || kind === \"percent\" || showsAsPercent ? SHORT_REFUSAL.number : read.refusal.length <= 32 ? read.refusal : SHORT_REFUSAL.value;\n return short === read.refusal ? { refusal: short } : { refusal: short, why: read.refusal };\n }\n // A percent kept as a fraction is typed as the percent a person reads.\n if (typeof read.value === \"number\" && format && (format.id === \"percent\" || format.id === \"progress\") && format.options?.percentScale === \"fraction\") {\n return { value: Math.round((read.value / 100) * 1e9) / 1e9 };\n }\n return { value: read.value };\n}\n\n/**\n * WHICH HELPER SITS BESIDE A TYPED BOX: a calendar for a date, a calendar and a list of times for a\n * moment, a list of times for a time of day — or none. `value` is the stored value, when there is one.\n */\nexport function dateHelperKind(field: Field, value?: unknown): DateHelperKind | null {\n const format = formatForField(field);\n if (format && format.id === \"time\") return \"time\";\n if (String(editorKindFor(field)) !== \"datetime\") return null;\n return String(field.config?.[\"kind\"] ?? \"\") === \"datetime\" || carriesTimeOfDay(field, value) ? \"datetime\" : \"date\";\n}\n\n/** The words a stored value opens as in its column's typed box — the words the reader reads back to it. */\nexport function openingText(field: Field, value: unknown): string {\n if (value === null || value === undefined || value === \"\") return \"\";\n const helper = dateHelperKind(field, value);\n if (helper === \"time\") {\n const read = readTypedTime(String(value));\n if (!read.ok) return String(value);\n const [h, m] = read.value.split(\":\").map(Number);\n return typedTimeText(h!, m!);\n }\n if (helper) return typedDateText(value, { withTime: helper === \"datetime\" });\n const format = formatForField(field);\n return format ? typedText(format, value) : String(value);\n}\n\n/** Kinds whose Enter / double-click / F2 editor is the typed box too — never the browser's own control. */\nconst OPENS_AS_TYPED_TEXT = new Set([\"datetime\", \"number\", \"currency\", \"percent\"]);\n\n/**\n * 🚨 THE DRAFT A CELL OPENS WITH BY ENTER, A DOUBLE-CLICK OR F2 (grids review 3, 2026-09-30, a\n * BLOCKER). A date, a time or a date-and-time column opened the browser's own picker, which lost a\n * typed time and saved \"now\"; a money column's own box dropped a typed percent sign. Every way into\n * these columns is now the SAME typed box a keystroke opens, holding the stored value's words and\n * read once on commit. `undefined` for every other column (it keeps its own control).\n */\nexport function draftForOpening(field: Field, current: unknown): TypedDraft | undefined {\n const format = formatForField(field);\n if (format && format.id === \"rating\") return undefined;\n const opens = (format && format.id === \"time\") || OPENS_AS_TYPED_TEXT.has(String(editorKindFor(field)));\n if (!opens) return undefined;\n const text = openingText(field, current);\n return { typedDraft: true, text, judged: judgeTyped(field, text), openedAs: text };\n}\n\n/**\n * THE DRAFT A KEYSTROKE OPENS A CELL WITH — or `undefined` when typing does not open this column.\n * A text column takes the typed words as its value; every other typed column holds a TypedDraft.\n */\nexport function draftFromTyping(field: Field, seed: string): string | TypedDraft | undefined {\n const opens = typingOpens(field);\n if (opens === \"none\") return undefined;\n if (opens === \"words\") return seed;\n return { typedDraft: true, text: seed, judged: judgeTyped(field, seed) };\n}\n\n/**\n * \"Reads as …\" EARNS ITS PLACE (interface-text): it floats over the cell only when it tells the person\n * something the box does not. Typed \"9/5/2026\" it would repeat the box, so it is not drawn; typed\n * \"Sep 5 2026\" or \"12.5\" for a money column, what it reads as is news. `always`: an addition to a\n * list of choices is always said. Keyed by the typed words, so it is measured again as they change.\n */\nfunction ReadsAsNote({ typed, always, children }: { typed: string; always: boolean; children: ReactNode }) {\n const note = useRef<HTMLSpanElement | null>(null);\n const [repeats, setRepeats] = useState(false);\n useLayoutEffect(() => {\n if (always) return;\n const words = (t: string | null | undefined) => (t ?? \"\").replace(/^Reads as/, \"\").replace(/\\s+/g, \"\").toLowerCase();\n setRepeats(words(note.current?.textContent) === words(typed));\n }, [typed, always]);\n if (repeats) return null;\n return (\n <span ref={note} data-records-typed-reads-as=\"\" data-records-cell-note=\"\" className=\"text-[10px] text-muted-foreground\">\n {children}\n </span>\n );\n}\n\n/** The box a typed draft is edited in: the words, and what they read as — or why they are not a value. */\nfunction TypedTextControl({ field, value, onChange, disabled, id, onCommit, onCancel }: FieldEditorControlProps & { value: TypedDraft }) {\n const client = useOptionalRecordsClient();\n const kind = String(editorKindFor(field));\n const needsChoices = kind === \"select\" || kind === \"multi_select\";\n const nudge = useChoiceNudge(needsChoices);\n const [choices, setChoices] = useState<StoredRecord[] | null>(null);\n useEffect(() => {\n if (!needsChoices || !client) return;\n let cancelled = false;\n void fieldOptionsOnce(client, field.id).then((result) => {\n if (!cancelled) setChoices(result.ok ? inTheStoresOrder(result.data ?? []) : []);\n });\n return () => {\n cancelled = true;\n };\n }, [client, field.id, needsChoices]);\n // The verdict on what is ALREADY in the box once the choices (and the knob) arrive.\n useEffect(() => {\n if (choices && nudge && value.judged === null) onChange({ ...value, judged: judgeTyped(field, value.text, choices, nudge) });\n }, [choices, nudge, value, field, onChange]);\n const judged = value.judged;\n const format = formatForField(field);\n const helper = dateHelperKind(field);\n const retype = (text: string) =>\n onChange({\n typedDraft: true,\n text,\n judged: judgeTyped(field, text, needsChoices ? choices : undefined, needsChoices ? nudge : undefined),\n ...(value.openedAs !== undefined ? { openedAs: value.openedAs } : {}),\n });\n const box = (\n <BasicInput\n id={id}\n value={value.text}\n disabled={disabled}\n autoComplete=\"off\"\n aria-label={fieldName(field)}\n aria-invalid={judged !== null && \"refusal\" in judged ? true : undefined}\n onChange={(e) => retype(e.target.value)}\n />\n );\n return (\n <span className=\"flex flex-col gap-0.5\">\n {helper && !disabled ? (\n <span className=\"flex min-w-0 items-center gap-0.5\">\n {box}\n <TypedDateHelper kind={helper} text={value.text} onText={retype} label={fieldName(field)} onPicked={onCommit} startOpen={value.openedAs !== undefined} />\n </span>\n ) : (\n box\n )}\n {judged === null ? (\n <span data-records-cell-note=\"\" className=\"text-[10px] text-muted-foreground\">Reading {fieldName(field)}'s choices…</span>\n ) : \"ask\" in judged ? (\n <ChoiceAskButtons\n field={field}\n words={judged.ask.words}\n keepOffered={judged.ask.keepOffered}\n onAdd={() => {\n onChange({ ...value, judged: { value: judged.ask.onAdd } });\n onCommit?.();\n }}\n onKeep={() => {\n onChange({ ...value, judged: { value: judged.ask.asTyped } });\n onCommit?.();\n }}\n onCancel={() => onCancel?.()}\n />\n ) : \"refusal\" in judged ? (\n <>\n <FloatingRefusal text={judged.refusal} why={\"why\" in judged ? judged.why : undefined} />\n {judged.cancelOnly && onCancel ? (\n <span data-records-cell-note=\"\" data-records-choice-ask=\"\">\n <Button type=\"button\" size=\"sm\" variant=\"ghost\" className=\"h-6 px-2 text-xs\" onClick={() => onCancel()}>\n Cancel\n </Button>\n </span>\n ) : null}\n </>\n ) : judged.value === null || judged.value === undefined ? null : (\n <ReadsAsNote key={value.text} typed={value.text} always={isChoiceAddition(judged.value)}>\n {isChoiceAddition(judged.value) ? `Adds ${quoted(judged.value.add)} to the choices for ${fieldName(field)}. ` : null}\n Reads as{\" \"}\n {needsChoices ? (\n String(\n (Array.isArray(withoutAddition(judged.value).value) ? (withoutAddition(judged.value).value as unknown[]) : [withoutAddition(judged.value).value])\n .map((k) => {\n const option = choices?.find((o) => optionKey(o) === k);\n return option ? recordName(option.data as RecordDocument | undefined, null, String(k)) : String(k);\n })\n .join(\", \"),\n )\n ) : (\n (() => {\n const shown = format ?? (kind === \"datetime\" ? { id: carriesTimeOfDay(field, judged.value) ? \"datetime\" : \"date\" } : undefined);\n return shown ? <FormattedValue value={judged.value} format={shown} /> : String(judged.value);\n })()\n )}\n </ReadsAsNote>\n )}\n </span>\n );\n}\n\n/** A column that holds the person's own name (\"Name\", \"Full name\", \"Your name\"). */\nfunction isPersonsName(field: Field): boolean {\n const words = `${field.key} ${field.label ?? \"\"}`.toLowerCase();\n return /(^|[\\s_])(full[\\s_]?)?name(\\s|$)/.test(words) && !/(therapist|doctor|physician|company|business|pet|room)/.test(words);\n}\n\nexport function FieldControl({ field, value, onChange, disabled, id, autoOpen, onClose, onCommit, onCancel, addsChoices, initialSearch, asForm, onChosen, recordId }: FieldEditorControlProps) {\n const host = useRecordsUi();\n const kind = editorKindFor(field);\n const inputId = id ?? `field-${field.key}`;\n // A STRANGER'S OWN PAGE FILLS HER OWN DETAILS (lane HANDOVER, 2026-09-28). A public form or\n // booking page has no records client (nobody is signed in), and there the browser may offer the\n // person's own name, email and phone. In a signed-in grid or record form it never does: the\n // cell holds somebody else's email, and the browser's suggestions would be her own.\n const ownDetails = useOptionalRecordsClient() === null;\n\n // A CELL OPENED BY TYPING edits the typed words, whatever the column's own control is.\n if (isTypedDraft(value)) return <TypedTextControl field={field} value={value} onChange={onChange} disabled={disabled} id={inputId} onCommit={onCommit} onCancel={onCancel} />;\n\n // A SIGNATURE IS DRAWN, never typed (lane 10 W1-A): the one pad, in every form, record panel\n // and grid editor that asks for this column (`signature.tsx`).\n if (isSignatureField(field)) return <SignaturePad id={inputId} value={value} onChange={onChange} disabled={disabled} />;\n\n // THE NEWER KINDS (lane 10 P4): a length of time typed as 45 min, an address in its parts, a\n // barcode typed or photographed; who made it and a count are shown, never typed.\n // NOTION-PROPS-3: a button has no control — it holds no value (a form leaves it out; a record page presses it).\n // REVIEW-3 #5: in a form for a record that exists the button presses it; before it exists it is shown, disabled,\n // with its reason (the person sees what the record will offer), never hidden and never pressable into nothing.\n if (isButtonField(field)) return <ButtonValue field={field} recordId={recordId ?? null} beforeSave={!recordId} />;\n const newerControl = newerKindControl({ field, value, onChange, disabled, id: inputId });\n if (newerControl !== undefined) return newerControl;\n\n // THE COLUMN'S OWN FORMAT EDITS ITS VALUE (merge tranche 6e): stars for a rating, a percent\n // typed as a percent whatever scale it is kept in, money typed with its symbol and commas.\n // A format with no opinion about its input falls through to the kind's own control below.\n const format = formatForField(field);\n // A TIME OF DAY IS TYPED WORDS AND A HELPER, NEVER THE BROWSER'S TIME CONTROL (grids review 3).\n if (format && format.id === \"time\") return <TypedWordsControl field={field} value={value} onChange={onChange} disabled={disabled} id={inputId} />;\n if (format && !FORMAT_BLIND_KINDS.has(String(kind))) {\n const own = formatControl({ format, value, onChange, disabled, id: inputId, label: fieldName(field), ownDetails });\n if (own) return own;\n }\n\n // A TEXT VALUE WITH INSIDES (lane JSON-FIELDS) is edited as its text, in a box that says whether it\n // still reads as structure — an offer, never a block: what is typed is what is saved.\n if ((kind === \"text\" || kind === \"long_text\") && typeof value === \"string\" && /^\\s*(?:\\[|\\{|```json)/.test(value)) {\n return <StructuredTextControl field={field} value={value} onChange={onChange} disabled={disabled} id={inputId} rows={asForm ? 8 : 3} />;\n }\n\n switch (kind) {\n case \"formula\":\n case \"lookup\":\n case \"rollup\":\n return (\n <div id={inputId} className=\"rounded border border-dashed px-2 py-1.5 text-xs text-muted-foreground\">\n {/* The store's own sentence for typing into a computed field. */}\n {value === null || value === undefined ? \"—\" : String(value)}\n <span className=\"ml-2 italic\">\n {fieldName(field)} is calculated, so it cannot be typed in\n </span>\n </div>\n );\n case \"json\":\n return <JsonControl field={field} value={value} onChange={onChange} disabled={disabled} id={inputId} />;\n case \"long_text\":\n // THE HOST'S TEXT BOX when it lends one (`textBox`): its \"…\" menu (Clean up, Help with this…,\n // Copy, Save, Share) inside the cell editor and the record form, as the Sheet had.\n if (host.textBox) {\n return host.textBox({\n value: value === null || value === undefined ? \"\" : String(value),\n onChange: (next) => onChange(next === \"\" ? null : next),\n label: fieldName(field),\n rows: 3,\n where: asForm ? \"form\" : \"cell\",\n id: inputId,\n disabled,\n });\n }\n return (\n <BasicTextarea\n id={inputId}\n rows={3}\n value={value === null || value === undefined ? \"\" : String(value)}\n disabled={disabled}\n onChange={(e) => onChange(e.target.value === \"\" ? null : e.target.value)}\n />\n );\n case \"number\":\n case \"currency\":\n case \"percent\":\n return (\n <BasicInput\n id={inputId}\n type=\"number\"\n inputMode=\"decimal\"\n className=\"tabular-nums\"\n value={value === null || value === undefined ? \"\" : String(value)}\n disabled={disabled}\n onChange={(e) => onChange(e.target.value === \"\" ? null : Number(e.target.value))}\n />\n );\n case \"datetime\":\n // A TYPED BOX AND A HELPER, NEVER THE BROWSER'S PICKER (grids review 3): the record form,\n // a public form and a bulk change read what is typed through the one date reader.\n return <TypedWordsControl field={field} value={value} onChange={onChange} disabled={disabled} id={inputId} />;\n case \"email\":\n case \"phone\":\n case \"url\":\n return (\n <BasicInput\n id={inputId}\n type={kind === \"email\" ? \"email\" : kind === \"phone\" ? \"tel\" : \"url\"}\n // THE RIGHT KEYBOARD (lane TYPEFORM-2): @ on the email keyboard, the dial pad for a phone, / and .com for a link.\n inputMode={kind === \"email\" ? \"email\" : kind === \"phone\" ? \"tel\" : \"url\"}\n {...(ownDetails ? { autoComplete: kind === \"email\" ? \"email\" : kind === \"phone\" ? \"tel\" : \"url\" } : {})}\n value={value === null || value === undefined ? \"\" : String(value)}\n disabled={disabled}\n onChange={(e) => onChange(e.target.value === \"\" ? null : e.target.value)}\n />\n );\n case \"checkbox\":\n return <CheckboxControl field={field} value={value} onChange={onChange} disabled={disabled} id={inputId} />;\n case \"select\":\n case \"multi_select\":\n return <OptionControl field={field} value={value} onChange={onChange} disabled={disabled} id={inputId} autoOpen={autoOpen} onClose={onClose} onCancel={onCancel} addsChoices={addsChoices} initialSearch={initialSearch} asForm={asForm} onChosen={onChosen} />;\n case \"member\":\n // A person field asks who is in the organization, never what is in a\n // Table — see PersonPicker's header for the screen that made this split.\n return <PersonPicker field={field} value={value} onChange={onChange} disabled={disabled} id={inputId} autoOpen={autoOpen} onClose={onClose} onCancel={onCancel} initialSearch={initialSearch} />;\n case \"entity_reference\":\n // SC-R: a note, a web site, an agent … — chips of what it names, never a text box.\n return <EntityReferenceControl field={field} value={value} onChange={onChange} disabled={disabled} id={inputId} />;\n case \"attachment\":\n // A FILE COMES FROM THE HOST'S FILE WINDOW OR AN UPLOAD (`gridAttachments.tsx`), never from a\n // list of the kernel File Table's rows. A host with neither port keeps the relation picker.\n if (hostTakesFiles(host)) {\n return <AttachmentControl field={field} value={value} onChange={onChange} disabled={disabled} id={inputId} autoOpen={autoOpen} onClose={onClose} />;\n }\n return <RelationPicker field={field} value={value} onChange={onChange} disabled={disabled} id={inputId} excludeId={recordId} />;\n case \"relation\":\n return <RelationPicker field={field} value={value} onChange={onChange} disabled={disabled} id={inputId} onPicked={onCommit} autoOpen={autoOpen} onClose={onClose} onCancel={onCancel} excludeId={recordId} />;\n default:\n if (typeof value === \"boolean\" || field.config?.[\"kind\"] === \"boolean\") {\n return (\n <Checkbox\n id={inputId}\n checked={value === true}\n disabled={disabled}\n onCheckedChange={(next) => onChange(next === true)}\n />\n );\n }\n return (\n <BasicInput\n id={inputId}\n {...(ownDetails && isPersonsName(field) ? { autoComplete: \"name\" } : {})}\n value={value === null || value === undefined ? \"\" : String(value)}\n disabled={disabled}\n onChange={(e) => onChange(e.target.value === \"\" ? null : e.target.value)}\n />\n );\n }\n}\n\n/**\n * A DATE, A TIME OR A MOMENT OUTSIDE A GRID CELL (the record form, a public form, a bulk change):\n * the same typed box and helper a cell opens, for a host that holds plain VALUES. The words are read\n * on every keystroke and the value is handed over the moment they read; words that do not read keep\n * their sentence under the box, the value stays what it was, and leaving the box puts the words back\n * to that value — so what the box shows is always what will be saved.\n */\nexport function TypedWordsControl({ field, value, onChange, disabled, id }: FieldEditorControlProps) {\n const [text, setText] = useState(() => openingText(field, value));\n const [refusal, setRefusal] = useState<string | null>(null);\n const [why, setWhy] = useState<string | undefined>(undefined);\n const sent = useRef<unknown>(value);\n // A value that moves under the box (a reload, another control) is shown — unless it is what was just read.\n useEffect(() => {\n if (value === sent.current) return;\n sent.current = value;\n setText(openingText(field, value));\n setRefusal(null);\n }, [value, field]);\n const helper = dateHelperKind(field, value);\n const retype = (next: string) => {\n setText(next);\n const judged = judgeTyped(field, next);\n if (judged && \"value\" in judged) {\n setRefusal(null);\n sent.current = judged.value;\n onChange(judged.value);\n } else if (judged && \"refusal\" in judged) {\n setRefusal(judged.refusal);\n setWhy(\"why\" in judged ? judged.why : undefined);\n }\n };\n return (\n <span className=\"flex flex-col gap-0.5\">\n <span className=\"flex min-w-0 items-center gap-0.5\">\n <BasicInput\n id={id}\n value={text}\n disabled={disabled}\n autoComplete=\"off\"\n aria-invalid={refusal ? true : undefined}\n placeholder={helper ? typedDatePlaceholder(helper) : undefined}\n onChange={(e) => retype(e.target.value)}\n onBlur={() => {\n if (!refusal) return;\n setText(openingText(field, sent.current));\n setRefusal(null);\n }}\n />\n {helper && !disabled ? <TypedDateHelper kind={helper} text={text} onText={retype} label={fieldName(field)} /> : null}\n </span>\n {refusal ? <FloatingRefusal text={refusal} why={why} /> : null}\n </span>\n );\n}\n\n/**\n * WHAT AN EMPTY DATE BOX SHOWS: the SHAPE to type, never a date (WALK3-FIX, 2026-10-07). It showed\n * \"10/03/2026 2:30 PM\" — a real-looking day — and on 10/07 a person read it as a stale default\n * prefilled into Cleanings' Appointment Date. The pattern follows the locale's own order.\n */\nexport function typedDatePlaceholder(helper: \"date\" | \"datetime\" | \"time\" | string): string {\n const time = \"h:mm AM\";\n if (helper === \"time\") return time;\n const pattern = typedDateText(\"2026-11-22\").replace(\"2026\", \"YYYY\").replace(\"11\", \"MM\").replace(\"22\", \"DD\");\n return helper === \"datetime\" ? `${pattern} ${time}` : pattern;\n}\n\n/**\n * A TICK BOX, WITH ITS THIRD STATE SAID OUT LOUD.\n *\n * LIMITS-FIX 2026-09-21. `checkbox` is the store's fourteenth parity type and it holds a\n * REAL boolean — but a record nobody has answered holds NO VALUE AT ALL, and that is a\n * different fact from `false`. An unticked box cannot show the difference, so this control\n * draws the box AND, while the answer is missing, the word \"not answered yet\" beside it\n * with the way to keep it that way. Ticking writes `true`, unticking writes `false`, and\n * \"Clear\" puts the record back to never having said — which no plain checkbox can do.\n */\nfunction CheckboxControl({ field, value, onChange, disabled, id }: FieldEditorControlProps) {\n const unanswered = value === null || value === undefined;\n return (\n <div className=\"flex items-center gap-2\">\n <Checkbox\n id={id}\n checked={value === true}\n disabled={disabled}\n aria-label={fieldName(field)}\n onCheckedChange={(next) => onChange(next === true)}\n />\n {unanswered ? (\n <span className=\"text-xs italic text-muted-foreground\">not answered yet</span>\n ) : (\n <>\n <span className=\"text-xs text-muted-foreground\">{value === true ? \"Yes\" : \"No\"}</span>\n {field.required ? null : (\n <Button\n size=\"sm\"\n variant=\"ghost\"\n className=\"h-5 px-1 text-[10px]\"\n disabled={disabled}\n onClick={() => onChange(null)}\n >\n Clear\n </Button>\n )}\n </>\n )}\n </div>\n );\n}\n\n/**\n * A document-shaped value, edited as the text it is. It is parsed on every\n * keystroke and the PARSE FAILURE IS SHOWN — a box that silently handed the\n * store unparseable text and let it answer `22P02 invalid input syntax` is a\n * refusal the person could have been spared half a second earlier.\n */\n/** Text that holds JSON, edited as text: Format indents it, and a line says when it no longer reads as JSON. */\nfunction StructuredTextControl({ field, value, onChange, disabled, id, rows }: FieldEditorControlProps & { rows: number }) {\n const text = typeof value === \"string\" ? value : \"\";\n const reads = structuredOf(text) !== null;\n return (\n <div className=\"flex flex-col gap-1\" data-records-structured-editor=\"\">\n <BasicTextarea\n id={id}\n rows={rows}\n aria-label={fieldName(field)}\n className=\"font-mono text-[11px]\"\n value={text}\n disabled={disabled}\n onChange={(e) => onChange(e.target.value === \"\" ? null : e.target.value)}\n />\n <span className=\"flex h-6 items-center gap-2 text-xs\">\n {reads ? (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"h-6 px-2 text-xs\"\n disabled={disabled}\n onClick={() => onChange(prettyJsonText(text))}\n data-records-structured-format=\"\"\n >\n Format\n </Button>\n ) : (\n <span className=\"text-amber-700 dark:text-amber-400\" data-records-structured-broken=\"\">\n Not valid JSON — saves as plain text\n </span>\n )}\n </span>\n </div>\n );\n}\n\nfunction JsonControl({ field, value, onChange, disabled, id }: FieldEditorControlProps) {\n const initial = value === null || value === undefined ? \"\" : typeof value === \"string\" ? value : JSON.stringify(value, null, 2);\n const [text, setText] = useState(initial);\n const [broken, setBroken] = useState<RecordsError | null>(null);\n return (\n <div className=\"flex flex-col gap-1\">\n <BasicTextarea\n id={id}\n rows={4}\n className=\"font-mono text-[11px]\"\n value={text}\n disabled={disabled}\n onChange={(e) => {\n const next = e.target.value;\n setText(next);\n if (next.trim() === \"\") {\n setBroken(null);\n onChange(null);\n return;\n }\n try {\n onChange(JSON.parse(next));\n setBroken(null);\n } catch (thrown) {\n // The parser's own words (\"Unexpected token } in JSON at position 14\")\n // are an engineer's: they go out of sight, the person reads a sentence.\n setBroken(\n refusalFromThrown(\n thrown,\n `${fieldName(field)} is not readable as structured data yet.`,\n \"Fix the text so it reads as structured data, or discard it to put back what was there.\",\n \"invalid_argument\",\n ),\n );\n }\n }}\n />\n {broken ? (\n // The typed text is still in the box: the notice owns the two doors out. In a grid cell it\n // floats over the table (`data-records-cell-note`), so the row never grows.\n <span data-records-cell-note=\"\" className=\"block\">\n <RefusalNotice\n error={broken}\n onKeepEditing={() => (id ? document.getElementById(id)?.focus() : undefined)}\n onDiscard={() => {\n setText(initial);\n setBroken(null);\n }}\n />\n </span>\n ) : null}\n </div>\n );\n}\n\n/**\n * THE ORDER THE STORE KEEPS (STORE-RULE-GAPS). Every option carries the position it was\n * declared at in `metadata.option_position` — the list as a person wrote it, and a choice\n * added by typing goes LAST, where the store put it. `custom.field_options` answers in no\n * particular order, so this control orders by that position (a row with none after those\n * that have one, then by when it was made) instead of drawing whatever order came back.\n */\nexport function inTheStoresOrder(options: StoredRecord[]): StoredRecord[] {\n const position = (o: StoredRecord): number => {\n const raw = (o as { metadata?: Record<string, unknown> | null }).metadata?.[\"option_position\"];\n const n = typeof raw === \"number\" ? raw : typeof raw === \"string\" ? Number(raw) : Number.NaN;\n return Number.isFinite(n) ? n : Number.POSITIVE_INFINITY;\n };\n const made = (o: StoredRecord): string => String((o as { created_at?: unknown }).created_at ?? \"\");\n return [...options].sort((a, b) => position(a) - position(b) || made(a).localeCompare(made(b)));\n}\n\n/**\n * FLD-5 / FLD-6. A pick-list IS a Table and an option is a Record of it — that part is\n * unchanged. What a CELL holds is the option's own stable WORD (its key), not the\n * option record's uuid, so renaming a choice rewrites no row; the read doors hand\n * back the LABEL and name the key beside it in `_choices`. This control therefore\n * recognizes all three ways of naming the same choice — `isTheChosen` — and WRITES\n * the key, which is the contract. The options are read through the store's own\n * `custom.field_options` door, which resolves the options Table from the Field's\n * config — this component never has to know which Table that is.\n */\nfunction OptionControl({ field, value, onChange, disabled, id, autoOpen, onClose, onCancel, addsChoices, initialSearch, asForm, onChosen }: FieldEditorControlProps) {\n // NOT `useRecordsClient`. A drop-down is the commonest question on a public\n // form, and this control asked the hook that THROWS for a client the public\n // arm of `FormRunner` deliberately never mounts — so a stranger opening a\n // form with one choice question got HTTP 500 (VERIFIER-10, F1).\n const client = useOptionalRecordsClient();\n const [options, setOptions] = useState<StoredRecord[] | null>(null);\n const [refusal, setRefusal] = useState<RecordsError | null>(null);\n /** Bumped when this control added a choice, so the list is read again. */\n const [reread, setReread] = useState(0);\n\n useEffect(() => {\n if (!client) return;\n let cancelled = false;\n void fieldOptionsOnce(client, field.id).then((result) => {\n if (cancelled) return;\n if (result.ok) setOptions(inTheStoresOrder(result.data ?? []));\n else setRefusal(result.error);\n });\n return () => {\n cancelled = true;\n };\n }, [client, field.id, reread]);\n\n // EVERY STATE CARRIES THE CELL'S OWN ID. A cell that identified itself only\n // when it happened to be a text box is a cell nobody can tell apart from the\n // developer window that used to open instead of it.\n // A PUBLIC PAGE CARRIES THE CHOICES IT ASKS (lane HANDOVER, 2026-09-28): the form and booking\n // doors hand each choice question its live choices' labels as `public_choices`, so a stranger\n // picks \"Follow-up\" instead of typing a word the owner then has to match up.\n const handed = publicChoicesOf(field);\n if (!client && handed.length > 0) {\n // A public page IS a form: its choices are laid out in their own colors (`ChoiceAnswer`).\n return <ChoiceAnswer field={field} choices={handed} value={value} onChange={onChange} disabled={disabled} id={id} onChosen={onChosen} />;\n }\n if (!client) {\n // ABSENT AND HONEST. The choices of a field live in the owner's own data,\n // and a page answered without an account may not read it — so the question\n // says what it is and takes the answer as text rather than drawing an empty\n // drop-down or taking the page down.\n return (\n <div className=\"flex flex-col gap-1\">\n <BasicInput\n id={id}\n value={value === null || value === undefined ? \"\" : String(value)}\n disabled={disabled}\n onChange={(e) => onChange(e.target.value === \"\" ? null : e.target.value)}\n />\n {/* The Field's own name is printed above by `FieldLabel`; saying it\n again here is how the screen read \"Service typeService type is…\". */}\n <p className=\"text-xs text-muted-foreground\">\n This is normally picked from a list. A page answered without an account cannot read that\n list, so type your answer and whoever receives it will match it up.\n </p>\n </div>\n );\n }\n if (refusal)\n return (\n <div id={id}>\n <RefusalLine error={refusal} />\n </div>\n );\n if (!options) return <p id={id} className=\"text-xs text-muted-foreground\">Reading this field's choices…</p>;\n if (asForm && options.length > 0) {\n const titled = (option: StoredRecord) => recordName(option.data as RecordDocument | undefined, null, \"Unnamed choice\");\n return (\n <ChoiceAnswer\n field={field}\n choices={options.map((option) => ({ key: optionKey(option), label: titled(option) }))}\n value={value}\n onChange={onChange}\n disabled={disabled}\n id={id}\n onChosen={onChosen}\n isChosen={(choice, v) => {\n const option = options.find((o) => optionKey(o) === choice.key);\n return option ? isTheChosen(option, v) : false;\n }}\n />\n );\n }\n // ONE PICKER FOR EVERY CHOICE COLUMN (lane CHOICE-TAILS, 2026-09-27). A column that takes other\n // values and one that takes only its own choices draw the same combobox: search the choices,\n // pick one, or type a word that is none of them and be asked (Add / Keep as typed only where\n // the column takes other values / Cancel), exactly as a grid cell asks. The record form used to\n // draw a closed drop-down for a closed column, so a person filling in a record had no way to\n // add the word they needed. Outside a grid cell (the record form, the form runner) there is no\n // `autoOpen`, so the list opens on a press; in a grid cell it opens at once and closing it commits.\n // A GRID CELL IS NO EXCEPTION (merged-grid review 2, A2): its list used to be a plain drop-down\n // with no search, so Enter opened a list a person could not type into. Every choice cell now\n // opens THIS picker — search, arrows, Enter picks, Escape closes.\n // A COLUMN WITH NO CHOICES OFFERS TO GET THEM HERE (Law 6: offers, never blocks).\n const noChoicesYet = client && options.length === 0 && !disabled;\n const offerChoices = noChoicesYet ? (\n <AddChoicesInline\n field={field}\n onAdded={() => {\n forgetAsked(client, `field_options:${field.id}`);\n setReread((n) => n + 1);\n }}\n />\n ) : null;\n if (CHOICE_EDITOR_ADDS_WHAT_IS_TYPED) {\n return (\n <>\n {offerChoices}\n <OpenChoicePicker\n field={field}\n options={options}\n value={value}\n onChange={onChange}\n disabled={disabled}\n id={id}\n autoOpen={autoOpen}\n onClose={onClose}\n onCancel={onCancel}\n initialSearch={initialSearch}\n addsChoices={addsChoices}\n allowOther={allowsOtherValues(field)}\n onChoicesChanged={() => {\n // The kept answer is stale now: the next read asks the store.\n if (client) forgetAsked(client, `field_options:${field.id}`);\n setReread((n) => n + 1);\n }}\n />\n </>\n );\n }\n if (options.length === 0) {\n // Two different facts, and a person acts on them differently: a choice\n // field whose Table is empty, and a choice field that names no Table at\n // all. One blank control for both is the silent failure.\n return (\n <p id={id} className=\"text-xs text-muted-foreground\">\n {field.options_table_id\n ? `${fieldName(field)} takes its choices from a Table that has no records yet — add the choices there and they appear here.`\n : `${fieldName(field)} does not name the Table its choices come from yet, so there is nothing to choose. A table admin sets it in the field editor.`}\n </p>\n );\n }\n\n const titleOf = (option: StoredRecord) =>\n recordName(option.data as RecordDocument | undefined, null, \"Unnamed choice\");\n\n if (field.multi) {\n // WHAT IS PICKED, however the value says it. The document a read door hands this\n // control carries LABELS; the row holds KEYS; a screen written before this contract\n // sends IDS. `isTheChosen` knows all three, and what goes back is always the key.\n const chosen = options.filter((option) => choiceValuesOf(value).some((v) => isTheChosen(option, v)));\n const picked = new Set(chosen.map((option) => optionKey(option)));\n const toggles = (\n <div id={autoOpen ? undefined : id} className=\"flex flex-wrap gap-1\">\n {options.map((option) => (\n <Button\n key={option.id}\n type=\"button\"\n size=\"sm\"\n variant={picked.has(optionKey(option)) ? \"default\" : \"outline\"}\n disabled={disabled}\n onClick={() => {\n const next = new Set(picked);\n if (next.has(optionKey(option))) next.delete(optionKey(option));\n else next.add(optionKey(option));\n onChange(next.size === 0 ? null : [...next]);\n }}\n >\n {titleOf(option)}\n </Button>\n ))}\n </div>\n );\n if (!autoOpen) return toggles;\n // IN A GRID CELL: the list floats over the grid (portalled), so the row never grows; the cell\n // commits what is ticked when the list closes.\n return (\n <Popover\n defaultOpen\n onOpenChange={(open) => {\n if (!open) onClose?.();\n }}\n >\n <PopoverTrigger asChild>\n <Button id={id} type=\"button\" size=\"sm\" variant=\"outline\" className=\"h-6 max-w-full truncate\">\n {chosen.length === 0 ? \"Choose\" : chosen.map(titleOf).join(\", \")}\n </Button>\n </PopoverTrigger>\n <PopoverContent sizing=\"content\" className=\"max-w-[20rem] p-2\" align=\"start\">\n {toggles}\n </PopoverContent>\n </Popover>\n );\n }\n\n // The SINGLE choice, the same way: what is selected is worked out from the option, not\n // from a string comparison against whatever spelling the document happened to use, and\n // what goes back is the key.\n const current = options.find((option) => isTheChosen(option, value));\n return (\n <Select\n value={current ? optionKey(current) : \"\"}\n disabled={disabled ?? false}\n onValueChange={(next) => onChange(next === \"\" ? null : next)}\n {...(autoOpen\n ? {\n // IN A GRID CELL the list opens at once and a pick is the commit (Airtable).\n defaultOpen: true,\n onOpenChange: (open: boolean) => {\n if (!open) onClose?.();\n },\n }\n : {})}\n >\n <SelectTrigger id={id} size=\"sm\">\n <SelectValue placeholder=\"Choose\" />\n </SelectTrigger>\n <SelectContent>\n {options.map((option) => (\n <SelectItem key={option.id} value={optionKey(option)}>\n {titleOf(option)}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n );\n}\n\n/**\n * A CHOICE COLUMN THAT TAKES OTHER VALUES (STORE-RULE-GAPS). The relation picker's shape —\n * a search box over the choices and a line at the foot for words that are not one of them.\n * What that line does is `decideTypedChoice` with the `custom/choice_nudge` knob: ask (Add /\n * Keep as typed / Cancel), add without asking, or keep as typed. Add REALLY adds (see\n * `ChoiceAddition` above); Keep as typed sends the words and the store keeps them as an other\n * value. A word that already names a choice (by key or label, any case) is that choice.\n */\nfunction OpenChoicePicker({\n field,\n options,\n value,\n onChange,\n disabled,\n id,\n addsChoices,\n autoOpen,\n onClose,\n onCancel,\n initialSearch,\n allowOther = true,\n onChoicesChanged,\n}: FieldEditorControlProps & { options: StoredRecord[]; allowOther?: boolean; onChoicesChanged: () => void }) {\n const client = useOptionalRecordsClient();\n const nudge = useChoiceNudge();\n // IN A GRID CELL the list is open from the start and closing it is the cell's commit.\n const [open, setOpenState] = useState(autoOpen === true);\n const onCloseRef = useRef(onClose);\n onCloseRef.current = onClose;\n const setOpen = useCallback((next: boolean) => {\n setOpenState(next);\n if (!next) onCloseRef.current?.();\n }, []);\n const [search, setSearch] = useState(initialSearch ?? \"\");\n const [adding, setAdding] = useState(false);\n const [addRefused, setAddRefused] = useState<RecordsError | null>(null);\n const titleOf = (option: StoredRecord) =>\n recordName(option.data as RecordDocument | undefined, null, \"Unnamed choice\");\n const held = withoutAddition(value);\n const current = choiceValuesOf(held.value);\n const pickedWords = current.map((v) => {\n const option = options.find((o) => isTheChosen(o, v));\n return option ? titleOf(option) : String(v);\n });\n // A CHOICE WEARS ITS OWN COLOR HERE TOO (W1-B item 2): the picked chip and every option in the\n // list are the chip the grid cell draws (`choiceChipLookOf`), never the theme's accent.\n const chipOf = (option: StoredRecord | undefined, word: string) =>\n option ? choiceChipLookOf(field, optionKey(option), titleOf(option)) : choiceChipLookOf(field, word);\n const q = search.trim();\n // THE ONE RANKING (`@ai-matrx/records` `rankTypedMatches`, grids review 3): exact, starts with,\n // a word starts with, contains — `Cal` highlights Calibration, never Electrical.\n const visible = rankTypedMatches(options, q, titleOf);\n const decided = decideTypedChoice({ words: q, options, allowOther, nudge: nudge ?? \"ask\" });\n\n /** The cell takes `word`; `adding` says whether it is also added to the choices. */\n const choose = (word: string, addingIt = false) => {\n const pending = held.add.filter((w) => w.toLowerCase() !== word.toLowerCase());\n let next: unknown;\n let add: string[] = [...pending];\n if (field.multi) {\n const existing = current.map((v) => {\n const option = options.find((o) => isTheChosen(o, v));\n return option ? optionKey(option) : String(v);\n });\n const has = existing.some((v) => v.toLowerCase() === word.toLowerCase());\n const list = has ? existing.filter((v) => v.toLowerCase() !== word.toLowerCase()) : [...existing, word];\n if (addingIt && !has) add.push(word);\n add = add.filter((w) => list.some((v) => v.toLowerCase() === w.toLowerCase()));\n next = list.length === 0 ? null : list;\n } else {\n add = addingIt ? [word] : [];\n next = word;\n }\n onChange(add.length > 0 ? choiceAddition(next, add) : next);\n setSearch(\"\");\n // A SINGLE CHOICE IS DONE ON THE PICK — closed AFTER the value is handed over, because in a grid\n // cell closing is the commit and it must commit what was just picked.\n if (!field.multi) setOpen(false);\n };\n\n /** Add the typed words to the choices, and the cell takes them. */\n const addTyped = () => {\n setAddRefused(null);\n if (addsChoices || !client) {\n choose(q, Boolean(addsChoices));\n return;\n }\n // A HOST THAT SAVES WORDS ONLY (the record form): the choice is added now, through the\n // column's own door, and the cell then takes its words — which name a choice by then.\n setAdding(true);\n void client.fieldUpdate({ field_id: field.id, patch: { options_add: [q] } }).then((result) => {\n setAdding(false);\n if (!result.ok) {\n setAddRefused(result.error);\n return;\n }\n onChoicesChanged();\n choose(q);\n });\n };\n\n const offList = q !== \"\" && decided.decision !== \"chosen\" && decided.decision !== \"empty\";\n // A NEW WORD IS ONE \"CREATE\" ROW, NEVER A QUESTION (lane CELL-EDITORS, night walk 2026-10-06; Notion):\n // typing \"Webinar\" in Kind of work replaced the list with 'Add \"Webinar\" to the choices for Kind of\n // work?' and Add / Cancel. Now the list shows what matches and \"Create “Webinar”\" sits at its foot.\n // ONE FIXED SPOT, AND THE LIST FILTERED (REVIEW-FIX 7, 2026-10-06 — Notion): the Create row used to\n // jump to the top when nothing matched, and a no-match search listed every choice. Now it is always\n // the last row, under the matches only; with no match it is the only row, so one Enter creates it.\n // A column that takes no new choices says so instead.\n const foot = null;\n const add =\n offList && (decided.decision === \"ask\" || decided.decision === \"add\")\n ? { label: `Create “${q}”`, onAdd: addTyped, disabled: adding }\n : offList && decided.decision === \"keep_as_typed\"\n ? { label: `Use “${q}”`, onAdd: () => choose(q) }\n : null;\n const listed = visible;\n\n const pickedOptions = current.map((v) => options.find((o) => isTheChosen(o, v)));\n const cellChips = pickedWords.map((word, i) => {\n const chip = chipOf(pickedOptions[i], word);\n return (\n <Badge key={word} variant=\"outline\" className={cn(\"text-[11px]\", chip.className)} data-records-choice-chip=\"\">\n {word}\n </Badge>\n );\n });\n // WHAT IS PICKED, AT THE HEAD OF THE OPEN LIST, EACH WITH ITS × (Airtable, Notion, the old Sheet).\n const headChips = pickedWords.map((word, i) => {\n const option = pickedOptions[i];\n return {\n id: `${word}-${i}`,\n label: word,\n chip: chipOf(option, word).className,\n onRemove: () => {\n if (field.multi) choose(option ? optionKey(option) : String(current[i]));\n else onChange(null);\n },\n };\n });\n const anchored = autoOpen === true;\n\n return (\n <div id={id} className=\"flex flex-wrap items-center gap-1\">\n {anchored || disabled ? null : cellChips}\n {disabled ? (\n cellChips\n ) : (\n // THE ONE \"PICK OR ADD\" BUILDER (PickOrAdd.tsx) — the relation picker draws the same one.\n // In a grid cell it hangs from the cell's own chips; no button is drawn in the cell.\n <PickOrAdd\n anchored={anchored}\n {...(anchored && onCancel ? { onEscape: onCancel } : {})}\n chips={headChips}\n multi={field.multi}\n triggerLabel={`Pick for ${fieldName(field)}`}\n triggerText={pickedWords.length === 0 ? \"Choose\" : \"Change\"}\n open={open}\n onOpenChange={setOpen}\n search={search}\n onSearch={(next) => {\n setSearch(next);\n setAddRefused(null);\n }}\n items={listed.map((option) => ({\n id: option.id,\n label: titleOf(option),\n chip: chipOf(option, titleOf(option)).className,\n picked: current.some((v) => isTheChosen(option, v)),\n }))}\n onPick={(optionId) => {\n const option = options.find((o) => o.id === optionId);\n if (option) choose(optionKey(option));\n }}\n empty={q === \"\" ? <p className=\"p-2 text-xs text-muted-foreground\">No choices yet — type one to add it.</p> : null}\n add={add}\n foot={foot}\n // ENTER ON A NEW WORD answers the question with its first answer — Add — exactly as Tab\n // then Enter does (grids review 3); a column that may not take it says so and Enter waits.\n footNote={\n addRefused ? (\n <RefusalLine error={addRefused} />\n ) : offList && decided.decision === \"not_a_choice\" ? (\n // never_add on a column that takes only its choices: said, never a silent nothing.\n <>\n <p data-records-typed-refusal=\"\" className=\"p-2 text-xs text-muted-foreground\">\n {notAChoiceSentence(field, [q])}\n </p>\n {autoOpen ? (\n <span data-records-choice-ask=\"\" className=\"px-2 pb-1\">\n <Button type=\"button\" size=\"sm\" variant=\"ghost\" className=\"h-6 px-2 text-xs\" onClick={() => setOpen(false)}>\n Cancel\n </Button>\n </span>\n ) : null}\n </>\n ) : null\n }\n >\n {anchored ? cellChips : null}\n </PickOrAdd>\n )}\n </div>\n );\n}\n\n/** The chip a picked record shows as — REC-2's \"a record is a chip\" in one place. */\nexport function RecordChip({\n title,\n onRemove,\n className,\n}: {\n title: string;\n onRemove?: (() => void) | undefined;\n className?: string | undefined;\n}) {\n return (\n // A chip carries a RECORD'S OWN TITLE, which nobody here chose the length of —\n // \"Marisol Okonkwo — 418 Calle Puerto Vallarta, Camarillo\" is an ordinary customer\n // name. So it caps at its container and ends in an ellipsis with the whole name in\n // its tooltip, rather than being cut mid-word by whatever box it landed in\n // (lane FIX-14, 2026-09-22).\n <Badge variant=\"secondary\" className={cn(\"max-w-full gap-1 text-[11px]\", className)} title={title}>\n <span className=\"min-w-0 truncate\">{title}</span>\n {onRemove ? (\n <button type=\"button\" onClick={onRemove} aria-label={`Remove ${title}`} className=\"shrink-0 opacity-60 hover:opacity-100\">\n ×\n </button>\n ) : null}\n </Badge>\n );\n}\n\nexport type { Uuid };\n\n/** The choices a public page was handed for this question (`public_choices`), or none. */\nexport function publicChoicesOf(field: Field): Array<{ key: string; label: string }> {\n const raw = (field as unknown as { public_choices?: unknown }).public_choices;\n if (!Array.isArray(raw)) return [];\n return raw.flatMap((c) => {\n const o = c as { key?: unknown; label?: unknown };\n return typeof o.key === \"string\" && typeof o.label === \"string\" ? [{ key: o.key, label: o.label }] : [];\n });\n}\n\n/** How many choices a form lays out before it adds a search box above them. */\nexport const FORM_SEARCH_AFTER = 8;\n\n/** The keys a person presses to pick a choice, Typeform's way: A for the first, B for the second. */\nconst CHOICE_LETTERS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\n/**\n * A CHOICE ANSWERED ON A FORM (MAKE-HOME W5b — Typeform, Tally). Every choice is a full-width row in\n * the form's own color (the theme's primary, which the form's look sets), with its letter: pressing\n * A picks the first, B the second, and Enter goes on. The verifier walk (2026-10-02) found the\n * choices drawn as pills sized to their words in every color of the grid's palette — a stranger's\n * intake form read as a table's cells. Past eight choices a search box sits above the rows. A single\n * choice is a radio group; several are toggles. The answer is the choice's key.\n */\nexport function ChoiceAnswer({\n field,\n choices,\n value,\n onChange,\n disabled,\n id,\n isChosen,\n onChosen,\n}: {\n field: Field;\n /** A single choice was picked (not un-picked): the form may go on. */\n onChosen?: (() => void) | undefined;\n choices: ReadonlyArray<{ key: string; label: string }>;\n value: unknown;\n onChange: (value: unknown) => void;\n disabled?: boolean | undefined;\n id?: string | undefined;\n /** Whether `choice` is what `v` holds; defaults to its key or label, as written. */\n isChosen?: ((choice: { key: string; label: string }, v: unknown) => boolean) | undefined;\n}) {\n const [search, setSearch] = useState(\"\");\n const held = field.multi ? choiceValuesOf(value) : value === null || value === undefined || value === \"\" ? [] : [value];\n const on = (choice: { key: string; label: string }) =>\n held.some((v) => (isChosen ? isChosen(choice, v) : String(v) === choice.key || String(v) === choice.label));\n const press = (choice: { key: string; label: string }) => {\n if (!field.multi) {\n const picking = !on(choice);\n onChange(picking ? choice.key : null);\n if (picking) onChosen?.();\n return;\n }\n const keys = choices.filter((c) => (c.key === choice.key ? !on(c) : on(c))).map((c) => c.key);\n onChange(keys.length === 0 ? null : keys);\n };\n const lettered = choices.length <= CHOICE_LETTERS.length;\n // ROVING FOCUS (lane TYPEFORM-2): one Tab stop — the chosen choice, or the first — and the arrow\n // keys move between choices; on a single choice an arrow also picks, as a radio group does.\n const tabStop = choices.find((c) => on(c))?.key ?? choices[0]?.key;\n const option = (choice: { key: string; label: string }) => {\n const chosen = on(choice);\n const letter = lettered ? CHOICE_LETTERS[choices.indexOf(choice)] : null;\n return (\n <button\n key={choice.key}\n type=\"button\"\n role={field.multi ? \"checkbox\" : \"radio\"}\n aria-checked={chosen}\n aria-label={choice.label}\n disabled={disabled}\n tabIndex={field.multi || choice.key === tabStop ? 0 : -1}\n onClick={() => press(choice)}\n data-records-choice-answer={choice.key}\n className={cn(\n \"flex min-h-11 w-full items-center gap-3 rounded-md border px-3 py-2 text-left text-base font-medium text-foreground transition-colors sm:min-h-10 sm:text-sm\",\n chosen ? \"border-primary bg-primary/10\" : \"border-primary/30 bg-primary/[0.03] hover:bg-primary/10\",\n )}\n >\n {letter ? (\n <kbd\n aria-hidden=\"true\"\n className={cn(\n \"inline-flex h-6 w-6 shrink-0 items-center justify-center rounded border font-sans text-xs font-semibold\",\n chosen ? \"border-primary bg-primary text-primary-foreground\" : \"border-primary/40 text-primary\",\n )}\n >\n {letter}\n </kbd>\n ) : null}\n <span className=\"min-w-0 flex-1 break-words\">{choice.label}</span>\n {chosen ? (\n <span aria-hidden=\"true\" className=\"shrink-0 text-primary\">\n ✓\n </span>\n ) : null}\n </button>\n );\n };\n // THE LETTER KEYS: anywhere in the question but the search box, a letter picks its choice.\n const onKeyDown = (event: React.KeyboardEvent) => {\n if (disabled || event.metaKey || event.ctrlKey || event.altKey) return;\n if ((event.target as HTMLElement).tagName === \"INPUT\") return;\n const arrow = { ArrowDown: 1, ArrowRight: 1, ArrowUp: -1, ArrowLeft: -1 }[event.key];\n if (arrow) {\n const buttons = Array.from(\n (event.currentTarget as HTMLElement).querySelectorAll<HTMLButtonElement>(\"[data-records-choice-answer]\"),\n );\n const here = buttons.indexOf(event.target as HTMLButtonElement);\n if (buttons.length === 0) return;\n event.preventDefault();\n const next = buttons[(Math.max(here, 0) + arrow + buttons.length) % buttons.length]!;\n next.focus();\n if (!field.multi) {\n const choice = choices.find((c) => c.key === next.dataset[\"recordsChoiceAnswer\"]);\n if (choice && !on(choice)) onChange(choice.key);\n }\n return;\n }\n if (!lettered) return;\n const at = CHOICE_LETTERS.indexOf(event.key.toUpperCase());\n if (event.key.length !== 1 || at < 0 || at >= choices.length) return;\n event.preventDefault();\n press(choices[at]!);\n };\n const group = { role: field.multi ? \"group\" : \"radiogroup\", \"aria-label\": fieldName(field), onKeyDown } as const;\n if (choices.length <= FORM_SEARCH_AFTER) {\n return (\n <div id={id} className=\"flex w-full flex-col gap-2\" {...group}>\n {choices.map(option)}\n </div>\n );\n }\n const q = search.trim().toLowerCase();\n const shown = q === \"\" ? choices : choices.filter((c) => c.label.toLowerCase().includes(q));\n return (\n <div id={id} className=\"flex w-full flex-col gap-2\" onKeyDown={onKeyDown}>\n <BasicInput\n value={search}\n onChange={(e) => setSearch(e.target.value)}\n placeholder=\"Search\"\n aria-label={`Search — ${fieldName(field)}`}\n autoComplete=\"off\"\n className=\"h-11 text-base sm:h-9 sm:text-sm\"\n />\n <div className=\"flex max-h-80 w-full flex-col gap-2 overflow-y-auto\" role={group.role} aria-label={group[\"aria-label\"]}>\n {shown.map(option)}\n {shown.length === 0 ? <p className=\"text-xs text-muted-foreground\">No match</p> : null}\n </div>\n </div>\n );\n}\n","\"use client\";\n\n// src/newerKindValues.tsx — @ai-matrx/records-ui\n//\n// HOW THE NINE NEWER KINDS ARE SHOWN AND EDITED (lane 10 VIEWS-AND-FIELDS, sublane P4; champions:\n// Airtable's and SmartSuite's field types). One component per job, reached from the ONE value\n// drawing (`values.tsx`: RecordValue / renderValue / scalarText) and the ONE control\n// (`editors.tsx`: FieldControl), so the grid, the gallery, the board, the calendar, the record\n// panel and every form draw a kind the same way:\n//\n// rating stars (the registry's `rating` format, its top star read from the max Rule)\n// duration h:mm, typed as 45 min, 1:30 or 1h 30m\n// created by an initial and a name; last changed by — the same\n// status the choice chip, with its group's mark (To do ○, In progress ◐, Done ●)\n// address one line, opened in maps; edited in its five parts\n// barcode the code in monospace; on a phone that can, a photo of it fills it in\n// rich text Markdown drawn as React elements — never raw HTML, never innerHTML\n// count a whole number\n//\n// The store judges every value (`custom._kind_value_ok`); what is here only draws and reads.\n\nimport { useEffect, useRef, useState, type ReactNode } from \"react\";\nimport { codeSpanText, findInlineCodeSpans } from \"@ai-matrx/content-ir/source\";\nimport {\n ADDRESS_PARTS,\n NOT_A_MEMBER_WORDS,\n STATUS_GROUP_WORDS,\n addressMapUrl,\n addressValueText,\n durationText,\n isAddressValue,\n isPersonStamp,\n newerKindOf,\n personStampText,\n readTypedDuration,\n safeLinkHref,\n statusGroupOf,\n type AddressPart,\n type AddressValue,\n type Field,\n type PersonStamp,\n type StatusGroup,\n} from \"@ai-matrx/records\";\nimport { BasicInput, cn } from \"@ai-matrx/design-system\";\nimport { OutboundLink } from \"@ai-matrx/kit/outbound-react\";\n\nconst own = (event: { stopPropagation: () => void }) => event.stopPropagation();\n\n// ── READ ───────────────────────────────────────────────────────────────────────────────────\n\n/**\n * One value of a newer kind, drawn — or `undefined` when the field is not one of the kinds drawn\n * here (the caller's own drawing applies). Never called for an empty value.\n */\nexport function newerKindValue(field: Field, value: unknown, opts: { inCell?: boolean | undefined } = {}): ReactNode | undefined {\n switch (newerKindOf(field)) {\n case \"duration\": {\n const words = durationText(value);\n return words === null ? undefined : (\n <span className=\"tabular-nums\" data-records-duration=\"\">\n {words}\n </span>\n );\n }\n case \"created_by\":\n case \"modified_by\":\n return isPersonStamp(value) ? <PersonStampChip stamp={value} /> : undefined;\n case \"address\":\n return isAddressValue(value) || typeof value === \"string\" ? <AddressLink value={value} /> : undefined;\n case \"barcode\":\n return typeof value === \"string\" ? (\n <span className=\"inline-flex min-w-0 items-center gap-1 font-mono text-xs\" data-records-barcode=\"\" title={value}>\n <span aria-hidden=\"true\" className=\"text-muted-foreground\">\n ▮▯▮\n </span>\n <span className=\"truncate\">{value}</span>\n </span>\n ) : undefined;\n case \"rich_text\":\n return typeof value === \"string\" ? <SafeMarkdown text={value} clipped={opts.inCell === true} /> : undefined;\n case \"count\":\n return typeof value === \"number\" ? <span className=\"tabular-nums\">{value.toLocaleString()}</span> : undefined;\n default:\n return undefined;\n }\n}\n\n/**\n * Who made or last changed a record: an initial and a name — or, for a write the platform made,\n * \"System\", and for an agent's, \"Agent for\" the person it wrote for (V8 #4).\n */\nexport function PersonStampChip({ stamp }: { stamp: PersonStamp }) {\n const words = personStampText(stamp) ?? NOT_A_MEMBER_WORDS;\n const tier = stamp.actor ?? \"user\";\n const name = tier === \"user\" ? stamp.name : null;\n const initial = tier === \"system\" ? \"⚙\" : tier === \"agent\" ? \"✦\" : name && name.trim() !== \"\" ? name.trim()[0]!.toUpperCase() : \"?\";\n return (\n <span className=\"inline-flex min-w-0 items-center gap-1.5\" data-records-person-stamp={tier}>\n <span\n aria-hidden=\"true\"\n className=\"inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-muted text-[10px] font-medium text-foreground\"\n >\n {initial}\n </span>\n <span className={cn(\"truncate\", tier === \"user\" && !name ? \"italic text-muted-foreground\" : \"\")}>{words}</span>\n </span>\n );\n}\n\nfunction AddressLink({ value }: { value: AddressValue | string }) {\n const words = addressValueText(value);\n const href = addressMapUrl(value);\n if (!words || !href) return <span className=\"text-muted-foreground\">—</span>;\n return (\n <OutboundLink\n href={href}\n className=\"inline-flex min-w-0 items-center gap-1 text-primary hover:underline\"\n title=\"Open in maps\"\n data-records-address=\"\"\n onClick={own}\n >\n <span aria-hidden=\"true\">⌖</span>\n <span className=\"truncate\">{words}</span>\n </OutboundLink>\n );\n}\n\n/** The mark a status group wears beside its choice, Linear's way. */\nexport const STATUS_GROUP_MARK: Record<StatusGroup, string> = { todo: \"○\", in_progress: \"◐\", done: \"●\" };\n\n/**\n * The group mark for one status value, with the group's name for hover; null when not a status.\n * The read puts the choice's WORDS in the cell and its KEY under `_choices` (V8 #2: every chip read\n * \"○ To do\" because the words were looked up as a key) — so the key is read from `_choices` first.\n */\nexport function statusMarkOf(\n field: Field,\n value: unknown,\n document?: Record<string, unknown> | null,\n): { mark: string; group: StatusGroup; words: string } | null {\n if (newerKindOf(field) !== \"status\" || typeof value !== \"string\") return null;\n const chosen = (document?.[\"_choices\"] as Record<string, unknown> | undefined)?.[field.key];\n const key = chosen && typeof chosen === \"object\" && typeof (chosen as { key?: unknown }).key === \"string\" ? (chosen as { key: string }).key : value;\n const group = statusGroupOf(field, key);\n return { mark: STATUS_GROUP_MARK[group], group, words: STATUS_GROUP_WORDS[group] };\n}\n\n// ── RICH TEXT: A SAFE SUBSET OF MARKDOWN, AS REACT ELEMENTS ───────────────────────────────\n\n/**\n * Inline Markdown: **bold**, _italic_ / *italic*, `code`, [words](https://…). Everything else is text.\n * Code spans are found by THE rule (`findInlineCodeSpans`, @ai-matrx/content-ir/source) and drawn first;\n * the marks are read only in the text between them.\n */\nfunction inline(text: string, key: string): ReactNode[] {\n const out: ReactNode[] = [];\n let at = 0;\n let n = 0;\n for (const r of findInlineCodeSpans(text)) {\n if (r.start < at) continue;\n if (r.start > at) out.push(...marks(text.slice(at, r.start), `${key}-m${n++}`));\n out.push(<code key={`${key}-c${n++}`} className=\"rounded bg-muted px-1 font-mono text-[0.9em]\">{codeSpanText(text.slice(r.start, r.end))}</code>);\n at = r.end;\n }\n if (at < text.length) out.push(...marks(text.slice(at), `${key}-m${n++}`));\n return out;\n}\n\n/** The marks of inline text that holds no code span: bold, italic, links. */\nfunction marks(text: string, key: string): ReactNode[] {\n const out: ReactNode[] = [];\n const re = /(\\*\\*[^*]+\\*\\*|__[^_]+__|\\[[^\\]]+\\]\\([^)\\s]+\\)|\\*[^*\\s][^*]*\\*|_[^_\\s][^_]*_)/g;\n let last = 0;\n let i = 0;\n for (const m of text.matchAll(re)) {\n const at = m.index ?? 0;\n if (at > last) out.push(text.slice(last, at));\n const tok = m[0];\n const k = `${key}-${i++}`;\n if (tok.startsWith(\"**\") || tok.startsWith(\"__\")) out.push(<strong key={k}>{tok.slice(2, -2)}</strong>);\n else if (tok.startsWith(\"[\")) {\n const link = /^\\[([^\\]]+)\\]\\(([^)\\s]+)\\)$/.exec(tok);\n // Read as a browser would follow it — entities and escapes decoded (V8 #5) — and only a web\n // page, an email address or a phone number becomes a link.\n const href = safeLinkHref(link?.[2] ?? \"\");\n out.push(\n href ? (\n <OutboundLink key={k} href={href} className=\"text-primary underline-offset-2 hover:underline\" onClick={own}>\n {link?.[1]}\n </OutboundLink>\n ) : (\n link?.[1] ?? tok\n ),\n );\n } else out.push(<em key={k}>{tok.slice(1, -1)}</em>);\n last = at + tok.length;\n }\n if (last < text.length) out.push(text.slice(last));\n return out;\n}\n\n/**\n * Markdown drawn as React elements — paragraphs, # headings, - and 1. lists, and the inline marks.\n * No HTML is ever parsed or injected: a `<` in the text is drawn as the character it is.\n */\nexport function SafeMarkdown({ text, clipped }: { text: string; clipped?: boolean }) {\n const blocks: ReactNode[] = [];\n const lines = text.replace(/\\r\\n?/g, \"\\n\").split(\"\\n\");\n let list: { ordered: boolean; items: string[] } | null = null;\n let para: string[] = [];\n const flushPara = () => {\n if (para.length > 0) {\n blocks.push(<p key={`p${blocks.length}`}>{inline(para.join(\" \"), `p${blocks.length}`)}</p>);\n para = [];\n }\n };\n const flushList = () => {\n if (list) {\n const items = list.items.map((item, i) => <li key={i}>{inline(item, `l${blocks.length}-${i}`)}</li>);\n blocks.push(\n list.ordered ? (\n <ol key={`o${blocks.length}`} className=\"ml-4 list-decimal\">{items}</ol>\n ) : (\n <ul key={`u${blocks.length}`} className=\"ml-4 list-disc\">{items}</ul>\n ),\n );\n list = null;\n }\n };\n for (const raw of lines) {\n const line = raw.trimEnd();\n const bullet = /^\\s*[-*+]\\s+(.*)$/.exec(line);\n const numbered = /^\\s*\\d+[.)]\\s+(.*)$/.exec(line);\n const heading = /^(#{1,3})\\s+(.*)$/.exec(line);\n if (bullet || numbered) {\n flushPara();\n const ordered = Boolean(numbered);\n if (list && list.ordered !== ordered) flushList();\n if (!list) list = { ordered, items: [] };\n list.items.push((bullet ?? numbered)![1]!);\n } else if (heading) {\n flushPara();\n flushList();\n blocks.push(<p key={`h${blocks.length}`} className=\"font-semibold\">{inline(heading[2]!, `h${blocks.length}`)}</p>);\n } else if (line.trim() === \"\") {\n flushPara();\n flushList();\n } else {\n flushList();\n para.push(line.trim());\n }\n }\n flushPara();\n flushList();\n return (\n <span\n className={cn(\"block min-w-0 space-y-1 whitespace-normal text-sm\", clipped ? \"max-h-[4.5em] overflow-hidden\" : \"\")}\n data-records-rich-text=\"\"\n >\n {blocks}\n </span>\n );\n}\n\n// ── EDIT ───────────────────────────────────────────────────────────────────────────────────\n\ntype ControlProps = { field: Field; value: unknown; onChange: (value: unknown) => void; disabled?: boolean | undefined; id: string };\n\n/** The control for a newer kind, or undefined when the field's base control is right for it. */\nexport function newerKindControl(props: ControlProps): ReactNode | undefined {\n switch (newerKindOf(props.field)) {\n case \"duration\":\n return <DurationControl {...props} />;\n case \"address\":\n return <AddressControl {...props} />;\n case \"barcode\":\n return <BarcodeControl {...props} />;\n case \"created_by\":\n case \"modified_by\":\n case \"count\":\n return (\n <div id={props.id} className=\"rounded border border-dashed px-2 py-1.5 text-xs text-muted-foreground\">\n {props.value === null || props.value === undefined ? \"—\" : newerKindValue(props.field, props.value)}\n </div>\n );\n default:\n return undefined;\n }\n}\n\n/** A length of time, typed the way people say it; the value is seconds. */\nfunction DurationControl({ value, onChange, disabled, id }: ControlProps) {\n const [text, setText] = useState(() => durationText(value) ?? \"\");\n const [wrong, setWrong] = useState(false);\n useEffect(() => {\n setText(durationText(value) ?? \"\");\n }, [value]);\n return (\n <span className=\"flex flex-col gap-1\">\n <BasicInput\n id={id}\n value={text}\n disabled={disabled}\n inputMode=\"numeric\"\n placeholder=\"45 min\"\n aria-invalid={wrong || undefined}\n className=\"tabular-nums\"\n onChange={(e) => {\n setText(e.target.value);\n if (e.target.value.trim() === \"\") {\n setWrong(false);\n onChange(null);\n return;\n }\n const seconds = readTypedDuration(e.target.value);\n setWrong(seconds === null);\n if (seconds !== null) onChange(seconds);\n }}\n onBlur={() => {\n if (!wrong) setText(durationText(value) ?? \"\");\n }}\n />\n {wrong ? <span className=\"text-[11px] text-destructive\">Write it like 45 min, 1:30 or 1h 30m.</span> : null}\n </span>\n );\n}\n\nconst ADDRESS_LABELS: Record<AddressPart, string> = {\n street: \"Street\",\n city: \"City\",\n region: \"State or region\",\n postal_code: \"Postal code\",\n country: \"Country\",\n};\nconst ADDRESS_EXAMPLES: Record<AddressPart, string> = {\n street: \"1420 Cedar Ridge Pkwy\",\n city: \"Boulder\",\n region: \"CO\",\n postal_code: \"80301\",\n country: \"US\",\n};\n\n/** An address in its five parts; a part left empty is left out. */\nfunction AddressControl({ value, onChange, disabled, id }: ControlProps) {\n const held: AddressValue = isAddressValue(value) ? value : typeof value === \"string\" && value.trim() !== \"\" ? { street: value } : {};\n const set = (part: AddressPart, words: string) => {\n const next: AddressValue = { ...held, [part]: words };\n const kept = Object.fromEntries(Object.entries(next).filter(([, v]) => typeof v === \"string\" && v.trim() !== \"\")) as AddressValue;\n onChange(Object.keys(kept).length === 0 ? null : kept);\n };\n return (\n <span id={id} className=\"grid grid-cols-2 gap-1.5\" data-records-address-control=\"\">\n {ADDRESS_PARTS.map((part) => (\n <BasicInput\n key={part}\n aria-label={ADDRESS_LABELS[part]}\n placeholder={ADDRESS_EXAMPLES[part]}\n className={part === \"street\" ? \"col-span-2\" : \"\"}\n value={typeof held[part] === \"string\" ? (held[part] as string) : \"\"}\n disabled={disabled}\n {...(part === \"street\" ? { autoComplete: \"street-address\" } : {})}\n onChange={(e) => set(part, e.target.value)}\n />\n ))}\n </span>\n );\n}\n\ntype Detector = { detect: (source: ImageBitmapSource) => Promise<Array<{ rawValue: string }>> };\ntype DetectorCtor = new (opts?: { formats?: string[] }) => Detector;\n\n/** The phone's own barcode reader, when it has one (Chrome on Android). Null: no scanning here. */\nfunction barcodeDetector(): DetectorCtor | null {\n const ctor = (globalThis as { BarcodeDetector?: DetectorCtor }).BarcodeDetector;\n return typeof ctor === \"function\" ? ctor : null;\n}\n\n/** A barcode, typed — and on a phone that reads barcodes, photographed. */\nfunction BarcodeControl({ value, onChange, disabled, id }: ControlProps) {\n const file = useRef<HTMLInputElement>(null);\n const [said, setSaid] = useState<string | null>(null);\n const Detect = barcodeDetector();\n return (\n <span className=\"flex flex-col gap-1\">\n <span className=\"flex items-center gap-1.5\">\n <BasicInput\n id={id}\n className=\"font-mono\"\n value={typeof value === \"string\" ? value : \"\"}\n disabled={disabled}\n placeholder=\"4006381333931\"\n onChange={(e) => onChange(e.target.value === \"\" ? null : e.target.value)}\n />\n {Detect && !disabled ? (\n <>\n <button\n type=\"button\"\n className=\"shrink-0 rounded-md border px-2 py-1 text-xs hover:bg-accent\"\n onClick={() => file.current?.click()}\n >\n Scan\n </button>\n <input\n ref={file}\n type=\"file\"\n accept=\"image/*\"\n capture=\"environment\"\n className=\"hidden\"\n onChange={async (e) => {\n const photo = e.target.files?.[0];\n e.target.value = \"\";\n if (!photo) return;\n try {\n const found = await new Detect().detect(await createImageBitmap(photo));\n if (found[0]?.rawValue) {\n onChange(found[0].rawValue);\n setSaid(null);\n } else setSaid(\"No barcode in that photo. Try closer, in good light.\");\n } catch {\n setSaid(\"This phone could not read that photo. Type the code instead.\");\n }\n }}\n />\n </>\n ) : null}\n </span>\n {said ? <span className=\"text-[11px] text-muted-foreground\">{said}</span> : null}\n </span>\n );\n}\n","\"use client\";\n\n// src/RelationPicker.tsx — @ai-matrx/records-ui · SCR-N-2\n//\n// THE ONE GENERIC RELATION PICKER. Before it, every relation-shaped field in\n// the product had a type-specific picker (image, file, url, scope) and a plain\n// `relation` field was not editable at all.\n//\n// It reads the target Table's records through the read door, shows each one as\n// its own chip (REC-2: the title field is what makes a record a chip), and\n// respects `relation_max` by saying the number rather than silently dropping a\n// pick.\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport type { Field, ReadRow, RecordsError, Table, Uuid } from \"@ai-matrx/records\";\nimport { rankTypedMatches } from \"@ai-matrx/records\";\nimport { useOptionalRecordsClient } from \"@ai-matrx/records/react\";\nimport { BasicInput, Button, cn } from \"@ai-matrx/design-system\";\nimport { PickOrAdd } from \"./PickOrAdd\";\nimport { RecordChip } from \"./editors\";\nimport { UNREAD_RECORD_LABEL, WITHHELD_RECORD_LABEL, fieldName } from \"./names\";\nimport { RefusalLine, RefusalNotice } from \"./Refusal\";\nimport { refusal as refusalOf } from \"./refusals\";\nimport { tellApart } from \"./tellApart\";\n\nexport interface RelationPickerProps {\n field: Field;\n value: unknown;\n onChange: (value: unknown) => void;\n disabled?: boolean | undefined;\n id?: string | undefined;\n className?: string | undefined;\n /**\n * WHETHER A PERSON MAY MAKE THE THING SHE IS LOOKING FOR (RELATION-CREATE, 2026-09-22).\n *\n * On by default, because that is what this control is for on every surface a\n * person fills a record in: the grid cell, the generated form, a public form\n * runner. The one surface that passes `false` is the filter builder — picking\n * a value to FILTER by is not a reason to put a new customer in the book, and\n * a Create button there would write a row nobody asked for.\n */\n allowCreate?: boolean | undefined;\n /**\n * A SINGLE LINK'S PICK IS ITS COMMIT in a grid cell (Enter on the highlighted match, or a click):\n * called after a one-record column picks a record, so the cell saves without a second Save.\n */\n onPicked?: (() => void) | undefined;\n /**\n * IN A GRID CELL the list is open from the start and hangs from the cell (lane CELL-EDITORS,\n * 2026-10-06): no \"Pick\" button over a Save / Cancel row. Closing it is the cell's commit.\n */\n autoOpen?: boolean | undefined;\n /** The list closed: the cell commits what is picked. */\n onClose?: (() => void) | undefined;\n /** Escape in a grid cell's list: the cell's cancel — nothing is written (`PickOrAdd.onEscape`). */\n onCancel?: (() => void) | undefined;\n /**\n * THE RECORD BEING EDITED (walk 2026-10-08 D11): never offered in its own list — a row cannot be\n * blocked by, or the parent of, itself (the store refuses it too).\n */\n excludeId?: string | undefined;\n}\n\n/**\n * The sentence this control shows on a screen served to somebody with NO ACCOUNT.\n *\n * VERIFIER-10 finding F1, on production: a published job-request form whose\n * first question was a relation answered HTTP 500 to a stranger, because this\n * control asked `useRecordsClient` for a client that the public arm of\n * `FormRunner` deliberately never mounts — the browser on that page holds no\n * key, knows no organization and may not read a row. That is CORRECT; what was\n * wrong was asking for it with the hook that throws.\n *\n * A picker here cannot exist: searching the owner's records is exactly the read\n * `custom.form_public` refuses a stranger, and a control that offered it would\n * be the leak. So the question is ABSENT and says so, with what to do instead,\n * and the rest of the form is still answerable.\n */\n/** The rows a link may point at: never the record being edited (walk 2026-10-08 D11). */\nexport function withoutSelf<R extends { id: string }>(rows: R[], selfId: string | undefined): R[] {\n return selfId ? rows.filter((row) => row.id !== selfId) : rows;\n}\n\nexport const NO_STORE_ON_THIS_SCREEN_REASON =\n \"This question points at a record in somebody's own data, and a page answered without an \" +\n \"account is never allowed to search that. Leave it blank — whoever receives your answer will \" +\n \"fill it in.\";\n\nexport function RelationPicker({ field, value, onChange, disabled, id, className, allowCreate = true, onPicked, autoOpen, onClose, onCancel, excludeId }: RelationPickerProps) {\n // NOT `useRecordsClient`. See NO_STORE_ON_THIS_SCREEN_REASON above: this\n // control is drawn on the public form runner, which mounts no store client at\n // all, and the hook that throws took the whole page down with it.\n const client = useOptionalRecordsClient();\n const [rows, setRows] = useState<ReadRow[] | null>(null);\n // WHAT EACH ROW AND EACH PICKED ID IS CALLED — the store's answer, keyed by id.\n // Never derived here: see the block above the effect below.\n const [words, setWords] = useState<Record<string, string>>({});\n const [refusal, setRefusal] = useState<RecordsError | null>(null);\n const [search, setSearch] = useState(\"\");\n const [open, setOpenState] = useState(autoOpen === true);\n const onCloseRef = useRef(onClose);\n onCloseRef.current = onClose;\n // Closing the list — a pick, Escape, a click away — is what a grid cell commits on.\n const setOpen = useCallback((next: boolean) => {\n setOpenState(next);\n if (!next) onCloseRef.current?.();\n }, []);\n // ── MAKING THE ONE THAT IS NOT THERE YET (RELATION-CREATE, 2026-09-22).\n // A person filling in a Job whose customer has never been written down had\n // exactly one thing to read here — \"Nothing in that table matches.\" — and\n // nowhere to go: leave the record, find the Customers table, add a row, come\n // back, re-open the picker, search again. Airtable and Notion both end that\n // list with \"Create <what you typed>\", and so does this one now. It is added\n // HERE, in the one generic relation picker, so the grid cell, the generated\n // record form, the form runner and every future relation surface inherit it\n // from the same control instead of each growing its own.\n const [target, setTarget] = useState<Table | null>(null);\n const [targetRefusal, setTargetRefusal] = useState<RecordsError | null>(null);\n const [creating, setCreating] = useState(false);\n const [newTitle, setNewTitle] = useState(\"\");\n const [busy, setBusy] = useState(false);\n const [createRefusal, setCreateRefusal] = useState<RecordsError | null>(null);\n\n const picked = useMemo<string[]>(\n () => (Array.isArray(value) ? value.map(String) : value === null || value === undefined ? [] : [String(value)]),\n [value],\n );\n\n // ── THE TARGET'S ROWS, ON MOUNT AND NOT ON OPEN (RELATION-DECLARE, 2026-09-20).\n // This used to wait for the popover, so every chip on every relation cell read\n // \"Loading…\" until somebody clicked Pick — a word that never resolved, on a\n // screen nobody was going to click. A chip is a NAME; it is read far more often\n // than it is changed, so what it needs is fetched when the cell is drawn.\n //\n // WHAT IT NO LONGER FETCHES IS THE TABLE (lane RELATION-DISPLAY-2, 2026-09-21).\n // It used to read `tableList()` for the target's `title_field` and name every row\n // and every chip itself — the third of three copies of that derivation, and the\n // reason a column configured to read \"Maria Chen — Rincon\" still offered a flat\n // list of two identical \"Maria Chen\"s to pick between. The picker now shows the\n // SAME WORDS THE CELL SHOWS, because they come from the same place: this column's\n // own display spec, resolved by the store, with the ladder asked first.\n useEffect(() => {\n const target = field.relation_target;\n if (!target || !client) return;\n let cancelled = false;\n void client.list({ table_id: target as Uuid, limit: 200 }).then((result) => {\n if (cancelled) return;\n if (result.ok) setRows(withoutSelf(result.data.rows, excludeId));\n else setRefusal(result.error);\n });\n return () => {\n cancelled = true;\n };\n }, [client, field.relation_target]);\n\n // ── AND WHAT EVERY ONE OF THEM IS CALLED — IN ONE CALL.\n // The rows this reader may see AND the ids already picked go to the store together.\n // A picked id that is not in the visible page is the interesting case: a Job shared\n // with you may point at a Client nobody shared, and the two possibilities — \"further\n // down a long list\" and \"not hers\" — have different sentences. The door tells them\n // apart, because the ladder runs inside it; a name assembled out here has already\n // been read. An id the door gives no words for reads the same sentence the store\n // itself gives (`platform.relation_withheld_label()`): never the title, never a bare\n // id, and never a \"Loading…\" that resolves for nobody.\n useEffect(() => {\n if (!rows || !client) return;\n const wanted = [...new Set([...rows.map((row) => row.id), ...picked])].filter(\n (id) => words[id] === undefined,\n );\n if (wanted.length === 0) return;\n let cancelled = false;\n void client\n .relationWordsMany({ field_id: field.id, record_ids: wanted as Uuid[] })\n .then((result) => {\n if (cancelled) return;\n const learned: Record<string, string> = {};\n for (const id of wanted) {\n const said = result.ok ? result.data[id] : undefined;\n // A FAILED read is unread, never withheld — only an answer of nothing is withheld.\n learned[id] = !result.ok\n ? UNREAD_RECORD_LABEL\n : typeof said === \"string\" && said !== \"\"\n ? said\n : WITHHELD_RECORD_LABEL;\n }\n setWords((current) => ({ ...current, ...learned }));\n });\n return () => {\n cancelled = true;\n };\n }, [client, field.id, rows, picked, words]);\n\n // ── THE TARGET TABLE, READ ONLY WHEN SOMEBODY OPENS THE PICKER.\n // Deliberately NOT on mount: `RelationPicker` is drawn on every relation cell\n // of every row, and the read above was cut back to the rows for exactly that\n // reason (RELATION-DISPLAY-2). What a create needs — the Table's own name and\n // its `title_field` — is only needed once a person has opened the control, so\n // it is fetched then and cached for the life of the cell.\n useEffect(() => {\n if (!open || !allowCreate || target || targetRefusal || !client) return;\n const id = field.relation_target;\n if (!id) return;\n let cancelled = false;\n void client.tableList().then((result) => {\n if (cancelled) return;\n if (!result.ok) {\n setTargetRefusal(result.error);\n return;\n }\n const found = result.data.find((t) => t.id === id) ?? null;\n if (found) setTarget(found);\n else\n setTargetRefusal(\n refusalOf(\n \"door\",\n \"That Table is not one you can open, so a new record cannot be added to it from here.\",\n ),\n );\n });\n return () => {\n cancelled = true;\n };\n }, [client, open, allowCreate, target, targetRefusal, field.relation_target]);\n\n if (!client) {\n // ABSENT AND HONEST, never a dead popover. No store client is mounted on\n // this screen at all, which on a public form is the correct posture.\n return (\n // The Field's own name is already printed above this control by\n // `FieldLabel`, so the sentence does not say it a second time.\n <p id={id} className={cn(\"text-xs text-muted-foreground\", className)}>\n {NO_STORE_ON_THIS_SCREEN_REASON}\n </p>\n );\n }\n\n if (!field.relation_target) {\n // Absent, and honest about why: a relation with no declared target is a\n // Field the store has not finished, not a picker that \"has no options\".\n return (\n <p className=\"text-xs text-muted-foreground\">\n {fieldName(field)} points at records, but it does not say which Table yet, so there is nothing to pick\n from. A table admin sets its target in the field editor.\n </p>\n );\n }\n\n // A chip carries the record's NAME. Before `names.ts`, a relation whose target had\n // not loaded yet drew `8f2c1b0a` — a bare identifier, which the verdict of 19\n // September counted among the three things a first-time user feels within a minute.\n // It now reads THIS COLUMN'S OWN WORDS, resolved by the store: the same string the\n // cell shows, so what a person picks from and what they then read back are never two\n // different answers. A record that is not this reader's says so in the store's own\n // words instead of waiting forever.\n const titleOf = (recordId: string) => words[recordId] ?? \"Loading…\";\n const full = field.multi && field.relation_max !== null && picked.length >= field.relation_max;\n\n const toggle = (recordId: string) => {\n if (!field.multi) {\n const choosing = picked[0] !== recordId;\n onChange(choosing ? recordId : null);\n setOpen(false);\n // After the draft has taken the pick, so the cell saves what was just chosen.\n if (choosing && onPicked) setTimeout(onPicked, 0);\n return;\n }\n const next = new Set(picked);\n if (next.has(recordId)) next.delete(recordId);\n else if (!full) next.add(recordId);\n onChange(next.size === 0 ? null : [...next]);\n };\n\n // WHAT THE NEW ONE IS CALLED IN THE BUTTON — the Table's own singular label if\n // it has one, its name otherwise. Never a hardcoded \"item\": a person adding a\n // customer reads \"New customer\".\n const targetWord = (target?.label_singular ?? \"\").trim() || (target?.name ?? \"\").trim() || \"record\";\n\n const create = async (rawTitle: string) => {\n const title = rawTitle.trim();\n const tableId = field.relation_target;\n if (!tableId || title === \"\" || busy) return;\n if (!target) {\n // Cannot happen from the rendered control (it draws only once the Table is\n // in hand), and if it ever does the person is told rather than ignored.\n setCreateRefusal(refusalOf(\"unreachable\", \"Still reading that Table.\", \"Try again in a moment.\"));\n return;\n }\n const titleField = target.title_field;\n if (!titleField) {\n // ABSENT AND HONEST, never a dead button: REC-2 says a record without a\n // title column cannot be a chip, so a row made here would come back\n // nameless. The remedy names who can fix it and where.\n setCreateRefusal(\n refusalOf(\n \"not_supported\",\n `${target.name} has no column that names a record yet, so a new one would have nothing to show here.`,\n \"A table admin picks its title column in that table's settings.\",\n ),\n );\n return;\n }\n setBusy(true);\n setCreateRefusal(null);\n const written = await client.recordWrite({ table_id: tableId as Uuid, data: { [titleField]: title } });\n if (!written.ok) {\n setBusy(false);\n setCreateRefusal(written.error);\n return;\n }\n const createdId = String(written.data);\n // THE NEW ROW AND ITS WORDS COME BACK FROM THE STORE, never assembled here:\n // this column's display spec may join two of the target's columns, and the\n // only body that knows that is the door (`custom.relation_words_many`). The\n // words effect above picks the new id up because `picked` now carries it.\n const refreshed = await client.list({ table_id: tableId as Uuid, limit: 200 });\n if (refreshed.ok) setRows(withoutSelf(refreshed.data.rows, excludeId));\n setBusy(false);\n setCreating(false);\n setNewTitle(\"\");\n setSearch(\"\");\n toggle(createdId);\n };\n\n // Two records with one name carry the words that tell them apart (see tellApart.ts),\n // and a search reads those words too — \"Sunset\" finds the Patricia Marsh on Sunset Blvd.\n const apart = tellApart(rows ?? [], titleOf);\n // THE ONE RANKING (`rankTypedMatches`, grids review 3): the name ranks exact, starts with, a word\n // starts with, contains; the words that tell two apart only ever find a record.\n const visible = rankTypedMatches(rows ?? [], search, (row) => [titleOf(row.id), apart.get(row.id) ?? \"\"]);\n\n const anchored = autoOpen === true;\n const cellChips = picked.map((recordId) => (\n <RecordChip\n key={recordId}\n title={titleOf(recordId)}\n {...(disabled || anchored ? {} : { onRemove: () => toggle(recordId) })}\n />\n ));\n\n return (\n // Never wider than where it is drawn (a grid cell beside a sticky column: B3-07) — chips truncate, the button wraps.\n <div className={cn(\"flex min-w-0 max-w-full flex-wrap items-center gap-1\", className)}>\n {anchored && !disabled ? null : cellChips}\n {disabled ? null : (\n // THE ONE \"PICK OR ADD\" BUILDER (PickOrAdd.tsx) — the choice editor draws the same one.\n // In a grid cell it hangs from the cell's own chips; what is picked heads the list with its ×.\n <PickOrAdd\n anchored={anchored}\n {...(anchored && onCancel ? { onEscape: onCancel } : {})}\n multi={field.multi}\n chips={picked.map((recordId) => ({ id: recordId, label: titleOf(recordId), onRemove: () => toggle(recordId) }))}\n triggerId={id}\n triggerLabel={`Pick for ${fieldName(field)}`}\n triggerText={picked.length === 0 ? \"Pick\" : \"Change\"}\n open={open}\n onOpenChange={setOpen}\n search={search}\n onSearch={setSearch}\n items={visible.map((row) => ({\n id: row.id,\n label: titleOf(row.id),\n detail: apart.get(row.id) ?? null,\n picked: picked.includes(row.id),\n title: apart.has(row.id) ? `${titleOf(row.id)} — ${apart.get(row.id)}` : titleOf(row.id),\n attrs: { \"data-relation-candidate\": row.id },\n }))}\n onPick={toggle}\n notice={\n <>\n {refusal ? <RefusalLine error={refusal} className=\"p-2\" /> : null}\n {!rows && !refusal ? <p className=\"p-2 text-xs text-muted-foreground\">Reading…</p> : null}\n {full ? (\n <p className=\"p-2 text-xs text-muted-foreground\">\n {fieldName(field)} can point at {field.relation_max} at most. Remove one to add another.\n </p>\n ) : null}\n </>\n }\n empty={rows ? <p className=\"p-2 text-xs text-muted-foreground\">Nothing in that table matches.</p> : null}\n add={\n allowCreate && !full && !targetRefusal && target && !creating\n ? {\n label: search.trim() !== \"\" ? `Create “${search.trim()}”` : `New ${targetWord}`,\n disabled: busy,\n // TYPED SOMETHING THAT IS NOT THERE? That IS the name. The champions\n // (Airtable, Notion) make the search text the new record's title in one\n // press; an empty box asks for one.\n onAdd: () => {\n if (search.trim() !== \"\") void create(search);\n else {\n setNewTitle(\"\");\n setCreating(true);\n }\n },\n }\n : null\n }\n foot={\n !allowCreate || full ? undefined : targetRefusal ? (\n <RefusalLine error={targetRefusal} className=\"p-2\" />\n ) : !target ? (\n <p className=\"p-2 text-xs text-muted-foreground\">Reading that table…</p>\n ) : creating ? (\n <div className=\"flex items-center gap-1 p-1\">\n <BasicInput\n autoFocus\n value={newTitle}\n onChange={(e) => setNewTitle(e.target.value)}\n onKeyDown={(e) => {\n if (e.key === \"Enter\") {\n e.preventDefault();\n void create(newTitle);\n }\n }}\n placeholder={`New ${targetWord}`}\n className=\"h-7 flex-1 text-xs\"\n aria-label={`Name the new ${targetWord}`}\n />\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"default\"\n disabled={busy || newTitle.trim() === \"\"}\n onClick={() => void create(newTitle)}\n >\n {busy ? \"Creating…\" : \"Create\"}\n </Button>\n </div>\n ) : undefined\n }\n footNote={\n allowCreate && !full && createRefusal ? (\n // The typed title is still in the search box: the notice owns the\n // two doors out (lane REFUSAL-SWEEP).\n <RefusalNotice\n error={createRefusal}\n className=\"mt-1 max-w-72\"\n onKeepEditing={() => setCreateRefusal(null)}\n onDiscard={() => {\n setCreateRefusal(null);\n setSearch(\"\");\n }}\n />\n ) : null\n }\n >\n {anchored ? cellChips : null}\n </PickOrAdd>\n )}\n </div>\n );\n}\n","// src/tellApart.ts — @ai-matrx/records-ui · lane RECORDS-UI-FIX (2026-09-23)\n//\n// TWO RECORDS WITH ONE NAME ARE TOLD APART, NEVER LISTED AS TWINS.\n//\n// 🚨 WHAT A PERSON MET (guide re-walk, VERIFIER-15/16 LOW): Rincon's linked-record\n// picker listed Patricia Marsh, Robert Marsh, Maria Chen \"and the rest\" twice each.\n// They are not duplicates: Rincon's Customers table holds two Patricia Marshes — 156\n// Willow Way and 261 Sunset Blvd — and the picker drew only the name, so a dispatcher\n// could not tell which one she was attaching to a job. Airtable's record picker shows\n// the record's other fields for exactly this reason.\n//\n// So when names collide, each colliding row gets ONE short line from its own document:\n// the first column whose values differ across the rows that share the name (an\n// address, a phone), and a second one only when the first still leaves two alike.\n// A name nobody else holds gets nothing — the list stays a list of names.\n\nimport type { ReadRow } from \"@ai-matrx/records\";\n\nfunction shown(value: unknown): string | null {\n if (value === null || value === undefined) return null;\n if (typeof value === \"string\") return value.trim() === \"\" ? null : value.trim();\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n return null;\n}\n\n/** For every row whose name another row also has: the words that tell it apart. */\nexport function tellApart(rows: ReadRow[], nameOf: (id: string) => string): Map<string, string> {\n const byName = new Map<string, ReadRow[]>();\n for (const row of rows) {\n const name = nameOf(row.id).trim().toLowerCase();\n byName.set(name, [...(byName.get(name) ?? []), row]);\n }\n const out = new Map<string, string>();\n for (const [name, group] of byName) {\n if (group.length < 2) continue;\n const keys = [\n ...new Set(\n group.flatMap((row) =>\n Object.keys(row.document ?? {}).filter((k) => !k.startsWith(\"_\") && shown(row.document?.[k]) !== null),\n ),\n ),\n ].filter((k) => group.some((row) => (shown(row.document?.[k]) ?? \"\").toLowerCase() !== name));\n const valuesOf = (k: string) => group.map((row) => shown(row.document?.[k]) ?? \"\");\n const differs = keys.filter((k) => new Set(valuesOf(k)).size > 1);\n const whole = differs.find((k) => new Set(valuesOf(k)).size === group.length);\n const chosen = whole ? [whole] : differs.slice(0, 2);\n if (chosen.length === 0) continue;\n for (const row of group) {\n const words = chosen.map((k) => shown(row.document?.[k])).filter((w): w is string => w !== null);\n if (words.length > 0) out.set(row.id, words.join(\" · \"));\n }\n }\n return out;\n}\n","/**\n * A link as a person reads it: \"mailto:ann%40example.com\" reads \"mailto:ann@example.com\".\n * Only the TEXT is decoded — the href a click follows stays exactly as given. A value that does not\n * decode (a stray \"%\") reads as it is.\n */\nexport function readableLink(raw: string): string {\n try {\n return decodeURI(raw).replace(/%40/gi, \"@\");\n } catch {\n return raw;\n }\n}\n","// src/buttonCell.tsx — @ai-matrx/records-ui\n//\n// A BUTTON COLUMN ON SCREEN (lane NOTION-PROPS-3; champions: Notion's and Airtable's Button). Drawn the same\n// in a grid cell, a card and a record page (`RecordValue` hands every button here): the column's label in\n// its color. A press goes to the store (`custom.button_press`) and its answer is said beside the button,\n// in a popover, so nothing on the page moves:\n//\n// a link opens in a new tab (and, when the browser blocks it, is offered as a link)\n// a row action says it ran, or the store's refusal\n// an automation says its run's status and words\n// nothing set says what to set up, and opens the column's settings\n//\n// A public page has no store client: the button is drawn, says it works only for signed-in people, and\n// never pretends to run.\n\nimport { readableLink } from \"./readableLink\";\nimport { useContext, useEffect, useRef, useState, type MouseEvent, type PointerEvent } from \"react\";\nimport { Button, Dialog, ErrorBox, DialogContent, DialogDescription, DialogHeader, DialogTitle, Popover, PopoverContent, PopoverTrigger, cn } from \"@ai-matrx/design-system\";\nimport { CHOICE_CHIP_CLASS, NEUTRAL_CHIP_CLASS, isStyleColor } from \"@ai-matrx/design-system/data-table\";\nimport { buttonNeeds, buttonOf, type AutomationRun, type ButtonPressed, type Field, type RecordDocument, type RecordsError, type Table, type Uuid } from \"@ai-matrx/records\";\nimport { useOptionalRecordsClient, useTable } from \"@ai-matrx/records/react\";\nimport { useRecordsUi } from \"./host\";\nimport { OpenRecordHereContext } from \"./gridOpen\";\nimport { RefusalLine } from \"./Refusal\";\nimport { FieldEditor } from \"./FieldEditor\";\nimport { fieldName, recordNameIn, tableName } from \"./names\";\nimport { StructuredValueView, structuredOf, type Structured } from \"./structuredValue\";\nimport { refusalIsMissingInput } from \"./plainWords\";\nimport { OutboundLink } from \"@ai-matrx/kit/outbound-react\";\nimport { openOutbound } from \"@ai-matrx/kit/outbound\";\n\ntype Said =\n | { kind: \"needs\"; says: string }\n | { kind: \"waiting\"; says: string }\n | { kind: \"failed\"; says: string }\n | { kind: \"ran\"; says: string; link?: string | undefined; value?: Structured | undefined }\n | { kind: \"refused\"; error: RecordsError }\n | { kind: \"public\" };\n\n/** What a press answered, in words a person reads. */\nexport function buttonPressWords(label: string, pressed: ButtonPressed): string {\n if (pressed.do === \"open_url\") return `${label} opened ${readableLink(pressed.url)}`;\n if (pressed.do === \"add_row\") return `${label}: a row was added.`;\n if (pressed.do === \"run_action\") {\n const n = Number(pressed.result?.ran ?? 1);\n return `${label} ran on ${n === 1 ? \"this record\" : `${n} records`}.`;\n }\n const status = pressed.status ?? \"ran\";\n return [`${pressed.automation ?? label}: ${status}.`, pressed.says].filter(Boolean).join(\" \");\n}\n\n/** What an add-a-row press says once the row is open: it names the row (its title), else the table's noun. Never a path. */\nexport function addRowWords(label: string, table: Table, document: RecordDocument | undefined): string {\n const name = recordNameIn(table, document, \"\");\n return name !== \"\" ? `${label}: added \\u201C${name}\\u201D and opened it.` : `${label}: added to ${tableName(table)} and opened it.`;\n}\n\nconst POLL_EVERY_MS = 1200;\nconst POLL_FOR_MS = 120_000;\n\n/** The bookkeeping an agent step adds beside its answer; never part of what a person reads. */\nconst RUN_BOOKKEEPING = new Set([\"run_id\", \"conversation_id\"]);\n\n/**\n * A step's stored answer, read for a person: an agent's `{\"text\": \"...\"}` is its text, a bare JSON string is that\n * string, a structured answer (an object with more than text, a list) is handed to the structured-value renderer,\n * and anything else is the words as stored. Never raw JSON braces.\n */\nexport function answerOf(output: string | undefined): { words: string; value?: Structured } {\n const raw = (output ?? \"\").trim();\n if (raw === \"\") return { words: \"\" };\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return { words: raw };\n }\n if (typeof parsed === \"string\") return { words: parsed.trim() };\n if (typeof parsed === \"object\" && parsed !== null && !Array.isArray(parsed)) {\n const shown = Object.fromEntries(Object.entries(parsed).filter(([k]) => !RUN_BOOKKEEPING.has(k)));\n const keys = Object.keys(shown);\n if (keys.length === 1 && typeof shown.text === \"string\") return { words: shown.text.trim() };\n const value = structuredOf(shown);\n return value ? { words: \"\", value } : { words: raw };\n }\n const value = structuredOf(parsed);\n return value ? { words: \"\", value } : { words: raw };\n}\n\n/** What a finished run answered: its last step's own answer, else the store's sentence. */\nexport function runAnswer(label: string, run: Pick<AutomationRun, \"status\" | \"says\" | \"steps\">): { words: string; value?: Structured } {\n const steps = run.steps ?? [];\n const failedStep = [...steps].reverse().find((s) => s.status === \"failed\");\n if (run.status === \"failed\") {\n const failed = answerOf(failedStep?.output_text).words || failedStep?.says;\n return { words: [failed, run.says].filter((t, i, all) => t && all.indexOf(t) === i).join(\" \") || `${label} failed.` };\n }\n for (const step of [...steps].reverse()) {\n const answered = answerOf(step.output_text);\n if (answered.words !== \"\" || answered.value) return answered;\n }\n return { words: run.says || `${label} ran.` };\n}\n\n/** The runs a press left waiting on the server: its own run, and every automation it triggered (deduped by run). */\nexport function waitingRunsOf(pressed: Extract<ButtonPressed, { do: \"run_automation\" }>): Array<{ run_id: Uuid; automation: string | null }> {\n const out: Array<{ run_id: Uuid; automation: string | null }> = [];\n if (pressed.run_id && pressed.status === \"waiting\") out.push({ run_id: pressed.run_id, automation: pressed.automation });\n for (const r of pressed.runs ?? []) {\n if (r.status === \"waiting\" && !out.some((o) => o.run_id === r.run_id)) out.push({ run_id: r.run_id, automation: r.automation });\n }\n return out;\n}\n\nconst stop = (event: MouseEvent | PointerEvent) => event.stopPropagation();\n\nexport function ButtonValue({ field, recordId, inCell, beforeSave }: { field: Field; recordId?: string | null | undefined; inCell?: boolean | undefined; beforeSave?: boolean | undefined }) {\n const client = useOptionalRecordsClient();\n const b = buttonOf(field);\n const [busy, setBusy] = useState(false);\n const [said, setSaid] = useState<Said | null>(null);\n const [settingUp, setSettingUp] = useState(false);\n // True from the press until the new row is on screen: the button shows it at once, not after the wait.\n const [opening, setOpening] = useState(false);\n const here = useContext(OpenRecordHereContext);\n // W2-A: an add_row button opens the row it made, on the host's record page (the table it adds to is known up front).\n const host = useRecordsUi();\n const addsTo = useTable((b?.do === \"add_row\" ? (b.table_id ?? field.entity_definition_id) : null) as Uuid | null);\n // The press that is being waited on: a newer press or a closed popover cancels the older wait.\n const waitingOn = useRef(0);\n useEffect(() => () => void (waitingOn.current += 1), []);\n if (!b) return null;\n const color = isStyleColor(b.color) ? CHOICE_CHIP_CLASS[b.color] : NEUTRAL_CHIP_CLASS;\n // A NEW RECORD'S FORM (REVIEW-3 #5): the button it will offer, disabled, with why. Nothing to press yet.\n if (beforeSave) {\n return (\n <span className=\"inline-flex min-w-0 items-center gap-2\" data-records-button-before-save={field.key}>\n <Button type=\"button\" size=\"xs\" variant=\"outline\" disabled aria-describedby={`${field.key}-before-save`} data-records-button={field.key} className={cn(\"max-w-full gap-1 border px-2 font-medium\", inCell ? \"h-5\" : \"h-6\", color)}>\n <span className=\"truncate\">{b.label}</span>\n </Button>\n <span id={`${field.key}-before-save`} className=\"whitespace-nowrap text-xs text-muted-foreground\">\n Save the record first\n </span>\n </span>\n );\n }\n const needs = buttonNeeds(b);\n const tableId = field.entity_definition_id;\n\n const press = async () => {\n if (!client || !recordId) return setSaid({ kind: \"public\" });\n // A button with a half-set action says what is missing without asking. One with NO action may still be the\n // trigger of automations (Airtable's shape), which only the store knows: it is asked, and it refuses by name\n // (22023) when nothing starts, which is when the person is offered the settings.\n if (needs && b.do) return setSaid({ kind: \"needs\", says: needs });\n setBusy(true);\n const answered = await client.buttonPress({ record_id: recordId as Uuid, field_id: field.id });\n setBusy(false);\n if (!answered.ok) {\n if (needs && refusalIsMissingInput(answered.error)) return setSaid({ kind: \"needs\", says: needs });\n return setSaid({ kind: \"refused\", error: answered.error });\n }\n const pressed = answered.data;\n if (pressed.do === \"open_url\") {\n const opened = typeof window !== \"undefined\" ? openOutbound(pressed.url, \"_blank\", \"noopener\") : null;\n // `noopener` makes window.open answer null even when the tab opened, so the link is always offered.\n return setSaid({ kind: \"ran\", says: opened ? `${b.label} opened.` : `${b.label} is ready:`, link: pressed.url });\n }\n if (pressed.do === \"add_row\") {\n // The row opens in the table page's own panel when it was added to this page's table.\n if (here && String(here.tableId) === String(pressed.table_id)) {\n here.open(pressed.record_id);\n return setSaid({ kind: \"ran\", says: `${b.label}: a row was added and opened.` });\n }\n // A host whose rows open in its own peek or panel (Spaces) opens the new row there, and the words name the row.\n if (host.openRecord && addsTo.data) {\n const made = addsTo.data;\n host.openRecord({ table: made, recordId: pressed.record_id });\n const read = await client.recordRead({ record_id: pressed.record_id });\n return setSaid({ kind: \"ran\", says: addRowWords(b.label, made, read.ok ? read.data.document : undefined) });\n }\n const href = addsTo.data ? host.hrefForRecord?.({ table: addsTo.data, recordId: pressed.record_id }) : undefined;\n if (href) {\n // A page far away is a route that may have to compile: the button keeps saying it is working.\n setOpening(true);\n if (host.navigate) host.navigate(href);\n else if (typeof window !== \"undefined\") window.location.assign(href);\n }\n return setSaid({ kind: \"ran\", says: `${b.label}: a row was added.`, ...(href ? { link: href } : {}) });\n }\n const words = buttonPressWords(b.label, pressed);\n // The store queues a server run (a script, an agent, a text) and answers at once: wait for it here.\n // A button that is the TRIGGER of automations (Airtable's shape) names them in `runs`; each is waited on.\n if (pressed.do === \"run_automation\") {\n const queued = waitingRunsOf(pressed);\n if (queued.length > 0) {\n const mine = (waitingOn.current += 1);\n setBusy(true);\n setSaid({ kind: \"waiting\", says: `${b.label} is running` });\n let ids: Map<string, Uuid> | null = null;\n if (!(queued.length === 1 && b.automation_id) && tableId) {\n const listed = await client.automations({ table_id: tableId as Uuid });\n if (waitingOn.current !== mine) return;\n ids = new Map(listed.ok ? listed.data.automations.map((a) => [a.name, a.id] as const) : []);\n }\n const targets = queued.flatMap((q) => {\n const id = queued.length === 1 && b.automation_id ? (b.automation_id as Uuid) : q.automation ? ids?.get(q.automation) : undefined;\n return id ? [{ ...q, id }] : [];\n });\n if (targets.length === 0) {\n setBusy(false);\n return setSaid({ kind: \"ran\", says: words });\n }\n const done = new Map<string, AutomationRun>();\n const until = Date.now() + POLL_FOR_MS;\n while (waitingOn.current === mine) {\n await new Promise((r) => setTimeout(r, POLL_EVERY_MS));\n if (waitingOn.current !== mine) return;\n for (const t of targets) {\n if (done.has(t.run_id)) continue;\n const runs = await client.automationRuns({ automation_id: t.id, limit: 10 });\n if (!runs.ok) {\n setBusy(false);\n return setSaid({ kind: \"refused\", error: runs.error });\n }\n const run = runs.data.runs.find((r) => r.run_id === t.run_id);\n if (run && run.status !== \"waiting\") done.set(t.run_id, run);\n }\n if (done.size === targets.length) {\n setBusy(false);\n const answers = targets.map((t) => ({ name: t.automation ?? b.label, run: done.get(t.run_id)! }));\n const failed = answers.find((a) => a.run.status !== \"ran\");\n if (answers.length === 1) {\n const answer = runAnswer(b.label, answers[0]!.run);\n return setSaid(failed ? { kind: \"failed\", says: answer.words } : { kind: \"ran\", says: answer.words, value: answer.value });\n }\n const lines = answers.map((a) => `${a.name}: ${runAnswer(b.label, a.run).words}`).join(\" \");\n return setSaid(failed ? { kind: \"failed\", says: lines } : { kind: \"ran\", says: lines });\n }\n if (Date.now() > until) {\n setBusy(false);\n return setSaid({ kind: \"ran\", says: `${b.label} is still running. Its answer will be in the automation's runs.` });\n }\n }\n return;\n }\n }\n setSaid({ kind: \"ran\", says: words });\n };\n\n return (\n <>\n <Popover open={said !== null} onOpenChange={(open) => {\n if (open) return;\n waitingOn.current += 1;\n setBusy(false);\n setSaid(null);\n }}\n >\n <PopoverTrigger asChild>\n <Button\n type=\"button\"\n size=\"xs\"\n variant=\"outline\"\n data-records-button={field.key}\n data-records-button-unset={needs ? \"\" : undefined}\n aria-busy={busy || opening || undefined}\n data-records-button-pending={busy || opening ? \"\" : undefined}\n disabled={busy || opening}\n className={cn(\"max-w-full gap-1 border px-2 font-medium\", inCell ? \"h-5\" : \"h-6\", color, needs && \"border-dashed opacity-80\")}\n onPointerDown={stop}\n onDoubleClick={stop}\n onClick={(event) => {\n event.stopPropagation();\n event.preventDefault();\n void press();\n }}\n >\n <span className={cn(\"truncate\", (busy || opening) && \"matrx-shimmer\")}>{b.label}</span>\n </Button>\n </PopoverTrigger>\n <PopoverContent className=\"w-72 space-y-2 p-3 text-sm\" onClick={stop} onPointerDown={stop} data-records-button-said={said?.kind}>\n {said?.kind === \"refused\" ? <RefusalLine error={said.error} /> : null}\n {said?.kind === \"waiting\" ? (\n <p className=\"matrx-shimmer rounded px-1 py-0.5\" role=\"status\" aria-live=\"polite\">\n {said.says}\n </p>\n ) : null}\n {said?.kind === \"failed\" ? (\n <ErrorBox as=\"p\" className=\"break-words text-destructive\" message={said.says} origin=\"records-ui/buttonCell\">\n {said.says}\n </ErrorBox>\n ) : null}\n {said?.kind === \"public\" ? <p>Buttons run for signed-in people.</p> : null}\n {said?.kind === \"ran\" ? (\n <div className=\"break-words\">\n {said.value ? <StructuredValueView structured={said.value} label={b.label} /> : null}\n {said.says}{\" \"}\n {said.link ? (\n <OutboundLink href={said.link} className=\"text-primary underline\">\n {readableLink(said.link)}\n </OutboundLink>\n ) : null}\n </div>\n ) : null}\n {said?.kind === \"needs\" ? (\n <>\n <p>{said.says}</p>\n {tableId ? (\n <Button\n type=\"button\"\n size=\"sm\"\n data-records-button-set-up=\"\"\n onClick={() => {\n setSaid(null);\n setSettingUp(true);\n }}\n >\n Set up {b.label}\n </Button>\n ) : null}\n </>\n ) : null}\n </PopoverContent>\n </Popover>\n {settingUp && tableId ? (\n <Dialog open onOpenChange={(open) => (open ? null : setSettingUp(false))}>\n <DialogContent className=\"max-h-[85vh] overflow-y-auto sm:max-w-2xl\" onClick={stop} onPointerDown={stop}>\n <DialogHeader>\n <DialogTitle>{`Column settings · ${fieldName(field)}`}</DialogTitle>\n <DialogDescription className=\"sr-only\">What the button does</DialogDescription>\n </DialogHeader>\n <FieldEditor tableId={tableId} field={field} onSaved={() => setSettingUp(false)} onCancel={() => setSettingUp(false)} />\n </DialogContent>\n </Dialog>\n ) : null}\n </>\n );\n}\n","// src/gridOpen.tsx — @ai-matrx/records-ui · lane DEFAULT-GRID-PARITY (VERIFIER-17 finding)\n//\n// THE ONE WAY A GRID ROW OPENS ITS RECORD.\n//\n// VERIFIER-17 walked production's default grid (2026-09-24): nothing in a row opened the record.\n// A click on the title began editing it (every cell of an editable grid is the cell's own\n// control, so the data table's row click never fires), and the record panel appeared only when\n// somebody typed `?record=<id>` into the address. Airtable puts an expand control on every row and\n// opens the record with Space. Notion shows OPEN on the title cell. So this grid does both:\n//\n// · the FIRST column's cell carries an Open control. It is always drawn (quiet until the row is\n// hovered or the control is focused), so touch and keyboard users can reach it too; on touch it is\n// an icon-only 44px target beside the title, never over it;\n// · Space on any focused cell opens that row's record. Enter and F2 still edit, and `h` still\n// asks who changed it.\n//\n// Cards (kanban, calendar, gallery) already open on click, so this is the grid's half of one\n// behavior. It is drawn only when the host can open a record (`onOpenRecord`). Absent, never\n// dead.\n\nimport { createContext, type KeyboardEvent, type MouseEvent, type ReactNode } from \"react\";\nimport type { MatrxColumnDef } from \"@ai-matrx/design-system/data-table/types\";\nimport { openOutbound } from \"@ai-matrx/kit/outbound\";\n\n/** What inside the title cell keeps its own click: an open editor, a link, a real button, a picker. The cell's own text control (role=button, `data-matrx-cell-control`) is the title's TEXT, not one of these. */\nconst TITLE_OWN_CONTROLS =\n 'input, textarea, select, button, a[href], [role=\"combobox\"], [contenteditable=\"true\"], [contenteditable=\"\"]';\n\n/** True inside the title cell: a click there opens the record, so its editable text says so (Enter still edits). */\nexport const TitleCellOpensContext = createContext(false);\n\n/**\n * THE TABLE PAGE'S OWN RECORD PANEL, OFFERED TO WHAT RUNS INSIDE IT. A button that adds a row to the table\n * it sits in opens that row in the panel beside the grid, the way every other row opens, instead of going to\n * the record's page (a cold route, 10-20 s). Absent (a cell outside a table page): the button uses the page.\n */\nexport const OpenRecordHereContext = createContext<{ tableId: string; open: (recordId: string) => void } | null>(null);\n\n/** The words on the control, in one place: tests and the walk read them. */\nexport function openRecordLabel(name: string): string {\n return `Open ${name}`;\n}\n\n/** Space opens, unless the key is being typed into an editor. */\nfunction opensOnKey(event: KeyboardEvent<HTMLElement>): boolean {\n if (event.key !== \" \" || event.altKey || event.ctrlKey || event.metaKey) return false;\n const target = event.target as HTMLElement | null;\n if (!target) return false;\n const tag = target.tagName;\n if (tag === \"INPUT\" || tag === \"TEXTAREA\" || tag === \"SELECT\" || tag === \"BUTTON\") return false;\n // An editor INSIDE the grid. A grid mounted in a contenteditable host (a page) is not one.\n if (target.isContentEditable) {\n const editor = target.closest('[contenteditable=\"\"], [contenteditable=\"true\"], [contenteditable=\"plaintext-only\"]');\n const inside = event.currentTarget as HTMLElement | null;\n if (!editor || !inside || inside.contains(editor)) return false;\n }\n return true;\n}\n\n/**\n * Every column gets Space-to-open, and the first also gets the Open control. `nameOf` names the\n * record the way the grid names it everywhere else (its row label).\n */\nexport function withOpenRecord<T extends { id: string }>(\n columns: MatrxColumnDef<T>[],\n onOpen: ((rowId: string) => void) | undefined,\n nameOf: (row: T) => string,\n /** Where the Open control sits in the first cell: at the row's START (the merged grid) or its end. */\n place: \"start\" | \"end\" = \"end\",\n /**\n * The record's own PAGE (the host's `hrefForRecord`), when the host has one: only ⌘/Ctrl-click goes there (a new tab).\n * Every other way in opens the side panel (`openOnly`, which never closes what is already open; `onOpen` is the Space toggle).\n */\n hrefOf?: (row: T) => string | undefined,\n openOnly?: (rowId: string) => void,\n): MatrxColumnDef<T>[] {\n if (!onOpen) return columns;\n return columns.map((column, index) => {\n const original = column.cell;\n const render = (row: T, rowIndex: number): ReactNode =>\n original ? original(row, rowIndex) : String((row as Record<string, unknown>)[column.id ?? \"\"] ?? \"\");\n // ONE PLACE FOR EVERY OPEN GESTURE (the chip, a click or double-click on the title): the record side panel,\n // Notion's side peek (it has Expand to full page); ⌘/Ctrl-click opens the record's page in a new tab.\n const openFrom = (row: T, event: { metaKey: boolean; ctrlKey: boolean }) => {\n const href = hrefOf?.(row);\n if (href && (event.metaKey || event.ctrlKey)) openOutbound(href, \"_blank\", \"noopener\");\n else (openOnly ?? onOpen)(row.id);\n };\n // OPEN CHIP (Notion's OPEN). WITH A POINTER THAT HOVERS: icon + the word, a 24px target, drawn OVER\n // the cell's trailing edge only while the row is hovered or the chip focused, so it never pushes the\n // title. ON TOUCH (no hover): always shown, icon only, a 44px target IN THE ROW'S FLOW — it takes its\n // own width beside the title and never lies over it (W4 live walk, 2026-10-18: an always-on overlay\n // chip covered the titles at phone width, so they read \"Iter…\"). `-my-2.5` keeps the 44px target\n // from growing a short row.\n const handle = (row: T) => (\n <button\n type=\"button\"\n data-records-open-record={row.id}\n aria-label={openRecordLabel(nameOf(row))}\n title={`${openRecordLabel(nameOf(row))} (Space) · ⌘-click: new tab`}\n className=\"absolute right-0 top-1/2 z-10 inline-flex h-6 -translate-y-1/2 items-center gap-1 rounded border border-border bg-card px-1.5 text-xs font-medium leading-none text-foreground no-underline opacity-0 shadow-sm hover:bg-muted focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover/matrx-row:opacity-100 [@media(hover:none)]:static [@media(hover:none)]:-my-2.5 [@media(hover:none)]:h-11 [@media(hover:none)]:w-11 [@media(hover:none)]:shrink-0 [@media(hover:none)]:translate-y-0 [@media(hover:none)]:justify-center [@media(hover:none)]:border-0 [@media(hover:none)]:bg-transparent [@media(hover:none)]:px-0 [@media(hover:none)]:text-muted-foreground [@media(hover:none)]:opacity-100 [@media(hover:none)]:shadow-none\"\n onClick={(event) => {\n event.stopPropagation();\n openFrom(row, event);\n }}\n // The title's own double-click must not run under the chip.\n onDoubleClick={(event) => event.stopPropagation()}\n >\n <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" width=\"12\" height=\"12\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <path d=\"M9.5 2.5h4v4M13.5 2.5 8.5 7.5M6.5 3.5h-3a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1v-3\" />\n </svg>\n <span className=\"[@media(hover:none)]:sr-only\">Open</span>\n </button>\n );\n /** A click on the title text itself; an editor, a link or a button inside the cell keeps its own click. */\n const titleTarget = (event: MouseEvent<HTMLElement>): boolean => {\n const target = event.target as HTMLElement | null;\n if (!target || typeof target.closest !== \"function\") return false;\n const hit = target.closest(TITLE_OWN_CONTROLS);\n return hit === null || !event.currentTarget.contains(hit);\n };\n return {\n ...column,\n cell: (row: T, rowIndex: number) => (\n <span\n className={index === 0 ? \"relative flex min-w-0 items-center gap-1\" : \"contents\"}\n data-records-opens-on-space={row.id}\n onKeyDown={(event) => {\n if (!opensOnKey(event)) return;\n event.preventDefault();\n event.stopPropagation();\n onOpen(row.id);\n }}\n >\n {index === 0 ? (\n <>\n {place === \"start\" ? handle(row) : null}\n <span\n className=\"min-w-0 flex-1 decoration-muted-foreground/60 underline-offset-2 hover:underline\"\n data-clickable=\"\"\n data-records-opens-on-click={row.id}\n // CAPTURE, never stopped: the cell's own text control handles (and swallows) its click, and the title\n // must open whatever the control inside it does with the same click.\n onClickCapture={(event) => {\n if (!titleTarget(event)) return;\n openFrom(row, event);\n }}\n // CAPTURE: the cell's own text control edits on a double-click (\"double-click or press Enter to\n // edit\"); on the title that gesture opens the record, and Enter / F2 still edit.\n onDoubleClickCapture={(event) => {\n if (!titleTarget(event)) return;\n // The title is a link, not a text box: the row's double-click (which edits a cell) stops here.\n event.stopPropagation();\n openFrom(row, event);\n }}\n >\n <TitleCellOpensContext.Provider value={true}>{render(row, rowIndex)}</TitleCellOpensContext.Provider>\n </span>\n {place === \"end\" ? handle(row) : null}\n </>\n ) : (\n render(row, rowIndex)\n )}\n </span>\n ),\n };\n });\n}\n","// src/columnName.ts — @ai-matrx/records-ui · Sheet retirement (lane data-tables-grid-overhaul; the\n// Sheet's `column-name-taken.ts`, deleted in matrx-frontend 1c4e8b0d0d).\n//\n// A NAME ANOTHER COLUMN ALREADY HAS IS SAID WHILE IT IS TYPED. The store refuses it on Save\n// (`custom.field_declare`: same label, case and surrounding spaces ignored); the columns are already\n// on screen, so the name box says it as the person types. Names compare as a person reads them:\n// case, surrounding spaces and runs of spaces do not make two names different. The store stays the\n// final judge — this offers, it never blocks.\n//\n// RESERVED NAMES AND LENGTH (the Sheet's `columnNameProblem`): a name that reads as a word every\n// table keeps for itself (\"id\", \"created_at\") is offered a person's word instead, and a name past\n// `COLUMN_NAME_MAX` is said, because a 300-letter heading draws a 2,418 px column (BREAKER-2 B2-17).\n// Both are said, never enforced: the store judges on Save.\n\nconst said = (name: string) => name.trim().replace(/\\s+/g, \" \");\n\n/** The other column's name when `name` reads the same as one of `others`, else null. */\nexport function columnNameTakenBy(name: string, others: readonly string[]): string | null {\n const wanted = said(name).toLocaleLowerCase();\n if (wanted === \"\") return null;\n const hit = others.find((other) => said(other).toLocaleLowerCase() === wanted);\n return hit === undefined ? null : said(hit);\n}\n\n/** The line the name box shows, short layout text. */\nexport function columnNameTakenLine(taken: string, noun: \"column\" | \"field\" = \"column\"): string {\n return `Another ${noun} is already called “${taken}”`;\n}\n\n/** The longest name a column takes, the Sheet's limit. Said while typing; never enforced here. */\nexport const COLUMN_NAME_MAX = 80;\n\n/** Words every table keeps for itself, and what a person likely means by each. */\nconst KEPT_NAMES: Record<string, string> = {\n id: \"Reference number\", created_at: \"Date added\", updated_at: \"Last updated\", deleted_at: \"Date removed\",\n created_by: \"Added by\", updated_by: \"Changed by\", organization_id: \"Organization\", table_id: \"Table\",\n version: \"Version number\", data: \"Details\", metadata: \"More details\", data_class: \"Category\",\n};\n\n/** The name as a kept word reads it: lower case, words joined by `_`. */\nconst asKept = (name: string) =>\n said(name).toLowerCase().replace(/[^a-z0-9\\s_]/g, \"\").replace(/\\s+/g, \"_\").replace(/^_+|_+$/g, \"\").replace(/_+/g, \"_\");\n\n/**\n * What else is wrong with a typed name, as one short line, or null: too long, or a word every table\n * keeps. A name another column has is `columnNameTakenBy`'s line; an empty one is Save's.\n */\nexport function columnNameProblemLine(name: string, noun: \"column\" | \"field\" = \"column\"): string | null {\n const wanted = said(name);\n if (wanted === \"\") return null;\n if (wanted.length > COLUMN_NAME_MAX) return `${wanted.length} characters; a ${noun} name takes up to ${COLUMN_NAME_MAX}`;\n const instead = KEPT_NAMES[asKept(wanted)];\n return instead ? `“${wanted}” is kept by every table. Try “${instead}”` : null;\n}\n","\"use client\";\n\n// src/FieldEditor.tsx — @ai-matrx/records-ui · SCR-9\n//\n// ADDING A COLUMN, WHICH IS THE FIRST THING ANYBODY DOES WITH A TABLE.\n//\n// On 19 September this panel refused every column a person tried to add — a\n// Number and a Date with \"the table does not declare a field called day_rate —\n// declare it there first\", a Person as though it were a formula, and a choice\n// list with \"has to say which table its choices come from\" and nowhere to say\n// it. One cause: the panel assembled a Field DOCUMENT itself and wrote it with\n// the ordinary record writer, which can neither tell the Table about the field\n// nor stamp the row as a field. Both of those are the store's to do, and now it\n// does them: `custom.field_declare` takes what a person knows — a type, a name,\n// and for a choice list the choices — and turns it into the document its own\n// guards demand.\n//\n// So this panel's whole job is to collect an INTENTION. It never writes a\n// behavior, a format, a unit, a relation target, a relation maximum, a\n// compute_on or a pattern Rule; every one of those is the store's answer to the\n// type a person picked, and a screen that answered them itself is a second\n// place for the thirteen types to be wrong.\n//\n// The key is derived from the name and shown, never demanded: a blank, unmarked,\n// required box that refused the first attempt every time is what a person hit\n// before anything else on this panel.\n//\n// THE SIXTEENTH TYPE (independent verdict, fifth pass, 19 September). Fifteen\n// of the sixteen went in. \"Total of linked records\" did not: the panel\n// explained honestly that the table had no column pointing at several records\n// — and left Add field live, so pressing it sent a rollup with no relation on\n// it and the store answered \"the field Total hours has to say which relation it\n// reads through — FLD-11: … config.via names a relation Field of this same\n// table, by its key.\" A contract row id and three database words, at the\n// person.\n//\n// THE SEVENTEENTH TYPE (independent verifier, 2026-09-20). The kind list had\n// sixteen entries and not one of them was \"Points at another record\". The only\n// relations on offer were Person and File, which point at the PLATFORM's own\n// tables — so the first thing anybody arriving from Airtable reaches for, \"this\n// job belongs to that customer\", could not be built on this screen at all,\n// while the store had taken it since that morning. It is here now, and it asks\n// the ONE question it needs: which table. The tables come from the store\n// (`tableList`, the same door TablesHome reads), never from a guess here, so a\n// person is only ever offered a table they may actually know.\n//\n// AND \"CAN HOLD MORE THAN ONE\" WAS A DEAD CONTROL ON AN EXISTING COLUMN. It\n// carried `disabled={editing}`, so the tick would not go down; and the editing\n// branch of `save()` built a patch that never mentioned `multi`, so even a tick\n// that went down sent nothing. Underneath both sat the store: `custom.field_update`\n// read `multi` only inside its behavior arm, so a patch carrying `multi` alone\n// was answered \"saved\" and changed nothing. All three are closed — the door by\n// lane FIX-7B-FIELD's migration (matrx-frontend\n// `migrations/campaign/fix7b_field_multi_arm.sql`, which gives\n// `custom.field_update`'s SETTINGS branch an arm for `multi` and moves a\n// relation's `relation_max` with it), the two here — and the roll-up panel's own remedy\n// sentence (\"Tick 'Can hold more than one' on Photos\") now names a control that\n// works.\n//\n// Both halves are closed here. The picker now offers EVERY relation column this\n// table has, not only the ones that hold several, and says in one plain\n// sentence what a single-valued one cannot do — because \"Crew lead\" IS the\n// column a person means, and hiding it taught them nothing. And the panel never\n// sends a declaration it already knows the store must refuse: `whatIsMissing`\n// asks, in this panel's own words, what has not been answered yet, the sentence\n// sits under the button, and the button says so rather than failing.\n\nimport { columnNameProblemLine, columnNameTakenBy, columnNameTakenLine } from \"./columnName\";\nimport { useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport {\n type ContextPolicy,\n type Field,\n type FieldPatch,\n type FieldRule,\n type FieldSensitivity,\n type NewEntityFieldDeclaration,\n type NewFieldDeclaration,\n type RelationDisplay,\n type RecordsError,\n type RuleExpression,\n type Uuid,\n} from \"@ai-matrx/records\";\nimport {\n tableShapeChanged,\n useEntityFieldMutation,\n useEntityFieldRights,\n useEntityFields,\n useFieldMutation,\n useFields,\n useRecords,\n useRecordsClient,\n useReverseColumns,\n useTable,\n type ReverseColumn,\n} from \"@ai-matrx/records/react\";\nimport { announceRecordChanged } from \"@ai-matrx/records/core\";\nimport type { ChoiceRehome, ChoicesRehomed, RecordsError as ChoiceSaveError } from \"@ai-matrx/records\";\nimport {\n BasicInput,\n Button,\n Checkbox,\n Label,\n Select,\n SelectContent,\n SelectGroup,\n SelectItem,\n SelectLabel,\n SelectTrigger,\n SelectValue,\n Separator,\n cn,\n} from \"@ai-matrx/design-system\";\nimport { WatchFieldsPicker, watchedFieldsOf, watchedFieldsPatch } from \"./WatchFieldsPicker\";\nimport { editorKindFor, pickableTypeOf } from \"./parity\";\nimport {\n ADD_FIELD_SAVE_LABEL,\n EDIT_FIELD_SAVE_LABEL,\n FIELD_TYPE_CATALOGUE,\n FIELD_TYPE_CHOICES,\n LOOK_KINDS,\n declaredAsLook,\n FIELD_TYPE_GROUPS,\n fieldTypeChoice,\n isParityFieldType,\n isPlainFieldType,\n isRelationFieldType,\n type LookFieldKind,\n type PickableFieldType,\n} from \"./fieldTypes\";\nimport { ReferenceBuilder } from \"./ReferenceBuilder\";\nimport { FormulaTextEditor } from \"./FormulaTextEditor\";\nimport { EntityReferenceKindPicker, whatIsMissingForEntityReference } from \"./EntityReferenceKindPicker\";\nimport { RefusalNotice } from \"./Refusal\";\nimport { SourceArchivedNotice } from \"./SourceArchivedNotice\";\nimport { ChoiceListTermsContext, ConditionGroup, conditionInWords, conditionIsDrawable, type ConditionField } from \"./Condition\";\nimport { FieldRetype } from \"./FieldRetype\";\nimport { FieldRulePreview, rulesChanged } from \"./FieldRulePreview\";\nimport { formulaTextNow } from \"./formulaNames\";\nimport { refusal as refusalOf } from \"./refusals\";\nimport { CHOICE_EDITOR_ADDS_WHAT_IS_TYPED, FieldControl } from \"./editors\";\nimport { useTableRights } from \"./host\";\nimport { choiceLookForNewList, choiceLookFromList } from \"./ColumnLook\";\nimport { ChoiceListEditor, choiceListPatch, choiceRowsFrom, newChoiceRow, whatTheChoiceListIsMissing, type ChoiceListRow } from \"./ChoiceListEditor\";\nimport {\n BarcodeSymbologyQuestion,\n RatingMaxQuestion,\n STATUS_STARTING_CHOICES,\n StatusGroupsQuestion,\n statusGroupRows,\n} from \"./NewerKindQuestions\";\nimport { FieldFormatPicker, formatPatch, startingChoice, type FormatChoice } from \"./FieldFormatPicker\";\nimport { fieldName } from \"./names\";\nimport { humanizeIdentifier } from \"@ai-matrx/kit/text-case\";\nimport { archiveConfirmSentence, readersSentence } from \"./archiveWords\";\nimport { nextFieldSort } from \"./gridMenus\";\nimport {\n FIELD_RULE_KIND_LABEL,\n FIELD_RULE_KIND_VALUES,\n FIELD_SENSITIVITY_LABEL,\n CONTEXT_POLICY_LABEL,\n ROLLUP_AGG_LABEL,\n ROLLUP_AGG_VALUES,\n FORMULA_OP_LABEL,\n FORMULA_OP_JOINS,\n FORMULA_OP_VALUES,\n} from \"./enumLabels\";\nimport { autonumberPrefixOf, buttonNeeds, buttonOf, type ButtonSettings } from \"@ai-matrx/records\";\nimport { ButtonSettingsEditor } from \"./ButtonSettings\";\nimport { FIELD_SENSITIVITIES, CONTEXT_POLICIES, optionKey, ratingMaxOf, rulesWithTopStar, type StatusGroup } from \"@ai-matrx/records\";\n\n// Every array below is DERIVED from `enumLabels.ts` — the value order a person\n// sees on the menu, plus the ONE label map for its enum. No panel keeps its own\n// copy of the words; see `enumLabels.ts` for the canonical source of each.\n\nexport const RULE_KINDS = FIELD_RULE_KIND_VALUES.map((kind) => ({ kind, label: FIELD_RULE_KIND_LABEL[kind] }));\n\n/** FLD-12, in the words the setting actually means to the person setting it. */\nexport const SENSITIVITIES = FIELD_SENSITIVITIES.map((value) => ({ value, label: FIELD_SENSITIVITY_LABEL[value] }));\n\nexport const AGENT_VISIBILITY = CONTEXT_POLICIES.map((value) => ({ value, label: CONTEXT_POLICY_LABEL[value] }));\n\nexport const ROLLUP_OPERATIONS = ROLLUP_AGG_VALUES.map((value) => ({\n value: value as NonNullable<NewFieldDeclaration[\"agg\"]>,\n label: ROLLUP_AGG_LABEL[value],\n}));\n\n/**\n * F5 (VERIFIER-11). The one spelling of the separator control, and its default.\n * Exported because the panel, its suite and the published tarball all have to be talking\n * about the same words.\n */\nexport const FORMULA_SEPARATOR_LABEL = \"Joined by\";\n/** What this panel says over an existing worked-out column, rather than nothing. */\nexport const EDITING_A_WORKED_OUT_COLUMN = \"Written as a formula. Edit it below.\";\nexport const FORMULA_DEFAULT_SEPARATOR = \" — \";\n\nexport const FORMULA_OPERATIONS = FORMULA_OP_VALUES.map((value) => ({\n value,\n label: FORMULA_OP_LABEL[value],\n joins: FORMULA_OP_JOINS[value],\n}));\n\n// What a standard table's field can be is pure, so `/helpers` carries it (records-ui front door, 2026-10-16).\nimport { STANDARD_TABLE_FIELD_CHOICES } from \"./standardFieldChoices\";\nexport { STANDARD_TABLE_FIELD_CHOICES, holdsAValueOnAStandardTable } from \"./standardFieldChoices\";\n\n/** The record page's commit button. A record page has fields, not columns. */\nexport const ADD_STANDARD_FIELD_SAVE_LABEL = \"Create field\";\n\n/**\n * A COLUMN'S DEFAULT (Sheet parity, DATA-V2-BASICS-2): what a new record that does not name this\n * column starts with. The store keeps it on the Field (`default`) and fills it in\n * `custom.record_write`; `custom.field_update` takes it in its settings arm. Offered only on the\n * kinds a person types or picks one value into — a worked-out column, a link, a file, a person or\n * a signature has no fixed value to start from.\n */\nconst KINDS_WITH_A_DEFAULT: ReadonlySet<string> = new Set([\n \"text\", \"long_text\", \"email\", \"phone\", \"url\", \"number\", \"currency\", \"percent\", \"rating\",\n \"duration\", \"time\", \"datetime\", \"select\", \"multi_select\", \"status\", \"checkbox\",\n]);\n\nexport function takesADefault(field: Field): boolean {\n return KINDS_WITH_A_DEFAULT.has(String(pickableTypeOf(field) ?? editorKindFor(field)));\n}\n\n/** The same question for a column not made yet: the kind a person picked in the menu. */\nexport function newColumnTakesADefault(type: string): boolean {\n return KINDS_WITH_A_DEFAULT.has(type);\n}\n\n/**\n * HOW A NEW COLUMN'S DEFAULT TRAVELS. `custom.field_declare` takes `default` in its spec and fits\n * it to the column (`custom._field_default_fitted`). A choice column's default is one of its\n * choices, which exist only once the column does, so it goes in ONE follow-up `field_update`\n * right after the create.\n */\nexport function newColumnDefaultGoes(type: string): \"in-the-create\" | \"right-after\" {\n return type === \"select\" || type === \"multi_select\" || type === \"status\" ? \"right-after\" : \"in-the-create\";\n}\n\n/** The default as the store keeps it: an empty box, blank words or an empty list is \"no default\". */\nexport function defaultToKeep(value: unknown): unknown {\n if (value === undefined || value === null) return null;\n if (typeof value === \"string\") {\n const words = value.trim();\n return words === \"\" ? null : words;\n }\n if (Array.isArray(value) && value.length === 0) return null;\n return value;\n}\n\n/**\n * \"EVERY VALUE MUST BE DIFFERENT\" — the store's `unique` rule (FLD-3 / B1), enforced on every write\n * under an advisory lock (`custom._unique_rule_holds`), whose refusal names the column and the value.\n * Offered on the kinds whose one value can be compared as words; a list of several, a tick, a link\n * or a worked-out column cannot be \"the same as\" another in a way a person means.\n */\nconst KINDS_THAT_CAN_BE_UNIQUE: ReadonlySet<string> = new Set([\n \"text\", \"long_text\", \"email\", \"phone\", \"url\", \"barcode\", \"number\", \"currency\", \"percent\", \"datetime\", \"time\", \"duration\", \"select\",\n]);\n\nexport function canBeUnique(type: string, multi: boolean): boolean {\n return !multi && KINDS_THAT_CAN_BE_UNIQUE.has(type);\n}\n\n/** The rules with the unique rule on or off — one at most, every other rule kept in place. */\nexport function withUnique(rules: readonly FieldRule[], on: boolean): FieldRule[] {\n const rest = rules.filter((r) => r.kind !== \"unique\");\n return on ? [...rest, { kind: \"unique\" }] : rest;\n}\n\nexport const UNIQUE_LABEL = \"Every value must be different\";\nexport const DEFAULT_LABEL = \"New records start with\";\n\n/** `Day rate` → `day_rate`. Shown, so nothing about it is a surprise. */\nexport function keyFor(label: string): string {\n const token = label\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\")\n .slice(0, 48);\n if (token === \"\") return \"\";\n return /^[a-z]/.test(token) ? token : `f_${token}`;\n}\n\ninterface FieldEditorCommon {\n /**\n * The name the host's page gives this table's records (\"Contact\"), when the store's own label\n * is not the word a person reads there. Shown in the header and in place of the store's label\n * inside its refusal sentence.\n */\n tableLabel?: string | undefined;\n onSaved?: (() => void) | undefined;\n onCancel?: (() => void) | undefined;\n /** Called after the store has accepted the removal, so the list can re-read. */\n onRemoved?: (() => void) | undefined;\n className?: string | undefined;\n /**\n * A NEW column that starts as this kind (and name) — a host's own type menu (Spaces' \"New property\"\n * → Formula / Rollup) opens the panel already on the kind the person picked. Ignored when `field`\n * or `copyOf` is given.\n */\n startAs?: { type: PickableFieldType; label?: string | undefined } | undefined;\n}\n\n/**\n * ONE EDITOR FOR BOTH KINDS OF TABLE (lane 7 STANDARD-TABLES, wave 1; Doctrine R13).\n *\n * A column of one of an organization's own tables is named by its Table's uuid (`tableId`). A\n * custom field of a STANDARD table — a CRM contact, a deal, any registry Entity or Detail — has no\n * Table record and is named by its registry token (`entityToken`). Both are the same primitive to\n * a person: the same palette (`fieldTypes.ts`), the same questions, the same governance (who sees\n * it, whether an assistant reads it, what counts as a good value). The only difference is which\n * store door takes the declaration — `custom.field_declare` or `custom.entity_field_declare`,\n * which resolves the spec through the same `custom._field_document_for` — and who may change the\n * shape: the table's own Owner/Admin level, or the organization's admins\n * (`custom.entity_field_rights`, whose sentence is shown as it is).\n *\n * A standard table's field is DECLARED here; editing an existing one stays with the record page's\n * own section (rename, remove), because the edit arms below (choice re-homing, retype, look) are\n * custom-table doors.\n */\nexport type FieldEditorProps = FieldEditorCommon &\n (\n | {\n tableId: Uuid;\n entityToken?: undefined;\n /** The Field being edited. Absent means a new one. */\n field?: Field | undefined;\n /**\n * DUPLICATE PROPERTY (Notion N5): a NEW column that starts as a copy of this one — its kind,\n * choices and colors, unit, link, formula and rules — named \"<name> (1)\". Ignored when\n * `field` is given.\n */\n copyOf?: Field | undefined;\n }\n | {\n /** The standard table's registry token (REC-33), e.g. `party`, `crm_deal`. */\n entityToken: string;\n tableId?: undefined;\n field?: undefined;\n copyOf?: undefined;\n }\n );\n\n/**\n * THE SENTENCE FOR A COLUMN THE STORE TOOK AND THE TABLE HAS NOT GOT.\n *\n * Crew C, on fifty-one real national parks: \"Every 'Add field' attempt appeared to\n * succeed on screen (no error text), but a direct fields() read afterward showed only\n * the table's default Title column.\" The panel closed on the DOOR'S answer, and the\n * grid then drew \"This table has no columns yet\" over real, complete data. A screen\n * that reports a success it has not confirmed is the one thing a person cannot recover\n * from, because they move on.\n */\nconst COLUMN_DID_NOT_LAND_SENTENCE =\n \"The column was accepted but the table does not have it yet. Nothing was lost — \" +\n \"your record values are untouched — but the column is not there, so this panel is staying open.\";\nconst COLUMN_DID_NOT_LAND_REMEDY =\n \"Press Save again; if it keeps happening, tell us — that is ours to fix.\";\nexport const COLUMN_DID_NOT_LAND = `${COLUMN_DID_NOT_LAND_SENTENCE} ${COLUMN_DID_NOT_LAND_REMEDY}`;\n\nexport function FieldEditor(props: FieldEditorProps) {\n const { field, onSaved, onCancel, onRemoved, className } = props;\n const entityToken = props.entityToken ?? null;\n const onEntity = entityToken !== null;\n // A standard table has no Table uuid; the subpanels that take one (the relation builder's\n // \"this table\" mark, the formula checker) are handed the empty id and answer for no table.\n const tableId = (props.tableId ?? \"\") as Uuid;\n // Every hook is called on every render; the one that does not apply is asked about nothing.\n const table = useTable(onEntity ? null : tableId);\n const tableFields = useFields(onEntity ? null : tableId);\n const entityFields = useEntityFields(entityToken);\n const fields = onEntity ? entityFields : tableFields;\n const tableRights = useTableRights(onEntity ? null : table.data);\n const entityRights = useEntityFieldRights(entityToken);\n const tableMutation = useFieldMutation();\n const entityMutation = useEntityFieldMutation();\n const mutation = onEntity\n ? { saving: entityMutation.saving, error: entityMutation.error }\n : { saving: tableMutation.saving, error: tableMutation.error };\n const client = useRecordsClient();\n /** May this person change the shape of this table — and if not, the sentence saying why. */\n const mayShape = onEntity ? entityRights.data?.may_declare === true : tableRights.structure;\n const whyNot = onEntity ? (entityRights.data?.reason ?? null) : tableRights.why(\"structure\");\n const storeLabel = onEntity ? (entityRights.data?.label ?? null) : (table.data?.name ?? null);\n const tableLabel = props.tableLabel ?? storeLabel;\n /** The kinds this menu offers: a standard table's are the ones that hold a value there. */\n const offered = onEntity ? STANDARD_TABLE_FIELD_CHOICES : FIELD_TYPE_CHOICES;\n /**\n * WHO MAY SEE A STANDARD TABLE'S FIELD (lane 7 ruling via the chair, 2026-10-02). A standard row's\n * `custom_fields` column is read by every member the table's own row security admits, so the\n * store cannot yet hold a value back from some of them; until it can, it refuses the two levels\n * that promise to (`confidential`, `restricted`) on a standard token, and this panel does not\n * offer them there. A custom table keeps all four. If the store refuses anyway, its sentence is\n * shown by the refusal notice below like any other.\n */\n const sensitivities = onEntity\n ? SENSITIVITIES.filter((row) => row.value === \"public\" || row.value === \"internal\")\n : SENSITIVITIES;\n\n /** What the panel's answers start from: the Field being edited, or the one being duplicated. */\n const copyOf = field ? undefined : props.copyOf;\n const start = field ?? copyOf;\n const startAs = start ? undefined : props.startAs;\n const [label, setLabel] = useState(field?.label ?? (copyOf ? `${copyOf.label} (1)` : (startAs?.label ?? \"\")));\n const [type, setType] = useState<PickableFieldType>(() => (startAs ? startAs.type : startingType(start)));\n const [required, setRequired] = useState(start?.required ?? false);\n const [multi, setMulti] = useState(start?.multi ?? false);\n const [dated, setDated] = useState(start?.dated ?? false);\n const [sensitivity, setSensitivity] = useState(String(start?.sensitivity ?? \"internal\"));\n const [contextPolicy, setContextPolicy] = useState(String(start?.context_policy ?? \"include\"));\n const [rules, setRules] = useState<FieldRule[]>(start?.rules ?? []);\n // What a new record starts with (Sheet parity). Held as the column's own value shape.\n const [startsWith, setStartsWith] = useState<unknown>(start?.default ?? null);\n // LANE 10 P4: a rating's top star, a status's groups (by choice words), a barcode's code type.\n const [ratingMax, setRatingMax] = useState(() => (start ? ratingMaxOf(start) : 5));\n // What the store will judge on Save: a rating's top star travels as its `max` check.\n const savedRules = useMemo(\n () => (field ? (type === \"rating\" ? rulesWithTopStar(field.rules ?? [], ratingMaxOf(field)) : (field.rules ?? [])) : []),\n [field, type],\n );\n const editedRules = useMemo(() => (type === \"rating\" ? rulesWithTopStar(rules, ratingMax) : rules), [type, rules, ratingMax]);\n const [statusGroups, setStatusGroups] = useState<Record<string, StatusGroup>>({});\n // An existing status column's choices: option id → the key the store keeps its group under.\n const [statusKeys, setStatusKeys] = useState<Record<string, string>>({});\n const [symbology, setSymbology] = useState(String(start?.config?.[\"symbology\"] ?? \"\"));\n // AIRTABLE PARITY: the column's help text (`config.description`), shown when its header is hovered.\n const descriptionStart = String(start?.config?.[\"description\"] ?? \"\");\n const [description, setDescription] = useState(descriptionStart);\n // NOTION-PROPS-3: a button's settings, a record number's prefix, a self-link's dependency switch.\n const buttonStart = useMemo(() => buttonOf(start) ?? { label: \"\" }, [start]);\n const [buttonSettings, setButtonSettings] = useState<ButtonSettings>(buttonStart);\n const prefixStart = autonumberPrefixOf(start as Parameters<typeof autonumberPrefixOf>[0]);\n const [numberPrefix, setNumberPrefix] = useState(prefixStart);\n const dependencyStart = start?.config?.[\"dependency\"] === true;\n // W2-A 4: a Last changed time column's watched fields (`config.only_fields`); none = the whole record.\n const watchStart = useMemo(() => watchedFieldsOf(start), [start]);\n const [watchFields, setWatchFields] = useState<string[]>(watchStart);\n const [dependency, setDependency] = useState(dependencyStart);\n // AT-SHARE-B: a Person column's \"Notify people when they're added\" (custom.field_notify_on_assign). An existing\n // column's answer is READ from the store (its two automations); null until it has answered. A new column starts off.\n const [notifyStart, setNotifyStart] = useState<boolean | null>(field ? null : false);\n const [notify, setNotify] = useState(false);\n const [notifyReadError, setNotifyReadError] = useState<RecordsError | null>(null);\n const personColumn = !onEntity && type === \"member\";\n useEffect(() => {\n if (!field || onEntity || type !== \"member\") return;\n let live = true;\n void client.fieldNotifyOnAssign({ field_id: field.id, on: null }).then((got) => {\n if (!live) return;\n if (got.ok) {\n setNotifyStart(got.data.notify_on_assign === true);\n setNotify(got.data.notify_on_assign === true);\n setNotifyReadError(null);\n } else setNotifyReadError(got.error);\n });\n return () => {\n live = false;\n };\n }, [client, field, onEntity, type]);\n useEffect(() => {\n if (!field || type !== \"status\") return;\n let live = true;\n void client.fieldOptions({ field_id: field.id }).then((got) => {\n if (live && got.ok) setStatusKeys(Object.fromEntries((got.data ?? []).map((o) => [String(o.id), optionKey(o)])));\n });\n return () => {\n live = false;\n };\n }, [client, field, type]);\n // A NEW Status column starts with Notion's three choices, one in each group (lane 10 P4).\n useEffect(() => {\n if (field || type !== \"status\") return;\n setNewChoices((rows) =>\n rows.length > 0 ? rows : STATUS_STARTING_CHOICES.map((c, i) => ({ id: null, words: c.words, row: `status-${i}` })),\n );\n }, [field, type]);\n // A NEW Choice / Several-choices column OPENS ON ONE EMPTY CHOICE ROW: the choices are asked for right\n // where the column is made. An empty row is dropped at save, so this offers and never blocks (Law 6).\n useEffect(() => {\n if (field || (type !== \"select\" && type !== \"multi_select\")) return;\n setNewChoices((rows) => (rows.length > 0 ? rows : [newChoiceRow([])]));\n }, [field, type]);\n // STORE-RULE-GAPS: a choice list may take values that are not one of its\n // choices (the older grid's allowOther). Off unless the column says so.\n const [allowOther, setAllowOther] = useState(start?.config?.[\"allow_other\"] === true);\n // A NEW choice column's choices, one row each with its color (the same editor an existing\n // column's settings draw — lane VIEWS-AND-FIELDS W1-B).\n const [newChoices, setNewChoices] = useState<ChoiceListRow[]>([]);\n // DUPLICATE PROPERTY: the copy starts with the original's choices, in their colors and order.\n const copyOfId = copyOf?.id ?? null;\n useEffect(() => {\n if (!copyOf || !copyOfId) return;\n let live = true;\n void client.fieldOptions({ field_id: copyOfId }).then((got) => {\n if (!live || !got.ok) return;\n const rows = choiceRowsFrom(got.data ?? [], copyOf);\n if (rows.length > 0) setNewChoices(rows.map((r, i) => ({ ...r, id: null, row: `copy-${i}` })));\n });\n return () => {\n live = false;\n };\n // The original is read once, by its id.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [client, copyOfId]);\n // CHOICE-COLUMN-EDIT: an EXISTING choice column's choices, one row each, as the store answered\n // them (`start`) and as the person has them now (`choiceList`). Null until they are read.\n const [choiceList, setChoiceList] = useState<ChoiceListRow[] | null>(null);\n const [choiceListStart, setChoiceListStart] = useState<ChoiceListRow[] | null>(null);\n // CHOICE-TAILS: where the records of each removed choice go (by option id), and — once a save\n // moved, kept or cleared some — what it did and its undo, said here before the panel closes.\n const [rehome, setRehome] = useState<Record<string, ChoiceRehome>>({});\n const [rehomed, setRehomed] = useState<{ said: string; undo: ChoicesRehomed[\"undo\"] | null } | null>(null);\n const [rehomeRefused, setRehomeRefused] = useState<ChoiceSaveError | null>(null);\n const [unit, setUnit] = useState(start?.unit ?? \"$\");\n const [withTime, setWithTime] = useState(String(start?.config?.[\"kind\"] ?? \"date\") === \"datetime\");\n const [via, setVia] = useState(String(start?.config?.[\"via\"] ?? \"\"));\n const [pick, setPick] = useState(String(start?.config?.[\"pick\"] ?? \"\"));\n const [agg, setAgg] = useState<NonNullable<NewFieldDeclaration[\"agg\"]>>(\n (start?.config?.[\"agg\"] as NewFieldDeclaration[\"agg\"]) ?? \"count\",\n );\n const [of, setOf] = useState(String(start?.config?.[\"of\"] ?? \"\"));\n // CHAIR-UI-STORE item 1: WHICH of the linked records a total adds up — `config.filter`, in the\n // saved view's own Rule grammar over the far table, built in the one condition builder.\n const savedRollupFilter = (field?.config?.[\"filter\"] ?? null) as RuleExpression | null;\n const [rollupFilter, setRollupFilter] = useState<RuleExpression | null>(\n field ? savedRollupFilter : ((copyOf?.config?.[\"filter\"] ?? null) as RuleExpression | null),\n );\n const rollupFilterChanged = JSON.stringify(rollupFilter) !== JSON.stringify(savedRollupFilter);\n // THE ONE QUESTION A LINK NEEDS: which table. Never guessed, never typed.\n const [relationTarget, setRelationTarget] = useState(String(start?.relation_target ?? \"\"));\n // NOTION-PROPS — \"Show on <table>\": a new link is a column on BOTH tables (Notion's two-way relation),\n // on by default; off leaves the read-only back-link the other table already shows.\n const [showOnOther, setShowOnOther] = useState(true);\n // NOTION-PROPS — SUB-ITEMS: a new link to THIS table may name each record's parent (`subItems.tsx`).\n const [nestsSubItems, setNestsSubItems] = useState(false);\n const [reverseRefused, setReverseRefused] = useState<RecordsError | null>(null);\n const otherTable = useTable(!field && type === \"relation\" && relationTarget !== \"\" ? (relationTarget as Uuid) : null);\n // REL-DISP: and WHICH OF ITS COLUMNS this one shows. Null means the target\n // Table's own reference column, which is what every relation did before.\n const [display, setDisplay] = useState<RelationDisplay | null>(start?.display ?? null);\n // ── THE WORKED-OUT COLUMN, READ BACK OFF THE FIELD IT IS EDITING (lane STORE-TAILS-2).\n // These three used to start at \"concat\" / [] / — even when the panel was opened on an\n // existing formula, so opening one to rename it and pressing save rewrote its expression\n // into a formula that reads nothing. `formulaExprOf` reads the one shape this panel\n // writes and the store keeps.\n const [formulaOp, setFormulaOp] = useState(() => formulaOpOf(start));\n const [formulaFields, setFormulaFields] = useState<string[]>(() => formulaFieldIdsOf(start));\n // F5 (VERIFIER-11): WHAT GOES BETWEEN THEM. Greenline's route sheet read `GL-2034mow_edge`\n // — the machine's word AND no separator, because nothing on this panel ever asked for one.\n // The store takes `{\"op\":\"concat\",\"separator\":\" — \",\"args\":[…]}`; this is where a person\n // says it. An em dash by default, because a joined label is read by somebody and every\n // label anyone actually wants has something between its parts.\n const [formulaSeparator, setFormulaSeparator] = useState(() => formulaSeparatorOf(start));\n // SC-R: which kinds of platform thing an entity-reference column may point at.\n const [allowedTypes, setAllowedTypes] = useState<string[]>(() => entityReferenceKindsOf(start));\n // K2 (lane DEFAULT-GRID-PARITY): THE FORMULA IN THE LANGUAGE A PERSON TYPES. A column that\n // already carries text opens on it; a new one starts on the picker and may switch.\n // …IN TODAY'S COLUMN NAMES (review 2, C3): `{Quote}` reads `{Quote amount}` after the rename —\n // the store keeps the formula by field id, so the text is drawn from the ids (`formulaNames.ts`).\n const startingFormulaText = start\n ? formulaTextNow(String(start.config?.[\"formula_text\"] ?? \"\"), start.config?.[\"expr\"] ?? (start as { expr?: unknown }).expr, fields.data)\n : \"\";\n const [formulaText, setFormulaText] = useState(startingFormulaText);\n // The columns arrive after the panel opens: an untouched formula follows them to today's names.\n const shownFormula = useRef(startingFormulaText);\n useEffect(() => {\n if (shownFormula.current === startingFormulaText) return;\n setFormulaText((typed) => (typed === shownFormula.current ? startingFormulaText : typed));\n shownFormula.current = startingFormulaText;\n }, [startingFormulaText]);\n // A host's own \"Formula\" choice (`startAs`) opens on writing one, the way Notion's formula editor does.\n const [formulaWritten, setFormulaWritten] = useState(() => startingFormulaText.trim() !== \"\" || Boolean(field) || startAs?.type === \"formula\");\n /** The store's verdict on `formulaText`: true, false, or null while it is asked. */\n const [formulaOk, setFormulaOk] = useState<boolean | null>(null);\n const [askingToRemove, setAskingToRemove] = useState(false);\n /** A Save press or leaving the name box: only then does the footer say what is missing (WALK3-FIX). */\n const [attempted, setAttempted] = useState(false);\n // HOW THE COLUMN LOOKS (merge tranche 6a): what a plain column shows as — the Field's own\n // `display_format`, sent in the same settings patch as the rest. A choice's color rides on its\n // row of the choice editor (`choiceLookFromList`).\n const [showsAs, setShowsAs] = useState<FormatChoice>(() => (start ? startingChoice(start) : { format: null, retype: null }));\n /** The store refused to number the records already here (H2). */\n const [backfillError, setBackfillError] = useState<RecordsError | null>(null);\n /** The store took the column and the table does not have it. See `save`. */\n const [notLanded, setNotLanded] = useState(false);\n\n // WHAT IT HOLDS AFTER A RETYPE (grids review 3, lane H item 5): \"Change what this column holds\"\n // converts through the store and the table's columns are read again — the panel follows the\n // Field as the store now has it, so \"What it holds\" never keeps saying \"Number\" over a column that\n // holds words until a reload.\n const liveField = field ? (fields.data?.find((f) => f.id === field.id) ?? field) : undefined;\n const heldAs = liveField\n ? JSON.stringify([liveField.type, liveField.config?.[\"kind\"] ?? null, liveField.format ?? null, liveField.multi ?? false, liveField.unit ?? null])\n : \"\";\n const seededAs = useRef(heldAs);\n useEffect(() => {\n if (!liveField || seededAs.current === heldAs) return;\n seededAs.current = heldAs;\n setType(startingType(liveField));\n setShowsAs(startingChoice(liveField));\n setMulti(liveField.multi ?? false);\n setUnit(liveField.unit ?? \"$\");\n setWithTime(String(liveField.config?.[\"kind\"] ?? \"date\") === \"datetime\");\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [heldAs]);\n\n const others = useMemo(\n () => (fields.data ?? []).filter((f) => f.id !== field?.id),\n [fields.data, field?.id],\n );\n // THE COLUMNS A LOOKUP OR A ROLLUP READS THROUGH: the link-like ones — a link to another table's\n // records, a Person, a File — which the store resolves a borrowed value or a total through (a\n // Person lookup reads the person's name; a count through a Person counts them). Never a\n // platform reference (`entity_reference`), whose `{token, id}` the store reads nothing through,\n // and never a plain column. `sourceKindOf` says which, so the list names a person or a file.\n const relations = useMemo(() => others.filter((f) => sourceKindOf(f) !== null), [others]);\n // CHAIR-UI-STORE item 2: A BACK-LINK IS A TOTAL'S NATURAL SOURCE. \"Booked visits per patient\"\n // counts the Appointments that link here — the reverse column REL-9 shows on this table. The\n // store reads a roll-up through it (`custom._back_link_relation`); a borrowed value reads ONE\n // record, so a back-link (many) is offered to a total only.\n const reverse = useReverseColumns(onEntity ? null : tableId);\n const backLinks = useMemo(() => (reverse.data ?? []).map(backLinkAsSource), [reverse.data]);\n const totalSources = useMemo(() => [...relations, ...backLinks], [relations, backLinks]);\n const sourcesFor = (kind: PickableFieldType) => (kind === \"rollup\" || kind === \"count\" ? totalSources : relations);\n const choice = fieldTypeChoice(type);\n const editing = Boolean(field);\n // A new column's default is typed for the kind picked; another kind starts it over.\n useEffect(() => {\n if (!editing) setStartsWith(null);\n }, [type, editing]);\n const newDefault = !editing && !onEntity && newColumnTakesADefault(type) ? defaultToKeep(startsWith) : null;\n // A LINK COLUMN'S REMOVE NAMES THE TOTALS READING THROUGH IT, on the table it points at (their\n // `via` is this column's back-link key) — the same count and sentence the back-link dialog gives.\n const farFieldsOfLink = useFields(field && sourceKindOf(field) === \"link\" && !onEntity ? ((field.relation_target ?? null) as Uuid | null) : null);\n const farTable = useTable(field && sourceKindOf(field) === \"link\" && !onEntity ? ((field.relation_target ?? null) as Uuid | null) : null);\n const linkReaders = useMemo(\n () => (field ? readingThroughLink(field, farFieldsOfLink.data ?? []) : []),\n [field, farFieldsOfLink.data],\n );\n // G3 (lane 5's dry run, 2026-10-02): THE TITLE NAMES THE RECORD, ONE NAME EACH (REC-2). A title\n // saved as \"can hold more than one\" made the import refuse every row (\"… holds many values, so\n // it takes a list\"). So the tick is never offered on the table's title column, and a save from\n // it always says one value — which also mends a title the store had kept as a list.\n const isTitle = Boolean(field) && !onEntity && table.data?.title_field === field?.key;\n const offersMany = multiApplies(type) && !isTitle;\n // The key is DERIVED, never asked for and never shown: the blank, unmarked,\n // required box it replaced refused the first attempt on this panel every\n // time, and the line that printed the derived token instead was the last\n // machine identity on this screen. `keyFor` stays exported for callers that\n // need to predict it; a person does not.\n\n // SCR-4: a person who does not administer the table never sees this panel.\n if (!mayShape) {\n // A standard table's right is still being read: nothing yet, rather than a refusal it has not given.\n if (onEntity && entityRights.loading) return null;\n return (\n <p className={cn(\"text-xs text-muted-foreground\", className)}>\n {/* Honest, not dead: the reason, in a sentence — what level it takes\n and who can give it to you. */}\n {props.tableLabel && storeLabel && whyNot ? whyNot.split(storeLabel).join(props.tableLabel) : whyNot}\n </p>\n );\n }\n\n const options = newChoices.map((r) => r.words.trim()).filter((word) => word !== \"\");\n // LANE 10 P4: A STATUS's choices each sit in a group. A new Status column starts with Notion's\n // three; every choice shown (new or existing) has its group, read from the column or guessed\n // from its words, and changed here.\n // V8 #3: rows named by option id (an existing choice) or words (a new one); only what changed is sent,\n // and the store MERGES it into the groups the column keeps.\n const shownStatusRows =\n type !== \"status\" ? [] : statusGroupRows(field, editing ? (choiceList ?? []) : newChoices, statusKeys, statusGroups);\n const statusGroupsSent = Object.fromEntries(shownStatusRows.filter((r) => !editing || r.ref in statusGroups || !(r.ref in statusKeys)).map((r) => [r.ref, r.group]));\n const statusGroupsChanged = type === \"status\" && editing && Object.keys(statusGroupsSent).length > 0;\n\n /**\n * WHAT THIS PANEL STILL NEEDS, in the words of the panel that asked for it.\n *\n * Never the store's sentence: the store refuses by contract row and document\n * path, which is right for a caller and wrong for a person. `null` means the\n * declaration is complete as far as this screen can tell — the store is still\n * the one that decides, and whatever it says then is shown as it always was.\n */\n const formulaChanged = formulaText.trim() !== startingFormulaText.trim();\n const formulaMissing =\n type !== \"formula\" || !formulaWritten\n ? null\n : editing && !formulaChanged\n ? null\n : formulaText.trim() === \"\"\n ? \"Write the formula\"\n : formulaOk === false\n ? \"The formula has a mistake — it is marked above.\"\n : formulaOk === null\n ? \"Checking the formula…\"\n : null;\n /** What the thing being made is called here: a table's column, a record page's field. */\n const noun: \"column\" | \"field\" = onEntity ? \"field\" : \"column\";\n /** Another column's name, when the one typed reads the same (said live; `columnName`). */\n const nameTaken = columnNameTakenBy(label, others.map(fieldName));\n /** Too long, or a word every table keeps (`columnName`); said live and held at Save. */\n const nameLine = nameTaken ? columnNameTakenLine(nameTaken, noun) : columnNameProblemLine(label, noun);\n const listsChoices = type === \"select\" || type === \"multi_select\" || type === \"status\";\n // A button that says what it does but not with what (Set fields with no row action) is not saved as a\n // silent no-op; the sentence stands beside Save (walk 2026-10-08 D1). Label only stays allowed.\n const buttonMissing = type === \"button\" && buttonSettings.do ? buttonNeeds(buttonSettings) : null;\n const missing = buttonMissing ?? (editing\n ? (formulaMissing ?? (listsChoices ? whatTheChoiceListIsMissing(choiceList) : null))\n : (formulaMissing ??\n (listsChoices ? whatTheChoiceListIsMissing(newChoices) : null) ??\n (type === \"formula\" && formulaWritten\n ? null\n : whatIsMissing(\n type === \"count\"\n ? { type: \"rollup\", label, options, via, pick, agg: \"count\", of, relations: totalSources, formulaFields, relationTarget, allowedTypes, noun }\n : { type, label, options, via, pick, agg, of, relations: sourcesFor(type), formulaFields, relationTarget, allowedTypes, noun },\n ))));\n\n // A formula's own check speaks as it is written; everything else waits for an attempt.\n const missingShown: string | null = missing && (attempted || formulaMissing) ? missing : null;\n /** What Remove does, said on the destructive button itself (its tooltip), before it happens. */\n const removeConsequence = field\n ? `${archiveConfirmSentence(`the field \\u201c${fieldName(field)}\\u201d`)} Its values stay in every record and come back with it.${\n linkReaders.length > 0 ? ` ${readersSentence(linkReaders.length, farTable.data?.name ?? null)}` : \"\"\n }`\n : \"\";\n\n const save = async () => {\n // A declaration this panel already knows is incomplete is not sent. The\n // person gets the sentence beside the button, now, instead of a refusal\n // written for a caller, a second later.\n if (missing) return;\n if (editing && field) {\n const chooses = type === \"select\" || type === \"multi_select\" || type === \"status\";\n // Each choice's color rides on its row; a re-worded choice keeps its color (`choiceLookFromList`).\n const look = chooses && choiceList && choiceListStart ? choiceLookFromList(field, choiceListStart, choiceList) : null;\n // \"SHOWS AS\" (tranche 6e): the look, and for an Other kind the column's new type word.\n const shownAs = chooses ? undefined : formatPatch(field, showsAs);\n // THE DEFAULT, sent only when it changed; an emptied box sends `null`, which clears it. The\n // door's settings arm takes `default` (the Sheet's seam writes it); `FieldPatch` does not\n // declare the key yet (store gap, reported), the same way `display_format` rides below.\n const defaultNow = defaultToKeep(startsWith);\n const defaultChanged = takesADefault(field) && JSON.stringify(defaultNow) !== JSON.stringify(defaultToKeep(field.default));\n const patch: FieldPatch & { display_format?: unknown; default?: unknown; description?: string | null } = {\n ...(defaultChanged ? { default: defaultNow } : {}),\n ...(description.trim() !== descriptionStart.trim() ? { description: description.trim() === \"\" ? null : description.trim() } : {}),\n // The column's look travels in the same settings patch (`display_format`), so a save is\n // still one store call. `FieldPatch` does not declare the key yet (store gap, reported);\n // the door has carried it since the Sheet's seam started writing it.\n ...(chooses ? (look ? { display_format: look } : {}) : (shownAs ?? {})),\n label,\n required,\n dated,\n sensitivity: sensitivity as FieldSensitivity,\n context_policy: contextPolicy as ContextPolicy,\n rules,\n // FLD-2. THE SHAPE OF THE VALUE, WHICH IS A SETTING LIKE ANY OTHER. This\n // patch never carried it, so the tick beside \"Can hold more than one\"\n // was decoration on an existing column — and the store's own roll-up\n // refusal tells a person to use exactly that tick. It is sent ALONE:\n // `custom.field_update` honors a `multi`-only patch since FIX-7B-FIELD's\n // migration (before it, the door read `multi` only inside its behavior\n // arm, answered \"saved\" and changed nothing), so there is no behavior\n // word to send beside it and sending one would retype a column nobody\n // asked to retype.\n ...(multiApplies(type) ? { multi: isTitle ? false : multi } : {}),\n ...(unitApplies(type) ? { unit } : {}),\n // LANE 10 P4: a status's groups and a barcode's code type, sent only when they changed.\n ...(statusGroupsChanged ? { status_groups: statusGroupsSent } : {}),\n // V11 #4/#10: a rating's top star goes as `max`, the word custom.field_update now takes the way\n // custom.field_declare does; the store writes the max Rule and sets aside any score above it.\n ...(type === \"rating\" && ratingMax !== ratingMaxOf(field) ? { max: ratingMax } : {}),\n ...(type === \"barcode\" && symbology !== String(field.config?.[\"symbology\"] ?? \"\") ? { symbology: symbology === \"\" ? null : symbology } : {}),\n ...(type === \"button\" && JSON.stringify(buttonSettings) !== JSON.stringify(buttonStart) ? { button: buttonSettings } : {}),\n ...(field.type === \"relation\" && dependency !== dependencyStart ? { dependency } : {}),\n ...(type === \"modified_time\" ? watchedFieldsPatch(watchStart, watchFields) : {}),\n ...(type === \"autonumber\" && numberPrefix.trim() !== prefixStart\n ? { display_format: { id: \"autonumber\", options: numberPrefix.trim() === \"\" ? {} : { prefix: numberPrefix.trim() } } }\n : {}),\n // THE CHOICES, ONE ROW EACH, IN ORDER (CHOICE-COLUMN-EDIT): `{id, words}` re-words a\n // choice in place, plain words add one, a choice left out is retired. Sent only when the\n // list is not what the store already holds.\n ...(() => {\n if (!chooses || !choiceList || !choiceListStart) return {};\n const edited = choiceListPatch(choiceListStart, choiceList);\n return edited ? { options: edited } : {};\n })(),\n // REL-DISP. Which of the other record's columns this one shows. Sent for\n // every relation column, `null` included, because `null` is how the door\n // REMOVES a spec and the column goes back to the target table's own\n // reference column — a panel that only sent the key when it was set\n // could turn the override on and never off.\n ...(field.type === \"relation\" ? { display } : {}),\n // STORE-RULE-GAPS: a choice list's own setting, sent for every list so\n // turning it off is as possible as turning it on.\n ...(field.type === \"list\" ? { allow_other: allowOther } : {}),\n // CHAIR-UI-STORE item 1: a total's filter, sent only when it changed; `null` takes it off.\n ...(type === \"rollup\" && rollupFilterChanged ? { filter: (rollupFilter ?? null) as Record<string, unknown> | null } : {}),\n // K2: a re-aimed formula goes WITH its type word, the arm `field_update` reads it in.\n ...(type === \"formula\" && formulaWritten && formulaChanged && formulaText.trim() !== \"\"\n ? { type: \"formula\" as const, formula_text: formulaText.trim() }\n : {}),\n };\n // CHOICE-TAILS: when a removed choice's records have somewhere to go, the list and those\n // records are ONE save through `fieldUpdateRehomingChoices`, and the panel says what it did\n // and offers Undo before it closes.\n if (Object.keys(rehome).length > 0 && Array.isArray((patch as { options?: unknown }).options)) {\n setRehomeRefused(null);\n const done = await client.fieldUpdateRehomingChoices({ field_id: field.id, patch: patch as FieldPatch, rehome });\n if (!done.ok) {\n setRehomeRefused(done.error);\n return;\n }\n tableShapeChanged(tableId);\n for (const c of done.data.undo.cells_back) announceRecordChanged(c.record_id as Uuid);\n const n = done.data.rehomed.reduce((sum, r) => sum + r.records, 0);\n setRehome({});\n setRehomed({ said: `Saved. ${n} ${n === 1 ? \"record was\" : \"records were\"} changed with the choices.`, undo: done.data.undo });\n return;\n }\n const written = await tableMutation.update({ field_id: field.id, patch: patch as FieldPatch });\n if (written === null) return;\n if (personColumn && notifyStart !== null && notify !== notifyStart) {\n const told = await client.fieldNotifyOnAssign({ field_id: field.id, on: notify });\n if (!told.ok) {\n setBackfillError(told.error);\n return;\n }\n setNotifyStart(notify);\n }\n onSaved?.();\n return;\n }\n const spec: NewFieldDeclaration = {\n label,\n // A NEW COLUMN LANDS AT THE END (lane C, review 2026-09-26 C5): declared one past the last\n // column's `sort`, so every view and every client draws it last — never in the alphabetical\n // slot of its internal key.\n sort: nextFieldSort(fields.data),\n ...(isRelationFieldType(type)\n ? {\n type: \"relation\" as const,\n relation_target: relationTarget as Uuid,\n // REL-DISP. Left out entirely when the person did not override it,\n // so a plain relation's document is byte-identical to yesterday's.\n ...(display ? { display } : {}),\n // REL-2. What happens to this record when the thing it points at\n // goes. The panel asks nothing about it yet, so it names the store's\n // own default rather than leaving the key out — nothing is silently\n // decided somewhere else.\n on_target_delete: \"set_null\" as const,\n ...(type === \"relation\" && nestsSubItems && relationTarget === tableId ? { config: { sub_items: true } } : {}),\n }\n : declaredAsLook(type)\n ? // A RATING OR A TIME the store does not publish as its own word: a plain column wearing\n // its look, in the same declaration (`LOOK_KINDS`, grids review 3 item 5).\n { plain: LOOK_KINDS[type]!.plain, display_format: LOOK_KINDS[type]!.look({ ratingMax }) }\n : isPlainFieldType(type)\n ? { plain: type }\n : isParityFieldType(type)\n ? { parity_type: type }\n // ── FIX-10B-F6: EVERY OTHER KIND GOES AS ITS WORD. ────────────────────────\n // `custom._field_document_for` resolves the WORD a person picked — it is the\n // one body that knows a signature is text wearing a format, a checkbox is a\n // boolean, and a `banana` is nothing — and `parity_type` is only for the\n // fourteen it publishes as such. This branch used to be `{ parity_type: type }`\n // for everything that was not plain or a relation, so the moment the menu gained\n // a kind that is not one of the fourteen the panel would have sent it as a\n // parity type and been refused \"There is no field type called signature\". The\n // menu is the store's list now (`DECLARABLE_FIELD_KINDS`), so this is the arm\n // every future kind arrives through.\n : { type: type as Exclude<PickableFieldType, LookFieldKind> }),\n required,\n dated,\n multi: multiApplies(type) ? multi : type === \"multi_select\",\n sensitivity: sensitivity as FieldSensitivity,\n context_policy: contextPolicy as ContextPolicy,\n rules,\n ...(type === \"select\" || type === \"multi_select\" || type === \"status\" ? { options } : {}),\n // LANE 10 P4: what the panel asked of a rating, a status, a barcode and a count.\n ...(type === \"rating\" && !declaredAsLook(type) ? { max: ratingMax } : {}),\n ...(type === \"status\" ? { status_groups: statusGroupsSent } : {}),\n ...(type === \"barcode\" && symbology !== \"\" ? { symbology } : {}),\n ...(type === \"button\" ? { button: buttonSettings } : {}),\n ...(type === \"modified_time\" && watchFields.length ? { config: { only_fields: watchFields } } : {}),\n ...(type === \"autonumber\" && numberPrefix.trim() !== \"\" ? { display_format: { id: \"autonumber\", options: { prefix: numberPrefix.trim() } } } : {}),\n ...(type === \"count\" ? { via } : {}),\n // THE COLORS ITS CHOICES WERE GIVEN (W1-B), on the Field's look in the same declaration:\n // both declare doors build the Field through `custom._field_document_for`, which keeps a\n // `display_format` it is handed — so the grid paints them from its first draw.\n ...(() => {\n const look = listsChoices ? choiceLookForNewList(type === \"multi_select\", newChoices) : null;\n return look ? { display_format: look } : {};\n })(),\n ...((type === \"select\" || type === \"multi_select\") && allowOther ? { allow_other: true } : {}),\n ...(type === \"entity_reference\" ? { allowed_types: allowedTypes } : {}),\n ...(type === \"currency\" ? { unit } : {}),\n ...(type === \"datetime\" ? { kind: withTime ? (\"datetime\" as const) : (\"date\" as const) } : {}),\n ...(type === \"lookup\" ? { via, pick } : {}),\n ...(type === \"rollup\"\n ? { via, agg, ...(agg === \"count\" ? {} : { of }), ...(rollupFilter ? { filter: rollupFilter as unknown as Record<string, unknown> } : {}) }\n : {}),\n ...(type === \"formula\"\n ? formulaWritten\n ? { formula_text: formulaText.trim() }\n : { expr: formulaExpression(formulaOp, formulaFields, formulaSeparator) }\n : {}),\n };\n // THE DEFAULT (Sheet parity): the declare door takes `default`; `NewFieldDeclaration` does not\n // declare the key yet (store gap), the same way `display_format` rides on an edit.\n if (newDefault !== null && newColumnDefaultGoes(type) === \"in-the-create\") (spec as NewFieldDeclaration & { default?: unknown }).default = newDefault;\n const written = onEntity\n ? await entityMutation.declare({ token: entityToken as string, spec: spec as unknown as NewEntityFieldDeclaration })\n : await tableMutation.declare({ table_id: tableId, spec });\n if (written === null) return;\n // 🚨 SUCCESS IS A READ-BACK, NOT A WRITE'S ANSWER (lane LIMITS-FIX-UI, 2026-09-21).\n //\n // Crew C, on fifty-one real national parks: \"Every 'Add field' attempt appeared to\n // succeed on screen (no error text), but a direct fields() read afterward showed\n // only the table's default Title column — none of the 5 fields actually persisted.\"\n // This panel closed on the DOOR'S ANSWER, and the grid then drew \"This table has no\n // columns yet\" over real, complete data. A screen that reports a success it has not\n // confirmed is the one thing a person cannot recover from, because they move on.\n //\n // So it asks the table for its columns and looks for the one it just made, BY ID.\n // The store's own cause was fixed by lane LIMITS-FIX the same day; this is the half\n // that means the SCREEN can never claim it again, whatever the store does next.\n const landed = onEntity ? await client.entityFields({ token: entityToken as string }) : await client.fields({ table_id: tableId });\n if (landed.ok && !landed.data.some((f) => f.id === written)) {\n setNotLanded(true);\n return;\n }\n setNotLanded(false);\n // A choice column's default names one of the choices the create just made: one update, right after.\n if (newDefault !== null && newColumnDefaultGoes(type) === \"right-after\") {\n const defaulted = await client.fieldUpdate({ field_id: written as Uuid, patch: { default: newDefault } as never });\n if (!defaulted.ok) {\n tableShapeChanged(tableId);\n setBackfillError(defaulted.error);\n return;\n }\n }\n // H2 (lane DEFAULT-GRID-PARITY): an autonumber column numbers what is ALREADY here too, in\n // the order it was made — the older grid's backfill. A refusal is said, and the panel stays,\n // because a column that numbers only tomorrow's records would be a quiet half-answer.\n if (type === \"autonumber\") {\n const numbered = await client.autonumberBackfill({ field_id: written });\n if (!numbered.ok) {\n setBackfillError(numbered.error);\n return;\n }\n }\n // AT-SHARE-B: a new Person column made with \"Notify people when they're added\" ticked.\n if (personColumn && notify) {\n const told = await client.fieldNotifyOnAssign({ field_id: written as Uuid, on: true });\n if (!told.ok) {\n setBackfillError(told.error);\n return;\n }\n }\n setBackfillError(null);\n // A SELF-LINK MADE AS A DEPENDENCY (walk 2026-10-08 D10): \"Waits on the linked records\" is asked when the\n // column is made, not only later in its settings; the store marks it through the same field_update.\n if (type === \"relation\" && relationTarget === tableId && dependency && !onEntity) {\n const marked = await client.fieldUpdate({ field_id: written as Uuid, patch: { dependency: true } as never });\n if (!marked.ok) {\n setBackfillError(marked.error);\n return;\n }\n }\n // NOTION-PROPS: the same link as a column on the other table, made through the store's own door.\n if (type === \"relation\" && showOnOther && otherTable.data && otherTable.data.id !== tableId) {\n const made = await client.relationReverseField({ field_id: written });\n if (!made.ok) {\n setReverseRefused(made.error);\n return;\n }\n tableShapeChanged(relationTarget as Uuid);\n }\n setReverseRefused(null);\n onSaved?.();\n };\n\n const remove = async () => {\n if (!field) return;\n const gone = await tableMutation.retire({ field_id: field.id });\n // Left asking while the dialog closes, so nothing in it moves as it goes (WALK3-FIX).\n if (gone) (onRemoved ?? onSaved)?.();\n else setAskingToRemove(false);\n };\n\n return (\n <div className={cn(\"flex min-w-0 flex-col gap-3 text-xs\", className)} data-records-field-editor=\"\">\n {/* One row of header: what this is, and nothing restating it. */}\n <div className=\"flex items-center gap-2\">\n <span className=\"font-medium\">{field ? `Field · ${fieldName(field)}` : \"New field\"}</span>\n <span className=\"ml-auto text-muted-foreground\">{tableLabel}</span>\n </div>\n\n <div className=\"grid gap-3 sm:grid-cols-2\">\n <label className=\"flex flex-col gap-1\">\n <Label className=\"text-xs\">Name</Label>\n <BasicInput\n value={label}\n autoFocus\n aria-label=\"Field name\"\n placeholder=\"Day rate\"\n onChange={(e) => setLabel(e.target.value)}\n onBlur={(e) => {\n // Leaving an empty name box is an attempt; a click on Cancel is not.\n const to = e.relatedTarget as HTMLElement | null;\n if (to?.textContent === \"Cancel\") return;\n setAttempted(true);\n }}\n {...(nameLine ? { \"aria-invalid\": true, \"aria-describedby\": \"field-editor-name-taken\" } : {})}\n />\n {/* SAID AS IT IS TYPED (the Sheet's column-name check): the store still judges on Save. */}\n {nameLine ? (\n <span\n id=\"field-editor-name-taken\"\n {...(nameTaken ? { \"data-field-editor-name-taken\": \"\" } : { \"data-field-editor-name-problem\": \"\" })}\n className=\"truncate text-[11px] text-destructive\"\n title={nameLine}\n >\n {nameLine}\n </span>\n ) : null}\n </label>\n {field ? (<label className=\"flex flex-col gap-1 sm:col-span-2\">\n <Label className=\"text-xs\">Help text</Label>\n <BasicInput\n value={description}\n maxLength={300}\n aria-label=\"Help text\"\n placeholder=\"Shown when the column name is hovered\"\n onChange={(e) => setDescription(e.target.value)}\n />\n </label>) : null}\n\n <div className=\"flex flex-col gap-1\">\n <Label className=\"text-xs\">What it holds</Label>\n <Select\n value={type}\n disabled={editing}\n onValueChange={(next) => setType(next as PickableFieldType)}\n >\n <SelectTrigger size=\"sm\" aria-label=\"What this field holds\" {...(choice?.explanation ? { title: choice.explanation } : {})}>\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {FIELD_TYPE_GROUPS.filter((group) => offered.some((c) => c.group === group)).map((group) => (\n <SelectGroup key={group}>\n <SelectLabel>{group}</SelectLabel>\n {/* An existing column of a kind the menu does not offer yet still reads as its own kind (P4). */}\n {FIELD_TYPE_CATALOGUE.filter((c) => c.group === group && (c.id === type || offered.includes(c))).map((c) => (\n <SelectItem key={c.id} value={c.id}>\n {c.label}\n </SelectItem>\n ))}\n </SelectGroup>\n ))}\n </SelectContent>\n </Select>\n {/* CHANGE WHAT IT HOLDS (review 2, C3): the store's retype door, with the count before. */}\n {editing && field ? (\n <FieldRetype field={liveField ?? field} tableId={tableId} />\n ) : null}\n </div>\n </div>\n\n {/* WHAT THE PANEL ASKS FOR NEXT depends entirely on the answer above, and\n nothing else on this panel knows the difference between the sixteen. */}\n {/* REL-DISP: a relation is asked its questions when EDITING too. Until\n 2026-09-21 this branch skipped every existing column that was not a\n choice list, so there was nowhere to say which of the other record's\n columns a link should show — the one thing about an existing relation\n a person most wants to change. The target itself stays locked there\n (`lockTarget={editing}`): this panel sends no `relation_target` in a\n patch, and a picker that let a person change it would be a control\n that silently does nothing. */}\n {/* F5 (lane STORE-TAILS-2): a worked-out column that is ALREADY THERE gets no formula\n controls on this panel, and until now it got no sentence either — the panel simply\n showed nothing about the one thing that column is. It cannot get the controls in this\n lane: `custom.field_update` takes an `expr` patch (its own FLD-11 arm), but\n `FieldPatch` in `@ai-matrx/records` has no `expr` key, so sending one would need that\n package published too. A live control that cannot send is worse than none, so the\n panel SAYS so instead of standing silent over it. */}\n {type === \"formula\" && others.length > 0 ? (\n <div className=\"flex flex-col gap-2\">\n {editing ? (\n startingFormulaText.trim() === \"\" ? (\n <p className=\"text-[11px] text-muted-foreground\">{EDITING_A_WORKED_OUT_COLUMN}</p>\n ) : null\n ) : (\n <div className=\"flex items-center gap-1\" role=\"group\" aria-label=\"How to make this column\">\n <Button\n type=\"button\"\n size=\"sm\"\n variant={formulaWritten ? \"ghost\" : \"secondary\"}\n aria-pressed={!formulaWritten}\n onClick={() => setFormulaWritten(false)}\n >\n Pick the columns\n </Button>\n <Button\n type=\"button\"\n size=\"sm\"\n variant={formulaWritten ? \"secondary\" : \"ghost\"}\n aria-pressed={formulaWritten}\n onClick={() => setFormulaWritten(true)}\n >\n Write a formula\n </Button>\n </div>\n )}\n {formulaWritten ? (\n <FormulaTextEditor\n tableId={tableId}\n text={formulaText}\n onText={setFormulaText}\n onChecked={setFormulaOk}\n columns={others}\n />\n ) : null}\n </div>\n ) : editing && type === \"formula\" ? (\n <p className=\"text-[11px] text-muted-foreground\">No other column to read.</p>\n ) : null}\n {/* CHAIR-ROLLUP-HONEST: a column this lookup or roll-up reads is archived — named, with Bring back. */}\n {editing && field && !onEntity && (type === \"lookup\" || type === \"rollup\") ? (\n <SourceArchivedNotice fieldId={field.id} tableId={tableId} />\n ) : null}\n {(!editing && !(type === \"formula\" && formulaWritten)) ||\n type === \"select\" ||\n type === \"multi_select\" ||\n type === \"status\" ||\n type === \"rating\" ||\n type === \"barcode\" ||\n type === \"relation\" ||\n type === \"entity_reference\" ? (\n <TypeQuestions\n type={type}\n editing={editing}\n tableId={tableId}\n relationTarget={relationTarget}\n setRelationTarget={setRelationTarget}\n display={display}\n setDisplay={setDisplay}\n unit={unit}\n setUnit={setUnit}\n withTime={withTime}\n setWithTime={setWithTime}\n via={via}\n setVia={setVia}\n pick={pick}\n setPick={setPick}\n agg={agg}\n setAgg={setAgg}\n of={of}\n setOf={setOf}\n formulaOp={formulaOp}\n setFormulaOp={setFormulaOp}\n formulaFields={formulaFields}\n setFormulaFields={setFormulaFields}\n formulaSeparator={formulaSeparator}\n setFormulaSeparator={setFormulaSeparator}\n relations={sourcesFor(type)}\n others={others}\n choiceList={\n editing && field ? (\n <ChoiceListEditor\n field={field}\n rows={choiceList}\n onRows={setChoiceList}\n onStart={setChoiceListStart}\n allowOther={allowOther}\n rehome={rehome}\n onRehome={setRehome}\n />\n ) : (\n <ChoiceListEditor isNew rows={newChoices} onRows={setNewChoices} />\n )\n }\n allowedTypes={allowedTypes}\n setAllowedTypes={setAllowedTypes}\n newer={\n type === \"rating\" ? (\n <RatingMaxQuestion\n value={ratingMax}\n onChange={(next) => {\n setRatingMax(next);\n // An existing rating's top star is its max Rule, saved with the rules.\n // An existing rating's new top star is sent as `max` with the save (above).\n }}\n />\n ) : type === \"status\" ? (\n <StatusGroupsQuestion rows={shownStatusRows} onGroup={(ref, next) => setStatusGroups({ ...statusGroups, [ref]: next })} />\n ) : type === \"barcode\" ? (\n <BarcodeSymbologyQuestion value={symbology} onChange={setSymbology} />\n ) : null\n }\n />\n ) : null}\n\n {type === \"button\" ? (\n <ButtonSettingsEditor value={buttonSettings} onChange={setButtonSettings} tableId={onEntity ? null : tableId} fields={others} />\n ) : null}\n {type === \"modified_time\" ? <WatchFieldsPicker fields={others} value={watchFields} onChange={setWatchFields} /> : null}\n {type === \"autonumber\" ? (\n <label className=\"flex max-w-[16rem] flex-col gap-1\">\n <Label className=\"text-xs\">Prefix</Label>\n <BasicInput className=\"h-8 text-xs\" placeholder=\"TASK-\" maxLength={16} data-records-autonumber-prefix=\"\" value={numberPrefix} onChange={(e) => setNumberPrefix(e.target.value)} />\n </label>\n ) : null}\n {editing && field?.type === \"relation\" && field.relation_target && field.relation_target === field.entity_definition_id ? (\n <label className=\"flex items-center gap-1.5 text-sm\" title=\"A timeline draws a line to each record this one waits on\">\n <Checkbox checked={dependency} aria-label=\"Waits on the linked records\" data-records-dependency=\"\" onCheckedChange={(v) => setDependency(v === true)} />\n <span>Waits on the linked records</span>\n </label>\n ) : null}\n {personColumn ? (\n <label className=\"flex items-center gap-1.5 text-sm\" title=\"Each person added to this column gets a notice\">\n <Checkbox\n checked={notify}\n disabled={notifyStart === null}\n aria-label=\"Notify people when they're added\"\n data-records-notify-on-assign=\"\"\n onCheckedChange={(v) => setNotify(v === true)}\n />\n <span>Notify people when they're added</span>\n </label>\n ) : null}\n {notifyReadError ? <RefusalNotice error={notifyReadError} /> : null}\n {type === \"rollup\" ? (\n <RollupFilterQuestion\n relation={totalSources.find((f) => f.key === via)}\n agg={agg}\n editing={editing}\n value={rollupFilter}\n onChange={setRollupFilter}\n />\n ) : null}\n\n {/* A record number's look is its Prefix box above; a second \"Shows as\" with its own Prefix was a\n duplicate (walk 2026-10-08 D5). */}\n {editing && field && !(type === \"select\" || type === \"multi_select\" || type === \"status\" || type === \"autonumber\") ? (\n <FieldFormatPicker field={field} value={showsAs} onValue={setShowsAs} />\n ) : null}\n\n <div className=\"flex flex-wrap items-center gap-4\">\n <label className=\"flex items-center gap-1.5\">\n <Checkbox\n checked={required}\n aria-label=\"Required\"\n onCheckedChange={(v) => setRequired(v === true)}\n />\n <span title=\"Every record has to have one\">Required</span>\n </label>\n {offersMany ? (\n <label className=\"flex items-center gap-1.5\">\n <Checkbox\n checked={multi}\n aria-label=\"Can hold more than one\"\n onCheckedChange={(v) => setMulti(v === true)}\n />\n Can hold more than one\n </label>\n ) : null}\n <label className=\"flex items-center gap-1.5\">\n <Checkbox\n checked={dated}\n aria-label=\"Each value has its own date\"\n onCheckedChange={(v) => setDated(v === true)}\n />\n Each value has its own date\n </label>\n {!field && type === \"relation\" && otherTable.data && otherTable.data.id !== tableId ? (\n <label className=\"flex items-center gap-1.5\">\n <Checkbox\n checked={showOnOther}\n aria-label={`Show on ${otherTable.data.name ?? \"the other table\"}`}\n onCheckedChange={(v) => setShowOnOther(v === true)}\n data-records-show-on-other=\"\"\n />\n Show on {otherTable.data.name ?? \"the other table\"}\n </label>\n ) : null}\n {!field && type === \"relation\" && relationTarget === tableId ? (\n <label className=\"flex items-center gap-1.5\" title=\"A timeline draws a line to each record this one waits on\">\n <Checkbox checked={dependency} aria-label=\"Waits on the linked records\" data-records-dependency=\"\" onCheckedChange={(v) => setDependency(v === true)} />\n <span>Waits on the linked records</span>\n </label>\n ) : null}\n {!field && type === \"relation\" && relationTarget === tableId ? (\n <label className=\"flex items-center gap-1.5\">\n <Checkbox\n checked={nestsSubItems}\n aria-label=\"Sub-items\"\n onCheckedChange={(v) => {\n setNestsSubItems(v === true);\n if (v === true) setMulti(false);\n }}\n data-records-sub-items=\"\"\n />\n <span title=\"Each record sits under the one this column names\">Sub-items</span>\n </label>\n ) : null}\n {/* Offered only because the choice editor honors it (editors.tsx). */}\n {CHOICE_EDITOR_ADDS_WHAT_IS_TYPED && (type === \"select\" || type === \"multi_select\") ? (\n <label className=\"flex items-center gap-1.5\">\n <Checkbox\n checked={allowOther}\n aria-label=\"A value that is not one of the choices is added to them\"\n onCheckedChange={(v) => setAllowOther(v === true)}\n />\n A value that is not one of the choices is added to them\n </label>\n ) : null}\n </div>\n\n {/* SHEET PARITY: a new column's default, asked as it is made. */}\n {!editing && !onEntity && newColumnTakesADefault(type) ? (\n <NewColumnDefault type={type} choices={options} value={startsWith} onChange={setStartsWith} />\n ) : null}\n {/* SHEET PARITY: the column's default, typed in the column's own editor. */}\n {editing && field && takesADefault(liveField ?? field) ? (\n <div className=\"flex flex-col gap-1\" data-records-field-default=\"\">\n <Label htmlFor=\"records-field-default\" className=\"text-xs\">\n {DEFAULT_LABEL}\n </Label>\n <FieldControl\n id=\"records-field-default\"\n // The column itself, minus what would make a default write or refuse on its own: it is\n // never required (an empty default is \"none\"), and typed words are never added to a\n // choice list from here — Save is the one write.\n field={{ ...(liveField ?? field), required: false, config: { ...((liveField ?? field).config ?? {}), allow_other: false } }}\n value={startsWith}\n onChange={setStartsWith}\n />\n </div>\n ) : null}\n\n <Separator />\n\n <div className=\"grid gap-3 sm:grid-cols-2\">\n <div className=\"flex flex-col gap-1\">\n <Label className=\"text-xs\">Who can see what is in it</Label>\n <Select value={sensitivity} onValueChange={setSensitivity}>\n <SelectTrigger size=\"sm\" aria-label=\"Who can see what is in it\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {sensitivities.map((row) => (\n <SelectItem key={row.value} value={row.value}>\n {row.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <div className=\"flex flex-col gap-1\">\n <Label className=\"text-xs\">Can an assistant read it</Label>\n <Select value={contextPolicy} onValueChange={setContextPolicy}>\n <SelectTrigger size=\"sm\" aria-label=\"Can an assistant read it\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {AGENT_VISIBILITY.map((row) => (\n <SelectItem key={row.value} value={row.value}>\n {row.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n </div>\n\n <Separator />\n\n {/* FLD-3: a constraint is a RULE attached to the Field, never a behavior. */}\n <div className=\"flex flex-col gap-2\">\n <div className=\"flex items-center gap-2\">\n <span className=\"font-medium\">What counts as a good value</span>\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"outline\"\n className=\"ml-auto\"\n onClick={() => setRules([...rules, { kind: \"min\", value: 0 }])}\n >\n Add a check\n </Button>\n </div>\n {/* FLD-3 / B1: the store's `unique` rule, as one tick rather than a row with a value box. */}\n {canBeUnique(type, multi) || rules.some((r) => r.kind === \"unique\") ? (\n <label className=\"flex items-center gap-1.5\" data-records-field-unique=\"\">\n <Checkbox\n checked={rules.some((r) => r.kind === \"unique\")}\n aria-label={UNIQUE_LABEL}\n onCheckedChange={(v) => setRules(withUnique(rules, v === true))}\n />\n {UNIQUE_LABEL}\n </label>\n ) : null}\n {rules.length === 0 ? (\n <p className=\"text-muted-foreground\">\n No checks.\n </p>\n ) : null}\n {rules.map((rule, index) => rule.kind === \"unique\" ? null : (\n <div key={`${rule.kind}-${index}`} className=\"flex items-center gap-1\">\n <Select\n value={rule.kind}\n onValueChange={(kind) =>\n setRules(rules.map((r, i) => (i === index ? { ...r, kind: kind as FieldRule[\"kind\"] } : r)))\n }\n >\n <SelectTrigger size=\"sm\" className=\"w-52\" aria-label={`Check ${index + 1}`}>\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {RULE_KINDS.map((row) => (\n <SelectItem key={row.kind} value={row.kind}>\n {row.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n {/* STORE-RULE-GAPS: a length has a shortest beside its longest\n (the older grid's minLength). A blank box sends nothing. */}\n {rule.kind === \"length\" ? (\n <BasicInput\n className=\"h-8 w-24\"\n inputMode=\"numeric\"\n placeholder=\"fewest\"\n value={rule.min === undefined ? \"\" : String(rule.min)}\n aria-label={`Check ${index + 1} fewest characters`}\n onChange={(e) =>\n setRules(rules.map((r, i) => (i === index ? withNumber(r, \"min\", e.target.value) : r)))\n }\n />\n ) : null}\n <BasicInput\n className=\"h-8\"\n {...(rule.kind === \"length\" ? { inputMode: \"numeric\" as const, placeholder: \"most\" } : {})}\n value={String(rule.value ?? \"\")}\n aria-label={rule.kind === \"length\" ? `Check ${index + 1} most characters` : `Check ${index + 1} value`}\n onChange={(e) => setRules(rules.map((r, i) => (i === index ? { ...r, value: e.target.value } : r)))}\n />\n {/* STORE-RULE-GAPS: how a person writes it (the older grid's\n patternHint). A refused value is told \"Enter it like …\". */}\n {rule.kind === \"pattern\" ? (\n <BasicInput\n className=\"h-8\"\n placeholder=\"for example 949-555-0142\"\n value={rule.example ?? \"\"}\n aria-label={`Check ${index + 1} example`}\n onChange={(e) =>\n setRules(rules.map((r, i) => (i === index ? withText(r, \"example\", e.target.value) : r)))\n }\n />\n ) : null}\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"ghost\"\n aria-label={`Remove check ${index + 1}`}\n onClick={() => setRules(rules.filter((_, i) => i !== index))}\n >\n ×\n </Button>\n </div>\n ))}\n </div>\n\n {/* V13 #4: a check that tightens, or a lower top star, sets aside what no longer fits — counted\n here before Save, the way a retype is (`FieldRulePreview`). */}\n {editing && field && !onEntity && rulesChanged(savedRules, editedRules) ? (\n <FieldRulePreview field={field} tableId={tableId} rules={editedRules} />\n ) : null}\n\n {mutation.error ? <RefusalNotice error={mutation.error} /> : null}\n\n {/* WHAT IS STILL MISSING, where the person is about to press. Not a\n disabled button with nothing beside it, and not a refusal from the\n store a second after the press: the sentence and the control are one\n thing, and the sentence names what to do. */}\n {/* 🚨 NOT A REFUSAL YET, SO NOT RED (lane REFUSAL-SWEEP, 2026-09-23). Nothing\n was pressed and nothing was refused: this is the reason Save is waiting,\n read BEFORE the press. Drawn as an alarm it told somebody half-way through\n naming a column that they had already failed. It is the Save button's own\n description, so a screen reader reads it on the button. */}\n {/* WALK3-FIX (2026-10-07): the sentence now sits IN the footer row, beside Save, so it never\n adds a line to the dialog (typing a name shifted the card 0.0094), and it waits for an\n attempt — a Save press or leaving the name box — so a fresh dialog opens without\n \"Give the column a name.\" before anything was typed. A formula's own check still speaks\n as it is written. */}\n {/* The store took the column and the table does not have it. Never a silent\n \"saved\" over a table that did not change — see `save`. */}\n {notLanded ? (\n <RefusalNotice\n error={refusalOf(\n \"internal\",\n onEntity\n ? \"The field was accepted but these records do not have it yet. Nothing was lost, and this panel is staying open.\"\n : COLUMN_DID_NOT_LAND_SENTENCE,\n COLUMN_DID_NOT_LAND_REMEDY,\n )}\n />\n ) : null}\n {rehomeRefused ? <RefusalNotice error={rehomeRefused} /> : null}\n {/* CHOICE-TAILS: what the save did to the records of removed choices, with its Undo. */}\n {rehomed ? (\n <div data-records-choice-rehomed=\"\" className=\"flex flex-wrap items-center gap-2 text-[11px]\">\n <span>{rehomed.said}</span>\n {rehomed.undo ? (\n <Button\n type=\"button\"\n size=\"sm\"\n variant=\"outline\"\n className=\"h-6 px-2 text-xs\"\n onClick={() => {\n const undo = rehomed.undo;\n if (!undo || !field) return;\n void client\n .fieldUpdateRehomingChoices({ field_id: field.id, patch: { options: undo.options }, cells_back: undo.cells_back })\n .then((back) => {\n if (!back.ok) {\n setRehomeRefused(back.error);\n return;\n }\n tableShapeChanged(tableId);\n for (const c of undo.cells_back) announceRecordChanged(c.record_id as Uuid);\n setChoiceList(null);\n setChoiceListStart(null);\n setRehomed({ said: \"Undone. The choices and the records that held them are back as they were.\", undo: null });\n });\n }}\n >\n Undo\n </Button>\n ) : null}\n <Button type=\"button\" size=\"sm\" className=\"h-6 px-2 text-xs\" onClick={() => onSaved?.()}>\n Done\n </Button>\n </div>\n ) : null}\n {/* NOTION-PROPS: the link is made here; the other table's column was not. */}\n {reverseRefused ? (\n <div data-records-reverse-field-refused=\"\" className=\"flex flex-col gap-1\">\n <p className=\"text-[11px]\">The link is made. Its column on the other table was not:</p>\n <RefusalNotice error={reverseRefused} />\n </div>\n ) : null}\n {/* H2: the column is made, but the records already here were not numbered. */}\n {backfillError ? (\n <div data-records-autonumber-backfill-refused=\"\" className=\"flex flex-col gap-1\">\n <p className=\"text-[11px]\">The column is made. The records already in the table were not numbered:</p>\n <RefusalNotice error={backfillError} />\n </div>\n ) : null}\n\n <div className=\"flex min-w-0 flex-nowrap items-center gap-2\" data-field-editor-footer=\"\">\n <Button\n size=\"sm\"\n // A formula the store cannot read and a name problem are said as they are written; the\n // UI holds Save until the person fixes either one.\n disabled={mutation.saving || Boolean(formulaMissing) || (Boolean(nameLine) && label.trim() !== (field?.label ?? \"\").trim())}\n {...(missingShown ? { \"aria-describedby\": \"field-editor-missing\" } : {})}\n onClick={() => {\n if (missing) {\n setAttempted(true);\n return;\n }\n void save();\n }}\n >\n {mutation.saving ? \"Saving…\" : field ? EDIT_FIELD_SAVE_LABEL : onEntity ? ADD_STANDARD_FIELD_SAVE_LABEL : ADD_FIELD_SAVE_LABEL}\n </Button>\n {onCancel ? (\n <Button size=\"sm\" variant=\"ghost\" onClick={onCancel}>\n Cancel\n </Button>\n ) : null}\n <span\n id=\"field-editor-missing\"\n data-field-editor-missing={missingShown ? \"\" : undefined}\n title={missingShown ?? undefined}\n className=\"min-w-0 flex-1 truncate text-[11px] text-muted-foreground\"\n >\n {missingShown}\n </span>\n {field ? (\n /* WALK3-FIX (2026-10-07): the confirm appears IN PLACE. Both states share one grid cell,\n the idle one drawn invisibly under the asking one and the other way round, so the\n footer is always as wide and as tall as its larger state: opening the confirm moved\n the dialog card 0.2278 and closing it 0.1303. The consequence is the tooltip of\n \"Remove it\" (interface-text: the slot holds a label, never a paragraph). */\n <div className=\"ml-auto grid shrink-0 items-center\" data-field-editor-remove={askingToRemove ? \"asking\" : \"idle\"}>\n <div className={cn(\"col-start-1 row-start-1 flex items-center justify-end gap-2\", askingToRemove && \"invisible\")} aria-hidden={askingToRemove || undefined}>\n <Button size=\"sm\" variant=\"outline\" tabIndex={askingToRemove ? -1 : undefined} onClick={() => setAskingToRemove(true)}>\n Remove this field\n </Button>\n </div>\n <div className={cn(\"col-start-1 row-start-1 flex items-center justify-end gap-2\", !askingToRemove && \"invisible\")} aria-hidden={!askingToRemove || undefined}>\n <span className=\"whitespace-nowrap text-destructive\" data-field-editor-remove-ask=\"\">\n Archive this field?\n </span>\n <Button\n size=\"sm\"\n variant=\"destructive\"\n tabIndex={askingToRemove ? undefined : -1}\n disabled={mutation.saving}\n title={removeConsequence}\n aria-description={removeConsequence}\n onClick={() => void remove()}\n >\n Remove it\n </Button>\n <Button size=\"sm\" variant=\"ghost\" tabIndex={askingToRemove ? undefined : -1} onClick={() => setAskingToRemove(false)}>\n Keep it\n </Button>\n </div>\n </div>\n ) : null}\n </div>\n </div>\n );\n}\n\n/**\n * WHAT THE PANEL STILL NEEDS BEFORE THE STORE WOULD TAKE THIS, in plain words.\n *\n * It answers exactly the questions this panel asked, so every sentence names a\n * control the person is looking at. It is NOT a second copy of the store's\n * rules and it is not allowed to become one: the store decides, and every one\n * of these is something the panel can see is unanswered without asking it.\n *\n * Exported so the suite can assert the sentences without driving the whole\n * panel, and so the red twin can assert that removing it puts the contract row\n * id back in front of a person.\n */\n/**\n * WHAT A LOOKUP OR A ROLLUP CAN READ THROUGH, by kind: a link, a person, a file — or null when the\n * column is not link-like (the store resolves `via` through every relation it can follow to a\n * record; a platform reference is `{token, id}` and is not one of them).\n */\nexport function sourceKindOf(field: Field): \"link\" | \"person\" | \"file\" | null {\n if (isBackLinkSource(field)) return \"link\";\n const kind = editorKindFor(field);\n if (kind === \"relation\") return \"link\";\n if (kind === \"member\") return \"person\";\n if (kind === \"attachment\") return \"file\";\n return null;\n}\n\nexport function whatIsMissing(state: {\n type: PickableFieldType;\n label: string;\n options: string[];\n via: string;\n pick: string;\n agg: NonNullable<NewFieldDeclaration[\"agg\"]>;\n of: string;\n relations: Field[];\n formulaFields: string[];\n /** Only a link asks for one, so a caller about any other kind leaves it out. */\n relationTarget?: string;\n /** Only an entity-reference column asks for these (SC-R). */\n allowedTypes?: readonly string[];\n /** What the thing being made is called where it is made: a table's \"column\", a record page's \"field\". */\n noun?: \"column\" | \"field\";\n}): string | null {\n const noun = state.noun ?? \"column\";\n const { type, label, via, pick, agg, of, relations, formulaFields } = state;\n const relationTarget = state.relationTarget ?? \"\";\n if (label.trim() === \"\") return `Give the ${noun} a name.`;\n\n if (type === \"entity_reference\") return whatIsMissingForEntityReference(state.allowedTypes ?? []);\n\n // A LINK WITH NOWHERE TO POINT. The store refuses it — \"relation_target names\n // the Table whose records this column may point at\" — which is a caller's\n // sentence; this is the panel's, and it names the control above it.\n if (type === \"relation\") {\n if (relationTarget.trim() === \"\") return `Choose the table this ${noun} points at.`;\n return null;\n }\n\n // A choice column may start with no choices (lane CHOICE-COLUMN-EDIT b): the store makes it an\n // empty list, and its first choice is added later, from its settings or from a cell.\n if (type === \"select\" || type === \"multi_select\") {\n return null;\n }\n\n if (type === \"lookup\" || type === \"rollup\") {\n if (relations.length === 0) {\n return type === \"rollup\"\n ? \"A total is worked out across the records a link, Person or File column holds, and this table has none yet. Add one that can hold more than one, then come back.\"\n : \"A borrowed value is read from the record a link, Person or File column holds, and this table has none yet. Add one, then come back.\";\n }\n const chosen = relations.find((relation) => relation.key === via);\n if (!chosen) {\n return type === \"rollup\"\n ? \"Choose the column whose records this one adds up.\"\n : \"Choose the column whose record this one reads from.\";\n }\n // THE ONE THE VERDICT HIT. The column a person means is usually there and\n // simply holds one thing; saying which column and what to do about it beats\n // hiding it from the list and beats \"config.via names a relation Field\".\n if (type === \"rollup\" && !chosen.multi) {\n return `${fieldName(chosen)} points at one record at a time, so there is nothing to total. Tick \"Can hold more than one\" on ${fieldName(chosen)}, or use Borrowed value to read its one value.`;\n }\n if (type === \"lookup\" && pick.trim() === \"\") {\n return `Say which value to read from the record ${fieldName(chosen)} points at.`;\n }\n if (type === \"rollup\" && agg !== \"count\" && of.trim() === \"\") {\n return \"Say which value of those records to work out.\";\n }\n return null;\n }\n\n // ── FIX-10B-F5, 2026-09-22: THE FORMULA, WHICH THIS FUNCTION USED TO WAVE THROUGH. ──\n //\n // It used to return null here, reasoning that \"the store already accepts it (it writes\n // `{op, args:[{const:\"\"}]}`)… if it should be refused, it is the store's rule to make.\"\n // VERIFIER-10 is what that costs. On Rincon Plumbing Co's \"Truck 1 dispatch backlog\" an\n // admin added \"Ticket label\" as a worked-out column and pressed Create field; the column\n // appeared in the grid and **every cell read `—`, on all 100 rows**, before a write, after\n // a write to a source column, and after a reload. The field the panel wrote, read back off\n // the live store: `\"expr\": {\"op\": \"concat\", \"args\": [{\"const\": \"\"}]}` — a formula that\n // reads NO column. `custom.rule_eval` evaluates it exactly as written, answers the empty\n // string every time, and the grid draws an empty string as `—`. The evaluator was never\n // broken: the same door over the same record, with the two field ids in the expr, answers\n // `RPC-T1-7000 — 100 Ventura Ave, Ventura`.\n //\n // AND IT IS NOT THE STORE'S RULE TO MAKE, which is why it never got made. A formula column\n // whose expression is trivial is LEGITIMATE at the store: a Rule with `target_field_id` can\n // be the thing that works it out (`scripts/campaign-tests/w1_rule_apply.sql` declares\n // exactly that pair, deliberately, and the Rules that fill them come afterwards). The store\n // cannot tell that column apart from this one. THIS SCREEN CAN, and only this screen can:\n // it is the one that asked the person which columns and was answered with none. So the\n // refusal lives where the knowledge is, the button says what is still needed, and the\n // placeholder expression is never sent. Nothing about the store's behavior moves, so there\n // is no second truth.\n if (type === \"formula\") {\n if (formulaFields.length === 0) return \"Pick the columns this one works out its answer from.\";\n return null;\n }\n\n return null;\n}\n\n/**\n * Whether \"can hold more than one\" is a question for this type at all.\n *\n * A link a person aimed themselves is exactly the column the roll-up panel\n * sends them to tick this on, so leaving it off the list here would have left\n * that remedy sentence pointing at a control that is not drawn.\n */\nfunction multiApplies(type: PickableFieldType): boolean {\n return (\n type === \"member\" || type === \"attachment\" || type === \"text\" || type === \"relation\" || type === \"entity_reference\"\n );\n}\n\nfunction unitApplies(type: PickableFieldType): boolean {\n return type === \"currency\";\n}\n\n/**\n * Which kind an existing Field already is, in the words this panel offers — `pickableTypeOf`,\n * the same reader the Settings list uses, so the panel and the list can never disagree (a\n * signature opened here and saved must stay a signature; a Record number must not reopen as a\n * formula and be saved as one).\n */\nfunction startingType(field: Field | undefined): PickableFieldType {\n if (!field) return \"text\";\n return pickableTypeOf(field) ?? \"text\";\n}\n\n/**\n * REC-15 / REC-17: a Rule expression is an object of nodes, and it points at a\n * Field BY ITS ID, never by its name — a name changes and the rule would stop\n * resolving. The panel therefore collects columns, not text.\n */\nfunction formulaExpression(op: string, fieldIds: string[], separator: string): Record<string, unknown> {\n const args = fieldIds.filter((id) => id !== \"\").map((id) => ({ field: id }));\n // F5: only a JOIN has anything between its parts. Sending `separator` on `add` would be a\n // key the evaluator ignores, which is a setting that silently does nothing.\n const joined = op === \"concat\" && separator !== \"\" ? { separator } : {};\n if (args.length === 0) return { op, ...joined, args: [{ const: \"\" }] };\n return { op, ...joined, args };\n}\n\n/** The expression a formula Field is already carrying, in the shape this panel writes. */\nfunction formulaExprOf(field: Field | undefined): Record<string, unknown> | null {\n const expr = (field?.config as Record<string, unknown> | undefined)?.[\"expr\"];\n return expr !== null && typeof expr === \"object\" ? (expr as Record<string, unknown>) : null;\n}\n\nfunction formulaOpOf(field: Field | undefined): string {\n const op = formulaExprOf(field)?.[\"op\"];\n return typeof op === \"string\" && op !== \"\" ? op : \"concat\";\n}\n\n/** REC-17: the args hold field IDS, so they map straight back onto the picked columns. */\nfunction formulaFieldIdsOf(field: Field | undefined): string[] {\n const args = formulaExprOf(field)?.[\"args\"];\n if (!Array.isArray(args)) return [];\n return args\n .map((a) => (a !== null && typeof a === \"object\" ? (a as Record<string, unknown>)[\"field\"] : undefined))\n .filter((id): id is string => typeof id === \"string\" && id !== \"\");\n}\n\n/**\n * What a person asked to go between the parts. A formula written before this control\n * existed has no `separator` key at all and keeps answering exactly as it always did —\n * so the default below applies to a NEW column and never rewrites an old one.\n */\nfunction formulaSeparatorOf(field: Field | undefined): string {\n const expr = formulaExprOf(field);\n if (expr === null) return FORMULA_DEFAULT_SEPARATOR;\n const sep = expr[\"separator\"];\n return typeof sep === \"string\" ? sep : \"\";\n}\n\nfunction TypeQuestions(props: {\n type: PickableFieldType;\n editing: boolean;\n tableId: Uuid;\n relationTarget: string;\n display: RelationDisplay | null;\n setDisplay: (next: RelationDisplay | null) => void;\n setRelationTarget: (value: string) => void;\n unit: string;\n setUnit: (value: string) => void;\n withTime: boolean;\n setWithTime: (value: boolean) => void;\n via: string;\n setVia: (value: string) => void;\n pick: string;\n setPick: (value: string) => void;\n agg: NonNullable<NewFieldDeclaration[\"agg\"]>;\n setAgg: (value: NonNullable<NewFieldDeclaration[\"agg\"]>) => void;\n of: string;\n setOf: (value: string) => void;\n formulaOp: string;\n setFormulaOp: (value: string) => void;\n formulaFields: string[];\n setFormulaFields: (value: string[]) => void;\n formulaSeparator: string;\n setFormulaSeparator: (value: string) => void;\n relations: Field[];\n others: Field[];\n /** An EXISTING choice column's per-choice list, drawn in place of the one-per-line box. */\n choiceList?: ReactNode;\n allowedTypes: string[];\n setAllowedTypes: (next: string[]) => void;\n /** LANE 10 P4: the question a rating, a status or a barcode asks. */\n newer?: ReactNode;\n}) {\n const { type } = props;\n\n if (type === \"entity_reference\") {\n // SC-R: which kinds of platform thing it points at. On an existing column the store keeps its\n // kinds and this panel sends no change, so the list is shown locked, never as a dead control.\n return <EntityReferenceKindPicker value={props.allowedTypes} onChange={props.setAllowedTypes} locked={props.editing} />;\n }\n\n if (type === \"relation\") {\n // THE ONE BUILDER. Which table, which of its columns, in which order, joined\n // by what — asked here exactly as it is asked from the grid's column\n // settings, a condition, a form and a portal, because it is one component.\n // On an EXISTING column the target is locked: `custom.field_update` is sent\n // no `relation_target` from this panel, so a picker that let a person change\n // it would be a control that silently does nothing.\n return (\n <ReferenceBuilder\n tableId={props.tableId}\n lockTarget={props.editing}\n value={{ targetTableId: props.relationTarget as Uuid | \"\", display: props.display }}\n onChange={(next) => {\n props.setRelationTarget(String(next.targetTableId));\n props.setDisplay(next.display);\n }}\n />\n );\n }\n\n // LANE 10 P4: a rating's stars and a barcode's code type; a status's choices and their groups.\n if (type === \"rating\" || type === \"barcode\") return <>{props.newer}</>;\n if (type === \"status\") {\n return (\n <div className=\"flex flex-col gap-3\">\n {props.choiceList}\n {props.newer}\n </div>\n );\n }\n\n if (type === \"select\" || type === \"multi_select\") {\n // THE ONE CHOICE EDITOR — a row per choice, each with its color, for a new column and an\n // existing one alike (`ChoiceListEditor.tsx`).\n return <>{props.choiceList}</>;\n }\n\n if (type === \"currency\") {\n return (\n <label className=\"flex max-w-[16rem] flex-col gap-1\">\n <Label className=\"text-xs\">The currency</Label>\n <BasicInput\n value={props.unit}\n aria-label=\"The currency\"\n placeholder=\"$\"\n onChange={(e) => props.setUnit(e.target.value)}\n />\n </label>\n );\n }\n\n if (type === \"datetime\") {\n return (\n <label className=\"flex items-center gap-1.5\">\n <Checkbox\n checked={props.withTime}\n aria-label=\"Include a time of day\"\n onCheckedChange={(v) => props.setWithTime(v === true)}\n />\n Include a time of day, not just the day\n </label>\n );\n }\n\n if (type === \"lookup\" || type === \"rollup\" || type === \"count\") {\n // EVERY relation column this table has — including the ones that hold ONE\n // record. A rollup needs one that holds several, and the store says so; but\n // a person looking for \"Crew lead\" and not finding it in the list learns\n // nothing, and the sentence under the button tells them exactly what to do\n // about the one they picked. Hiding the answer is not the same as giving it.\n const usable = props.relations;\n if (usable.length === 0) {\n // NEVER A DEAD CONTROL. The reason, and the thing to do about it.\n return (\n <p className=\"text-[11px] text-muted-foreground\">\n No link, Person or File column yet.\n </p>\n );\n }\n return (\n <div className=\"grid gap-3 sm:grid-cols-2\">\n <div className=\"flex flex-col gap-1\">\n <Label className=\"text-xs\">{type !== \"lookup\" ? \"Across the records in\" : \"Read it from\"}</Label>\n <Select value={props.via} onValueChange={props.setVia}>\n <SelectTrigger size=\"sm\" aria-label={type !== \"lookup\" ? \"Across the records in\" : \"Read it from\"}>\n <SelectValue placeholder=\"Choose a column\" />\n </SelectTrigger>\n <SelectContent>\n {usable.map((f) => (\n <SelectItem key={f.id} value={f.key}>\n {fieldName(f)}\n {isBackLinkSource(f) ? BACK_LINK_SOURCE_SUFFIX : \"\"}\n {sourceKindOf(f) === \"person\" ? \" — a person\" : sourceKindOf(f) === \"file\" ? \" — a file\" : \"\"}\n {type !== \"lookup\" && !f.multi ? \" — holds one\" : \"\"}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n {type === \"lookup\" ? (\n <ValueOnTheOtherSide\n label=\"The value to read\"\n help=\"The column on the other record whose value is borrowed.\"\n relation={usable.find((f) => f.key === props.via)}\n value={props.pick}\n onChange={props.setPick}\n />\n ) : type === \"count\" ? null : (\n <div className=\"flex flex-col gap-1\">\n <Label className=\"text-xs\">What to work out</Label>\n <Select value={props.agg} onValueChange={(v) => props.setAgg(v as never)}>\n <SelectTrigger size=\"sm\" aria-label=\"What to work out\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {ROLLUP_OPERATIONS.map((row) => (\n <SelectItem key={row.value} value={row.value}>\n {row.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n {props.agg !== \"count\" ? (\n <ValueOnTheOtherSide\n label=\"Of which value\"\n help=\"The column on those records whose values are worked out.\"\n relation={usable.find((f) => f.key === props.via)}\n value={props.of}\n onChange={props.setOf}\n compact\n />\n ) : null}\n </div>\n )}\n </div>\n );\n }\n\n if (type === \"formula\") {\n if (props.others.length === 0) {\n return (\n <p className=\"text-[11px] text-muted-foreground\">\n No other columns yet.\n </p>\n );\n }\n return (\n <div className=\"flex flex-col gap-2\">\n <div className=\"flex flex-col gap-1\">\n <Label className=\"text-xs\">What to do</Label>\n <Select value={props.formulaOp} onValueChange={props.setFormulaOp}>\n <SelectTrigger size=\"sm\" className=\"max-w-[18rem]\" aria-label=\"What to do\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {FORMULA_OPERATIONS.map((row) => (\n <SelectItem key={row.value} value={row.value}>\n {row.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n <div className=\"flex flex-col gap-1\">\n <Label className=\"text-xs\">Which columns</Label>\n <div className=\"flex flex-wrap gap-1\">\n {props.others.map((f) => {\n const picked = props.formulaFields.includes(f.id);\n return (\n <Button\n key={f.id}\n type=\"button\"\n size=\"sm\"\n variant={picked ? \"default\" : \"outline\"}\n onClick={() =>\n props.setFormulaFields(\n picked\n ? props.formulaFields.filter((id) => id !== f.id)\n : [...props.formulaFields, f.id],\n )\n }\n >\n {fieldName(f)}\n </Button>\n );\n })}\n </div>\n </div>\n {/* F5 (VERIFIER-11): only a join has anything between its parts, so only a join asks. */}\n {props.formulaOp === \"concat\" ? (\n <div className=\"flex flex-col gap-1\">\n <Label className=\"text-xs\">{FORMULA_SEPARATOR_LABEL}</Label>\n <BasicInput\n value={props.formulaSeparator}\n aria-label={FORMULA_SEPARATOR_LABEL}\n placeholder=\"—\"\n className=\"max-w-[10rem]\"\n onChange={(e) => props.setFormulaSeparator(e.target.value)}\n />\n </div>\n ) : null}\n </div>\n );\n }\n\n return null;\n}\n\n/** What a back-link reads as in the source list: the linking table's records, pointing here. */\nexport const BACK_LINK_SOURCE_SUFFIX = \" — links here\";\nconst BACK_LINK = Symbol.for(\"@ai-matrx/records-ui/back-link\");\n\n/**\n * A REVERSE COLUMN AS A TOTAL'S SOURCE (CHAIR-UI-STORE item 2). Virtual (REL-9: never a Field), so it\n * is drawn in the source list as the relation it mirrors from this end — many records of the linking\n * table — keyed exactly as `custom.reverse_columns` keys it, which is the `via` the store reads.\n */\nexport function backLinkAsSource(column: ReverseColumn): Field {\n return {\n id: `linked:${column.key}`,\n key: column.key,\n label: column.label,\n type: \"relation\",\n multi: true,\n relation_target: column.source_table_id,\n config: {},\n [BACK_LINK]: column,\n } as unknown as Field;\n}\n\nexport function isBackLinkSource(field: Field): boolean {\n return (field as unknown as Record<symbol, unknown>)[BACK_LINK] !== undefined;\n}\n\n/** The totals and lookups on the far table that read through this link column's back-link. */\nexport function readingThroughLink(link: Field, farFields: readonly Field[]): Field[] {\n const key = link.inverse_key ?? `linked_${link.id}`;\n return farFields.filter((f) => {\n const kind = editorKindFor(f);\n return (kind === \"rollup\" || kind === \"lookup\") && (f.config as Record<string, unknown> | undefined)?.[\"via\"] === key;\n });\n}\n\n/** The lead of a total's filter row, in the words of what it works out. */\nexport function rollupFilterLead(agg: string): string {\n return agg === \"count\" ? \"Only count records where\" : \"Only use records where\";\n}\n\n/**\n * \"ONLY COUNT RECORDS WHERE…\" (CHAIR-UI-STORE item 1). A total's `config.filter`, built in THE one\n * condition builder the grid's saved views use (`ConditionGroup`, `ViewFilter.tsx`), over the columns\n * of the table its source points at. It writes the store's Rule shape by far-side field id, which\n * `custom.field_declare` / `custom.field_update` validate and `custom.rollup_value` compiles with\n * `custom.record_filter_sql` — the same grammar, never a second one. A filter written elsewhere in a\n * shape the builder cannot draw is read out and can be cleared, never silently overwritten.\n */\nfunction RollupFilterQuestion({\n relation,\n agg,\n editing,\n value,\n onChange,\n}: {\n relation: Field | undefined;\n agg: string;\n editing: boolean;\n value: RuleExpression | null;\n onChange: (next: RuleExpression | null) => void;\n}) {\n const far = (relation?.relation_target ?? null) as Uuid | null;\n const farFields = useFields(far);\n const conditionFields = useMemo<ConditionField[]>(\n () =>\n (farFields.data ?? [])\n .filter((f) => f.type !== \"formula\")\n .map((f) => ({ id: f.id, key: f.key, label: fieldName(f), field: f })),\n [farFields.data],\n );\n // A new total's source changed: the old conditions name another table's columns.\n const lastFar = useRef(far);\n useEffect(() => {\n if (lastFar.current !== null && far !== lastFar.current && !editing) onChange(null);\n lastFar.current = far;\n }, [far, editing, onChange]);\n if (!relation || !far) return null;\n return (\n <div className=\"flex flex-col gap-1\" data-records-rollup-filter=\"\">\n {!conditionIsDrawable(value) ? (\n <div className=\"flex flex-wrap items-center gap-2 text-[11px]\">\n <span className=\"text-muted-foreground\">\n {rollupFilterLead(agg)} {conditionInWords(value, conditionFields)}.\n </span>\n <Button type=\"button\" size=\"sm\" variant=\"ghost\" className=\"h-6 px-2 text-xs\" onClick={() => onChange(null)}>\n Clear\n </Button>\n </div>\n ) : (\n <ChoiceListTermsContext.Provider value>\n <ConditionGroup\n lead={rollupFilterLead(agg)}\n emptyLabel={`every record in ${fieldName(relation)}`}\n expr={value}\n fields={conditionFields}\n onChange={onChange}\n />\n </ChoiceListTermsContext.Provider>\n )}\n </div>\n );\n}\n\n/**\n * WHICH VALUE, ON THE OTHER SIDE — offered by NAME, never typed as a key.\n *\n * A borrowed value and a total both read one column of the records the chosen\n * relation points at, and this panel used to ask for that column as free text\n * with the placeholder `name`. So the one question on the panel that a person\n * could not answer without knowing an internal key was the last question on the\n * two column types the sixth-pass verdict could not create — and a typo in it\n * is a column that silently borrows nothing.\n *\n * The relation says which Table it points at, so the columns of that Table are\n * simply offered. When it points at nothing yet, this says so and offers\n * nothing, which is the honest half of the same rule.\n *\n * AND A TABLE THE STORE KEEPS ITSELF STILL HAS COLUMNS. `custom.applicable_fields`\n * answers the Fields a table DECLARES, and the kernels declare none: a Person\n * column points at the person kernel, which has 441 records and zero Field rows.\n * So the picker offered nothing for every Person and every File relation — and\n * the only two column types a person cannot build without it are exactly the\n * two the sixth-pass verdict could not build. Measured 2026-09-20.\n *\n * The store reads the far side with `custom.record_values(…) -> pick`\n * (`custom.lookup_value`), so what a pick may name is a KEY THOSE RECORDS\n * CARRY. When the target declares no Fields, this reads one of its records\n * through the ordinary read door and offers the keys it actually has — the same\n * fact the store will use, asked the same way. Nothing is typed, and nothing is\n * guessed.\n */\nfunction ValueOnTheOtherSide({\n label,\n help,\n relation,\n value,\n onChange,\n compact,\n}: {\n label: string;\n help: string;\n relation: Field | undefined;\n value: string;\n onChange: (value: string) => void;\n compact?: boolean | undefined;\n}) {\n const target = (relation?.relation_target ?? null) as Uuid | null;\n const columns = useFields(target);\n const declared = (columns.data ?? []).filter((f) => f.type !== \"formula\");\n // Only asked when the target declares nothing — the ordinary case costs no\n // extra call, and this one is a single row.\n const sample = useRecords(declared.length === 0 && !columns.loading ? target : null, { pageSize: 1 });\n const carried = sample.data?.rows[0]?.document ?? null;\n const offered: { key: string; name: string }[] =\n declared.length > 0\n ? declared.map((f) => ({ key: f.key, name: fieldName(f) }))\n : Object.keys(carried ?? {}).map((key) => ({ key, name: humanizeIdentifier(key) }));\n const stillAsking = columns.loading || (declared.length === 0 && sample.loading);\n\n const body = !relation ? (\n <p className=\"text-[11px] text-muted-foreground\">Choose the column above first.</p>\n ) : stillAsking ? (\n <p className=\"text-[11px] text-muted-foreground\">Reading that table's columns…</p>\n ) : offered.length === 0 ? (\n <p className=\"text-[11px] text-muted-foreground\">\n No columns to read yet.\n </p>\n ) : (\n <Select value={value} onValueChange={onChange}>\n <SelectTrigger size=\"sm\" aria-label={label}>\n <SelectValue placeholder=\"Choose a column\" />\n </SelectTrigger>\n <SelectContent>\n {offered.map((column) => (\n <SelectItem key={column.key} value={column.key}>\n {column.name}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n );\n\n if (compact) return <div className=\"mt-1 flex flex-col gap-1\">{body}</div>;\n return (\n <div className=\"flex flex-col gap-1\">\n <Label className=\"text-xs\" title={help}>{label}</Label>\n {body}\n </div>\n );\n}\n\n/** A rule with one number set, or taken off when the box is blank (STORE-RULE-GAPS). */\nfunction withNumber(rule: FieldRule, key: \"min\", typed: string): FieldRule {\n const { [key]: _gone, ...rest } = rule;\n const trimmed = typed.trim();\n if (trimmed === \"\") return rest;\n const n = Number(trimmed);\n return Number.isFinite(n) ? { ...rest, [key]: n } : { ...rest, [key]: trimmed as unknown as number };\n}\n\n/** A rule with one word set, or taken off when the box is blank (STORE-RULE-GAPS). */\nfunction withText(rule: FieldRule, key: \"example\", typed: string): FieldRule {\n const { [key]: _gone, ...rest } = rule;\n return typed.trim() === \"\" ? rest : { ...rest, [key]: typed };\n}\n\n/** The kinds an existing entity-reference column already points at (`config.allowed_types`). */\nfunction entityReferenceKindsOf(field: Field | null | undefined): string[] {\n const raw = (field?.config ?? {})[\"allowed_types\"];\n return Array.isArray(raw) ? raw.filter((t): t is string => typeof t === \"string\") : [];\n}\n\n/**\n * A NEW COLUMN'S DEFAULT, BEFORE THE COLUMN EXISTS. There is no Field yet to draw the column's own\n * editor from, so: a tick for a yes / no, one of the typed choices for a choice column, and typed\n * words for everything else, which the store converts to the column's kind or refuses by name.\n */\nexport function NewColumnDefault({\n type,\n choices,\n value,\n onChange,\n}: {\n type: string;\n choices: readonly string[];\n value: unknown;\n onChange: (next: unknown) => void;\n}) {\n const none = \"__none__\";\n return (\n <div className=\"flex flex-col gap-1\" data-records-field-default=\"\" data-records-new-field-default=\"\">\n <Label htmlFor=\"records-new-field-default\" className=\"text-xs\">\n {DEFAULT_LABEL}\n </Label>\n {type === \"checkbox\" ? (\n <label className=\"flex items-center gap-2\">\n <Checkbox id=\"records-new-field-default\" aria-label={DEFAULT_LABEL} checked={value === true} onCheckedChange={(on) => onChange(on === true ? true : null)} />\n <span>Ticked</span>\n </label>\n ) : type === \"select\" || type === \"multi_select\" || type === \"status\" ? (\n <Select value={typeof value === \"string\" && choices.includes(value) ? value : none} onValueChange={(v) => onChange(v === none ? null : v)}>\n <SelectTrigger id=\"records-new-field-default\" size=\"sm\" aria-label={DEFAULT_LABEL}>\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value={none}>Nothing</SelectItem>\n {choices.map((c) => (\n <SelectItem key={c} value={c}>\n {c}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n ) : (\n <BasicInput\n id=\"records-new-field-default\"\n value={typeof value === \"string\" ? value : value === null || value === undefined ? \"\" : String(value)}\n placeholder=\"Nothing\"\n onChange={(e) => onChange(e.target.value)}\n />\n )}\n </div>\n );\n}\n","// src/WatchFieldsPicker.tsx — @ai-matrx/records-ui\n//\n// W2-A 4 (AIRTABLE-PARITY row 89): A LAST CHANGED TIME COLUMN WATCHES ONLY THE FIELDS CHOSEN HERE.\n// Airtable's \"When specific fields change\". The store keeps the list on the Field (`config.only_fields`,\n// field keys) and `custom.field_update` takes it as `only_fields`; nothing chosen = the whole record.\n\nimport { Checkbox, Label } from \"@ai-matrx/design-system\";\nimport type { Field } from \"@ai-matrx/records\";\n\n/** The keys an existing column watches; an empty list when it follows the whole record. */\nexport function watchedFieldsOf(field: Pick<Field, \"config\"> | undefined): string[] {\n const list = field?.config?.[\"only_fields\"];\n return Array.isArray(list) ? list.filter((k): k is string => typeof k === \"string\") : [];\n}\n\n/** The `only_fields` patch for a save, or nothing when the choice did not change. `null` = the whole record again. */\nexport function watchedFieldsPatch(before: string[], now: string[]): { only_fields: string[] | null } | Record<string, never> {\n const same = before.length === now.length && before.every((k) => now.includes(k));\n if (same) return {};\n return { only_fields: now.length ? now : null };\n}\n\n/** Columns a stamp may watch: the table's own typed columns, never another stamp or worked-out column. */\nfunction watchable(field: Field): boolean {\n const system = field.config?.[\"system\"];\n return typeof system !== \"string\" && field.type !== \"formula\";\n}\n\nexport function WatchFieldsPicker({ fields, value, onChange }: { fields: Field[]; value: string[]; onChange: (next: string[]) => void }) {\n const choices = fields.filter(watchable);\n return (\n <fieldset className=\"flex flex-col gap-1\" data-records-watch-fields=\"\">\n <Label className=\"text-xs\">Changes to</Label>\n <div className=\"flex flex-wrap gap-x-3 gap-y-1\">\n <label className=\"flex items-center gap-1.5 text-sm\">\n <Checkbox checked={value.length === 0} aria-label=\"Any field\" onCheckedChange={(v) => v === true && onChange([])} />\n <span>Any field</span>\n </label>\n {choices.map((f) => (\n <label key={f.id} className=\"flex items-center gap-1.5 text-sm\">\n <Checkbox\n checked={value.includes(f.key)}\n aria-label={f.label}\n data-records-watch-field={f.key}\n onCheckedChange={(v) => onChange(v === true ? [...value.filter((k) => k !== f.key), f.key] : value.filter((k) => k !== f.key))}\n />\n <span>{f.label}</span>\n </label>\n ))}\n </div>\n </fieldset>\n );\n}\n","\"use client\";\n\n// src/FormulaTextEditor.tsx — @ai-matrx/records-ui · lane DEFAULT-GRID-PARITY (TABLE-PARITY K2)\n//\n// A FORMULA, WRITTEN THE WAY A PERSON WRITES ONE, AND CHECKED BY THE STORE AS THEY TYPE.\n//\n// The field panel could only build a worked-out column from a fixed list of operations over\n// picked columns. The store has spoken the older grid's whole formula language since\n// GRID-PRIMITIVES G3 (`custom.formula_parse`, 530 of 530 answers equal to the older\n// evaluator) — `{Visit fee} - {Deposit taken}`, `IF({Status} = \"No-show\", 0, {Fee})` — and\n// nothing on this panel could say it.\n//\n// THE STORE IS THE CHECKER. Every pause in typing asks `formula_parse`, which answers either\n// the columns it reads and the kind of answer it gives, or the mistake and where it is. This\n// screen never parses a formula itself: a second parser here would be a second answer to\n// \"is this formula right\", and the two would drift within a month. Airtable's formula field is\n// the reference — the reference check and the function list are right under the box.\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport { useRecordsClient, type Field, type Uuid } from \"@ai-matrx/records/react\";\nimport { RULE_NODE_KINDS, type FormulaPreview } from \"@ai-matrx/records\";\nimport { BasicTextarea, Button, Label, cn } from \"@ai-matrx/design-system\";\n\nimport type { RecordsError } from \"@ai-matrx/records\";\n\nimport { useRecordsUi } from \"./host\";\nimport { RefusalLine } from \"./Refusal\";\nimport { refusalSentence } from \"./plainWords\";\nimport { fieldName } from \"./names\";\n\n/**\n * The `fx.*` nodes a person never types by name — the same list `custom._fxp_level` refuses as a\n * function name: the operators (`fx.ne` is `!=`; `fx.mod` is `%` AND typed as MOD, as in Airtable) and the autonumber\n * system kind (an autonumber column is a column kind, not a function). CREATED_TIME(), MODIFIED_TIME() and\n * LAST_MODIFIED_TIME() are typed by name, as in Airtable.\n */\nconst NOT_TYPED_BY_NAME = new Set([\n \"fx.add\", \"fx.sub\", \"fx.mul\", \"fx.div\", \"fx.neg\",\n \"fx.eq\", \"fx.ne\", \"fx.lt\", \"fx.lte\", \"fx.gt\", \"fx.gte\",\n \"fx.autonumber\",\n]);\n\n/** The functions a vocabulary offers, as a person types them (`fx.regex_match` → REGEX_MATCH). */\nexport function formulaFunctionNames(kinds: readonly { node: string }[]): string[] {\n return [...new Set(kinds.map((row) => row.node))]\n .filter((node) => node.startsWith(\"fx.\") && !NOT_TYPED_BY_NAME.has(node))\n .map((node) => node.slice(3).toUpperCase())\n .sort();\n}\n\n/** The help list follows the store vocabulary used to validate typed formulas. */\nexport const STORE_FORMULA_FUNCTION_NAMES: string[] = formulaFunctionNames(RULE_NODE_KINDS);\n\nconst RESULT_WORD: Record<string, string> = {\n number: \"a number\",\n text: \"text\",\n boolean: \"a yes or no\",\n date: \"a date\",\n unknown: \"an answer whose kind depends on the row\",\n};\n\n/** The sampled answer as one line: the value, \"empty\", or why it could not be worked out. */\nexport function sampleWords(preview: FormulaPreview): string {\n if (preview.ok && preview.error) return preview.error;\n const v = preview.value;\n if (v === null || v === undefined || v === \"\") return \"empty\";\n if (typeof v === \"boolean\") return v ? \"Yes\" : \"No\";\n if (typeof v === \"number\" || typeof v === \"string\") return String(v);\n return JSON.stringify(v);\n}\n\nexport function FormulaTextEditor({\n tableId,\n text,\n onText,\n onChecked,\n columns,\n sampleRecordId,\n purpose,\n className,\n}: {\n tableId: Uuid;\n text: string;\n onText: (next: string) => void;\n /** The store's verdict on the text as it stands: true, false, or null while it is asked. */\n onChecked: (ok: boolean | null) => void;\n /** The other columns of this table, offered to insert by name. */\n columns: readonly Field[];\n /**\n * NOTION-PROPS — THE LIVE SAMPLE: the record whose answer is shown as the formula is typed. Left\n * out, the table's first row is sampled; `null` samples nothing.\n */\n sampleRecordId?: Uuid | null | undefined;\n /** What the formula is for, handed to the host's help (`FormulaHelpAsk.purpose`). */\n purpose?: string | undefined;\n className?: string | undefined;\n}) {\n const client = useRecordsClient();\n const host = useRecordsUi();\n const [parsed, setParsed] = useState<FormulaPreview | null>(null);\n // The row sampled when the host names none: the table's first, read once.\n const [firstRow, setFirstRow] = useState<Uuid | null>(null);\n useEffect(() => {\n if (sampleRecordId !== undefined) return;\n let live = true;\n void client.list({ table_id: tableId, limit: 1 }).then((read) => {\n if (live && read.ok) setFirstRow((read.data.rows[0]?.id as Uuid | undefined) ?? null);\n });\n return () => {\n live = false;\n };\n }, [client, tableId, sampleRecordId]);\n const sampled = sampleRecordId !== undefined ? sampleRecordId : firstRow;\n const [error, setError] = useState<RecordsError | null>(null);\n const box = useRef<HTMLTextAreaElement | null>(null);\n // The parent's setter, held so the question (the text, the table) alone drives the ask.\n const report = useRef(onChecked);\n report.current = onChecked;\n\n useEffect(() => {\n const asked = text.trim();\n if (asked === \"\") {\n setParsed(null);\n setError(null);\n report.current(null);\n return;\n }\n report.current(null);\n let cancelled = false;\n const timer = setTimeout(() => {\n // One call parses AND works the answer out on the sampled row. The sample is extra: when that\n // door cannot answer (absent, or the row is not this reader's), the parse is asked on its own.\n void client\n .formulaPreview({ table_id: tableId, record_id: sampled, text: asked })\n .then((previewed) => (previewed.ok ? previewed : client.formulaParse({ table_id: tableId, text: asked })))\n .then((answered) => {\n if (cancelled) return;\n if (!answered.ok) {\n setError(answered.error);\n setParsed(null);\n report.current(false);\n return;\n }\n setError(null);\n setParsed(answered.data);\n report.current(answered.data.ok);\n });\n }, 300);\n return () => {\n cancelled = true;\n clearTimeout(timer);\n };\n }, [client, tableId, text, sampled]);\n\n const insert = (piece: string) => {\n const el = box.current;\n const at = el?.selectionStart ?? text.length;\n const to = el?.selectionEnd ?? at;\n onText(`${text.slice(0, at)}${piece}${text.slice(to)}`);\n requestAnimationFrame(() => {\n el?.focus();\n const caret = at + piece.length - (piece.endsWith(\"()\") ? 1 : 0);\n el?.setSelectionRange(caret, caret);\n });\n };\n\n const where = useMemo(() => {\n if (!parsed || parsed.ok) return null;\n const at = Math.max(0, Math.min(parsed.position ?? 0, parsed.text.length));\n return { before: parsed.text.slice(0, at), after: parsed.text.slice(at) };\n }, [parsed]);\n\n return (\n <div data-records-formula-editor=\"\" className={cn(\"flex flex-col gap-1.5\", className)}>\n <div className=\"flex items-center gap-1\">\n <Label className=\"text-xs\">The formula</Label>\n {host.formulaHelp ? (\n <span data-records-formula-help=\"\" className=\"ml-auto\">\n {host.formulaHelp({\n tableId,\n text,\n columns,\n mistake: parsed && !parsed.ok ? parsed.error : error ? refusalSentence(error) : null,\n functions: STORE_FORMULA_FUNCTION_NAMES,\n onFormula: onText,\n ...(purpose ? { purpose } : {}),\n })}\n </span>\n ) : null}\n </div>\n <BasicTextarea\n ref={box}\n value={text}\n rows={2}\n aria-label=\"The formula\"\n placeholder={columns.length > 0 ? `{${fieldName(columns[0]!)}}` : \"Write a formula\"}\n className=\"font-mono text-xs\"\n onChange={(e) => onText(e.target.value)}\n />\n {parsed?.ok ? (\n <p data-records-formula-ok=\"\" className=\"text-[11px] text-muted-foreground\">\n Reads {parsed.references.length === 0 ? \"no column\" : parsed.references.map((r) => r.name).join(\", \")} ·\n gives {RESULT_WORD[parsed.result_type] ?? \"an answer\"}.\n </p>\n ) : null}\n {parsed?.ok && parsed.record_id ? (\n <p data-records-formula-sample=\"\" className=\"truncate text-[11px]\" title={sampleWords(parsed)}>\n <span className=\"text-muted-foreground\">{sampleRecordId ? \"This record\" : \"First row\"}: </span>\n <span className={cn(\"font-mono\", parsed.error ? \"text-muted-foreground\" : \"text-foreground\")}>{sampleWords(parsed)}</span>\n </p>\n ) : null}\n {parsed && !parsed.ok ? (\n // NOT A REFUSAL, SO NOT RED: nothing was pressed. It is the store's reading of the\n // text as it stands, drawn the way the panel draws what Save is still waiting for.\n <div data-records-formula-mistake=\"\" role=\"status\" className=\"text-[11px] text-foreground\">\n <p>{parsed.error}</p>\n {where ? (\n <p className=\"mt-0.5 font-mono text-foreground\">\n {where.before}\n <span className=\"bg-amber-500/30 px-0.5\">▏</span>\n {where.after}\n </p>\n ) : null}\n </div>\n ) : null}\n {error ? <RefusalLine error={error} /> : null}\n <div className=\"flex flex-wrap items-center gap-1\">\n <span className=\"text-[11px] text-muted-foreground\">Columns:</span>\n {columns.map((f) => (\n <Button key={f.id} type=\"button\" size=\"sm\" variant=\"outline\" className=\"h-6 px-1.5 text-[11px]\" onClick={() => insert(`{${fieldName(f)}}`)}>\n {fieldName(f)}\n </Button>\n ))}\n </div>\n {STORE_FORMULA_FUNCTION_NAMES.length > 0 ? (\n <details className=\"text-[11px] text-muted-foreground\">\n <summary className=\"cursor-pointer\">Functions you can use ({STORE_FORMULA_FUNCTION_NAMES.length})</summary>\n <div className=\"mt-1 flex flex-wrap gap-1\">\n {STORE_FORMULA_FUNCTION_NAMES.map((name) => (\n <Button key={name} type=\"button\" size=\"sm\" variant=\"ghost\" className=\"h-6 px-1.5 font-mono text-[11px]\" onClick={() => insert(`${name}()`)}>\n {name}\n </Button>\n ))}\n </div>\n </details>\n ) : null}\n </div>\n );\n}\n","\"use client\";\n\n// src/EntityReferenceKindPicker.tsx — @ai-matrx/records-ui · lane SC-R (P12)\n//\n// WHAT A COLUMN THAT POINTS AT A PLATFORM THING MAY POINT AT.\n//\n// An `entity_reference` column holds `{token, id}` values naming a note, a web site, an agent, a\n// workbook, a conversation — anything in `platform.entity_types` that is not a record-store Table\n// (a File and a Person stay `attachment` / `member`). The store keeps the allowed kinds in\n// `config.allowed_types` and refuses a value of any other kind by name. This is the question the\n// field editor asks for it: WHICH kinds. The list is the store's own\n// (`custom.entity_reference_kinds`, through `useEntityReferenceKinds`), grouped by its category,\n// searchable because there are over a hundred, and the chosen kinds sit above it as removable\n// chips so a person always sees what the column will take.\n//\n// No new primitive: `BasicInput`, `Checkbox`, `Badge` and `Button` from the design system, and the\n// package's own `RefusalNotice` when the kinds cannot be read — a list that silently came back\n// empty would be a screen that lies about what the store takes.\n\nimport { useMemo, useState } from \"react\";\nimport type { EntityReferenceKind } from \"@ai-matrx/records\";\nimport { useEntityReferenceKinds } from \"@ai-matrx/records/react\";\nimport { Badge, BasicInput, Checkbox, Label, Skeleton, cn } from \"@ai-matrx/design-system\";\nimport { RefusalNotice } from \"./Refusal\";\n\n/** What the panel says while the chosen list is empty. */\nexport const ENTITY_REFERENCE_KINDS_MISSING = \"Choose at least one kind of thing this column points at.\";\n\n/**\n * The declaration an entity-reference column is sent as — the words `custom.field_declare`\n * reads (`type: \"entity_reference\"`, `allowed_types`, `multi`). One place builds it, so the field\n * editor, a table template and an agent never disagree on the shape.\n */\nexport function entityReferenceSpec(input: {\n label: string;\n allowedTypes: readonly string[];\n multi?: boolean;\n required?: boolean;\n}): { label: string; type: \"entity_reference\"; allowed_types: string[]; multi: boolean; required: boolean } {\n const seen = new Set<string>();\n const allowed: string[] = [];\n for (const raw of input.allowedTypes) {\n const token = raw.trim().toLowerCase();\n if (!token || seen.has(token)) continue;\n seen.add(token);\n allowed.push(token);\n }\n return {\n label: input.label,\n type: \"entity_reference\",\n allowed_types: allowed,\n multi: input.multi ?? false,\n required: input.required ?? false,\n };\n}\n\n/** The sentence the panel shows before it lets a person save, or `null` when nothing is missing. */\nexport function whatIsMissingForEntityReference(allowedTypes: readonly string[]): string | null {\n return allowedTypes.some((t) => t.trim() !== \"\") ? null : ENTITY_REFERENCE_KINDS_MISSING;\n}\n\nexport interface EntityReferenceKindPickerProps {\n /** The chosen entity tokens (`config.allowed_types`). */\n value: readonly string[];\n onChange: (next: string[]) => void;\n /**\n * An existing column: the store keeps its kinds and this panel sends no change to them,\n * so the list is shown read-only rather than as a control that silently does nothing.\n */\n locked?: boolean;\n className?: string;\n}\n\nfunction matches(kind: EntityReferenceKind, q: string): boolean {\n if (q === \"\") return true;\n return (\n kind.label.toLowerCase().includes(q) ||\n kind.token.toLowerCase().includes(q) ||\n kind.category.toLowerCase().includes(q)\n );\n}\n\nexport function EntityReferenceKindPicker({ value, onChange, locked = false, className }: EntityReferenceKindPickerProps) {\n const { data, loading, error } = useEntityReferenceKinds();\n const [query, setQuery] = useState(\"\");\n const chosen = useMemo(() => new Set(value), [value]);\n const labelOf = useMemo(() => {\n const m = new Map<string, string>();\n for (const k of data ?? []) m.set(k.token, k.label);\n return m;\n }, [data]);\n\n const groups = useMemo(() => {\n const q = query.trim().toLowerCase();\n const byCategory = new Map<string, EntityReferenceKind[]>();\n for (const k of data ?? []) {\n if (!matches(k, q)) continue;\n const list = byCategory.get(k.category) ?? [];\n list.push(k);\n byCategory.set(k.category, list);\n }\n return [...byCategory.entries()].sort(([a], [b]) => a.localeCompare(b));\n }, [data, query]);\n\n const toggle = (token: string, on: boolean) => {\n if (locked) return;\n if (on) onChange(chosen.has(token) ? [...value] : [...value, token]);\n else onChange(value.filter((t) => t !== token));\n };\n\n return (\n <div className={cn(\"flex flex-col gap-2\", className)}>\n <Label className=\"text-xs\">What it points at</Label>\n {value.length > 0 ? (\n <div className=\"flex flex-wrap gap-1\" aria-label=\"Chosen kinds\">\n {value.map((token) => (\n <Badge key={token} variant=\"secondary\" className=\"gap-1 text-[11px]\">\n {labelOf.get(token) ?? token}\n {locked ? null : (\n <button\n type=\"button\"\n className=\"ml-0.5 rounded-sm px-0.5 opacity-70 hover:opacity-100\"\n aria-label={`Remove ${labelOf.get(token) ?? token}`}\n onClick={() => toggle(token, false)}\n >\n ×\n </button>\n )}\n </Badge>\n ))}\n </div>\n ) : null}\n {locked ? (\n <p className=\"text-[11px] text-muted-foreground\">\n The kinds an existing column points at are kept as they are; add a new column to point at others.\n </p>\n ) : error ? (\n <RefusalNotice error={error} />\n ) : loading ? (\n <Skeleton className=\"h-24 w-full\" />\n ) : (\n <>\n <BasicInput\n aria-label=\"Find a kind of thing\"\n placeholder=\"Find a kind — note, web site, agent…\"\n className=\"text-xs\"\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n />\n <div className=\"max-h-56 overflow-y-auto rounded-md border border-border p-2\" role=\"group\" aria-label=\"Kinds of thing\">\n {groups.length === 0 ? (\n <p className=\"text-[11px] text-muted-foreground\">No kind of thing matches “{query.trim()}”.</p>\n ) : (\n groups.map(([category, kinds]) => (\n <div key={category} className=\"mb-2 last:mb-0\">\n <p className=\"mb-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground\">{category}</p>\n <div className=\"grid grid-cols-1 gap-1 sm:grid-cols-2\">\n {kinds.map((k) => (\n <label key={k.token} className=\"flex items-center gap-1.5 text-xs\">\n <Checkbox\n checked={chosen.has(k.token)}\n aria-label={k.label}\n onCheckedChange={(v) => toggle(k.token, v === true)}\n />\n {k.label}\n </label>\n ))}\n </div>\n </div>\n ))\n )}\n </div>\n {value.length === 0 ? (\n <p className=\"text-[11px] text-muted-foreground\">{ENTITY_REFERENCE_KINDS_MISSING}</p>\n ) : null}\n </>\n )}\n </div>\n );\n}\n","\"use client\";\n\n// SourceArchivedNotice.tsx — @ai-matrx/records-ui\n//\n// CHAIR-ROLLUP-HONEST (Law 4). Column settings for a lookup or roll-up asks the store whether a\n// column it reads is archived (`custom.field_source_archived`): the link it reads through, the\n// linking column of a back-link on another table, or the far column it totals. When one is, the\n// panel names it and offers ONE click to bring it back through the existing door\n// (`custom.field_restore`), after which every screen on both tables re-reads and the values return.\n// Nothing is drawn while every source is live.\n\nimport { useCallback, useEffect, useState } from \"react\";\nimport { Button } from \"@ai-matrx/design-system\";\nimport type { RecordsError, SourceArchived, Uuid } from \"@ai-matrx/records\";\nimport { tableShapeChanged, useRecordsClient } from \"@ai-matrx/records/react\";\nimport { RefusalNotice } from \"./Refusal\";\nimport { SOURCE_ARCHIVED_WORDS, sourceArchivedSentence } from \"./values\";\n\n/** The restore button's words: \"Bring back Patient\". */\nexport function bringBackLabel(state: SourceArchived): string {\n return state.label ? `Bring back ${state.label}` : \"Bring it back\";\n}\n\nexport function SourceArchivedNotice({ fieldId, tableId }: { fieldId: Uuid; tableId: Uuid }) {\n const client = useRecordsClient();\n const [state, setState] = useState<SourceArchived | null>(null);\n const [busy, setBusy] = useState(false);\n const [refused, setRefused] = useState<RecordsError | null>(null);\n\n const read = useCallback(async () => {\n const answer = await client.fieldSourceArchived({ field_id: fieldId });\n if (answer.ok) setState(answer.data);\n else setRefused(answer.error);\n }, [client, fieldId]);\n\n useEffect(() => {\n void read();\n }, [read]);\n\n if (refused && !state) return <RefusalNotice error={refused} />;\n if (!state) return null;\n\n const restore = async () => {\n if (!state.field_id) return;\n setBusy(true);\n setRefused(null);\n const done = await client.fieldRestore({ field_id: state.field_id });\n setBusy(false);\n if (!done.ok) {\n setRefused(done.error);\n return;\n }\n if (state.table_id) tableShapeChanged(state.table_id);\n tableShapeChanged(tableId);\n await read();\n };\n\n return (\n <div\n className=\"flex flex-wrap items-center gap-2 rounded-md border border-border px-3 py-2\"\n data-testid=\"source-archived-notice\"\n data-field-id={state.field_id ?? \"\"}\n >\n <div className=\"flex min-w-0 flex-1 flex-col\">\n <span className=\"text-sm\">{SOURCE_ARCHIVED_WORDS}</span>\n <span className=\"truncate text-xs text-muted-foreground\">{sourceArchivedSentence(state)}</span>\n </div>\n {state.field_id ? (\n <Button type=\"button\" size=\"sm\" variant=\"secondary\" disabled={busy} onClick={() => void restore()}>\n {bringBackLabel(state)}\n </Button>\n ) : null}\n {refused ? <RefusalNotice error={refused} className=\"basis-full\" /> : null}\n </div>\n );\n}\n","// src/leadingBlank.ts — @ai-matrx/records-ui\n//\n// A value pasted or scraped with blank lines and spaces ahead of its first word read as a big\n// leading indent on the record page (\"Unformatted About\" on a LinkedIn company). Display drops\n// ONLY what precedes the first non-blank character; inner lines, indents and breaks stay.\nexport function withoutLeadingBlank(text: string): string {\n return text.replace(/^\\s+/, \"\");\n}\n","\"use client\";\nimport { readableLink } from \"./readableLink\";\n\n// src/values.tsx — @ai-matrx/records-ui\n//\n// HOW A VALUE IS SHOWN, one function, used by the grid cell, the peek, the\n// custom-fields section and the form's read state alike. Per SCR it is never\n// per-feature: every surface that shows a Value in this platform shows it the\n// same way, because the way is a property of the Field, not of the screen.\n//\n// VAL-2: a blank is never unexplained. When the record's envelope says why a\n// value is missing, the reason is what is shown — \"never asked\" and \"refused\"\n// are different facts and a person acts on them differently.\n\nimport { withoutLeadingBlank } from \"./leadingBlank\";\nimport { PersonChip } from \"./personChip\";\nimport { SWATCH_CLASS, formatColumnValue } from \"@ai-matrx/design-system/data-table\";\nimport { formatFieldValue, type FieldFormatConfig } from \"@ai-matrx/design-system/field-formats\";\nimport type { Field, HiddenFieldNotice, RecordDocument, Uuid, ValueEnvelope } from \"@ai-matrx/records\";\nimport { WITHHELD_WORD, WithheldValue, withheldNoticeOf, withheldSentence } from \"./withheld\";\nimport { rowName } from \"./names\";\nimport { Badge, cn } from \"@ai-matrx/design-system\";\nimport { editorKindFor } from \"./parity\";\nimport { dateFormatFor, dateText, isDateField, systemStampOf } from \"./dates\";\nimport { useEmbeddedLook, type EmbeddedLook } from \"./embeddedLook\";\nimport { isId, useLabelWait, useRecordLabels, type LabelLookup } from \"./labels\";\nimport { ABSENCE_WORD_LABEL } from \"./enumLabels\";\nimport { entityReferenceText } from \"./EntityReferenceControl\";\nimport { wholeValueOf } from \"@ai-matrx/records/core\";\nimport { WholeValueCell } from \"./WholeValue\";\nimport { choiceChipLookOf } from \"./choiceLooks\";\nimport { formatPhone } from \"@ai-matrx/design-system/field-formats\";\nimport { FormattedValue, linkChipText } from \"./formattedValue\";\nimport { formatForField, isYearField, isYearValue, shownAsOf } from \"./presentation\";\nimport { useRecordsUi } from \"./host\";\nimport { LinkPreviewCard } from \"./LinkPreviewCard\";\nimport { AttachmentChips } from \"./gridAttachments\";\nimport { KindValueCell, ReferenceChip, ReferenceChips, referenceChipsOf } from \"./ReferenceChips\";\nimport { ClampedChips } from \"./ClampedChips\";\nimport { kindValueOf, kindValueWords } from \"./kindValues\";\nimport { formulaHasNothingToWorkOn, formulaSourceArchived } from \"./formulaNames\";\nimport { SignatureValue, isSignatureField, signatureWords } from \"./signature\";\nimport { autonumberPrefixOf, autonumberWords, isButtonField, newerKindWords, sourceArchivedOf, type SourceArchived } from \"@ai-matrx/records\";\nimport { ButtonValue } from \"./buttonCell\";\nimport { newerKindValue, statusMarkOf } from \"./newerKindValues\";\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\nimport { PERSON_NOT_IN_ORGANIZATION } from \"./userIds\";\nimport { knownPerson, openStoredPerson, usePeopleTick } from \"./personNames\";\nimport { KeptAsideValue, WorkedOutError, keptAsideFor, workedOutErrorFor } from \"./cellMarks\";\nimport { OutboundLink } from \"@ai-matrx/kit/outbound-react\";\nimport { StructuredCell, StructuredValueView, structuredOf, structuredSummary, type Structured } from \"./structuredValue\";\nimport { registeredLook } from \"./looks\";\n\n/** A status choice's group mark (lane 10 P4), before its words on the chip. */\nfunction statusMark(field: Field, item: unknown, document?: RecordDocument) {\n const mark = statusMarkOf(field, item, document as Record<string, unknown> | undefined);\n return mark ? (\n <span aria-label={mark.words} title={mark.words} className=\"mr-1\" data-records-status-group={mark.group}>\n {mark.mark}\n </span>\n ) : null;\n}\n\n/** The envelope for one key, when the document carries one. */\nexport function envelopeFor(document: RecordDocument | undefined, key: string): ValueEnvelope | undefined {\n const block = document?._values as Record<string, ValueEnvelope> | undefined;\n return block?.[key];\n}\n/** The identifier a relation cell held before it moved, when its target no longer existed. */\nexport function unresolvedFor(document: RecordDocument | undefined, key: string): string | undefined {\n const sources = document?._sources as Record<string, { unresolved?: Record<string, unknown> }> | undefined;\n if (!sources || typeof sources !== \"object\") return undefined;\n for (const source of Object.values(sources)) {\n const held = source?.unresolved?.[key];\n if (typeof held === \"string\" && held) return held;\n if (Array.isArray(held) && held.length) return held.map(String).join(\", \");\n }\n return undefined;\n}\n\n/** A worked-out column that actually carries something to work out. */\nfunction hasFormula(field: Field): boolean {\n const config = (field.config ?? {}) as Record<string, unknown>;\n return Boolean(config.expr) || Boolean(String(config.formula_text ?? \"\").trim());\n}\n\n/**\n * WHY A WORKED-OUT COLUMN IS EMPTY, by its own kind and THIS record (lane VIEWS-AND-FIELDS W1-B\n * item 6) — the census of every column the store works out:\n * · a lookup reads from the record its link holds: no link → \"Pick a linked record\"; a link\n * whose value is empty → \"Empty on the linked record\";\n * · a rollup or a count works over the records its link holds: none → \"No linked records yet\";\n * some, with nothing worked out → a count reads its own 0, a total \"—\" (\"Nothing to add up\");\n * · a formula with no formula yet says so in words; with one, and the store's stamps, plain \"—\".\n * With no record to look at, a lookup or rollup is a plain \"—\" (never a guessed reason).\n * `words` replaces the dash; `sentence` is drawn in its place in italics; `why` is the tooltip.\n * `null`: not a worked-out column.\n */\nexport function computedEmptyOf(\n field: Field,\n document?: Record<string, unknown> | null,\n): { kind: \"lookup\" | \"rollup\" | \"count\" | \"formula\" | \"stamp\"; why?: string; sentence?: string; words?: string } | null {\n const kind = editorKindFor(field);\n const config = (field.config ?? {}) as Record<string, unknown>;\n if (kind === \"lookup\" || kind === \"rollup\") {\n const via = typeof config[\"via\"] === \"string\" ? config[\"via\"] : null;\n const held = document && via ? document[via] : undefined;\n const known = Boolean(document && via);\n const linked = !(held === null || held === undefined || held === \"\" || (Array.isArray(held) && held.length === 0));\n const count = kind === \"rollup\" && config[\"agg\"] === \"count\";\n const which = kind === \"lookup\" ? \"lookup\" : count ? \"count\" : \"rollup\";\n if (!known) return { kind: which };\n if (kind === \"lookup\") return { kind: which, why: linked ? \"Empty on the linked record\" : \"Pick a linked record\" };\n if (!linked) return { kind: which, why: \"No linked records yet\" };\n return count ? { kind: which, words: \"0\" } : { kind: which, why: \"Nothing to add up\" };\n }\n if (kind !== \"formula\" && field.type !== \"formula\") return null;\n if (typeof config[\"system\"] === \"string\") return { kind: \"stamp\" };\n if (!hasFormula(field)) return { kind: \"formula\", sentence: \"Worked out once its formula is in place\" };\n return { kind: \"formula\" };\n}\n\n/** The cell words for a lookup or roll-up whose source is archived (CHAIR-ROLLUP-HONEST). */\nexport const SOURCE_ARCHIVED_WORDS = \"Source archived\";\n\n/** What it is that was archived, for a tooltip: \"Patient on Appointments is archived\". */\nexport function sourceArchivedSentence(state: SourceArchived): string {\n if (!state.label) return \"A column it reads is archived\";\n return state.table ? `${state.label} on ${state.table} is archived` : `${state.label} is archived`;\n}\n\n/**\n * A LOOKUP OR ROLL-UP WHOSE SOURCE IS ARCHIVED (CHAIR-ROLLUP-HONEST, Law 4): the store answers a\n * typed state in the value's place (`sourceArchivedOf`), never a 0. The cell says so in two words\n * and names the archived column on hover; Column settings carries \"Bring back\".\n */\nexport function SourceArchivedValue({ state }: { state: SourceArchived }) {\n return (\n <span className=\"text-xs italic text-muted-foreground\" title={sourceArchivedSentence(state)} data-records-source-archived={state.field_id ?? \"\"}>\n {SOURCE_ARCHIVED_WORDS}\n </span>\n );\n}\n\n// THE one map — see `enumLabels.ts`.\nexport const ABSENCE_WORDS: Record<string, string> = ABSENCE_WORD_LABEL;\n\n\n// Kinds whose value is a list or an object by design, drawn by their own component — never read as structure.\nconst NOT_STRUCTURE_KINDS = new Set([\"relation\", \"entity_reference\", \"member\", \"select\", \"multi_select\", \"attachment\", \"signature\", \"button\"]);\n\n/**\n * A VALUE WITH INSIDES (lane JSON-FIELDS): a JSON object or array in a text cell, or a json value kept\n * as an object — read once by `structuredOf`. Null for a column whose kind owns its own list shape.\n */\nexport function structuredValueOf(field: Field, value: unknown): Structured | null {\n if (field.type === \"list\" || NOT_STRUCTURE_KINDS.has(editorKindFor(field))) return null;\n // A column wearing a PLUG-IN LOOK (`looks/`) keeps its value as JSON text on purpose: the look draws it.\n if (registeredLook(shownAsOf(field))) return null;\n return structuredOf(value);\n}\n\n/** A structured value drawn in its room: one line that opens the whole (a cell), or the whole (a page). */\nfunction structuredNode(field: Field, structured: Structured, room: \"cell\" | \"full\") {\n const label = field.label || field.key;\n return room === \"cell\" ? <StructuredCell structured={structured} label={label} /> : <StructuredValueView structured={structured} label={label} />;\n}\n\nexport function renderValue(field: Field, value: unknown, document?: RecordDocument, labels?: LabelLookup, stillWaitingFor?: string | null, look?: EmbeddedLook | null, room: \"cell\" | \"full\" = \"cell\") {\n const archivedSource = sourceArchivedOf(value);\n if (archivedSource) return <SourceArchivedValue state={archivedSource} />;\n const envelope = envelopeFor(document, field.key);\n if (envelope?.absent) {\n return (\n <span className=\"text-xs italic text-muted-foreground\" title={`VAL-2: ${envelope.absent}`}>\n {ABSENCE_WORDS[String(envelope.absent)] ?? String(envelope.absent)}\n </span>\n );\n }\n if (value === null || value === undefined || value === \"\") {\n // VAL-2 AGAIN, FOR TWO BLANKS A DASH WOULD LIE ABOUT (VERIFIER-16, 2026-09-23).\n // A relation cell that pointed at a record which no longer exists moved EMPTY — the store\n // refuses a relation to nothing — and the id it held is kept on the record's own\n // provenance entry (`_sources.<ptr>.unresolved.<key>`). A dash there says \"nobody filled\n // this in\", which is false: somebody did, and what they chose is gone.\n const gone = unresolvedFor(document, field.key);\n if (gone) {\n return (\n <span className=\"text-xs italic text-muted-foreground\" title={`It pointed at ${gone}`}>\n The record this pointed at no longer exists\n </span>\n );\n }\n // A FORMULA OVER A COLUMN WHOSE SOURCE IS ARCHIVED says so, never a blank (v7 item 7).\n const archivedInput = formulaSourceArchived(field, document as Record<string, unknown> | undefined);\n if (archivedInput) return <SourceArchivedValue state={archivedInput} />;\n // A WORKED-OUT COLUMN'S EMPTY STATE IS ITS OWN KIND'S (`computedEmptyOf`): a lookup is empty\n // because no linked record is picked, never because \"its formula\" is missing.\n const computed = computedEmptyOf(field, document as Record<string, unknown> | undefined);\n if (computed?.sentence) return <span className=\"text-xs italic text-muted-foreground\">{computed.sentence}</span>;\n if (computed?.words) return <span data-records-empty-why={computed.kind}>{computed.words}</span>;\n if (computed?.why) {\n return (\n <span className=\"text-muted-foreground\" title={computed.why} data-records-empty-why={computed.kind}>\n —\n </span>\n );\n }\n // EMBEDDED (`embeddedLook.ts`): a plain empty cell is blank, as Notion's is.\n if (look?.blankEmpty) return null;\n return <span className=\"text-muted-foreground\">—</span>;\n }\n\n // A SIGNATURE IS SEEN AS ITS DRAWING (or the signer's name a sealed document wrote), never as\n // the image's data text (`signature.tsx`).\n if (isSignatureField(field)) return <SignatureValue value={value} fieldKey={field.key} document={document} />;\n\n if (isButtonField(field)) return <ButtonValue field={field} />;\n // THE NEWER KINDS (lane 10 P4) draw in their own shape (`newerKindValues.tsx`).\n const newer = newerKindValue(field, value);\n if (newer !== undefined) return newer;\n\n // A VALUE TOO BIG FOR ONE CELL: the words it keeps, and the way to the whole text (`WholeValue.tsx`).\n const whole = typeof value === \"string\" ? wholeValueOf(document, field.key) : null;\n if (whole) return <WholeValueCell words={value as string} pointer={whole} />;\n\n const kind = editorKindFor(field);\n // A REFERENCE IS A CHIP THAT OPENS WHAT IT NAMES (lane REFERENCE-CARRY): a relation's records and\n // an entity reference's platform things alike (`ReferenceChips.tsx`).\n if (kind === \"relation\" || kind === \"entity_reference\") {\n return <ReferenceChips refs={referenceChipsOf(field, value, kind, labels)} waiting={stillWaitingFor} />;\n }\n // A VALUE THAT NAMES ITS OWN SHAPE — `__kind` JSON, or a Matrx directive stored before the Kind\n // Directives merge (```matrx {\"matrx_version\":1,…}```) — is drawn by the kind system, never as\n // the raw fence (Arman, Department table, 2026-09-28).\n // A PERSON IS A PERSON CHIP, never the link chip (`personChip.tsx`, night walk 2026-10-06).\n if (kind === \"member\") {\n const ids = (Array.isArray(value) ? value : [value]).filter((v) => v !== null && v !== undefined && v !== \"\");\n return (\n <span className=\"flex min-w-0 flex-wrap gap-1\" data-records-person-chips=\"\">\n {ids.map((id, i) => (\n <LivePersonChip key={`${String(id)}-${i}`} id={String(id)} name={scalarText(field, id, labels, stillWaitingFor)} />\n ))}\n </span>\n );\n }\n const kv = kind === \"attachment\" ? null : kindValueOf(value);\n if (kv) return <KindValueCell kv={kv} where=\"cell\" title={field.label} />;\n // A VALUE WITH INSIDES IS DRAWN AS ITS INSIDES (lane JSON-FIELDS, `structuredValue.tsx`).\n const structured = structuredValueOf(field, value);\n if (structured) return structuredNode(field, structured, room);\n // A CHOICE WEARS THE COLOR ITS COLUMN KEEPS FOR IT (`choiceLooks.ts`) — never a color hashed\n // from its word — as a chip whose words can be read in both themes (`CHOICE_CHIP_CLASS`, lane C,\n // review 2026-09-26: white words on pale fills measured ~1.1:1). A choice the column keeps no\n // color for is a NEUTRAL chip, never bare text.\n const chosen = kind === \"select\" || kind === \"multi_select\";\n const chipOf = (item: unknown): { className: string; tinted: boolean; dot: string } => {\n const chipLook = choiceChipLookOf(field, item, scalarText(field, item, labels));\n return { className: chipLook.className, tinted: chipLook.color !== null, dot: SWATCH_CLASS[chipLook.color ?? \"gray\"] };\n };\n if (chosen) {\n const items = Array.isArray(value) ? value : [value];\n return (\n <span className=\"flex flex-wrap gap-1\" data-records-choice-chips=\"\">\n {items.map((item, i) => {\n const chip = chipOf(item);\n return (\n <Badge\n key={`${String(item)}-${i}`}\n variant=\"outline\"\n className={cn(\"text-[11px]\", chip.className)}\n data-records-choice-chip=\"\"\n {...(chip.tinted ? { \"data-records-choice-tint\": \"\" } : {})}\n >\n {look?.choiceDot ? <span aria-hidden=\"true\" data-matrx-pill-ink=\"\" data-records-choice-dot=\"\" className={cn(\"mr-1.5 inline-block size-1.5 shrink-0 rounded-full\", chip.dot)} /> : null}\n {statusMark(field, item, Array.isArray(value) ? undefined : document)}\n {scalarText(field, item, labels, Array.isArray(value) ? undefined : stillWaitingFor)}\n </Badge>\n );\n })}\n </span>\n );\n }\n // A FILE READS AS ITS NAME AND OPENS WHERE THE HOST KEEPS IT (`gridAttachments.tsx`).\n if (kind === \"attachment\") return <AttachmentChips value={value} />;\n if (Array.isArray(value)) {\n return (\n <span className=\"flex flex-wrap gap-1\">\n {value.map((item, i) => (\n <Badge key={`${String(item)}-${i}`} variant=\"secondary\" className=\"text-[11px]\">\n {scalarText(field, item, labels)}\n </Badge>\n ))}\n </span>\n );\n }\n // A TEXT FIELD HOLDING ONE IMAGE ADDRESS (a LinkedIn \"logo\") SHOWS THE PICTURE, the address one click away.\n const pictureAt = imageAddressOf(field, value);\n if (pictureAt) return <ImageUrlValue url={pictureAt} alt={field.label || field.key} room={room} />;\n if (kind === \"url\" && typeof value === \"string\") {\n // A LINK IS A CHIP NAMING WHERE IT GOES (lane C, review 2026-09-26 F1–F7: \"A URL column shows\n // raw image URLs\"): the site and the file, the whole address on hover. Airtable's link chip.\n const href = value.includes(\"://\") ? value : `https://${value}`;\n return (\n <LinkPreviewCard url={href}>\n <OutboundLink\n className=\"inline-flex min-w-0 max-w-full items-center gap-1 rounded-md border border-border bg-muted/60 px-1.5 py-0.5 text-[11px] text-foreground hover:bg-accent\"\n href={href}\n title={readableLink(value)}\n data-records-link-chip=\"\"\n onClick={(event) => event.stopPropagation()}\n >\n <span aria-hidden=\"true\" className=\"text-muted-foreground\">↗</span>\n <span className=\"truncate\">{linkChipText(value)}</span>\n </OutboundLink>\n </LinkPreviewCard>\n );\n }\n if (kind === \"phone\" && typeof value === \"string\" && value.trim() !== \"\") {\n return (\n <a\n className=\"truncate tabular-nums text-primary underline-offset-2 hover:underline\"\n href={`tel:${value.replace(/[^\\d+]/g, \"\")}`}\n title={value}\n data-records-phone=\"\"\n onClick={(event) => event.stopPropagation()}\n >\n {formatPhone(value)}\n </a>\n );\n }\n if (kind === \"email\" && typeof value === \"string\") {\n return (\n <a className=\"truncate text-primary underline-offset-2 hover:underline\" href={`mailto:${value}`}>\n {readableLink(value)}\n </a>\n );\n }\n if (typeof value === \"boolean\") {\n // LIMITS-FIX 2026-09-21: a tick box reads as a tick wherever it is only READ — a peek,\n // a portal, a form's answered state. The grid draws the real control instead, because\n // there a person expects to change it. (An UNANSWERED tick box never reaches here: it\n // has no value and left through the blank branch above, which is the third state.)\n return (\n <span className={kind === \"checkbox\" ? \"text-sm\" : \"\"} title={value ? \"Yes\" : \"No\"}>\n {value ? \"✓\" : \"—\"}\n </span>\n );\n }\n return <span className={cn(\"truncate\", kind === \"number\" || kind === \"currency\" || kind === \"percent\" ? \"tabular-nums\" : \"\")}>{scalarText(field, value, labels, stillWaitingFor)}</span>;\n}\n\n/** One address, nothing else, that names a picture: an image extension, or an `/image(s)/` path (a CDN's own). */\nexport function isImageUrl(value: string): boolean {\n const text = value.trim();\n if (!/^https?:\\/\\/[^\\s]+$/i.test(text)) return false;\n let url: URL;\n try {\n url = new URL(text);\n } catch {\n return false;\n }\n return /\\.(png|jpe?g|gif|webp|avif|svg|bmp|ico)$/i.test(url.pathname) || /\\/(images?|img)\\//i.test(url.pathname);\n}\n\n/** The one picture address a text or link field holds (a value that is one picture address, or any one address in a column named for a picture: logo, image, photo); else null. */\nexport function imageAddressOf(field: Field, value: unknown): string | null {\n if (typeof value !== \"string\") return null;\n const kind = editorKindFor(field);\n if (kind !== \"text\" && kind !== \"url\") return null;\n const text = value.trim();\n if (isImageUrl(text)) return text;\n const named = /(^|[^a-z])(logo|image|img|photo|picture|avatar|thumbnail|headshot)s?([^a-z]|$)/i.test(`${field.label ?? \"\"} ${field.key}`);\n return named && /^https?:\\/\\/[^\\s]+$/i.test(text) ? text : null;\n}\n\n/** The picture a text field's image address names, through the host's one file image element (`fileImage`); its link opens in a new tab. No element bound: the link chip says where it goes. */\nfunction ImageUrlValue({ url, alt, room }: { url: string; alt: string; room: \"cell\" | \"full\" }) {\n const host = useRecordsUi();\n const box = room === \"full\" ? \"size-24\" : \"size-6\";\n return (\n <OutboundLink\n className={cn(\"inline-flex shrink-0 overflow-hidden rounded-md border border-border bg-muted/40\", host.fileImage ? box : \"min-w-0 max-w-full items-center gap-1 px-1.5 py-0.5 text-[11px] text-foreground hover:bg-accent\")}\n href={url}\n title={url}\n data-records-image-url=\"\"\n onClick={(event) => event.stopPropagation()}\n >\n {host.fileImage ? host.fileImage({ fileId: url as Uuid, alt }) : <span className=\"truncate\">{linkChipText(url)}</span>}\n </OutboundLink>\n );\n}\n\n// Kinds that can never hold an id of something else, so an id in one is a kept person.\n/** A stored person in a cell or on the record page: their chip, which opens them through the host's `openPerson` (the peek of the account, or the contact held by email). */\nfunction LivePersonChip({ id, name }: { id: string; name: string }) {\n const open = useRecordsUi().openPerson;\n return <PersonChip name={name} {...(open ? { onOpen: () => void openStoredPerson(id, open) } : {})} />;\n}\n\nconst NEVER_AN_ID_KINDS = new Set([\"member\", \"person\", \"number\", \"currency\", \"percent\", \"date\", \"datetime\", \"checkbox\", \"boolean\"]);\n\n/** The words for a stored person id (or ids): the name, else the wait/not-here words — never the id. Null when the value holds no id to name. */\nfunction personWordsOf(kind: string, value: unknown): string | null {\n const items = Array.isArray(value) ? value : [value];\n const ids = items.filter(isUuidShape);\n if (ids.length === 0) return null;\n const wordsColumn = !NEVER_AN_ID_KINDS.has(kind);\n const named = ids.map((id) => knownPerson(id));\n // Any other column may legitimately hold an id of something else: only a known person is renamed.\n if (wordsColumn && named.some((n) => n === null)) return null;\n return named.map((n) => n ?? PERSON_NOT_IN_ORGANIZATION).join(\", \");\n}\n\n\n/**\n * The text of one scalar, with the Field's UNIT and FORMAT applied — FLD-N-1\n * says both change the MEANING — and with an id resolved to the NAME of the\n * record it points at.\n *\n * `labels` is the resolver from `RecordLabelProvider`. Without it, an id is\n * drawn as \"Loading…\" and never as itself: a 36-character identifier in a cell\n * reads like a value, and the 19 September verdict found it in choice cells,\n * relation cells and as every Kanban column heading.\n */\nexport function scalarText(\n field: Field,\n value: unknown,\n labels?: LabelLookup,\n /**\n * WHAT THIS COLUMN IS WAITING FOR, once it has been looking long enough to owe\n * a sentence (`useLabelWait`). \"Loading…\" is honest for a moment and a lie with\n * a spinner on it after that: VERIFIER-8 MEDIUM-1 watched a whole relation\n * column say it for 10-13 seconds while the rest of the grid sat readable\n * behind it, and nothing on screen said what it was waiting for.\n */\n stillWaitingFor?: string | null,\n): string {\n if (value === null || value === undefined) return \"—\";\n if (sourceArchivedOf(value)) return SOURCE_ARCHIVED_WORDS;\n // A drawn signature reads as \"Signed\" wherever only words fit (a card title, a sentence).\n if (isSignatureField(field)) return signatureWords(value) ?? \"—\";\n // NOTION-PROPS-3: a record number reads with its prefix (TASK-42) wherever only words fit.\n if (autonumberPrefixOf(field)) return autonumberWords(field, value) ?? String(value);\n // The newer kinds' own words (lane 10 P4): an address on one line, h:mm, who by name, 3 / 5.\n const newerWords = newerKindWords(field, value);\n if (newerWords !== null) return newerWords;\n const kind = editorKindFor(field);\n // SC-R: a reference to a platform thing reads as the thing's own words (withheld ones said so).\n if (kind === \"entity_reference\") return entityReferenceText(value);\n // A many-relation reads as its records' names, never \"2 of them\" (lane REFERENCE-CARRY) — and a\n // SEVERAL-CHOICE value reads as its choices' words the same way (BREAKER-2 B2-19: a board grouped\n // by Body Areas titled one column \"1 of them\").\n if ((kind === \"relation\" || field.type === \"list\") && Array.isArray(value)) {\n return value.map((item) => scalarText(field, item, labels, stillWaitingFor)).join(\", \");\n }\n // A kind value in words: its items' own names, else what it is (`kindValues.ts`).\n const kv = kindValueOf(value);\n if (kv) return kindValueWords(kv);\n if (isId(value) && (field.type === \"list\" || field.type === \"relation\")) {\n return labels?.(field, String(value)) ?? stillWaitingFor ?? \"Loading…\";\n }\n // A PERSON IS NEVER A UUID (lane PERSON-SWEEP): an id in a Person column, or an id a column that is not\n // words kept from a retired Person column, reads as the person's name (`personNames.ts`). A text column\n // holding an id reads as one only when the id is a person the resolver knows (a Person → Text retype\n // leaves the history's old values as ids).\n const personal = personWordsOf(kind, value);\n if (personal !== null) return personal;\n // A CHOICE HELD BY ITS KEY reads as its option's words (DATA-V2-BASICS-2): the key never\n // reaches a person. Until the options are read the column's own \"Shows as\" answers below.\n if (field.type === \"list\" && typeof value === \"string\" && labels) {\n const words = labels(field, value);\n if (words) return words;\n }\n // A column's own \"Shows as\" (tranche 6e) words a card and a sentence the way the grid shows it.\n const shownAs = shownAsOf(field);\n if (shownAs) {\n const said = formatFieldValue(value, shownAs.id === \"number\" && isYearField(field) && isYearValue(value) ? (formatForField(field) ?? shownAs) : shownAs);\n if (said.ok && !said.empty) return said.text;\n }\n if (typeof value === \"number\") {\n if (kind === \"percent\") return `${value}%`;\n // The symbol goes in FRONT of an amount of money and a unit goes AFTER a\n // quantity: `$3` and `3 units`. Before this, `editorKindFor` called any\n // range field with a unit longer than one character a currency, so three\n // things measured in units rendered as \"units3\".\n if (kind === \"currency\") return field.unit ? `${field.unit}${value.toLocaleString()}` : value.toLocaleString();\n // A YEAR IS NEVER GROUPED: \"Founded 2008\", not \"2,008\" (`isYearField`).\n const plain = isYearField(field) && isYearValue(value) ? String(value) : value.toLocaleString();\n return field.unit ? `${plain} ${field.unit}` : plain;\n }\n // A DATE IS READ BY THE ONE HELPER (`dates.ts`), the same registry the grid prints with:\n // a bare `2026-04-01` is April 1st in every zone, never UTC midnight moved to March 31st.\n // The store's own Created / Last changed stamps come through here too.\n if (kind === \"datetime\" || systemStampOf(field) === \"created_time\" || systemStampOf(field) === \"modified_time\") {\n const said = dateText(field, value);\n if (said !== null) return said;\n }\n // NEVER A JSON DUMP IN A CELL. A value with a shape a column cannot draw is\n // described; the raw document is available on the record panel, which is\n // where a person goes to look at it.\n if (Array.isArray(value)) return value.length === 0 ? \"\" : structuredSummary(value);\n if (typeof value === \"object\") return structuredOf(value) ? structuredSummary(value as Record<string, unknown>) : \"…\";\n return typeof value === \"string\" ? withoutLeadingBlank(value) : String(value);\n}\n\n/** The provenance badge a value carries when the store interned a source for it (SCR-27). */\nexport function ProvenanceBadge({ document, fieldKey }: { document: RecordDocument | undefined; fieldKey: string }) {\n const envelope = envelopeFor(document, fieldKey);\n if (!envelope?.src) return null;\n // A value kept as a file: the cell already says so and opens it (WholeValue.tsx); its pointer's\n // raw fields are not a provenance a person reads.\n if (wholeValueOf(document, fieldKey)) return null;\n const sources = document?._sources as Record<string, Record<string, unknown>> | undefined;\n const source = sources?.[envelope.src];\n const label = source ? Object.values(source).map(String).join(\" · \") : envelope.src;\n return (\n <Badge variant=\"outline\" className=\"text-[10px] font-normal\" title={`Written by ${envelope.actor ?? \"?\"}${envelope.at ? ` at ${envelope.at}` : \"\"}`}>\n {label}\n </Badge>\n );\n}\n\n/**\n * THE VALUE, AS A COMPONENT, so a cell can resolve the ids it holds.\n *\n * `renderValue` is a plain function called from inside a column's `cell`\n * callback and from a dozen other places; a function cannot ask the resolver\n * for a name, because asking is a hook. Every read-only surface therefore draws\n * through this instead, and the one that needs the raw function (a plain-text\n * export, a chat line) keeps calling `renderValue` with no resolver and says\n * \"Loading…\" rather than printing an id.\n */\nexport function RecordValue({\n field,\n value,\n document,\n format,\n withheld,\n inCell,\n roomy,\n recordId,\n}: {\n field: Field;\n value: unknown;\n document?: RecordDocument | undefined;\n /**\n * WHOSE VALUE THIS IS. A drawn signature a form sent is kept as a File the value's source names,\n * and the read doors give the value without its source — so the signature reader asks for it by\n * the record (`signature.tsx`). Every other kind ignores it.\n */\n recordId?: string | null | undefined;\n /**\n * The column's DECLARED format (`presentation.ts`), when it has one.\n *\n * A cell renderer beats `MatrxColumnDef.format` — the table hands the cell to\n * the consumer and steps back — so a store column that declared `currency`\n * and then drew itself here would have shown a raw `1250.5` while its own\n * header was right-aligned for money. The primitive's formatter is asked for\n * the text instead of a second one being written beside it, so the read view\n * and the table can never disagree about what a number means. THE FALLBACK\n * LAW rides along: a value that does not fit is amber with the reason, never\n * blank.\n */\n format?: FieldFormatConfig | undefined;\n /**\n * THE STORE'S REASON, when it withheld this value from the reader (`ReadRow.hidden[key]`).\n * A withheld value reads \"Withheld\" with the store's sentence on hover — never \"—\", which\n * means the cell is empty (`withheld.tsx`).\n */\n withheld?: HiddenFieldNotice | null | undefined;\n /**\n * Drawn in a GRID CELL. In the merged grid a long-text cell reads through the host's text\n * renderer (`RecordsUiHost.renderText`, slot `cell` — markdown, formatted), clipped to the row;\n * unbound, the words as written.\n */\n inCell?: boolean | undefined;\n /**\n * A ROOMY CELL — the record page's field, which is drawn by the grid's cell but has the width of a\n * page. A structured value shows whole there, not as the grid's one line.\n */\n roomy?: boolean | undefined;\n}) {\n usePeopleTick();\n const ui = useRecordsUi();\n const labels = useRecordLabels(ONE_FIELD_ARRAY_CACHE(field));\n // A CELL THAT IS STILL RESOLVING SAYS WHAT IT IS WAITING FOR — after one\n // second, not immediately: the word \"Loading…\" is honest for the moment it\n // takes, and a lie with a spinner on it after that.\n const stillWaitingFor = useLabelWait(field);\n const embeddedLook = useEmbeddedLook();\n // NOTION-PROPS-3: A BUTTON holds no value — it is drawn as itself and pressed (`buttonCell.tsx`).\n if (isButtonField(field)) return <ButtonValue field={field} recordId={recordId} inCell={inCell} />;\n if (withheld && (value === null || value === undefined)) return <WithheldValue field={field} notice={withheld} />;\n // A WORKED-OUT COLUMN THE STORE COULD NOT WORK OUT says so, with the store's sentence (`cellMarks.tsx`).\n if (value === null || value === undefined) {\n const failed = workedOutErrorFor(document, field.key);\n if (failed) return <WorkedOutError field={field} sentence={failed} floated={Boolean(inCell)} />;\n }\n // A VALUE KEPT ASIDE when its column changed stays where it was in a grid cell, amber, saying why.\n if (inCell) {\n const kept = keptAsideFor(document, field.key);\n if (kept) return <KeptAsideValue field={field} entry={kept} shown={scalarText(field, kept.value)} />;\n }\n const archivedSource = sourceArchivedOf(value);\n if (archivedSource) return <SourceArchivedValue state={archivedSource} />;\n // A WORKED-OUT COLUMN WITH NOTHING TO WORK ON IS EMPTY (review 2, A12): a new row's\n // `{Quote} * 1.08` is blank, never \"$0.00\" (`formulaNames.ts`).\n if (formulaHasNothingToWorkOn(field, document as Record<string, unknown> | undefined)) return embeddedLook?.blankEmpty ? null : <span className=\"text-muted-foreground\">—</span>;\n // THE NEWER KINDS (lane 10 P4) draw in their own shape in every layout (`newerKindValues.tsx`).\n if (value !== null && value !== undefined && value !== \"\" && !envelopeFor(document, field.key)?.absent) {\n const newer = newerKindValue(field, value, { inCell });\n if (newer !== undefined) return <>{newer}</>;\n }\n // A VALUE WITH INSIDES (lane JSON-FIELDS): a grid cell gets one line that opens the whole value;\n // the record page, a panel and a public page get the whole value, drawn by its shape.\n const room: \"cell\" | \"full\" = inCell && !roomy ? \"cell\" : \"full\";\n if (value !== null && value !== undefined && !wholeValueOf(document, field.key) && !envelopeFor(document, field.key)?.absent) {\n const structured = structuredValueOf(field, value);\n if (structured) return <>{structuredNode(field, structured, room)}</>;\n }\n if (\n inCell &&\n ui.grid === \"merged\" &&\n ui.renderText &&\n typeof value === \"string\" &&\n value.trim() !== \"\" &&\n editorKindFor(field) === \"long_text\" &&\n !shownAsOf(field) &&\n !wholeValueOf(document, field.key) &&\n !envelopeFor(document, field.key)?.absent &&\n // A long-text cell holding a kind is drawn by the kind system below, not as markdown.\n !kindValueOf(value)\n ) {\n // ONE LINE, AT A FIXED HEIGHT (live walk 2026-10-07, \"Note from the client\": a saved three-line\n // note grew its row 35 → 67px, and the markdown placeholder → rendered swap moved it again,\n // 43 → 47). The row is 35px whatever the note holds; the whole text is the peek and the editor.\n return (\n <span className=\"block h-[1.5em] min-w-0 overflow-hidden whitespace-normal [[data-matrx-cell-lines]:not([data-matrx-cell-lines=one])_&]:h-auto\" data-records-cell-text=\"\">\n {ui.renderText(withoutLeadingBlank(value), \"cell\")}\n </span>\n );\n }\n // A DATE COLUMN PRINTS EACH VALUE IN ITS OWN SHAPE (`dates.ts`): a bare date is a date,\n // a moment is a date and time, whatever the column's kind says — so the grid, the form, the\n // panel and the calendar read one date the same way.\n // THE COLUMN'S OWN \"SHOWS AS\" WHEN THE CALLER NAMED NONE (merge tranche 6e): the record panel,\n // a card and a public page read the Field's format the way the grid does, so a percent kept as\n // 0.45 is 45% everywhere and a rating is stars everywhere.\n // A signature in a grid cell is drawn at the row's height.\n if (isSignatureField(field) && value !== null && value !== undefined && value !== \"\") {\n return <SignatureValue value={value} inCell={inCell} recordId={recordId} fieldKey={field.key} document={document} />;\n }\n // A LINK CELL IS ONE LINE: as many chips as fit, then \"+N\" that opens the whole list.\n if (inCell) {\n const linkKind = editorKindFor(field);\n if (linkKind === \"relation\" || linkKind === \"entity_reference\") {\n const refs = referenceChipsOf(field, value, linkKind, labels);\n if (refs.length > 1) {\n return (\n <ClampedChips\n dataAttr={field.key}\n items={refs.map((r) => ({ key: `${r.token}:${r.id}`, node: <ReferenceChip reference={r} waiting={stillWaitingFor} /> }))}\n />\n );\n }\n }\n }\n // A PICTURE ADDRESS IS THE PICTURE, ahead of any \"shows as\" that would print it as a link.\n const pictureAt = value !== null && value !== undefined && !wholeValueOf(document, field.key) && !envelopeFor(document, field.key)?.absent ? imageAddressOf(field, value) : null;\n if (pictureAt) return <ImageUrlValue url={pictureAt} alt={field.label || field.key} room={room} />;\n const shown = format ?? formatForField(field);\n // THE VALUE'S OWN SHAPE (date or date-and-time) CHOSEN BY `dateFormatFor`, THE COLUMN'S OPTIONS KEPT\n // (`dateStyle: \"long\"` — \"January 1, 2026\"). Taking the shape alone dropped the options, so a long\n // date read medium in every layout.\n const shape = shown && (shown.id === \"date\" || shown.id === \"datetime\") && isDateField(field)\n ? dateFormatFor(field, value)\n : undefined;\n const dated: FieldFormatConfig | undefined = shape\n ? { ...shape, ...(shown?.options ? { options: shown.options } : {}) }\n : undefined;\n const formatted = shown ? formatColumnValue({ format: dated ?? shown }, value) : null;\n // EMBEDDED (`embeddedLook.tsx`): an empty value with a display format is as blank as an unformatted\n // one — it falls through to `renderValue`, which keeps every reason an empty cell may owe.\n if (formatted && !(embeddedLook?.blankEmpty && formatted.empty)) return <FormattedValue value={value} format={dated ?? shown!} />;\n return <>{renderValue(field, value, document, labels, stillWaitingFor, embeddedLook, room)}</>;\n}\n\n/**\n * `useRecordLabels` takes an array and declares what it is about to draw. A new\n * array literal per cell would re-declare on every render, so each Field gets\n * exactly one array for the life of the process.\n */\nconst ONE_FIELD_ARRAYS = new WeakMap<Field, Field[]>();\nfunction ONE_FIELD_ARRAY_CACHE(field: Field): Field[] {\n const held = ONE_FIELD_ARRAYS.get(field);\n if (held) return held;\n const made = [field];\n ONE_FIELD_ARRAYS.set(field, made);\n return made;\n}\n\n/**\n * WHAT ONE CARD SAYS — the kanban's, the calendar's, the gallery's and the pipeline's alike, so\n * no card can read a record differently from another. `field` is the card's title column\n * (`cardTitleField`); a value the store withheld reads \"Withheld\" and carries the store's reason\n * for the card's hover (`withheld.tsx`), never a bare \"—\".\n */\nexport function cardWords(\n record: { document?: RecordDocument | null; hidden?: Record<string, HiddenFieldNotice> | null } & Parameters<typeof rowName>[0],\n field: Field | undefined,\n labels?: LabelLookup,\n): { text: string; withheld: string | null } {\n if (!field) return { text: rowName(record, null, \"Untitled\"), withheld: null };\n const value = (record.document ?? {})[field.key];\n const notice = withheldNoticeOf(record.hidden, field.key);\n if (notice && (value === null || value === undefined)) {\n return { text: WITHHELD_WORD, withheld: withheldSentence(field, notice) };\n }\n // An empty title is never a blank card (walk 2026-10-08 D6: an untitled sub-item drew nothing).\n const empty = value === null || value === undefined || (typeof value === \"string\" && value.trim() === \"\");\n return { text: empty ? \"Untitled\" : scalarText(field, value, labels), withheld: null };\n}\n","// The withheld value's WORDS, with no React (`@ai-matrx/records-ui/helpers` serves this file alone).\n// The cell that shows them is `./withheld.tsx`, which re-exports these.\nimport type { Field, HiddenFieldNotice } from \"@ai-matrx/records\";\nimport { fieldName } from \"./names\";\n\n/** The word a withheld cell shows in place of a value. Never \"—\", which means empty. */\nexport const WITHHELD_WORD = \"Withheld\";\n\ntype Hidden = Readonly<Record<string, HiddenFieldNotice | undefined>> | null | undefined;\n\n/** The store's notice for this column of this row, when the store withheld it. */\nexport function withheldNoticeOf(hidden: Hidden, key: string): HiddenFieldNotice | null {\n const notice = hidden?.[key];\n return notice && typeof notice === \"object\" ? notice : null;\n}\n\n/**\n * THE SENTENCE, in the store's own words: the notice's `says` when the store wrote one (a\n * worked-out column names what it reads), else the notice's reason, the level it needs and the\n * other way in.\n */\nexport function withheldSentence(field: Pick<Field, \"key\" | \"label\" | \"name\">, notice: HiddenFieldNotice): string {\n const extra = notice as HiddenFieldNotice & { says?: unknown; part?: unknown; who?: unknown };\n if (typeof extra.says === \"string\" && extra.says.trim() !== \"\") return extra.says.trim();\n const name = fieldName(field as Field);\n // A PART'S NOTICE (access-setup PLAN §12.1): \"Hourly rate is in Pay — people with Record admin on this row see it.\"\n if (typeof extra.part === \"string\" && extra.part.trim() !== \"\" && typeof extra.who === \"string\" && extra.who.trim() !== \"\") {\n return `${name} is in ${extra.part.trim()} — ${extra.who.trim()} see it.`;\n }\n const reason = notice.reason ? ` It is ${notice.reason}` : \"\";\n const needs = notice.needs ? `${reason ? \",\" : \" It\"} and reading it needs ${notice.needs}` : \"\";\n const or = notice.or ? `${needs || reason ? \", or\" : \" It needs\"} ${notice.or}` : \"\";\n return `${name} is withheld from you.${reason}${needs}${or}${reason || needs || or ? \".\" : \"\"}`;\n}\n","/**\n * 🚨 A WITHHELD VALUE SAYS WHY — THE ONE HELPER EVERY LAYOUT READS (lane UI-FIX-18).\n *\n * The store masks a column a reader may not read: the value comes back PRESENT and null, and\n * the reason rides beside it (`custom.hidden_field_notice`, unfolded into `ReadRow.hidden` /\n * `RecordRead.hidden`). A worked-out column whose input is more sensitive is withheld too, and\n * its notice says what it is worked out from (\"Budget with contingency is worked out from\n * Budget, which you have not been given.\").\n *\n * MEASURED 2026-09-24 (VERIFIER-18 H1): test@test.com saw \"—\" in Rooms' confidential Budget —\n * the same mark an EMPTY cell wears — and nothing told her the column was withheld from her.\n * No layout in this package read `hidden` at all. Now the grid, the cards, the gallery, the\n * record panel, the public page and the export all ask this file: a withheld value reads\n * \"Withheld\", and the store's own sentence is one hover (and one screen-reader read) away. It\n * never decides what is withheld; it only says what the store already decided.\n */\nimport type { Field, HiddenFieldNotice } from \"@ai-matrx/records\";\nimport { WITHHELD_WORD, withheldSentence } from \"./withheldNotice\";\n\nexport { WITHHELD_WORD, withheldNoticeOf, withheldSentence } from \"./withheldNotice\";\n\n/** A withheld cell as a person reads it: the word, with the store's reason on hover. */\nexport function WithheldValue({ field, notice }: { field: Field; notice: HiddenFieldNotice }) {\n const sentence = withheldSentence(field, notice);\n return (\n <span\n data-records-withheld={field.key}\n title={sentence}\n aria-label={`${WITHHELD_WORD}. ${sentence}`}\n className=\"cursor-help italic text-muted-foreground\"\n >\n {WITHHELD_WORD}\n </span>\n );\n}\n","\"use client\";\n\n// src/EntityReferenceControl.tsx — @ai-matrx/records-ui · lane SC-R (P12), REFERENCE-CARRY\n//\n// A CELL THAT POINTS AT A PLATFORM THING — the intake note of a client matter, the client's web\n// site, the agent a row runs — drawn as what it names, never as `[object Object]` in a text box,\n// and edited with a PICKER, never by typing ids.\n//\n// Every read door answers an entity-reference value as `{token, id, label}`, the label withheld\n// (null) from a reader who may not open the thing. This control draws one chip per reference with\n// the store's label (or, for a value not yet saved, the words `useEntityReferenceWords` reads for\n// THIS person), lets a person take a reference off, and — since lane REFERENCE-CARRY — ADD one:\n// the store's search door (`custom.entity_reference_search`) lists the things of the column's kinds\n// this person may point a record at, each one the store's own write check would accept.\n\nimport { useMemo, useState, type ReactNode } from \"react\";\nimport { entityRefsOf, entityRefsToWrite, type EntityRefWithWords, type Field } from \"@ai-matrx/records\";\nimport { useEntityReferenceKinds, useEntityReferenceSearch, useEntityReferenceWords, useOptionalRecordsClient } from \"@ai-matrx/records/react\";\nimport { Badge, Button, cn } from \"@ai-matrx/design-system\";\nimport { PickOrAdd } from \"./PickOrAdd\";\nimport { RefusalLine } from \"./Refusal\";\nimport { PickOne } from \"./PickOne\";\n\n/** What a chip says when the store withheld the thing's words from this reader. */\nexport const WITHHELD_ENTITY_LABEL = \"Something you have not been given access to\";\n\n/** What an empty entity-reference cell says where nothing can be added (a signed-out form). */\nexport const ENTITY_REFERENCE_EMPTY = \"Nothing is pointed at yet.\";\n\n/** The words of an entity-reference value for a sentence or a plain-text cell. */\nexport function entityReferenceText(value: unknown): string {\n const refs = entityRefsOf(value);\n if (refs.length === 0) return \"—\";\n return refs.map((r) => r.label ?? WITHHELD_ENTITY_LABEL).join(\", \");\n}\n\n/** The kinds a column may point at (`config.allowed_types`), in the order it names them. */\nexport function allowedKindsOf(field: Field): string[] {\n const config = (field.config ?? {}) as Record<string, unknown>;\n const kinds = Array.isArray(config.allowed_types) ? config.allowed_types : [];\n return kinds.map((k) => String(k).trim().toLowerCase()).filter(Boolean);\n}\n\nexport interface EntityReferenceControlProps {\n field: Field;\n value: unknown;\n onChange: (next: unknown) => void;\n disabled?: boolean | undefined;\n id?: string | undefined;\n className?: string | undefined;\n}\n\n/**\n * A signed-out public form mounts no store client, so there is nobody to ask for words or search:\n * the chips there draw what the value already carries and nothing can be added. Inside a client the\n * unlabelled ones are read and the picker is offered.\n */\nexport function EntityReferenceControl(props: EntityReferenceControlProps) {\n const client = useOptionalRecordsClient();\n return client ? <WithWords {...props} /> : <Chips {...props} words={null} picker={null} />;\n}\n\ntype Words = { data: { token: string; id: string; label: string | null }[] | null; loading: boolean } | null;\n\nfunction WithWords(props: EntityReferenceControlProps) {\n const refs = useMemo(() => entityRefsOf(props.value), [props.value]);\n // Picked in this editing session: their words are known, so nobody is asked for them again.\n const [known, setKnown] = useState<EntityRefWithWords[]>([]);\n const withKnown = refs.map((r) => (r.label === null ? (known.find((k) => k.token === r.token && k.id === r.id) ?? r) : r));\n // Only the references that arrived WITHOUT words (a value not yet saved) are asked about.\n const unlabelled = useMemo(\n () => withKnown.filter((r) => r.label === null).map((r) => ({ token: r.token, id: r.id })),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [JSON.stringify(withKnown)],\n );\n const words = useEntityReferenceWords(unlabelled);\n const picker = props.disabled ? null : (\n <EntityReferencePicker\n field={props.field}\n refs={withKnown}\n onPick={(picked) => {\n setKnown((k) => [...k.filter((x) => !(x.token === picked.token && x.id === picked.id)), picked]);\n const multi = Boolean(props.field.multi);\n const next = multi ? [...withKnown.filter((x) => !(x.token === picked.token && x.id === picked.id)), picked] : [picked];\n props.onChange(entityRefsToWrite(next, multi));\n }}\n />\n );\n return <Chips {...props} value={withKnown} words={words} picker={picker} />;\n}\n\n/**\n * THE PICKER: which kind (when the column allows more than one), a search box, the things found.\n * Built from the one pick-or-add builder (`PickOrAdd.tsx`), so it keeps the keys every picker keeps.\n * There is no add line: a platform thing is made where it lives, never from a table cell.\n */\nfunction EntityReferencePicker({\n field,\n refs,\n onPick,\n}: {\n field: Field;\n refs: EntityRefWithWords[];\n onPick: (picked: EntityRefWithWords) => void;\n}) {\n const allowed = allowedKindsOf(field);\n const kinds = useEntityReferenceKinds();\n const labelOfKind = (token: string) => kinds.data?.find((k) => k.token === token)?.label ?? token.replace(/_/g, \" \");\n const [open, setOpen] = useState(false);\n const [search, setSearch] = useState(\"\");\n // \"Any of them\" first; one kind narrows the list.\n const [only, setOnly] = useState<string | null>(null);\n const tokens = only ? [only] : allowed;\n const found = useEntityReferenceSearch(tokens, search, open);\n const multi = Boolean(field.multi);\n const items = (found.data ?? []).map((r) => ({\n id: `${r.token}:${r.id}`,\n label: r.label ?? WITHHELD_ENTITY_LABEL,\n detail: allowed.length > 1 ? labelOfKind(r.token) : null,\n picked: refs.some((x) => x.token === r.token && x.id === r.id),\n attrs: { \"data-entity-reference-candidate\": `${r.token}:${r.id}` },\n }));\n const kindChoice =\n allowed.length > 1 ? (\n allowed.length <= 4 ? (\n <div className=\"mb-1 flex flex-wrap gap-1\" role=\"group\" aria-label={`Which kind — ${field.label}`}>\n {[null, ...allowed].map((token) => (\n <Button\n key={token ?? \"any\"}\n type=\"button\"\n size=\"sm\"\n variant={only === token ? \"secondary\" : \"ghost\"}\n className=\"h-6 px-2 text-[11px]\"\n aria-pressed={only === token}\n onClick={() => setOnly(token)}\n >\n {token ? labelOfKind(token) : \"Any\"}\n </Button>\n ))}\n </div>\n ) : (\n <PickOne\n label={`Which kind — ${field.label}`}\n className=\"mb-1 w-full\"\n value={only ?? \"\"}\n onChange={(picked) => setOnly(picked || null)}\n options={[{ value: \"\", label: \"Any kind\" }, ...allowed.map((token) => ({ value: token, label: labelOfKind(token) }))]}\n />\n )\n ) : null;\n const notice = (\n <>\n {kindChoice}\n {found.error ? <RefusalLine error={found.error} className=\"px-2 py-1 text-[11px]\" /> : null}\n {found.loading && !found.data ? <p className=\"px-2 py-1 text-[11px] text-muted-foreground\">Searching…</p> : null}\n </>\n );\n const kindWords = allowed.length === 1 ? labelOfKind(allowed[0]!).toLowerCase() : \"thing\";\n return (\n <PickOrAdd\n triggerLabel={`Pick for ${field.label}`}\n triggerText={refs.length > 0 && !multi ? \"Change\" : \"Pick\"}\n open={open}\n onOpenChange={(next) => {\n setOpen(next);\n if (!next) setSearch(\"\");\n }}\n search={search}\n onSearch={setSearch}\n items={items}\n notice={notice}\n empty={\n found.loading ? null : (\n <p className=\"px-2 py-1 text-[11px] text-muted-foreground\">\n {search.trim() ? `No ${kindWords} you can open is called “${search.trim()}”.` : `There is no ${kindWords} you can open yet.`}\n </p>\n )\n }\n onPick={(key) => {\n const r = (found.data ?? []).find((x) => `${x.token}:${x.id}` === key);\n if (!r) return;\n onPick(r);\n if (!multi) setOpen(false);\n }}\n />\n );\n}\n\nfunction Chips({\n field,\n value,\n onChange,\n disabled,\n id,\n className,\n words,\n picker,\n}: EntityReferenceControlProps & { words: Words; picker: ReactNode }) {\n const refs = useMemo(() => entityRefsOf(value), [value]);\n const labelOf = (token: string, refId: string, own: string | null): string => {\n if (own) return own;\n const read = words?.data?.find((w) => w.token === token && w.id === refId)?.label;\n if (read) return read;\n if (words === null) return \"A linked item (its name is read when you are signed in)\";\n if (words.loading) return \"Reading…\";\n return WITHHELD_ENTITY_LABEL;\n };\n const multi = Boolean(field.multi);\n\n return (\n <div id={id} className={cn(\"flex flex-wrap items-center gap-1\", className)} aria-label={`What ${field.label} points at`}>\n {refs.length === 0 && !picker ? <span className=\"text-[11px] text-muted-foreground\">{ENTITY_REFERENCE_EMPTY}</span> : null}\n {refs.map((r) => {\n const label = labelOf(r.token, r.id, r.label);\n return (\n <Badge key={`${r.token}:${r.id}`} variant=\"secondary\" className=\"gap-1 text-[11px]\" data-entity-reference-chip={`${r.token}:${r.id}`}>\n {label}\n {disabled ? null : (\n <button\n type=\"button\"\n className=\"ml-0.5 rounded-sm px-0.5 opacity-70 hover:opacity-100\"\n aria-label={`Take ${label} off`}\n onClick={() => {\n const rest = refs.filter((x) => !(x.token === r.token && x.id === r.id));\n onChange(entityRefsToWrite(rest, multi));\n }}\n >\n ×\n </button>\n )}\n </Badge>\n );\n })}\n {picker}\n </div>\n );\n}\n","\"use client\";\n\n// src/WholeValue.tsx — @ai-matrx/records-ui\n//\n// A VALUE TOO BIG FOR ONE CELL, SHOWN HONESTLY. The store keeps the whole text as a file and the\n// cell holds its first words (`@ai-matrx/records/core` `wholeValueOf`). A cell that drew only the\n// words would pass the start of a 700 KB research text off as the whole value; so it draws the\n// words, then says how big the whole text is and opens it — through the host's page for files\n// (`hrefForFile`). Unbound, it says the whole text is kept as a file this screen cannot open:\n// absent or honest, never a dead link.\n\nimport { useEffect, useState } from \"react\";\nimport type { Field, Uuid } from \"@ai-matrx/records\";\nimport { wholeValueSize, type WholeValuePointer } from \"@ai-matrx/records/core\";\nimport { BasicTextarea } from \"@ai-matrx/design-system\";\nimport { useRecordsUi } from \"./host\";\nimport { fieldName } from \"./names\";\nimport { OutboundLink } from \"@ai-matrx/kit/outbound-react\";\n\nexport const WHOLE_VALUE_UNBOUND =\n \"The whole text is kept as a file, and this screen has no way to open files yet.\";\n\nexport function wholeValueLine(pointer: WholeValuePointer): string {\n return `Open the whole text (${wholeValueSize(pointer)})`;\n}\n\nexport function WholeValueCell({ words, pointer }: { words: string; pointer: WholeValuePointer }) {\n const host = useRecordsUi();\n const href = host.hrefForFile?.({ fileId: pointer.file_id as Uuid });\n const line = wholeValueLine(pointer);\n return (\n <span className=\"flex min-w-0 items-baseline gap-2\" data-whole-value-file={pointer.file_id}>\n <span className=\"truncate\" title={`The first ${pointer.shown_chars} of ${pointer.chars} characters`}>\n {words}…\n </span>\n {href ? (\n host.Link ? (\n host.Link({ href, children: line, className: \"shrink-0 text-xs text-primary underline-offset-2 hover:underline\" })\n ) : (\n <OutboundLink className=\"shrink-0 text-xs text-primary underline-offset-2 hover:underline\" href={href}>\n {line}\n </OutboundLink>\n )\n ) : (\n <span className=\"shrink-0 text-xs italic text-muted-foreground\" title={WHOLE_VALUE_UNBOUND}>\n {`${wholeValueSize(pointer)} in a file`}\n </span>\n )}\n </span>\n );\n}\n\n// ── EDITING A TEXT KEPT AS A FILE (lane BIG-VALUES-WRITE, 2026-09-25) ─────────────────────────\n//\n// A text of any size simply saves: the store keeps the first 1000 characters in the cell and the\n// whole text as a file, behind the scenes. So an editor must never start from those 1000\n// characters — saving them would replace the whole text with its start. It opens the WHOLE text\n// (the host's `readFileText`), and a save writes the whole edited text; the store files it again as\n// the next version. A host that cannot read files gets the words and the link, never an editor\n// that would cut the value.\n\nexport const WHOLE_VALUE_NOT_EDITABLE_HERE =\n \"The whole text is kept as a file. Open it to read it; this screen cannot load it to edit.\";\n\n/** The sentence a person reads while the whole text is being opened. */\nexport function wholeValueOpening(pointer: WholeValuePointer): string {\n return `Opening the whole text (${wholeValueSize(pointer)})…`;\n}\n\nexport type WholeText =\n | { state: \"loading\" }\n | { state: \"ready\"; text: string }\n | { state: \"failed\"; why: string }\n | { state: \"unbound\" };\n\n/** The whole text behind a pointer, read once through the host. */\nexport function useWholeText(pointer: WholeValuePointer | null): WholeText {\n const host = useRecordsUi();\n const read = host.readFileText;\n const fileId = pointer?.file_id ?? null;\n const [answer, setAnswer] = useState<WholeText>({ state: \"loading\" });\n useEffect(() => {\n if (!fileId) return;\n if (!read) {\n setAnswer({ state: \"unbound\" });\n return;\n }\n let live = true;\n setAnswer({ state: \"loading\" });\n read({ fileId: fileId as Uuid }).then(\n (text) => live && setAnswer({ state: \"ready\", text }),\n (thrown: unknown) =>\n live && setAnswer({ state: \"failed\", why: thrown instanceof Error ? thrown.message : String(thrown) }),\n );\n return () => {\n live = false;\n };\n }, [fileId, read]);\n return answer;\n}\n\n/**\n * THE RECORD FORM'S EDITOR FOR A TEXT KEPT AS A FILE. `value` is what the form holds: the stored\n * words until the person types, then what they typed. Until they type, the box shows the whole text\n * read from the file — so nothing is marked changed by opening it.\n */\nexport function WholeValueEditor({\n field,\n pointer,\n words,\n value,\n onChange,\n id,\n disabled,\n}: {\n field: Field;\n pointer: WholeValuePointer;\n words: string;\n value: unknown;\n onChange: (value: unknown) => void;\n id: string;\n disabled?: boolean;\n}) {\n const whole = useWholeText(pointer);\n const touched = typeof value === \"string\" ? value !== words : value !== null && value !== undefined;\n if (touched) {\n return (\n <BasicTextarea\n id={id}\n rows={12}\n value={value === null || value === undefined ? \"\" : String(value)}\n disabled={disabled}\n onChange={(e) => onChange(e.target.value === \"\" ? null : e.target.value)}\n data-whole-value-editor={pointer.file_id}\n />\n );\n }\n if (whole.state === \"ready\") {\n return (\n <BasicTextarea\n id={id}\n rows={12}\n value={whole.text}\n disabled={disabled}\n onChange={(e) => onChange(e.target.value === \"\" ? null : e.target.value)}\n data-whole-value-editor={pointer.file_id}\n aria-label={fieldName(field)}\n />\n );\n }\n return (\n <div id={id} className=\"flex flex-col gap-1 rounded border px-2 py-1.5 text-sm\">\n <WholeValueCell words={words} pointer={pointer} />\n <span className=\"text-xs text-muted-foreground\">\n {whole.state === \"loading\"\n ? wholeValueOpening(pointer)\n : whole.state === \"failed\"\n ? `The whole text could not be opened to edit (${whole.why}). Open it to read it.`\n : WHOLE_VALUE_NOT_EDITABLE_HERE}\n </span>\n </div>\n );\n}\n","\"use client\";\nimport { readableLink } from \"./readableLink\";\n\n// src/formattedValue.tsx — @ai-matrx/records-ui · merge tranche 6e (formats)\n//\n// A VALUE IN THE FORMAT ITS COLUMN SHOWS AS — the older /data grid's `FormattedFieldValue`,\n// rewritten onto the platform registry (`@ai-matrx/design-system/field-formats`) with no app\n// import: a star rating is stars, a progress column is a bar, an email is a mail link, an\n// address opens in maps, a color is its swatch, tags are chips. Everything else is the\n// registry's own text, through the design-system's `FormattedCell`, so the fallback law rides\n// along: a value that does not fit its format is shown as stored, in amber, with the reason.\n//\n// A rating is ONE click from the read view (THE CLICK LAW, inventory A2): given `onRate`, each\n// star is a button that writes its number; without it the stars are a picture.\n\nimport { useRef, type ReactNode } from \"react\";\nimport { FormattedCell } from \"@ai-matrx/design-system/data-table\";\nimport { formatFieldValue, formatPhone, getFieldFormat, type FieldFormatConfig } from \"@ai-matrx/design-system/field-formats\";\nimport { cn } from \"@ai-matrx/design-system\";\nimport { OutboundLink } from \"@ai-matrx/kit/outbound-react\";\n\nimport { fieldLookFor } from \"./looks\";\nimport { LinkPreviewCard } from \"./LinkPreviewCard\";\n\nconst LINK = \"inline-flex min-w-0 items-center gap-1 text-primary hover:underline\";\n\n/** Stop a link's click from also opening the cell or the row behind it. */\nconst own = (event: { stopPropagation: () => void }) => event.stopPropagation();\n\n/** The number a rating or a bar reads, or null. */\nfunction numberOf(value: unknown): number | null {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const n = Number(value.replace(/[,\\s%]/g, \"\"));\n return Number.isFinite(n) ? n : null;\n }\n return null;\n}\n\n/** A star rating. `onRate` makes each star a control; a second press on the chosen star clears it. */\nexport function RatingStars({\n value,\n max = 5,\n onRate,\n label,\n selectFirst,\n}: {\n value: unknown;\n max?: number;\n onRate?: ((next: number | null) => void) | undefined;\n label?: string;\n /**\n * IN A GRID, A CLICK SELECTS (grids review 3, 2026-09-30: one click on a rating cell wrote 4\n * stars). A press on a star of a cell that is not yet the grid's cursor reaches the grid, which\n * selects the cell, and writes nothing; once the cell is selected a star press rates it (Airtable).\n * A keyboard press on a star (`detail === 0`) always rates.\n */\n selectFirst?: boolean | undefined;\n}) {\n // Was this star's cell already the grid's cursor when the pointer came down? Read at the press,\n // before the grid's own mousedown moves the cursor there.\n const armed = useRef(true);\n const score = numberOf(value) ?? 0;\n const shown = Math.round(score);\n const said = `${shown} out of ${max}`;\n return (\n <span\n data-records-rating=\"\"\n role={onRate ? \"radiogroup\" : \"img\"}\n aria-label={label ? `${label}: ${said}` : said}\n title={said}\n className=\"inline-flex items-center gap-0.5\"\n {...(onRate ? { \"data-matrx-cell-control\": \"\" } : {})}\n >\n {Array.from({ length: max }, (_, i) => {\n const n = i + 1;\n const lit = n <= shown;\n const star = (\n <span aria-hidden className={cn(\"text-sm leading-none\", lit ? \"text-amber-400\" : \"text-muted-foreground/40\")}>\n ★\n </span>\n );\n return onRate ? (\n <button\n key={n}\n type=\"button\"\n role=\"radio\"\n aria-checked={n === shown}\n aria-label={`${n} out of ${max}`}\n data-records-rating-star={n}\n className=\"rounded px-px focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring\"\n onMouseDown={(event) => {\n if (!selectFirst) {\n own(event);\n return;\n }\n // The press goes on to the grid, which selects the cell and keeps the keyboard.\n armed.current = event.currentTarget.closest(\"td\")?.hasAttribute(\"data-matrx-cell-active\") === true;\n }}\n onDoubleClick={own}\n onClick={(event) => {\n event.stopPropagation();\n if (selectFirst && event.detail !== 0 && !armed.current) return;\n onRate(n === shown ? null : n);\n }}\n >\n {star}\n </button>\n ) : (\n <span key={n}>{star}</span>\n );\n })}\n </span>\n );\n}\n\n/** The rich drawing for a format that has one, or undefined for the registry's text. */\nfunction rich(id: string, text: string, raw: unknown, format: FieldFormatConfig): ReactNode | undefined {\n switch (id) {\n case \"email\":\n return (\n <a href={`mailto:${text}`} className={LINK} onClick={own}>\n <span className=\"truncate\">{readableLink(text)}</span>\n </a>\n );\n case \"url\":\n // A Link column shown in its \"url\" format is the grid's and the record panel's way to draw a link: the hover\n // card (host `linkPreview` port) rides here too, or the preview never reaches the cell a person sees.\n return (\n <LinkPreviewCard url={text.includes(\"://\") ? text : `https://${text}`}>\n <OutboundLink href={text.includes(\"://\") ? text : `https://${text}`} className={LINK} onClick={own}>\n <span className=\"truncate\">{text}</span>\n </OutboundLink>\n </LinkPreviewCard>\n );\n case \"phone\":\n return (\n <a href={`tel:${text.replace(/[^\\d+]/g, \"\")}`} className={LINK} onClick={own} title={text}>\n <span className=\"truncate tabular-nums\">{formatPhone(text)}</span>\n </a>\n );\n case \"address\":\n return (\n <OutboundLink\n href={`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(text)}`}\n className={LINK}\n title=\"Open in maps\"\n onClick={own}\n >\n <span className=\"truncate\">{text}</span>\n </OutboundLink>\n );\n case \"progress\": {\n const n = numberOf(raw);\n if (n === null) return undefined;\n const pct = format.options?.percentScale === \"fraction\" ? n * 100 : n;\n const clamped = Math.max(0, Math.min(100, pct));\n return (\n <span className=\"inline-flex w-full min-w-0 items-center gap-2\" title={text}>\n <span\n role=\"progressbar\"\n aria-valuemin={0}\n aria-valuemax={100}\n aria-valuenow={Math.round(clamped)}\n className=\"h-1.5 min-w-8 flex-1 overflow-hidden rounded-full bg-muted\"\n >\n <span className={cn(\"block h-full rounded-full\", pct >= 100 ? \"bg-emerald-500\" : \"bg-primary\")} style={{ width: `${clamped}%` }} />\n </span>\n <span className=\"shrink-0 text-xs tabular-nums text-muted-foreground\">{text}</span>\n </span>\n );\n }\n case \"color\":\n return (\n <span className=\"inline-flex items-center gap-1.5\">\n <span className=\"h-4 w-4 shrink-0 rounded border border-border\" style={{ backgroundColor: text }} />\n <code className=\"font-mono text-xs\">{text}</code>\n </span>\n );\n case \"tags\": {\n const items = Array.isArray(raw) ? raw.map(String) : text.split(\",\").map((s) => s.trim()).filter(Boolean);\n if (items.length === 0) return undefined;\n return (\n <span className=\"flex flex-wrap items-center gap-1\">\n {items.map((item, i) => (\n <span key={`${item}-${i}`} className=\"inline-flex items-center rounded-md border border-border bg-muted px-1.5 py-0.5 text-xs\">\n {item}\n </span>\n ))}\n </span>\n );\n }\n case \"rating\":\n return numberOf(raw) === null ? undefined : <RatingStars value={raw} max={format.options?.ratingMax ?? 5} />;\n default:\n return undefined;\n }\n}\n\n/**\n * ONE VALUE, DRAWN IN ITS FORMAT. `null` when there is no format (the caller keeps its own\n * drawing); otherwise never blank and never a throw.\n */\nexport function FormattedValue({\n value,\n format,\n onRate,\n selectFirst,\n}: {\n value: unknown;\n format: FieldFormatConfig;\n /** A rating's one-click write, when this person may change the value. */\n onRate?: ((next: number | null) => void) | undefined;\n /** In a grid: the first press selects the cell, a press on the selected cell rates (`RatingStars`). */\n selectFirst?: boolean | undefined;\n}): ReactNode {\n const def = getFieldFormat(format.id);\n // A rating a person may change is stars even when empty — the empty stars ARE the control.\n // (A stored score outside 0…max is not a rating: it falls to the registry's amber below, so a\n // 1250 never draws as five lit stars.)\n const score = numberOf(value);\n const max = format.options?.ratingMax ?? 5;\n if (def?.id === \"rating\" && onRate && (value === null || value === undefined || value === \"\" || (score !== null && score >= 0 && score <= max))) {\n return <RatingStars value={value} max={format.options?.ratingMax ?? 5} onRate={onRate} selectFirst={selectFirst} />;\n }\n const result = formatFieldValue(value, format);\n if (!result.ok || result.empty || !def?.rich) return <FormattedCell result={result} />;\n // A PLUG-IN LOOK (`looks/`) draws first: the design tokens, and any look a host registered.\n const look = fieldLookFor(def.id);\n // Drawn as a COMPONENT (never called), so a host's look may use hooks. The format already read the\n // value (result.ok above), so the look always has something to draw.\n if (look) {\n const View = look.View;\n return <View value={value} format={format} />;\n }\n return rich(def.id, result.text, value, format) ?? <FormattedCell result={result} />;\n}\n\n/** What a link chip says: the site, and the page or file when there is one (\"unsplash.com · photo.jpg\"). */\nexport function linkChipText(raw: string): string {\n try {\n const url = new URL(raw.includes(\"://\") ? raw : `https://${raw}`);\n const host = url.hostname.replace(/^www\\./, \"\");\n const last = url.pathname.split(\"/\").filter(Boolean).pop();\n return last ? `${host} · ${decodeURIComponent(last)}` : host;\n } catch {\n return raw;\n }\n}\n","\"use client\";\n\n// LinkPreviewCard — Airtable's \"Preview links\" on a URL cell (lane AT-SHARE). Hovering the chip asks the host's\n// `linkPreview` port for the page's metadata ONCE per address and shows a card: site icon, title, description, image.\n// The host reads it through the server; the browser never fetches the page. No port, or nothing to show: the chip alone.\n\nimport { useEffect, useRef, useState, type ReactNode } from \"react\";\nimport { HoverCard, HoverCardContent, HoverCardTrigger, SiteIcon } from \"@ai-matrx/design-system\";\n\nimport { useRecordsUi } from \"./host\";\n\ntype Preview = {\n title: string | null;\n description: string | null;\n siteName: string | null;\n faviconUrl: string | null;\n imageUrl: string | null;\n};\n\n/** One answer per address for the life of the page: asked once, remembered, a failure is \"nothing to show\". */\nconst answers = new Map<string, Promise<Preview | null>>();\n\nexport function LinkPreviewCard({ url, children }: { url: string; children: ReactNode }) {\n const port = useRecordsUi().linkPreview;\n const [preview, setPreview] = useState<Preview | null | undefined>(undefined);\n const [open, setOpen] = useState(false);\n const timer = useRef<ReturnType<typeof setTimeout> | null>(null);\n useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []);\n if (!port) return <>{children}</>;\n const ask = () => {\n if (preview !== undefined) return;\n let pending = answers.get(url);\n if (!pending) {\n pending = port.read(url).catch(() => null);\n answers.set(url, pending);\n }\n void pending.then((found) => setPreview(found));\n };\n const enter = () => {\n ask();\n if (timer.current) clearTimeout(timer.current);\n timer.current = setTimeout(() => setOpen(true), 350);\n };\n const leave = () => {\n if (timer.current) clearTimeout(timer.current);\n setOpen(false);\n };\n const shown = preview && (preview.title || preview.description || preview.imageUrl) ? preview : null;\n return (\n <HoverCard open={open && shown !== null} onOpenChange={(next) => (next ? undefined : setOpen(false))}>\n <HoverCardTrigger asChild>\n <span className=\"inline-flex min-w-0 max-w-full\" onMouseEnter={enter} onMouseLeave={leave} onFocus={enter} onBlur={leave}>\n {children}\n </span>\n </HoverCardTrigger>\n {shown ? (\n <HoverCardContent align=\"start\" className=\"w-72 space-y-1.5 p-2 text-xs\" data-records-link-preview=\"\">\n {shown.imageUrl ? (\n // eslint-disable-next-line @next/next/no-img-element\n <img src={shown.imageUrl} alt=\"\" className=\"h-28 w-full rounded object-cover\" referrerPolicy=\"no-referrer\" />\n ) : null}\n <div className=\"flex items-center gap-1.5\">\n <SiteIcon site={url} iconUrl={shown.faviconUrl} className=\"h-3.5 w-3.5\" />\n <span className=\"truncate text-muted-foreground\">{shown.siteName ?? \"\"}</span>\n </div>\n {shown.title ? <div className=\"line-clamp-2 font-medium\">{shown.title}</div> : null}\n {shown.description ? <div className=\"line-clamp-3 text-muted-foreground\">{shown.description}</div> : null}\n </HoverCardContent>\n ) : null}\n </HoverCard>\n );\n}\n","\"use client\";\n\n// src/gridAttachments.tsx — @ai-matrx/records-ui · one-grid merge, host port `pickFiles`\n//\n// A FILE COLUMN: ITS CHIPS, AND HOW A FILE GETS INTO IT.\n//\n// An attachment column is a relation to the kernel File Table (REC-31). The store turns the id a\n// writer actually holds — a file from the host's file service — into that File record at every\n// write door (`custom.relation_kernel_record`), and the File record keeps the host's file id in\n// its own document (`file_id`). So:\n// · A CHIP names the File record and opens the host's page for its file (`hrefForFile`). Unbound,\n// the chip is plain words that say the file cannot be opened here — never a dead link.\n// · THE EDITOR adds files through the host's own file window (`pickFiles`, Airtable's \"Attach\"\n// over the person's own files) and/or a fresh upload (`upload`). Whatever the host returns is\n// written as the cell's value through the grid's one-cell write, so the store's attachment door\n// decides and refuses in its own words. With neither port bound the editor offers no chooser\n// at all and says so (`NO_UPLOAD_REASON`) — absent or honest, never dead.\n\nimport { useEffect, useRef, useState, type MouseEvent as ReactMouseEvent } from \"react\";\nimport type { Field, RecordDocument, Uuid } from \"@ai-matrx/records\";\nimport { useOptionalRecordsClient } from \"@ai-matrx/records/react\";\nimport { Badge, Button, cn, Dialog, DialogContent, DialogHeader, DialogTitle } from \"@ai-matrx/design-system\";\n\nimport { NO_UPLOAD_REASON, useRecordsUi } from \"./host\";\nimport { idsOf } from \"./labels\";\nimport { fieldName } from \"./names\";\nimport { FilePicker } from \"./FilePicker\";\nimport { RefusalLine } from \"./Refusal\";\nimport { refusal as refusalOf } from \"./refusals\";\nimport { refusalSentence } from \"./plainWords\";\nimport { OutboundLink } from \"@ai-matrx/kit/outbound-react\";\n\n/** The ids an attachment cell holds, in order: File record ids (or a host file id not yet written). */\nexport function attachmentIdsOf(value: unknown): string[] {\n return idsOf(value);\n}\n\n/** What an attachment cell writes after adding `added` to what it holds. */\nexport function withAttached(field: Field, value: unknown, added: readonly string[]): unknown {\n const held = attachmentIdsOf(value);\n if (!field.multi) return added.length > 0 ? added[added.length - 1]! : (held[0] ?? null);\n const next = [...held];\n for (const id of added) if (!next.includes(id)) next.push(id);\n return next.length > 0 ? next : null;\n}\n\n/** What an attachment cell writes after taking `removed` out. */\nexport function withoutAttached(field: Field, value: unknown, removed: string): unknown {\n const next = attachmentIdsOf(value).filter((id) => id !== removed);\n if (!field.multi) return next[0] ?? null;\n return next.length > 0 ? next : null;\n}\n\n/**\n * THE APP'S FILE IDS THIS SCREEN WAS JUST HANDED (merged-grid review 2, fix lane F item 4). A cell\n * holds File record ids, but right after \"Attach files…\" / an upload it briefly holds the host's own\n * file ids — the store turns each into its File record at the write door. A chip must not ask the\n * record door about those (every attach logged a 403 \"You do not have access to this record\"): it\n * opens them as the host's files. Filled by the editor below; ids live for the page's lifetime.\n */\nconst handedHostFileIds = new Set<string>();\n\n/** Remember ids the host handed back as ITS file ids (`pickFiles`, `upload`). */\nexport function rememberHostFileIds(ids: readonly string[]): void {\n for (const id of ids) handedHostFileIds.add(id);\n}\n\n/** The words a chip reads while (or when) a File record cannot be read. */\nexport const FILE_CHIP_UNREAD = \"File\";\n/** A chip's hover when the host has no page for files. */\nexport const FILE_CHIP_NO_PAGE = \"This screen has no way to open files yet.\";\n\ntype FileRead = { name: string | null; fileId: string | null; why: string | null; mime: string | null };\n\n/** The File record behind one attachment id: its name and the host's own file id. */\nexport function useFileRead(id: string): FileRead | null {\n const client = useOptionalRecordsClient();\n const [read, setRead] = useState<FileRead | null>(null);\n useEffect(() => {\n let cancelled = false;\n if (handedHostFileIds.has(id)) {\n // The host's own file id, not a File record yet: it opens as itself, and nobody asks the\n // record door about an id that is not a record.\n setRead({ name: null, fileId: id, why: null, mime: null });\n return;\n }\n if (!client) {\n setRead({ name: null, fileId: null, why: null, mime: null });\n return;\n }\n void client.recordRead({ record_id: id as Uuid }).then((answered) => {\n if (cancelled) return;\n if (!answered.ok) {\n // Not a File record (yet): a host file id written a moment ago opens as itself.\n setRead({ name: null, fileId: id, why: refusalSentence(answered.error), mime: null });\n return;\n }\n const doc = (answered.data.document ?? {}) as RecordDocument;\n const fileId = typeof doc[\"file_id\"] === \"string\" ? (doc[\"file_id\"] as string) : null;\n const name = typeof doc[\"name\"] === \"string\" && doc[\"name\"] !== \"\" ? (doc[\"name\"] as string) : null;\n const mime = typeof doc[\"mime\"] === \"string\" ? (doc[\"mime\"] as string) : null;\n setRead({ name, fileId, why: null, mime });\n });\n return () => {\n cancelled = true;\n };\n }, [client, id]);\n return read;\n}\n\n/**\n * ONE FILE: the File record's own name, opening the host's page for its file. A File record the\n * reader may not open reads the store's refusal on hover, never a guessed name.\n */\nexport function AttachmentChip({ id, onRemove, onPreview }: { id: string; onRemove?: (() => void) | undefined; onPreview?: (() => void) | undefined }) {\n const host = useRecordsUi();\n const read = useFileRead(id);\n const words = read?.name ?? (read ? FILE_CHIP_UNREAD : \"…\");\n const href = read?.fileId ? host.hrefForFile?.({ fileId: read.fileId as Uuid }) : undefined;\n const title = onPreview ? `Preview ${words}` : href ? `Open ${words}` : read?.why ?? FILE_CHIP_NO_PAGE;\n // AN IMAGE IS SEEN, NOT NAMED (Airtable): drawn through the host's one file element (`fileImage`, the media lane's\n // InlineMediaRef — never a renderer of this package's own). Its size follows where it sits: the grid's row height in\n // a cell (`data-matrx-cell-lines`), larger everywhere else (the record page).\n if (read?.fileId && read.mime?.startsWith(\"image/\") && host.fileImage) {\n return (\n <span className=\"relative inline-flex shrink-0\" data-records-file-thumb={id}>\n <button\n type=\"button\"\n title={title}\n aria-label={onPreview ? `Preview ${words}` : words}\n className={cn(\n \"relative block size-20 overflow-hidden rounded-md border bg-muted\",\n \"[[data-matrx-cell-lines]_&]:size-6 [[data-matrx-cell-lines=two]_&]:size-10 [[data-matrx-cell-lines=four]_&]:size-[4.5rem] [[data-matrx-cell-lines=six]_&]:size-24\",\n )}\n onClick={(event) => {\n event.stopPropagation();\n onPreview?.();\n }}\n onMouseDown={(event) => event.stopPropagation()}\n onDoubleClick={(event) => event.stopPropagation()}\n {...(onPreview ? { \"data-records-file-preview\": id } : {})}\n >\n {host.fileImage({ fileId: read.fileId as Uuid, alt: words })}\n </button>\n {onRemove ? (\n <button\n type=\"button\"\n aria-label={`Remove ${words}`}\n className=\"absolute -right-1 -top-1 rounded-full border bg-background px-1 text-[10px] leading-4 text-muted-foreground hover:text-foreground\"\n onClick={(event) => {\n event.stopPropagation();\n onRemove();\n }}\n >\n ×\n </button>\n ) : null}\n </span>\n );\n }\n return (\n <Badge\n variant=\"secondary\"\n className={cn(\"max-w-[14rem] gap-1 text-[11px]\", onPreview && \"cursor-pointer\")}\n data-records-file-chip={id}\n title={title}\n // THE WHOLE CHIP IS THE TARGET (lane AT-UIFIX item 2): only the words were a button, so a click on the chip's\n // padding fell through to the cell (which just selected itself) and the viewer opened only from a second,\n // luckier click. The press never reaches the grid, so the cell does not take focus from the viewer.\n {...(onPreview\n ? {\n onClick: (event: ReactMouseEvent) => {\n event.stopPropagation();\n onPreview();\n },\n onMouseDown: (event: ReactMouseEvent) => event.stopPropagation(),\n onDoubleClick: (event: ReactMouseEvent) => event.stopPropagation(),\n }\n : {})}\n >\n {onPreview ? (\n <button\n type=\"button\"\n className=\"truncate underline-offset-2 hover:underline\"\n data-records-file-preview={id}\n onClick={(event) => {\n event.stopPropagation();\n onPreview();\n }}\n onMouseDown={(event) => event.stopPropagation()}\n onDoubleClick={(event) => event.stopPropagation()}\n >\n {words}\n </button>\n ) : href ? (\n <OutboundLink\n href={href}\n className=\"truncate underline-offset-2 hover:underline\"\n data-records-file-link={read?.fileId ?? \"\"}\n onClick={(event) => event.stopPropagation()}\n onMouseDown={(event) => event.stopPropagation()}\n >\n {words}\n </OutboundLink>\n ) : (\n <span className=\"truncate\">{words}</span>\n )}\n {onRemove ? (\n <button\n type=\"button\"\n aria-label={`Remove ${words}`}\n className=\"shrink-0 rounded px-0.5 text-muted-foreground hover:text-foreground\"\n onClick={(event) => {\n event.stopPropagation();\n onRemove();\n }}\n >\n ×\n </button>\n ) : null}\n </Badge>\n );\n}\n\n/** Every file a cell holds, as chips. A click opens the viewer over THIS cell's files (arrows step through them). */\nexport function AttachmentChips({ value, onRemove }: { value: unknown; onRemove?: ((id: string) => void) | undefined }) {\n const host = useRecordsUi();\n const ids = attachmentIdsOf(value);\n const [viewing, setViewing] = useState<number | null>(null);\n if (ids.length === 0) return null;\n const canPreview = Boolean(host.fileImage);\n return (\n <span className=\"flex flex-wrap gap-1\" data-records-file-chips=\"\">\n {ids.map((id, index) => (\n <AttachmentChip\n key={id}\n id={id}\n {...(onRemove ? { onRemove: () => onRemove(id) } : {})}\n {...(canPreview ? { onPreview: () => setViewing(index) } : {})}\n />\n ))}\n {viewing !== null && canPreview ? (\n <AttachmentViewer ids={ids} index={Math.min(viewing, ids.length - 1)} onIndex={setViewing} onClose={() => setViewing(null)} />\n ) : null}\n </span>\n );\n}\n\n/** Step through `ids` by `way`, stopping at both ends (never wrapping). */\nexport function stepAttachment(index: number, total: number, way: -1 | 1): number {\n return Math.max(0, Math.min(total - 1, index + way));\n}\n\n/**\n * THE ATTACHMENT VIEWER (AT-RECORD item 4): one file large, with arrows across the cell's files. It draws\n * through the host's own file element (`fileImage`, the media lane's InlineMediaRef) — never a renderer of\n * its own — and opens the host's file page from a link.\n */\nexport function AttachmentViewer({\n ids,\n index,\n onIndex,\n onClose,\n}: {\n ids: string[];\n index: number;\n onIndex: (index: number) => void;\n onClose: () => void;\n}) {\n const host = useRecordsUi();\n const id = ids[index]!;\n const read = useFileRead(id);\n const name = read?.name ?? (read ? FILE_CHIP_UNREAD : \"…\");\n const href = read?.fileId ? host.hrefForFile?.({ fileId: read.fileId as Uuid }) : undefined;\n const go = (way: -1 | 1) => onIndex(stepAttachment(index, ids.length, way));\n return (\n <Dialog open onOpenChange={(open) => !open && onClose()}>\n <DialogContent\n className=\"sm:max-w-3xl\"\n data-records-attachment-viewer={id}\n // FOCUS GOES INTO THE VIEWER WHEN IT OPENS (so Esc and the arrows reach it) and BACK TO THE CHIP THAT OPENED IT\n // when it closes, never to the grid's key catcher behind it.\n tabIndex={-1}\n onOpenAutoFocus={(event) => {\n event.preventDefault();\n (event.currentTarget as HTMLElement).focus();\n }}\n onCloseAutoFocus={(event) => {\n const chip = document.querySelector<HTMLElement>(`[data-records-file-preview=\"${ids[index]}\"]`);\n if (chip) {\n event.preventDefault();\n chip.focus();\n }\n }}\n onKeyDown={(event) => {\n if (event.key === \"ArrowLeft\") {\n event.preventDefault();\n go(-1);\n } else if (event.key === \"ArrowRight\") {\n event.preventDefault();\n go(1);\n }\n }}\n onClick={(event) => event.stopPropagation()}\n >\n <DialogHeader>\n <DialogTitle className=\"truncate text-sm\">{name}</DialogTitle>\n </DialogHeader>\n <div className=\"relative h-[60vh] w-full overflow-hidden rounded-md bg-muted\" data-records-attachment-stage=\"\">\n {read?.fileId ? host.fileImage?.({ fileId: read.fileId as Uuid, alt: name }) : null}\n </div>\n <div className=\"flex items-center gap-2\">\n <Button size=\"sm\" variant=\"outline\" aria-label=\"Previous file\" disabled={index === 0} onClick={() => go(-1)} data-records-attachment-previous=\"\">\n ←\n </Button>\n <Button size=\"sm\" variant=\"outline\" aria-label=\"Next file\" disabled={index >= ids.length - 1} onClick={() => go(1)} data-records-attachment-next=\"\">\n →\n </Button>\n <span className=\"text-xs tabular-nums text-muted-foreground\" data-records-attachment-position=\"\">\n {index + 1} of {ids.length}\n </span>\n {href ? (\n <OutboundLink href={href} className=\"ml-auto text-xs underline-offset-2 hover:underline\">\n Open in new tab\n </OutboundLink>\n ) : null}\n </div>\n </DialogContent>\n </Dialog>\n );\n}\n\n/** Does this host have any way to put a file into a cell? */\nexport function hostTakesFiles(host: { pickFiles?: unknown; upload?: unknown }): boolean {\n return Boolean(host.pickFiles || host.upload);\n}\n\n/**\n * THE ATTACHMENT EDITOR. `autoOpen` (a grid cell opened by a click or Enter): the host's file\n * window opens at once, and whatever is picked is the commit (`onClose`), exactly as a choice\n * cell's list does. A canceled window closes the cell with nothing changed.\n */\nexport function AttachmentControl({\n field,\n value,\n onChange,\n disabled,\n id,\n autoOpen,\n onClose,\n}: {\n field: Field;\n value: unknown;\n onChange: (value: unknown) => void;\n disabled?: boolean | undefined;\n id?: string | undefined;\n autoOpen?: boolean | undefined;\n onClose?: (() => void) | undefined;\n}) {\n const host = useRecordsUi();\n const [busy, setBusy] = useState(false);\n const [why, setWhy] = useState<string | null>(null);\n const latest = useRef(value);\n latest.current = value;\n const multiple = Boolean(field.multi);\n\n const pick = async () => {\n if (!host.pickFiles || disabled) return;\n setBusy(true);\n setWhy(null);\n try {\n const picked = await host.pickFiles({ multiple });\n if (picked && picked.length > 0) {\n rememberHostFileIds(picked);\n onChange(withAttached(field, latest.current, picked));\n }\n } catch (cause) {\n setWhy(cause instanceof Error ? cause.message : String(cause));\n setBusy(false);\n return;\n }\n setBusy(false);\n onClose?.();\n };\n\n const opened = useRef(false);\n useEffect(() => {\n if (!autoOpen || opened.current || !host.pickFiles) return;\n opened.current = true;\n void pick();\n // Once per opening of the cell.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [autoOpen]);\n\n if (!hostTakesFiles(host)) {\n return (\n <p id={id} className=\"rounded border border-dashed px-2 py-1 text-xs text-muted-foreground\" data-records-no-file-door=\"\">\n {NO_UPLOAD_REASON}\n </p>\n );\n }\n\n return (\n <span id={id} className=\"flex flex-col gap-1\" data-records-attachment-editor=\"\">\n <AttachmentChips\n value={value}\n {...(disabled ? {} : { onRemove: (removed: string) => onChange(withoutAttached(field, latest.current, removed)) })}\n />\n <span className=\"flex flex-wrap items-center gap-1\">\n {host.pickFiles ? (\n <Button size=\"sm\" variant=\"outline\" disabled={disabled || busy} onClick={() => void pick()} data-records-attach-files=\"\">\n {busy ? \"Choosing…\" : attachmentIdsOf(value).length > 0 ? \"Add files…\" : \"Attach files…\"}\n </Button>\n ) : null}\n {host.upload ? (\n <FilePicker\n label=\"Upload a file\"\n inputLabel={`Upload a file to ${fieldName(field)}`}\n disabled={disabled || busy}\n onFile={(file) => {\n setBusy(true);\n setWhy(null);\n void host.upload!(file).then((result) => {\n setBusy(false);\n if (result.ok) {\n rememberHostFileIds([result.fileId]);\n onChange(withAttached(field, latest.current, [result.fileId]));\n }\n else setWhy(result.reason);\n });\n }}\n />\n ) : null}\n </span>\n {why ? <RefusalLine error={refusalOf(\"invalid_argument\", why, \"Pick another file, or try this one again.\")} /> : null}\n </span>\n );\n}\n","\"use client\";\n\n// src/ReferenceChips.tsx — @ai-matrx/records-ui · lane REFERENCE-CARRY\n//\n// A REFERENCE IS A CHIP THAT OPENS WHAT IT NAMES — wherever a value is read (grid cell, peek, record\n// panel, card). Two store declarations carry a reference (PROGRESS-REFERENCE-CARRY §D.1): a\n// `relation` Field holds record ids of one Table, an entity reference holds `{token, id}` of any\n// platform thing. A person sees ONE thing — a chip with the thing's own words — and the host's\n// `renderReference` port makes it a door (route, new tab, peek). Before this a relation cell drew\n// gray text badges that opened nothing, and a many-relation read \"2 of them\".\n//\n// Also here: `KindValueCell`, a cell whose value names its own shape (`kindValues.ts`), drawn by the\n// host's kind system (`renderKind`) — never the raw ```matrx fence.\n\nimport type { ReactNode } from \"react\";\nimport { entityRefsOf, type Field } from \"@ai-matrx/records\";\nimport { Badge, Skeleton, cn } from \"@ai-matrx/design-system\";\nimport { useRecordsUi, type ReferenceChipRef } from \"./host\";\nimport { isId, type LabelLookup } from \"./labels\";\nimport { WITHHELD_ENTITY_LABEL } from \"./EntityReferenceControl\";\nimport { useEmbeddedLook } from \"./embeddedLook\";\nimport { kindItemWords, kindLabel, kindValueWords, type KindValue } from \"./kindValues\";\n\n/**\n * NOTION'S ORDER: the related record's own icon, else its table's, else (the chip's) page glyph. Only\n * a drawable GLYPH counts — an emoji or short symbol; a table's icon kept as an icon NAME\n * (\"graduation-cap\") is not a glyph and falls through to the next.\n */\nexport function glyphOf(icon: string | null | undefined): string | null {\n const text = (icon ?? \"\").trim();\n return text !== \"\" && text.length <= 8 && /[^\\u0000-\\u007f]/.test(text) ? text : null;\n}\n/** The icon an icon-NAME is kept as (\"Briefcase\"): a word a host's `renderIcon` may draw. */\nfunction nameOf(icon: string | null | undefined): string | null {\n const text = (icon ?? \"\").trim();\n return /^[A-Za-z][A-Za-z0-9_-]{1,40}$/.test(text) ? text : null;\n}\nfunction iconOf(pair: { icon: string | null; tableIcon: string | null } | undefined): { icon?: string } {\n // The record's own icon first, whichever way it is kept; then its table's.\n const own = glyphOf(pair?.icon) ?? nameOf(pair?.icon);\n const table = glyphOf(pair?.tableIcon) ?? nameOf(pair?.tableIcon);\n const chosen = own ?? table;\n return chosen ? { icon: chosen } : {};\n}\n\n/** The references a relation or entity-reference value names, in the order it holds them. */\nexport function referenceChipsOf(field: Field, value: unknown, kind: string, labels?: LabelLookup): ReferenceChipRef[] {\n if (kind === \"entity_reference\") {\n return entityRefsOf(value).map((r) => ({ token: r.token, id: r.id, label: r.label }));\n }\n const ids = (Array.isArray(value) ? value : [value]).filter(isId).map(String);\n const tableId = typeof field.relation_target === \"string\" ? field.relation_target : undefined;\n return ids.map((id) => ({\n token: \"record\",\n id,\n label: labels?.(field, id) ?? null,\n tableId,\n ...iconOf(labels?.icons?.(field, id)),\n ...(labels?.archived?.(field, id) ? { archived: true } : {}),\n }));\n}\n\n/** The word an archived reference wears, and its one-sentence tooltip. */\nexport const ARCHIVED_REFERENCE_WORD = \"Archived\";\nexport const ARCHIVED_REFERENCE_TIP = \"In the Archived view; restore it to use it again\";\n\n/** A plain page glyph (Lucide file-text geometry), for a related record that has no icon. */\nfunction PageGlyph() {\n return (\n <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\" width={14} height={14} fill=\"none\" stroke=\"currentColor\" strokeWidth={2} strokeLinecap=\"round\" strokeLinejoin=\"round\" data-records-page-glyph=\"\">\n <path d=\"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z\" />\n <path d=\"M14 2v4a2 2 0 0 0 2 2h4\" />\n <path d=\"M10 13H8\" /><path d=\"M16 17H8\" />\n </svg>\n );\n}\n\n/** One chip. The host's door when it has one; otherwise the words, and nothing that looks openable. */\nexport function ReferenceChip({ reference, waiting }: { reference: ReferenceChipRef; waiting?: string | null | undefined }) {\n const host = useRecordsUi();\n const look = useEmbeddedLook();\n // A NAME ON ITS WAY IS A PULSE INSIDE THE CHIP, never the word \"Loading…\" in a capsule\n // (STABLE-TABLES, night walk 2026-10-06): the chip and its door are there; the name lands in the\n // box the placeholder held.\n const pending = reference.label == null && reference.token === \"record\" && !waiting && !host.renderReference;\n const pendingMark = <Skeleton aria-label=\"Loading\" data-records-reference-pending=\"\" className=\"inline-block h-3 w-16 shrink-0 rounded-sm align-middle\" />;\n const words = reference.label ?? (reference.token === \"record\" ? (waiting ?? \"Loading…\") : WITHHELD_ENTITY_LABEL);\n const drawn: ReactNode = host.renderReference ? host.renderReference({ ...reference, label: reference.label ?? words }) : null;\n // EMBEDDED (`embeddedLook.tsx` `plainRelation`): Notion's relation — icon, then title, nothing else.\n if (look?.plainRelation) {\n return (\n <span\n className={cn(\n \"inline-flex max-w-full min-w-0 items-center gap-1.5 text-sm text-foreground hover:underline [&_a]:text-inherit [&_a]:no-underline [&_a:hover]:underline\",\n reference.archived && \"opacity-70\",\n )}\n data-records-reference-chip={reference.token}\n data-records-reference-plain=\"\"\n data-records-reference-archived={reference.archived ? \"\" : undefined}\n title={reference.archived ? ARCHIVED_REFERENCE_TIP : words}\n >\n <span aria-hidden=\"true\" data-records-reference-icon=\"\" className=\"inline-flex size-4 shrink-0 items-center justify-center text-muted-foreground\">\n {glyphOf(reference.icon) ? <span className=\"text-sm leading-none\">{reference.icon}</span> : (reference.icon && host.renderIcon?.(reference.icon)) || <PageGlyph />}\n </span>\n {drawn ?? (pending ? pendingMark : <span className=\"truncate\">{words}</span>)}\n {reference.archived ? <span className=\"shrink-0 text-muted-foreground\">{ARCHIVED_REFERENCE_WORD}</span> : null}\n </span>\n );\n }\n // AN ARCHIVED RECORD IS STILL NAMED (chair ruling B3-21): the chip keeps its words and door, is\n // drawn muted, and says \"Archived\" — state, not prose. Restoring it brings the plain chip back.\n return (\n <Badge\n variant=\"secondary\"\n className={cn(\n \"max-w-full min-w-0 gap-1 px-1.5 py-0 text-[11px] font-normal\",\n reference.archived && \"opacity-70\",\n )}\n data-records-reference-chip={reference.token}\n data-records-reference-archived={reference.archived ? \"\" : undefined}\n title={reference.archived ? ARCHIVED_REFERENCE_TIP : words}\n >\n {drawn ?? (pending ? pendingMark : <span className=\"truncate\">{words}</span>)}\n {reference.archived ? <span className=\"shrink-0 text-muted-foreground\">{ARCHIVED_REFERENCE_WORD}</span> : null}\n </Badge>\n );\n}\n\n/** Every reference a value holds, as chips (a dash when it holds none). */\nexport function ReferenceChips({ refs, waiting }: { refs: ReferenceChipRef[]; waiting?: string | null | undefined }) {\n if (refs.length === 0) return <span className=\"text-muted-foreground\">—</span>;\n return (\n <span className=\"flex min-w-0 flex-wrap gap-1\" data-records-reference-chips=\"\">\n {refs.map((r) => (\n <ReferenceChip key={`${r.token}:${r.id}`} reference={r} waiting={waiting} />\n ))}\n </span>\n );\n}\n\n/**\n * A CELL HOLDING A KIND. The host's kind system draws it (`renderKind`): a reference directive as\n * chips, any other kind as a compact button that opens the real view. Unbound, a neutral chip names\n * what it is and the raw text is one hover away.\n */\nexport function KindValueCell({\n kv,\n where,\n title,\n}: {\n kv: KindValue;\n where: \"cell\" | \"panel\";\n title: string;\n}) {\n const host = useRecordsUi();\n if (host.renderKind) {\n return <span className=\"flex min-w-0 max-w-full items-center\" data-records-kind-value={kv.kind}>{host.renderKind({ value: kv.value, kind: kv.kind, where, title })}</span>;\n }\n const named = kv.items.map(kindItemWords).filter((w): w is string => w !== null);\n return (\n <span className={cn(\"flex min-w-0 flex-wrap gap-1\")} data-records-kind-value={kv.kind} title={JSON.stringify(kv.value)}>\n {named.length > 0 ? (\n named.map((w, i) => (\n <Badge key={`${w}-${i}`} variant=\"secondary\" className=\"px-1.5 py-0 text-[11px] font-normal\">\n {w}\n </Badge>\n ))\n ) : (\n <Badge variant=\"outline\" className=\"px-1.5 py-0 text-[11px] font-normal\">\n {kindLabel(kv.kind)}\n </Badge>\n )}\n </span>\n );\n}\n\nexport { kindValueWords };\n","\"use client\";\n\n// src/ClampedChips.tsx — @ai-matrx/records-ui · lane CHAIR-GRID-LINKS\n//\n// A LINK CELL IS ONE LINE (champion: Notion's relation cell). As many chips as fit, then a \"+N\"\n// chip that opens the whole list in a popover; the row never grows from a link cell. The \"+N\" is a\n// real button (Tab reaches it, Enter/Space opens, Escape closes), and the popover's chips are the\n// same `ReferenceChip` doors the cell draws.\n//\n// How many fit is measured, not guessed: every chip is drawn once (nowrap, clipped) so its width is\n// known, then the cell keeps the ones that fit beside the \"+N\". A resize measures again.\n\nimport { useCallback, useLayoutEffect, useRef, useState, type ReactNode } from \"react\";\nimport { Popover, PopoverContent, PopoverTrigger, cn } from \"@ai-matrx/design-system\";\n\nconst GAP = 4;\n/** The room the \"+N\" chip is given while measuring. */\nconst OVERFLOW_ROOM = 34;\n\nexport interface ClampedItem {\n key: string;\n node: ReactNode;\n}\n\nexport function ClampedChips({\n items,\n total,\n all,\n className,\n dataAttr,\n}: {\n items: readonly ClampedItem[];\n /** How many the cell stands for, when more than `items` were read (a back-link cell reads a page). */\n total?: number | undefined;\n /** The popover's body. Default: every item, wrapped. */\n all?: ReactNode;\n className?: string | undefined;\n dataAttr?: string | undefined;\n}) {\n const box = useRef<HTMLSpanElement | null>(null);\n const [fit, setFit] = useState<number | null>(null);\n const [measuring, setMeasuring] = useState(true);\n const count = items.length;\n const stands = Math.max(total ?? count, count);\n\n const measure = useCallback(() => {\n const el = box.current;\n if (!el) return;\n // A TALLER ROW (cell lines 2 / 4 / 6) wraps its chips onto lines and cuts at the cap: show them all.\n const lines = el.closest(\"[data-matrx-cell-lines]\")?.getAttribute(\"data-matrx-cell-lines\");\n if (lines && lines !== \"one\") {\n setFit(null);\n setMeasuring(false);\n return;\n }\n const room = el.clientWidth;\n const chips = Array.from(el.querySelectorAll<HTMLElement>(\"[data-clamp-item]\"));\n // No layout (a test DOM, a hidden tab): keep everything the cell was given.\n if (room <= 0 || chips.length === 0) {\n setFit(null);\n setMeasuring(false);\n return;\n }\n const widths = chips.map((c) => c.offsetWidth);\n let used = 0;\n let n = 0;\n for (let i = 0; i < widths.length; i += 1) {\n const next = used + (i > 0 ? GAP : 0) + (widths[i] ?? 0);\n const needsMore = stands - (i + 1) > 0;\n if (next + (needsMore ? GAP + OVERFLOW_ROOM : 0) > room) break;\n used = next;\n n = i + 1;\n }\n // One chip always shows (it truncates by itself); the rest are behind \"+N\".\n setFit(Math.max(1, n));\n setMeasuring(false);\n }, [stands]);\n\n const key = items.map((i) => i.key).join(\"|\");\n // Measure again when what is drawn changes.\n useLayoutEffect(() => {\n setMeasuring(true);\n }, [key, total]);\n useLayoutEffect(() => {\n if (measuring) measure();\n }, [measuring, measure]);\n // And when the column is resized.\n useLayoutEffect(() => {\n const el = box.current;\n if (!el || typeof ResizeObserver === \"undefined\") return;\n let last = el.clientWidth;\n const watcher = new ResizeObserver(() => {\n if (el.clientWidth !== last) {\n last = el.clientWidth;\n setMeasuring(true);\n }\n });\n watcher.observe(el);\n return () => watcher.disconnect();\n }, []);\n\n const shown = measuring || fit === null ? items : items.slice(0, fit);\n const hidden = stands - shown.length;\n return (\n <span\n ref={box}\n className={cn(\"flex min-w-0 max-w-full flex-nowrap items-center gap-1 overflow-hidden [[data-matrx-cell-lines]:not([data-matrx-cell-lines=one])_&]:flex-wrap\", className)}\n data-records-clamped={dataAttr ?? \"\"}\n >\n {shown.map((item) => (\n <span key={item.key} data-clamp-item=\"\" className=\"inline-flex min-w-0 shrink-0 max-w-full\">\n {item.node}\n </span>\n ))}\n {!measuring && hidden > 0 ? (\n <Popover>\n <PopoverTrigger asChild>\n <button\n type=\"button\"\n className=\"shrink-0 rounded-md bg-secondary px-1.5 text-[11px] text-muted-foreground hover:text-foreground focus-visible:outline focus-visible:outline-2 focus-visible:outline-ring\"\n aria-label={`${hidden} more, show all ${stands}`}\n data-records-clamped-more=\"\"\n onClick={(e) => e.stopPropagation()}\n >\n +{hidden}\n </button>\n </PopoverTrigger>\n <PopoverContent sizing=\"content\" align=\"start\" className=\"w-80 max-h-[50dvh] overflow-y-auto p-2\" data-records-clamped-all=\"\">\n {all ?? (\n <span className=\"flex flex-wrap gap-1\">\n {items.map((item) => (\n <span key={item.key} className=\"inline-flex max-w-full min-w-0\">\n {item.node}\n </span>\n ))}\n </span>\n )}\n </PopoverContent>\n </Popover>\n ) : null}\n </span>\n );\n}\n","// src/formulaNames.ts — @ai-matrx/records-ui\n//\n// A FORMULA READS WITH TODAY'S COLUMN NAMES (merged-grid review 2, 2026-09-27, C3).\n//\n// A formula written as `{Quote} * 1.08` kept reading `{Quote}` after the column was renamed\n// \"Quote amount\" — it still computed, because the store keeps the parsed expression by FIELD ID\n// (`config.expr`: `{\"field\": \"<id>\"}` nodes), but the words a person reads were the text as first\n// typed (`config.formula_text`). Airtable and Sheets both show a formula with the column's current\n// name. So the text is DRAWN from the ids: each `{name}` in the text is paired, in order, with the\n// expression's field references (the parser keeps left-to-right order), and a name that no longer\n// belongs to the id it points at is replaced by that id's current label.\n//\n// It changes only what is SHOWN. When the pairing cannot be trusted — the counts differ, or one\n// name would have to become two different columns — the text is shown exactly as it was.\n\nimport { sourceArchivedOf, type Field, type SourceArchived } from \"@ai-matrx/records\";\nimport { fieldName } from \"./names\";\n\n/** Every `{\"field\": id}` in an expression, depth-first, left to right. */\nexport function fieldRefsOf(expr: unknown): string[] {\n const out: string[] = [];\n const walk = (node: unknown) => {\n if (Array.isArray(node)) {\n for (const n of node) walk(n);\n return;\n }\n if (node === null || typeof node !== \"object\") return;\n const obj = node as Record<string, unknown>;\n if (typeof obj[\"field\"] === \"string\" && Object.keys(obj).length === 1) {\n out.push(obj[\"field\"]);\n return;\n }\n for (const value of Object.values(obj)) walk(value);\n };\n walk(expr);\n return out;\n}\n\nconst BRACE = /\\{([^{}]*)\\}/g;\n\n/** The formula's text with every column named as it is called NOW. */\nexport function formulaTextNow(text: string, expr: unknown, fields: readonly Field[] | null | undefined): string {\n if (!text || !fields || fields.length === 0) return text;\n const refs = fieldRefsOf(expr);\n const names = [...text.matchAll(BRACE)].map((m) => m[1] ?? \"\");\n if (refs.length === 0 || refs.length !== names.length) return text;\n const byId = new Map(fields.map((f) => [String(f.id), f]));\n // One stale name must become ONE column; otherwise the pairing is not trusted.\n const becomes = new Map<string, string>();\n const replacement: string[] = [];\n for (let i = 0; i < names.length; i += 1) {\n const name = names[i]!;\n const field = byId.get(refs[i]!);\n if (!field) return text;\n const now = fieldName(field);\n if (now.trim().toLowerCase() === name.trim().toLowerCase()) {\n replacement.push(name);\n continue;\n }\n const seen = becomes.get(name);\n if (seen !== undefined && seen !== now) return text;\n becomes.set(name, now);\n replacement.push(now);\n }\n let i = 0;\n return text.replace(BRACE, () => `{${replacement[i++]}}`);\n}\n\n/** The Field with its formula's text drawn in today's names (a copy; the Field is untouched). */\nexport function withFormulaNamesNow(field: Field, fields: readonly Field[] | null | undefined): Field {\n const config = (field.config ?? {}) as Record<string, unknown>;\n const text = typeof config[\"formula_text\"] === \"string\" ? (config[\"formula_text\"] as string) : \"\";\n if (text === \"\") return field;\n const now = formulaTextNow(text, config[\"expr\"] ?? (field as { expr?: unknown }).expr, fields);\n return now === text ? field : ({ ...field, config: { ...config, formula_text: now } } as Field);\n}\n\n/* ═══ HOW A WORKED-OUT COLUMN SHOWS BY DEFAULT (merged-grid review 2, 2026-09-27, A12) ══════════════\n *\n * A formula over money showed 2,639.875 until somebody set \"Shows as Currency\" by hand, and a row\n * with nothing typed yet showed \"$0.00\". Airtable: a formula's result format follows its inputs\n * (money in, money out) and a formula with nothing to work on is blank. So, when the column's own\n * settings chose no look:\n * · arithmetic over a money column shows as that money; arithmetic over plain numbers shows as a\n * number with the inputs' declared precision (2 when none says);\n * · a row where every column the formula reads is empty shows the cell empty.\n * A look the column's settings chose always wins; a formula that is not plain arithmetic (a\n * comparison, words, a date) keeps the value as the store answers it.\n */\n\n/** The store's arithmetic nodes: a result made only of these is a number. */\nconst ARITHMETIC = new Set([\"fx.add\", \"fx.sub\", \"fx.mul\", \"fx.div\", \"fx.sum\", \"fx.round\", \"fx.min\", \"fx.max\", \"fx.abs\", \"fx.avg\", \"fx.neg\", \"fx.ceil\", \"fx.floor\"]);\n\nfunction opsOf(expr: unknown, out: string[] = []): string[] {\n if (Array.isArray(expr)) for (const n of expr) opsOf(n, out);\n else if (expr && typeof expr === \"object\") {\n const obj = expr as Record<string, unknown>;\n if (typeof obj[\"op\"] === \"string\") out.push(obj[\"op\"]);\n for (const value of Object.values(obj)) if (value && typeof value === \"object\") opsOf(value, out);\n }\n return out;\n}\n\nfunction exprOf(field: Field): unknown {\n const config = (field.config ?? {}) as Record<string, unknown>;\n return config[\"expr\"] ?? (field as { expr?: unknown }).expr;\n}\n\n/** The columns a formula reads, as Fields (in order, once each); `null` when one cannot be found. */\nexport function formulaInputs(field: Field, fields: readonly Field[] | null | undefined): Field[] | null {\n const refs = fieldRefsOf(exprOf(field));\n if (refs.length === 0 || !fields) return null;\n const byId = new Map(fields.map((f) => [String(f.id), f]));\n const out: Field[] = [];\n for (const id of new Set(refs)) {\n const f = byId.get(id);\n if (!f) return null;\n out.push(f);\n }\n return out;\n}\n\nconst NUMERIC_KINDS = new Set([\"number\", \"currency\", \"percent\"]);\n\n/** The default look of a formula's result, from its inputs — or `undefined` to leave it as answered. */\nexport function formulaDefaultFormat(\n field: Field,\n fields: readonly Field[] | null | undefined,\n kindOf: (f: Field) => string,\n currencyCodeOf: (unit: string | null | undefined) => string,\n): { id: string; options?: Record<string, unknown> } | undefined {\n const inputs = formulaInputs(field, fields);\n if (!inputs || inputs.length === 0) return undefined;\n const ops = opsOf(exprOf(field));\n if (ops.length === 0 || !ops.every((op) => ARITHMETIC.has(op))) return undefined;\n if (!inputs.every((f) => NUMERIC_KINDS.has(kindOf(f)))) return undefined;\n const precisions = inputs\n .map((f) => ((f as unknown as { display_format?: { options?: { precision?: unknown } } }).display_format?.options?.precision))\n .filter((p): p is number => typeof p === \"number\");\n const precision = precisions.length > 0 ? Math.max(...precisions) : 2;\n // Money is a money column, or a number column whose settings show it as money.\n const lookOf = (f: Field) => (f as unknown as { display_format?: { id?: unknown; options?: { currency?: unknown } } }).display_format;\n const money = inputs.find((f) => kindOf(f) === \"currency\" || lookOf(f)?.id === \"currency\");\n if (money) {\n const code = lookOf(money)?.options?.currency;\n return { id: \"currency\", options: { currency: typeof code === \"string\" && code !== \"\" ? code : currencyCodeOf(money.unit) } };\n }\n return { id: \"decimal\", options: { precision } };\n}\n\n/** The keys a formula reads, stamped on the drawn copy so a cell can tell \"nothing to work on\". */\nexport const FORMULA_INPUT_KEYS = \"__formula_input_keys\";\n\n/** True when every column this formula reads is empty on this record: the cell is drawn empty. */\nexport function formulaHasNothingToWorkOn(field: Field, document: Record<string, unknown> | null | undefined): boolean {\n const keys = ((field.config ?? {}) as Record<string, unknown>)[FORMULA_INPUT_KEYS];\n if (!Array.isArray(keys) || keys.length === 0 || !document) return false;\n return keys.every((key) => {\n const v = document[String(key)];\n return v === null || v === undefined || v === \"\" || (Array.isArray(v) && v.length === 0);\n });\n}\n\n/**\n * A FORMULA THAT READS A COLUMN WHOSE SOURCE IS ARCHIVED (v7 TABLE-EXPERIENCE item 7, Law 4): the\n * first input holding the store's \"source archived\" answer, so an empty formula cell says why\n * instead of drawing a blank. Null when none does (or the inputs are not known on this copy).\n */\nexport function formulaSourceArchived(field: Field, document: Record<string, unknown> | null | undefined): SourceArchived | null {\n const keys = ((field.config ?? {}) as Record<string, unknown>)[FORMULA_INPUT_KEYS];\n if (!Array.isArray(keys) || !document) return null;\n for (const key of keys) {\n const state = sourceArchivedOf(document[String(key)]);\n if (state) return state;\n }\n return null;\n}\n\n/**\n * THE ONE DRAWN COPY OF A WORKED-OUT COLUMN: today's names in its text, its default look when its\n * settings chose none, and the keys it reads. Every other column comes back untouched.\n */\nexport function withFormulaDisplayNow(\n field: Field,\n fields: readonly Field[] | null | undefined,\n kindOf: (f: Field) => string,\n currencyCodeOf: (unit: string | null | undefined) => string,\n): Field {\n if (kindOf(field) !== \"formula\") return field;\n let next = withFormulaNamesNow(field, fields);\n const inputs = formulaInputs(field, fields);\n const config = (next.config ?? {}) as Record<string, unknown>;\n if (inputs && inputs.length > 0) next = { ...next, config: { ...config, [FORMULA_INPUT_KEYS]: inputs.map((f) => f.key) } } as Field;\n const chosen = (field as unknown as { display_format?: { id?: unknown } }).display_format;\n const hasLook = chosen && typeof chosen === \"object\" && typeof chosen.id === \"string\" && chosen.id !== \"formula\";\n if (!hasLook) {\n const look = formulaDefaultFormat(field, fields, kindOf, currencyCodeOf);\n if (look) next = { ...next, display_format: look } as unknown as Field;\n }\n return next;\n}\n","// src/userIds.ts — @ai-matrx/records-ui · the words for a person nobody holds.\n// Split out of memberNames.ts so plain-text renderers can use them without importing the picker.\n// The id-shape test is @ai-matrx/kit/uuid's isUuidShape.\n\n/** Words for a person the roster does not hold (an id is never the answer). */\nexport const PERSON_NOT_IN_ORGANIZATION = \"A person no longer in this organization\";\n","\"use client\";\n\n// src/personNames.ts — @ai-matrx/records-ui · lane PERSON-SWEEP\n//\n// A PERSON IS NEVER A UUID ON ANY SCREEN. `scalarText` and the other plain-text renderers cannot ask\n// the store who an id is (they are not hooks), so the answer lives here: a small cache of who is who,\n// filled by the ONE resolver (`resolveKeptPerson`, bound by `PersonNamesBridge` mounted in\n// `RecordsMount`), and a tick (`usePeopleTick`) so a cell that drew \"A person\" redraws with the name\n// the moment it is known. Until it is known — or when the id is nobody this organization holds — the\n// words are `PERSON_NOT_IN_ORGANIZATION`, never the id.\n\nimport { useSyncExternalStore } from \"react\";\n\nconst names = new Map<string, string>();\nconst asked = new Set<string>();\nconst listeners = new Set<() => void>();\nlet version = 0;\nlet resolver: ((id: string) => Promise<string | null>) | null = null;\nlet opener: ((id: string) => Promise<{ recordId: string; userId: string | null; email: string | null; name: string } | null>) | null = null;\n\n/** Bound by `PersonNamesBridge`: who a stored person id is, in full, so a chip can open them. */\nexport function setPersonOpener(next: typeof opener): void {\n opener = next;\n}\n\n/** Open a stored person (a Person row id) through the host: resolved first, so the host gets the account or the email. */\nexport async function openStoredPerson(\n id: string,\n open: ((target: { recordId: string; userId?: string | null; email?: string | null; name?: string }) => void) | undefined,\n): Promise<void> {\n if (!open) return;\n const who = opener ? await opener(id) : null;\n open(who ?? { recordId: id });\n}\n\nfunction bump() {\n version += 1;\n for (const l of listeners) l();\n}\n\n/** Remember who an id is (the one resolver, or a row a screen already read). */\nexport function rememberPerson(id: string, name: string): void {\n const key = id.toLowerCase();\n if (names.get(key) === name) return;\n names.set(key, name);\n bump();\n}\n\n/** The name known for this id right now, or null. Asks the resolver in the background when it has not been asked. */\nexport function knownPerson(id: string): string | null {\n const key = id.toLowerCase();\n const held = names.get(key);\n if (held !== undefined) return held;\n if (resolver && !asked.has(key)) {\n asked.add(key);\n const run = resolver;\n void run(id)\n .then((name) => {\n if (name) rememberPerson(key, name);\n })\n .catch(() => asked.delete(key));\n }\n return null;\n}\n\n/** Bound by `PersonNamesBridge`; `null` unbinds. Ids asked while none was bound are asked again once one is. */\nexport function setPersonResolver(next: ((id: string) => Promise<string | null>) | null): void {\n resolver = next;\n if (next) asked.clear();\n bump();\n}\n\n/** Forget everything (tests). */\nexport function resetPersonNames(): void {\n names.clear();\n asked.clear();\n resolver = null;\n bump();\n}\n\n/** Re-render when a person becomes known. Call from a component whose text may name a person. */\nexport function usePeopleTick(): number {\n return useSyncExternalStore(\n (cb) => {\n listeners.add(cb);\n return () => void listeners.delete(cb);\n },\n () => version,\n () => version,\n );\n}\n","\"use client\";\n\n// src/cellMarks.tsx — @ai-matrx/records-ui · lane data-tables-grid-overhaul\n//\n// TWO CELLS THAT USED TO READ \"—\" AND MEANT SOMETHING ELSE (live walk as admin@admin.com,\n// 2026-10-05). A blank is never unexplained (VAL-2), and the Sheet these grids replace never\n// drew one for either:\n//\n// · A VALUE KEPT ASIDE. Adding \"at least 1\" to Qty while a row held 0 made the store move the 0\n// into the record's `_retired`, with its reason (FLD-4). The cell then read \"—\", as if empty.\n// The cell now shows the kept value, in amber, and says why on hover — the Sheet's amber\n// mismatch, in its words (\"Must be at least 1\"). Restore stays where it is: the record panel.\n//\n// · A WORKED-OUT COLUMN THAT FAILED. `{Qty} / 0` read \"—\" on every row. The store catches the\n// formula's own sentence (\"This formula divides by zero.\") in `custom.derived_value` and\n// answers null, so the reason never reaches a reader yet. When the read doors carry it — the\n// record document's `_errors` block, keyed by the column's key — the cell is blank with a\n// floated \"!\" whose tooltip is that sentence (WALK3-FIX; it read \"#ERROR\" until 2026-10-07).\n\nimport type { Field, RecordDocument } from \"@ai-matrx/records\";\nimport { ruleThatRefuses } from \"@ai-matrx/records\";\nimport { retiredValuesOf, type RetiredValue } from \"./RetiredValues\";\nimport { useRecordsUi } from \"./host\";\nimport { withoutInternalCodes } from \"./plainWords\";\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\nimport { openStoredPerson } from \"./personNames\";\n\n/** The value the store kept aside for this column of this record, when the column is empty now. */\nexport function keptAsideFor(document: RecordDocument | null | undefined, key: string): RetiredValue | null {\n const doc = document as Record<string, unknown> | null | undefined;\n const now = doc?.[key];\n if (now !== null && now !== undefined && now !== \"\") return null;\n const kept = retiredValuesOf(doc).filter((entry) => entry.key === key);\n // The newest is the one a person last saw in the cell.\n return kept.length ? kept[kept.length - 1]! : null;\n}\n\nfunction bound(value: unknown): string {\n return value === undefined || value === null ? \"\" : String(value);\n}\n\n/**\n * WHY IT NO LONGER FITS, in the Sheet's words: the column's check the value fails NOW, judged by\n * the store's mirror (`ruleThatRefuses`). When no check refuses it (a retype set it aside), the\n * store's own reason, without its code.\n */\nexport function keptAsideReason(field: Pick<Field, \"rules\">, entry: RetiredValue): string {\n const rules = (field.rules ?? []) as Parameters<typeof ruleThatRefuses>[0];\n const numeric = typeof entry.value === \"string\" && /^-?\\d+(\\.\\d+)?$/.test(entry.value.trim()) ? Number(entry.value) : entry.value;\n const rule = ruleThatRefuses(rules, numeric);\n let why: string | null = null;\n if (rule?.kind === \"min\") why = `Must be at least ${bound(rule.value)}`;\n else if (rule?.kind === \"max\") why = `Must be at most ${bound(rule.value)}`;\n else if (rule?.kind === \"length\") {\n const chars = Array.from(String(entry.value)).length;\n const most = Number(rule.value);\n why = Number.isInteger(most) && chars > most\n ? `Must be at most ${most} character${most === 1 ? \"\" : \"s\"} (this is ${chars})`\n : `Must be at least ${rule.min} character${rule.min === 1 ? \"\" : \"s\"} (this is ${chars})`;\n } else if (rule?.kind === \"pattern\") why = \"Does not match the column's pattern\";\n if (!why) why = withoutInternalCodes(entry.reason ?? \"No longer fits the column\");\n return `${why}. Kept aside when the column changed; open the record to restore it.`;\n}\n\n/** The kept value, shown where it was, in amber, with why on hover. */\nexport function KeptAsideValue({ field, entry, shown }: { field: Pick<Field, \"key\" | \"rules\">; entry: RetiredValue; shown: string }) {\n const why = keptAsideReason(field, entry);\n const open = useRecordsUi().openPerson;\n // A KEPT PERSON OPENS (no dead ends): the id kept aside from a retired Person column opens the same\n // person peek as the live chip. Only a stored person id opens; any other kept value stays plain.\n const person = (Array.isArray(entry.value) ? entry.value : [entry.value]).find(isUuidShape);\n const opens = open && typeof person === \"string\";\n return (\n <span\n data-records-kept-aside={field.key}\n title={why}\n aria-label={`${shown}. ${why}`}\n className={`${opens ? \"cursor-pointer underline-offset-2 hover:underline\" : \"cursor-help\"} rounded-sm bg-amber-500/10 px-0.5 text-amber-700 dark:text-amber-300`}\n {...(opens\n ? {\n role: \"button\",\n tabIndex: 0,\n onClick: (e: { stopPropagation: () => void }) => {\n e.stopPropagation();\n void openStoredPerson(person, open);\n },\n onKeyDown: (e: { key: string; stopPropagation: () => void; preventDefault: () => void }) => {\n if (e.key === \"Enter\" || e.key === \" \") {\n e.preventDefault();\n e.stopPropagation();\n void openStoredPerson(person, open);\n }\n },\n }\n : {})}\n >\n {shown}\n </span>\n );\n}\n\n/** The store's sentence for a worked-out column it could not work out, when the read carries it. */\nexport function workedOutErrorFor(document: RecordDocument | null | undefined, key: string): string | null {\n const block = (document as Record<string, unknown> | null | undefined)?.[\"_errors\"];\n if (!block || typeof block !== \"object\" || Array.isArray(block)) return null;\n const said = (block as Record<string, unknown>)[key];\n if (typeof said === \"string\" && said.trim() !== \"\") return said.trim();\n if (said && typeof said === \"object\" && typeof (said as { says?: unknown }).says === \"string\") return String((said as { says: string }).says).trim() || null;\n return null;\n}\n\n/**\n * WHAT THE WHOLE CELL SAYS ON HOVER when it wears a mark (live walk 2026-10-05: the kept-aside\n * reason showed only over the amber glyph; the rest of the cell said \"double-click or press Enter\n * to edit\"). The grid cell takes this as its own title, so every pixel of it gives the reason.\n */\nexport function cellMarkSentence(\n field: Pick<Field, \"key\" | \"rules\">,\n document: RecordDocument | null | undefined,\n value: unknown,\n): string | null {\n if (value === null || value === undefined) {\n const failed = workedOutErrorFor(document, field.key);\n if (failed) return failed;\n }\n const kept = keptAsideFor(document, field.key);\n return kept ? keptAsideReason(field, kept) : null;\n}\n\n/**\n * A FAILED WORKED-OUT COLUMN IS BLANK WITH A \"!\" (WALK3-FIX, live walk 2026-10-07: Movers' Rate Card\n * read \"#ERROR\" in all three rows of Peak season rate). A spreadsheet code is not a value and not a\n * reason; the cell stays empty and wears the same \"!\" the grid floats over a refused cell\n * (`gridEditing.tsx` · `data-records-cell-refusal-line`), with the store's sentence as its tooltip.\n * In a grid cell it floats over the right edge (`floated`), out of the row's flow; elsewhere (the\n * record page, a card) it sits where the value would.\n */\nexport function WorkedOutError({ field, sentence, floated = false }: { field: Pick<Field, \"key\">; sentence: string; floated?: boolean }) {\n return (\n <span\n data-records-worked-out-error={field.key}\n role=\"img\"\n title={sentence}\n aria-label={sentence}\n className={\n (floated ? \"absolute right-1 top-1/2 z-10 flex -translate-y-1/2 \" : \"inline-flex align-middle \") +\n \"h-4 w-4 shrink-0 cursor-help items-center justify-center rounded-full bg-destructive text-[10px] font-bold leading-none text-destructive-foreground\"\n }\n >\n !\n </span>\n );\n}\n","\"use client\";\n\n// src/RetiredValues.tsx — @ai-matrx/records-ui · lane 10 P4c (V13 #4)\n//\n// WHAT THE STORE KEPT ASIDE, WHERE THE RECORD IS READ. When a column changes what it accepts (a\n// retype, a tighter check, a lower top star) a value that no longer fits is moved into the record's\n// `_retired` with its reason — neither changed nor deleted. A value kept and never shown is a value\n// lost, so the record panel lists each one with its reason and a Restore: the one-column restore\n// door (`valueRestore`, through `restoreAt`) puts the column back to the version that last held it, as a NEW version.\n// The store judges the value again on the way back; when it still does not fit, its refusal is\n// shown here in its own words.\n\nimport { useState } from \"react\";\nimport type { Field, RecordsError, Uuid } from \"@ai-matrx/records\";\nimport { useRecordsClient } from \"@ai-matrx/records/react\";\nimport { Button } from \"@ai-matrx/design-system\";\nimport { RefusalNotice } from \"./Refusal\";\nimport { withoutInternalCodes } from \"./plainWords\";\nimport { fieldName } from \"./names\";\nimport { readVersionNow, restoreAt } from \"./recordVersions\";\nimport { scalarText } from \"./values\";\nimport { PersonChip } from \"./personChip\";\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\nimport { useKeptPeople, useMemberRoster } from \"./memberNames\";\nimport type { OrganizationMember } from \"./host\";\nimport { useRecordsUi } from \"./host\";\n\n/** One value the store kept aside, as the read door returns it in `_retired`. */\nexport interface RetiredValue {\n key: string;\n label?: string;\n value: unknown;\n reason?: string;\n at?: string;\n}\n\nfunction same(a: unknown, b: unknown): boolean {\n return JSON.stringify(a) === JSON.stringify(b);\n}\n\n/**\n * The kept-aside values still worth showing: each entry of `_retired` whose value is not already\n * back in its column (a restored value stays in `_retired` as a record of what happened, but\n * offering to restore it again would be a dead control).\n */\nexport function retiredValuesOf(document: Record<string, unknown> | null | undefined): RetiredValue[] {\n const kept = document?.[\"_retired\"];\n if (!Array.isArray(kept)) return [];\n return kept\n .filter((x): x is RetiredValue => typeof x === \"object\" && x !== null && typeof (x as { key?: unknown }).key === \"string\")\n .filter((x) => x.value !== null && x.value !== undefined && !same(document?.[x.key], x.value));\n}\n\n/**\n * The version to put back: the newest one whose `after` for the column is the kept value. Field\n * history lists newest first; the entry that set the value aside has the value as its `before`, so\n * the version just before it is the one holding it, and that one is what a search for `after` finds.\n */\nexport function versionHolding(entries: ReadonlyArray<{ version: number; after: unknown }>, value: unknown): number | null {\n let best: number | null = null;\n for (const e of entries) if (same(e.after, value) && (best === null || e.version > best)) best = e.version;\n return best;\n}\n\n/** The people a kept value names: row id first, then user id; each opens through the host when it is a Person record. */\nfunction KeptPeople({ value, roster }: { value: unknown; roster: ReadonlyMap<string, OrganizationMember> | null }) {\n const host = useRecordsUi();\n // Until the roster and rows answer a kept id reads as a wait, never as the uuid.\n const people = useKeptPeople(value, roster);\n return (\n <span className=\"flex min-w-0 flex-wrap gap-1\" data-records-person-chips=\"\">\n {(people ?? [{ id: \"wait\", recordId: null, name: \"…\" }]).map((who, i) => (\n <PersonChip\n key={`${who.id}-${i}`}\n name={who.name}\n {...(who.recordId && host.openPerson ? { onOpen: () => host.openPerson!({ recordId: who.recordId!, userId: who.userId ?? null, email: who.email ?? null, name: who.name }) } : {})}\n />\n ))}\n </span>\n );\n}\n\nexport function RetiredValues({\n tableId,\n recordId,\n document,\n fields,\n mayWrite,\n onRestored,\n}: {\n tableId: Uuid;\n recordId: Uuid;\n document: Record<string, unknown> | null | undefined;\n fields: ReadonlyArray<Field>;\n mayWrite: boolean;\n onRestored?: (() => void) | undefined;\n}) {\n const client = useRecordsClient();\n const roster = useMemberRoster();\n const [busy, setBusy] = useState<string | null>(null);\n const [refusal, setRefusal] = useState<{ key: string; error: RecordsError } | null>(null);\n const [said, setSaid] = useState<string | null>(null);\n const [missing, setMissing] = useState<string | null>(null);\n const kept = retiredValuesOf(document);\n if (kept.length === 0) return null;\n\n const restore = async (entry: RetiredValue, index: number) => {\n const id = `${entry.key}-${index}`;\n setBusy(id);\n setRefusal(null);\n setSaid(null);\n setMissing(null);\n // The record's version as this click found it: the restore is refused if it moves before the write.\n const [history, seen] = await Promise.all([\n client.fieldHistory({ table_id: tableId, field_key: entry.key, record_id: recordId, limit: 200 }),\n readVersionNow(client, recordId),\n ]);\n if (!history.ok) {\n setBusy(null);\n setRefusal({ key: id, error: history.error });\n return;\n }\n const version = versionHolding(history.data, entry.value);\n if (version === null) {\n setBusy(null);\n setMissing(id);\n return;\n }\n const done = await restoreAt(client, { record_id: recordId, version, field_key: entry.key, seenVersion: seen });\n setBusy(null);\n if (!done.ok) {\n setRefusal({ key: id, error: done.error });\n return;\n }\n setSaid(`Put back as version ${done.data.version}.`);\n onRestored?.();\n };\n\n return (\n <div className=\"flex flex-col gap-1\" data-records-retired=\"\">\n <span className=\"font-medium\">Kept aside</span>\n {kept.map((entry, index) => {\n const id = `${entry.key}-${index}`;\n const field = fields.find((f) => f.key === entry.key);\n const name = field ? fieldName(field) : (entry.label ?? entry.key);\n const shown = field ? scalarText(field, entry.value) : typeof entry.value === \"string\" ? entry.value : JSON.stringify(entry.value);\n const holdsUserId = (Array.isArray(entry.value) ? entry.value : [entry.value]).some(isUuidShape);\n return (\n <div key={id} className=\"flex flex-col gap-0.5\" data-records-retired-key={entry.key}>\n <div className=\"flex flex-wrap items-baseline gap-2\">\n <span className=\"text-muted-foreground\">{name}</span>\n {/* A kept person is a person, never an id: named through the host's roster (`memberNames.ts`). */}\n {holdsUserId ? (\n <KeptPeople value={entry.value} roster={roster} />\n ) : (\n <span className=\"min-w-0 break-words\">{shown}</span>\n )}\n {mayWrite ? (\n <Button size=\"sm\" variant=\"outline\" className=\"h-6 px-2 text-xs\" disabled={busy !== null} onClick={() => void restore(entry, index)} data-records-retired-restore=\"\">\n {busy === id ? \"Restoring…\" : \"Restore\"}\n </Button>\n ) : null}\n </div>\n {entry.reason ? <p className=\"text-[11px] text-muted-foreground\">{withoutInternalCodes(entry.reason)}</p> : null}\n {refusal?.key === id ? <RefusalNotice error={refusal.error} /> : null}\n {missing === id ? <p className=\"text-[11px] text-muted-foreground\">No earlier version of {name} holds this value, so it cannot be put back from here.</p> : null}\n </div>\n );\n })}\n {said ? (\n <p role=\"status\" className=\"text-[11px] text-muted-foreground\">\n {said}\n </p>\n ) : null}\n </div>\n );\n}\n","\"use client\";\n\n// src/memberNames.ts — @ai-matrx/records-ui · record-fixes item 2\n//\n// A PERSON IS NEVER SHOWN AS THEIR ID. A value the store kept aside from a retired Created by / Last\n// edited by (or Person) column is the user's id; the screen names the person instead, through the\n// host's own roster (`members`). An id the roster does not hold reads as a person who is no longer\n// in the organization — never the uuid.\n\nimport { useEffect, useMemo, useState } from \"react\";\nimport type { RecordsClient } from \"@ai-matrx/records/core\";\nimport { useOptionalRecordsClient } from \"@ai-matrx/records/react\";\nimport { useRecordsUi, type OrganizationMember } from \"./host\";\nimport { personFromRow } from \"./PersonPicker\";\n\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\nimport { PERSON_NOT_IN_ORGANIZATION } from \"./userIds\";\nexport { PERSON_NOT_IN_ORGANIZATION };\n\n/** A member's words: their name, else their email, else null. */\nexport function memberWords(member: OrganizationMember | undefined): string | null {\n const name = member?.name?.trim();\n if (name) return name;\n const email = member?.email?.trim();\n return email ? email : null;\n}\n\n/**\n * The user ids in a kept value, named. `undefined` while the roster is read or when the value holds no id;\n * otherwise the names in order, `PERSON_NOT_IN_ORGANIZATION` for an id the roster does not hold.\n */\nexport function peopleIn(value: unknown, roster: ReadonlyMap<string, OrganizationMember>): string[] | undefined {\n const items = Array.isArray(value) ? value : [value];\n if (!items.some(isUuidShape)) return undefined;\n return items.filter(isUuidShape).map((id) => memberWords(roster.get(id.toLowerCase())) ?? PERSON_NOT_IN_ORGANIZATION);\n}\n\n/**\n * The organization's roster by user id, read once through the host's `members` port. `null` until it\n * answers (or forever when the host binds none — callers then name the person without a name).\n */\nexport function useMemberRoster(): ReadonlyMap<string, OrganizationMember> | null {\n const host = useRecordsUi();\n const members = host.members;\n const [roster, setRoster] = useState<ReadonlyMap<string, OrganizationMember> | null>(null);\n useEffect(() => {\n if (!members) {\n setRoster(new Map());\n return;\n }\n let cancelled = false;\n void members()\n .then((list) => !cancelled && setRoster(new Map(list.map((m) => [m.userId.toLowerCase(), m] as const))))\n .catch(() => !cancelled && setRoster(new Map()));\n return () => {\n cancelled = true;\n };\n }, [members]);\n return roster;\n}\n\n/** One kept person, named: the Person row it is (when it is one, so it can be opened) and their words. */\nexport interface KeptPerson {\n /** The stored id, as kept. */\n id: string;\n /** The Person record it names, when it is one: the host opens it. */\n recordId: string | null;\n name: string;\n /** The account it is, when matched (the host opens that person's peek). */\n userId?: string | null;\n /** Their email, when the row or roster holds one (an unmatched person is held by email). */\n email?: string | null;\n}\n\n/**\n * A stored person value is a Person ROW id (what the person picker writes); an older value may be a\n * USER id. Row first, through the same row-to-user mapping the picker uses (`personFromRow`), then the\n * roster by that user id; an id neither resolves to stays `PERSON_NOT_IN_ORGANIZATION`.\n */\nexport async function resolveKeptPerson(\n client: Pick<RecordsClient, \"recordRead\"> | null,\n id: string,\n roster: ReadonlyMap<string, OrganizationMember>,\n): Promise<KeptPerson> {\n if (client) {\n try {\n const read = await client.recordRead({ record_id: id as never });\n if (read.ok) {\n const person = personFromRow({ id: id as never, document: read.data.document });\n const member = person.userId ? roster.get(person.userId.toLowerCase()) : undefined;\n const named = memberWords(member) ?? (person.name !== \"\" ? person.name : null);\n const doc = (read.data.document ?? {}) as Record<string, unknown>;\n const email = (typeof doc[\"email\"] === \"string\" && doc[\"email\"].trim() !== \"\" ? doc[\"email\"].trim() : null) ?? member?.email?.trim() ?? null;\n if (person.userId || named) return { id, recordId: id, name: named ?? PERSON_NOT_IN_ORGANIZATION, userId: person.userId, email };\n }\n } catch {\n /* not a readable row: fall through to the user id */\n }\n }\n const direct = roster.get(id.toLowerCase());\n return { id, recordId: null, name: memberWords(direct) ?? PERSON_NOT_IN_ORGANIZATION, userId: direct ? id : null, email: direct?.email?.trim() || null };\n}\n\n/** The kept people in a value, named; `null` while they are read. Call only for a value that holds ids. */\nexport function useKeptPeople(value: unknown, roster: ReadonlyMap<string, OrganizationMember> | null): KeptPerson[] | null {\n const client = useOptionalRecordsClient();\n const ids = useMemo(() => (Array.isArray(value) ? value : [value]).filter(isUuidShape), [value]);\n const key = ids.join(\",\");\n const [people, setPeople] = useState<KeptPerson[] | null>(null);\n useEffect(() => {\n if (!roster) return;\n let cancelled = false;\n void Promise.all(ids.map((id) => resolveKeptPerson(client, id, roster))).then((named) => !cancelled && setPeople(named));\n return () => {\n cancelled = true;\n };\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [key, roster, client]);\n return people;\n}\n","\"use client\";\nimport { readableLink } from \"./readableLink\";\n\n// src/structuredValue.tsx — @ai-matrx/records-ui · lane JSON-FIELDS\n//\n// A VALUE WITH INSIDES IS DRAWN AS ITS INSIDES (Arman, 2026-10-15: \"the record is doing absolutely\n// NOTHING with fields that have json data\"). A text cell holding a JSON object or array — a scraper's\n// `employees`, `similar`, `locations` — or a json value the store keeps as an object, is read once\n// here and drawn by its shape:\n// · a list of like records → a compact table (pictures as thumbnails, links as link chips)\n// · a record → its keys as a property list, nested parts folded\n// · a list of plain values → chips\n// · a URL / picture URL → a link chip / a thumbnail; a date → a date; a number → grouped\n// · a `__kind` anywhere → the kind system's one component (`KindValueCell`), never a second\n// A grid cell gets one line (\"4 items · Matthew Santore, Linda Kennedy…\") that opens the whole value.\n// Every full view has \"Raw\" (the text exactly as stored) and the copy door (`AlchemyMenu`), and a\n// list of records offers \"Save as table\" (`SaveToTable`, the one screen) — an offer, never automatic.\n// Parsing is synchronous, so nothing swaps in after paint.\n\nimport { Suspense, lazy, useState, type ReactNode } from \"react\";\nimport {\n Badge,\n Button,\n Dialog,\n DialogContent,\n DialogHeader,\n DialogTitle,\n Popover,\n PopoverContent,\n PopoverTrigger,\n cn,\n} from \"@ai-matrx/design-system\";\nimport { PropertyRow } from \"@ai-matrx/design-system/controls\";\nimport { AlchemyMenu } from \"@ai-matrx/alchemy/react\";\nimport { OutboundLink } from \"@ai-matrx/kit/outbound-react\";\nimport { humanizeIdentifier } from \"@ai-matrx/kit/text-case\";\nimport { useRecordsUi } from \"./host\";\nimport { kindValueOf } from \"./kindValues\";\nimport { KindValueCell } from \"./ReferenceChips\";\nimport { linkChipText } from \"./formattedValue\";\nimport { shapeOfValue } from \"./tableShape\";\n// The one save screen, loaded when asked for: it carries the import wizard, which reads values back.\nconst SaveToTable = lazy(() => import(\"./SaveToTable\").then((m) => ({ default: m.SaveToTable })));\n\n/** A value read as structure: the parsed data, and the text it was stored as (null when it was never text). */\nexport interface Structured {\n data: Record<string, unknown> | unknown[];\n raw: string | null;\n}\n\nconst LONGEST_READ = 500_000;\nconst FENCE = /^```(?:json)?[ \\t]*\\r?\\n([\\s\\S]*?)\\r?\\n?```$/;\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v) && !(\"$$typeof\" in v);\n}\n\n/**\n * THE ONE DETECTOR. A JSON object or array — stored as an object, or as text (bare or in one ```json\n * fence). Null for everything else: plain words, numbers, quoted strings, broken JSON, and a value\n * that names its own kind (`__kind` / a Matrx directive), which the kind system draws.\n */\nexport function structuredOf(value: unknown): Structured | null {\n if (kindValueOf(value)) return null;\n if (Array.isArray(value)) return { data: value, raw: null };\n if (isPlainObject(value)) return { data: value, raw: null };\n if (typeof value !== \"string\" || value.length > LONGEST_READ) return null;\n const t = value.trim();\n const fenced = FENCE.exec(t);\n const body = fenced ? fenced[1]!.trim() : t;\n if (body.length < 2) return null;\n const opens = body[0];\n const closes = body[body.length - 1];\n if (!((opens === \"{\" && closes === \"}\") || (opens === \"[\" && closes === \"]\"))) return null;\n try {\n const parsed: unknown = JSON.parse(body);\n if (Array.isArray(parsed) || isPlainObject(parsed)) return { data: parsed, raw: value };\n } catch {\n return null;\n }\n return null;\n}\n\n// ── words ──────────────────────────────────────────────────────────────────\n\nconst NAME_KEYS = [\"title\", \"name\", \"label\", \"display_name\", \"full_name\", \"headline\"] as const;\n\nfunction nameOf(item: Record<string, unknown>): string | null {\n for (const k of NAME_KEYS) {\n const v = item[k];\n if (typeof v === \"string\" && v.trim() !== \"\") return v.trim();\n }\n return null;\n}\n\n/** A key as a person reads it: `company_size` → \"Company size\"; a key already in words stays. */\nexport function structuredKeyWords(key: string): string {\n return /\\s/.test(key) || /^[A-Z]/.test(key) ? key : humanizeIdentifier(key);\n}\n\nfunction plural(n: number, one: string, many: string): string {\n return `${n} ${n === 1 ? one : many}`;\n}\n\nfunction scalarWords(v: unknown): string {\n if (v === null || v === undefined) return \"—\";\n if (typeof v === \"number\") return v.toLocaleString();\n if (typeof v === \"boolean\") return v ? \"Yes\" : \"No\";\n if (typeof v === \"string\") {\n if (isUrl(v)) return linkChipText(v);\n return v;\n }\n if (Array.isArray(v)) return plural(v.length, \"item\", \"items\");\n return plural(Object.keys(v as object).length, \"field\", \"fields\");\n}\n\nfunction keysOf(items: Array<Record<string, unknown>>): string[] {\n const keys: string[] = [];\n for (const o of items) for (const k of Object.keys(o)) if (!keys.includes(k)) keys.push(k);\n return keys;\n}\n\n/**\n * ONE LINE FOR A STRUCTURED VALUE — a grid cell, a card, a sentence. Never a wall of braces:\n * \"4 items · Matthew Santore, Linda Kennedy, Arman Sadeghi…\", \"2 items · directions url\",\n * \"US\", \"Input: url\".\n */\nexport function structuredSummary(data: Record<string, unknown> | unknown[]): string {\n if (Array.isArray(data)) {\n if (data.length === 0) return \"Empty list\";\n const head = plural(data.length, \"item\", \"items\");\n const objects = data.filter(isPlainObject);\n if (objects.length === data.length) {\n const names = objects.map(nameOf).filter((n): n is string => n !== null);\n if (names.length > 0) return `${head} · ${names.slice(0, 3).join(\", \")}${names.length > 3 ? \"…\" : \"\"}`;\n const keys = keysOf(objects).slice(0, 3).map((k) => structuredKeyWords(k).toLowerCase());\n return `${head} · ${keys.join(\", \")}${keysOf(objects).length > 3 ? \"…\" : \"\"}`;\n }\n const words = data.filter((v) => v !== null && typeof v !== \"object\").map(scalarWords);\n if (data.length <= 3 && words.length === data.length) return words.join(\", \");\n return words.length > 0 ? `${head} · ${words.slice(0, 3).join(\", \")}${words.length > 3 ? \"…\" : \"\"}` : head;\n }\n const entries = Object.entries(data).filter(([k]) => k !== \"__kind\");\n if (entries.length === 0) return \"Empty\";\n const name = nameOf(data);\n if (name) return entries.length > 1 ? `${name} · ${plural(entries.length - 1, \"more field\", \"more fields\")}` : name;\n const shown = entries.slice(0, 2).map(([k, v]) => {\n if (isPlainObject(v)) return `${structuredKeyWords(k)}: ${Object.keys(v).map((x) => structuredKeyWords(x).toLowerCase()).slice(0, 2).join(\", \")}`;\n return `${structuredKeyWords(k)}: ${scalarWords(v)}`;\n });\n return entries.length > 2 ? `${shown.join(\" · \")} · +${entries.length - 2}` : shown.join(\" · \");\n}\n\n/** A structured value's one line, or null when the value is not structured (the caller's own words stand). */\nexport function structuredWords(value: unknown): string | null {\n const s = structuredOf(value);\n return s ? structuredSummary(s.data) : null;\n}\n\n// ── scalars ────────────────────────────────────────────────────────────────\n\nfunction isUrl(v: string): boolean {\n return /^https?:\\/\\/[^\\s]+$/i.test(v.trim());\n}\n\nconst IMAGE_EXT = /\\.(?:png|jpe?g|gif|webp|avif|svg|bmp|ico)(?:[?#]|$)/i;\nconst IMAGE_KEY = /(?:^|_)(?:img|image|images|logo|avatar|photo|picture|thumbnail|thumb|icon|cover|banner)(?:_|$|url)/i;\n\n/** A picture's address: an image file, or an address under a key that names a picture (`img`, `logo`). */\nexport function isImageUrl(v: unknown, key?: string): boolean {\n if (typeof v !== \"string\" || !isUrl(v)) return false;\n try {\n const path = new URL(v).pathname;\n if (IMAGE_EXT.test(path)) return true;\n if (/\\/(?:dms\\/image|images?)\\//i.test(path)) return true;\n } catch {\n return false;\n }\n return key !== undefined && IMAGE_KEY.test(key);\n}\n\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}(?:[T ][\\d:.]+(?:Z|[+-]\\d{2}:?\\d{2})?)?$/;\nconst MARKDOWN = /(^|\\n)\\s*(?:#{1,6}\\s|[-*]\\s|\\d+\\.\\s|>\\s)|\\*\\*[^*]+\\*\\*|\\[[^\\]]+\\]\\([^)]+\\)/;\n\nfunction dateWords(v: string): string | null {\n if (!ISO_DATE.test(v)) return null;\n if (v.length === 10) {\n const [y, m, d] = v.split(\"-\").map(Number);\n const local = new Date(y!, m! - 1, d!);\n return Number.isNaN(local.getTime()) ? null : local.toLocaleDateString(undefined, { dateStyle: \"medium\" });\n }\n const at = new Date(v);\n return Number.isNaN(at.getTime()) ? null : at.toLocaleString(undefined, { dateStyle: \"medium\", timeStyle: \"short\" });\n}\n\nfunction stop(event: { stopPropagation: () => void }) {\n event.stopPropagation();\n}\n\nfunction Thumb({ src, size }: { src: string; size: \"sm\" | \"md\" }) {\n return (\n <OutboundLink href={src} title={src} onClick={stop} className=\"inline-flex shrink-0\" data-records-structured-thumb=\"\">\n <img\n src={src}\n alt=\"\"\n loading=\"lazy\"\n referrerPolicy=\"no-referrer\"\n className={cn(\"rounded border border-border bg-muted object-cover\", size === \"sm\" ? \"size-6\" : \"size-12\")}\n />\n </OutboundLink>\n );\n}\n\nfunction LinkChip({ href, dense }: { href: string; dense?: boolean | undefined }) {\n return (\n <OutboundLink\n href={href}\n title={href}\n onClick={stop}\n className={cn(\n \"inline-flex min-w-0 max-w-full items-center gap-1 rounded-md border border-border bg-muted/60 px-1.5 py-0.5 text-[11px] text-foreground hover:bg-accent\",\n // A percentage max-width means nothing inside an auto-layout table cell, so a link column would hold\n // its full address; in a table the chip gets a real ceiling and shortens with an ellipsis.\n dense && \"max-w-[7rem]\",\n )}\n data-records-link-chip=\"\"\n >\n <span aria-hidden=\"true\" className=\"text-muted-foreground\">↗</span>\n <span className=\"truncate\">{linkChipText(href)}</span>\n </OutboundLink>\n );\n}\n\n/** One plain value inside a structure, drawn by what it is. */\nfunction Scalar({ value, keyName, dense }: { value: unknown; keyName?: string | undefined; dense?: boolean | undefined }) {\n const ui = useRecordsUi();\n if (value === null || value === undefined || value === \"\") return <span className=\"text-muted-foreground\">—</span>;\n if (typeof value === \"boolean\") return <span>{value ? \"Yes\" : \"No\"}</span>;\n if (typeof value === \"number\") return <span className=\"tabular-nums\">{value.toLocaleString()}</span>;\n if (typeof value !== \"string\") return <span>{String(value)}</span>;\n const text = value.trim();\n if (isImageUrl(text, keyName)) return <Thumb src={text} size={dense ? \"sm\" : \"md\"} />;\n if (isUrl(text)) return <LinkChip href={text} dense={dense} />;\n if (/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(text)) {\n return (\n <a href={`mailto:${text}`} onClick={stop} className=\"text-primary underline-offset-2 hover:underline\">\n {readableLink(text)}\n </a>\n );\n }\n const date = dateWords(text);\n if (date) return <span title={text}>{date}</span>;\n if (!dense && ui.renderText && text.length > 40 && MARKDOWN.test(text)) return <div className=\"min-w-0\">{ui.renderText(text, \"cell\")}</div>;\n return <span className={cn(dense ? \"line-clamp-2 break-words\" : \"whitespace-pre-wrap [overflow-wrap:anywhere]\")}>{text}</span>;\n}\n\n// ── shapes ─────────────────────────────────────────────────────────────────\n\nconst TABLE_ROWS = 8;\nconst TABLE_COLUMNS = 12;\n\n/** A list of like records as a compact table — the picture and the name first, as a person reads it. */\nfunction RecordsTable({ items }: { items: Array<Record<string, unknown>> }) {\n const [all, setAll] = useState(false);\n const keys = keysOf(items).filter((k) => k !== \"__kind\");\n const pictureFirst = [...keys].sort((a, b) => rank(a, items) - rank(b, items)).slice(0, TABLE_COLUMNS);\n const shown = all ? items : items.slice(0, TABLE_ROWS);\n return (\n <div className=\"min-w-0\" data-records-structured=\"table\">\n <div className=\"max-w-full overflow-x-auto rounded-md border border-border\" data-records-structured-table-frame=\"\">\n <table className=\"w-full border-collapse text-xs\">\n <thead className=\"bg-muted/60 text-left\">\n <tr>\n {pictureFirst.map((k) => (\n <th key={k} scope=\"col\" className=\"px-2 py-1 font-medium text-muted-foreground [overflow-wrap:anywhere]\">\n {structuredKeyWords(k)}\n </th>\n ))}\n </tr>\n </thead>\n <tbody>\n {shown.map((item, i) => (\n <tr key={i} className=\"border-t border-border/60 align-top\">\n {pictureFirst.map((k) => (\n <td key={k} className=\"min-w-[2rem] max-w-[18rem] break-words px-2 py-1 [overflow-wrap:anywhere]\">\n {k in item ? <Nested value={item[k]} keyName={k} dense /> : <span className=\"text-muted-foreground\">—</span>}\n </td>\n ))}\n </tr>\n ))}\n </tbody>\n </table>\n </div>\n {items.length > TABLE_ROWS ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"mt-1 h-6 px-2 text-xs\" onClick={(e) => { stop(e); setAll((a) => !a); }}>\n {all ? \"Show fewer\" : `Show all ${items.length}`}\n </Button>\n ) : null}\n </div>\n );\n}\n\n/** Pictures first, then the item's name, then everything else in the order it was written. */\nfunction rank(key: string, items: Array<Record<string, unknown>>): number {\n if (items.some((o) => isImageUrl(o[key], key))) return 0;\n if ((NAME_KEYS as readonly string[]).includes(key)) return 1;\n return 2;\n}\n\n/** A value inside a structure: a scalar, a kind, or a nested structure (one line when dense). */\nfunction Nested({ value, keyName, dense, depth = 0 }: { value: unknown; keyName?: string | undefined; dense?: boolean | undefined; depth?: number }) {\n const kv = kindValueOf(value);\n if (kv) return <KindValueCell kv={kv} where={dense ? \"cell\" : \"panel\"} title={keyName ? structuredKeyWords(keyName) : kv.kind} />;\n const s = structuredOf(value);\n if (!s) return <Scalar value={value} keyName={keyName} dense={dense} />;\n if (dense) {\n if (Array.isArray(s.data) && s.data.length > 0 && s.data.length <= 4 && s.data.every((v) => v === null || typeof v !== \"object\")) {\n return <ScalarChips items={s.data} keyName={keyName} />;\n }\n return <span className=\"text-muted-foreground\">{structuredSummary(s.data)}</span>;\n }\n return <Shape data={s.data} depth={depth} />;\n}\n\nfunction ScalarChips({ items, keyName }: { items: unknown[]; keyName?: string | undefined }) {\n return (\n <span className=\"flex min-w-0 flex-wrap gap-1\" data-records-structured=\"chips\">\n {items.map((item, i) =>\n typeof item === \"string\" && isUrl(item) ? (\n <Scalar key={i} value={item} keyName={keyName} dense />\n ) : (\n <Badge key={i} variant=\"secondary\" className=\"max-w-full text-[11px] font-normal\">\n <span className=\"truncate\">{scalarWords(item)}</span>\n </Badge>\n ),\n )}\n </span>\n );\n}\n\n/** THE SHAPE OF A STRUCTURE, drawn by what it is. */\nexport function Shape({ data, depth = 0 }: { data: Record<string, unknown> | unknown[]; depth?: number }) {\n if (Array.isArray(data)) {\n if (data.length === 0) return <span className=\"text-muted-foreground\">Empty list</span>;\n if (data.every(isPlainObject) && !data.some((o) => kindValueOf(o))) return <RecordsTable items={data} />;\n if (data.every((v) => v === null || typeof v !== \"object\")) return <ScalarChips items={data} />;\n return (\n <div className=\"min-w-0\" data-records-structured=\"list\">\n {data.map((item, i) => (\n <Row key={i} label={`${i + 1}`} value={item} depth={depth} />\n ))}\n </div>\n );\n }\n const entries = Object.entries(data).filter(([k]) => k !== \"__kind\");\n if (entries.length === 0) return <span className=\"text-muted-foreground\">Empty</span>;\n const folds = entries.some(([, v]) => structuredOf(v) !== null);\n return (\n <div className=\"min-w-0\" data-records-structured=\"properties\">\n {entries.map(([k, v]) => (\n <Row key={k} label={structuredKeyWords(k)} keyName={k} value={v} depth={depth} gutter={folds} />\n ))}\n </div>\n );\n}\n\nfunction Row({ label, keyName, value, depth, gutter }: { label: string; keyName?: string | undefined; value: unknown; depth: number; gutter?: boolean | undefined }) {\n const s = kindValueOf(value) ? null : structuredOf(value);\n if (!s) {\n return <PropertyRow label={label} gutter={gutter ?? false} value={<Nested value={value} keyName={keyName} />} />;\n }\n // A nested part opens on its own: shallow parts start open, deep ones start folded.\n return (\n <PropertyRow\n label={label}\n value={structuredSummary(s.data)}\n expanded={<Shape data={s.data} depth={depth + 1} />}\n defaultOpen={depth === 0}\n />\n );\n}\n\n// ── the full view and the cell ─────────────────────────────────────────────\n\nfunction recordsCount(data: Record<string, unknown> | unknown[]): string {\n return Array.isArray(data) && data.length > 0 && data.every(isPlainObject) ? plural(data.length, \"item\", \"items\") : \"\";\n}\n\nfunction rawTextOf(s: Structured): string {\n return s.raw ?? JSON.stringify(s.data, null, 2);\n}\n\n/**\n * THE WHOLE VALUE — its shape, with \"Raw\" beside it (the exact stored text), the copy door, and,\n * for a list of records, \"Save as table\".\n */\nexport function StructuredValueView({ structured, label, className }: { structured: Structured; label: string; className?: string }) {\n const [raw, setRaw] = useState(false);\n const [saving, setSaving] = useState(false);\n const ui = useRecordsUi();\n const savable = shapeOfValue(structured.data) !== null;\n const text = rawTextOf(structured);\n return (\n <div className={cn(\"flex min-w-0 flex-col gap-1.5 whitespace-normal\", className)} data-records-structured-view=\"\">\n <div className=\"flex min-w-0 items-center gap-1\" onClick={stop}>\n {/* The count heads a list of records only; any other shape below already says what it holds. */}\n <span className=\"min-w-0 flex-1 truncate text-xs text-muted-foreground\">{recordsCount(structured.data)}</span>\n {savable ? (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" className=\"h-6 px-2 text-xs\" onClick={() => setSaving(true)} data-records-structured-save=\"\">\n Save as table\n </Button>\n ) : null}\n <Button\n type=\"button\"\n variant={raw ? \"secondary\" : \"ghost\"}\n size=\"sm\"\n className=\"h-6 px-2 text-xs\"\n aria-pressed={raw}\n onClick={() => setRaw((r) => !r)}\n data-records-structured-raw-toggle=\"\"\n >\n Raw\n </Button>\n <AlchemyMenu label={label} sourceId={`records:value:${label}`} size=\"xs\" json={() => structured.data} human={() => text} />\n </div>\n {raw ? (\n <pre className=\"max-h-[60vh] overflow-auto whitespace-pre-wrap break-words rounded-md bg-muted/60 p-2 font-mono text-xs\" data-records-structured-raw=\"\">\n {structured.raw !== null ? prettyJsonText(structured.raw) : text}\n </pre>\n ) : (\n <Shape data={structured.data} />\n )}\n {saving ? (\n <Dialog open onOpenChange={(open) => { if (!open) setSaving(false); }}>\n <DialogContent className=\"max-h-[90vh] max-w-3xl overflow-y-auto\">\n <DialogHeader>\n <DialogTitle>Save {label} as a table</DialogTitle>\n </DialogHeader>\n <Suspense fallback={<div className=\"h-40 animate-pulse rounded-md bg-muted\" />}>\n <SaveToTable\n source={{ value: structured.data, title: label }}\n onClose={() => setSaving(false)}\n {...(ui.openRecords ? { onOpenTable: (tableId: string) => ui.openRecords?.({ tableId, filter: {}, label }) } : {})}\n />\n </Suspense>\n </DialogContent>\n </Dialog>\n ) : null}\n </div>\n );\n}\n\n/** The stored text, indented when it is JSON — the characters as stored, never re-typed. */\nexport function prettyJsonText(raw: string): string {\n try {\n return JSON.stringify(JSON.parse(raw.trim().replace(FENCE, \"$1\")), null, 2);\n } catch {\n return raw;\n }\n}\n\n/**\n * A STRUCTURED VALUE IN ONE LINE (a grid cell, a card): what it holds in words, and a click opens\n * the whole value. The row's height never moves.\n */\nexport function StructuredCell({ structured, label }: { structured: Structured; label: string }): ReactNode {\n const summary = structuredSummary(structured.data);\n const first = Array.isArray(structured.data) ? structured.data.find(isPlainObject) : structured.data;\n const picture = isPlainObject(first) ? Object.entries(first).find(([k, v]) => isImageUrl(v, k))?.[1] : undefined;\n return (\n <Popover>\n <PopoverTrigger asChild>\n <button\n type=\"button\"\n className=\"flex h-[1.5em] min-w-0 max-w-full items-center gap-1.5 text-left text-sm hover:underline\"\n data-records-structured-cell=\"\"\n onClick={stop}\n onDoubleClick={stop}\n aria-label={`Open ${label} (${summary})`}\n >\n {typeof picture === \"string\" ? (\n <img src={picture} alt=\"\" loading=\"lazy\" referrerPolicy=\"no-referrer\" className=\"size-4 shrink-0 rounded-sm object-cover\" />\n ) : null}\n <span className=\"min-w-0 truncate\">{summary}</span>\n </button>\n </PopoverTrigger>\n <PopoverContent\n align=\"start\"\n collisionPadding={8}\n className=\"max-h-[70vh] w-[min(40rem,calc(100vw-1rem))] max-w-[calc(100vw-1rem)] overflow-y-auto p-3\"\n onClick={stop}\n >\n <StructuredValueView structured={structured} label={label} />\n </PopoverContent>\n </Popover>\n );\n}\n","\"use client\";\n\n// src/Condition.tsx — @ai-matrx/records-ui\n//\n// THE ONE CONDITION BUILDER, AND IT IS THE ONE THAT WAS ALREADY HERE.\n//\n// It was a private function inside `FormBuilder.tsx` — \"Ask only when <field> <is> <value>\"\n// — writing the store's own Rule expression by Field id. Lane STAGE-RULES-2 needed a\n// condition builder for the stage-settings screen, and building a second one is how a\n// platform ends up with two dialects of the same language that disagree about what `gt`\n// does to an empty value. So the form builder's one moved here, unchanged in what it\n// writes, and both screens mount it.\n//\n// ONE THING DID CHANGE, AND IT IS A DEFECT THIS MOVE FOUND. The value was written as a\n// STRING, always. `{\"op\":\"gt\",\"args\":[{\"field\":…},{\"const\":\"5000\"}]}` compares a number\n// column against the TEXT \"5000\", which is not the question anybody asked — and on a\n// stage gate it is the difference between \"nothing over $5,000\" working and not. A value\n// that is a number is now written as a number, and a value that is not is left exactly as\n// it was typed. `true`/`false` go the same way, for the same reason.\n//\n// IT NESTS NOW, AND IT IS STILL ONE BUILDER (TAILS-2, 2026-09-21). \"It stays deliberately\n// SMALL: one field, one comparison, one value… when a second clause is actually needed, it\n// is added HERE and both screens get it\" — this is that day. The gate the homeowner\n// actually wanted, *\"anything over $10,000 without a signed contract needs sign-off\"*, is\n// two clauses, and until now writing it meant a raw `pipeline_declare` call, which is not\n// something a non-technical person does.\n//\n// SO: `ConditionGroup` draws a list of clauses joined by ALL / ANY, and a clause may itself\n// be one more ALL / ANY group.\n//\n// GROUPS INSIDE GROUPS, AS DEEP AS THE STORE (lane S2-PRIME FILTER-GROUPS, 2026-09-24). A\n// dispatcher's morning view — \"(Open or Scheduled) and (in Ojai or Maria's) and not Low\" — is\n// three groups, one of them a NOT, and the one-level limit could not draw it. The store now\n// compiles the Rule shape to any depth into the one WHERE clause the grid, the board and the\n// dashboard share (`custom.record_filter_sql`), so the builder draws what the store answers:\n// every group carries its own joiner (All / Any / None / Not all), and \"Add a group\" nests a\n// new one under any group. Airtable's and Notion's filter builders are the bar: a group is a\n// box with its own and/or, and nothing about depth is special. A condition the builder still\n// cannot draw (a sibling count, a comparison between two columns) keeps STAGE-RULES-2's\n// answer, unchanged: it is read out in the store's own words with a \"Replace it\" button.\n//\n// THE WORDS ARE ALL / ANY, NOT AND / OR. \"All of these are true\" and \"any of these are\n// true\" is what the person is choosing; `and`/`or` is what the store stores. The store's\n// own node names never reach the screen.\n\nimport { createContext, useContext, useEffect, useState } from \"react\";\nimport { BasicInput, Button } from \"@ai-matrx/design-system\";\nimport { optionKey, optionLabel, rankTypedMatches, type Field, type RuleExpression } from \"@ai-matrx/records\";\nimport { PickOrAdd } from \"./PickOrAdd\";\nimport { choiceChipLookOf } from \"./choiceLooks\";\nimport { useOptionalRecordsClient } from \"@ai-matrx/records/react\";\nimport { RelationPicker } from \"./RelationPicker\";\nimport { PickOne } from \"./PickOne\";\nimport { fieldOptionsOnce } from \"./askOnce\";\nimport { editorKindFor } from \"./parity\";\nimport { getPersonTimeZone } from \"./personTime\";\n\n/** The comparisons a condition can make. The store's own operator names. */\nexport const CONDITION_OPS: Array<{ op: string; label: string }> = [\n { op: \"eq\", label: \"is\" },\n { op: \"ne\", label: \"is not\" },\n { op: \"present\", label: \"has been answered\" },\n { op: \"gt\", label: \"is more than\" },\n { op: \"lt\", label: \"is less than\" },\n { op: \"gte\", label: \"is at least\" },\n { op: \"lte\", label: \"is at most\" },\n];\n\n/**\n * THE LIST QUESTIONS (lane NOTION-Q, 2026-10-14). A multi-select column holds a LIST of choices, so a view's filter\n * asks it Notion's way: contains / does not contain / is empty / is not empty. Offered only where a view's filter\n * mounts the builder (`FilterTermsContext`); the store answers them through `custom.filter_list_op`.\n */\nexport const LIST_TERMS: Array<{ op: string; label: string }> = [\n { op: \"contains\", label: \"contains\" },\n { op: \"not_contains\", label: \"does not contain\" },\n { op: \"is_empty\", label: \"is empty\" },\n { op: \"is_not_empty\", label: \"is not empty\" },\n];\n/**\n * ROLLUP-FILTER (2026-10-18): SEVERAL CHOICES AT ONCE. \"Status is any of Sent, Overdue\" / \"is none of Draft, Cancelled\" —\n * the store's `has_any` / `has_none` Rule nodes over a list of the column's choices (key or label, any case), so a total\n * can add up the invoices still awaiting payment. Offered on a choice column where the host mounts\n * `ChoiceListTermsContext` (the total's filter) or a view's filter (`FilterTermsContext`).\n */\nexport const CHOICE_LIST_TERMS: Array<{ op: string; label: string }> = [\n { op: \"has_any\", label: \"is any of\" },\n { op: \"has_none\", label: \"is none of\" },\n];\nexport const ChoiceListTermsContext = createContext(false);\nconst CHOICE_LIST_OPS: ReadonlySet<string> = new Set([\"has_any\", \"has_none\"]);\n/** The words a `has_any` / `has_none` condition holds, always as a list of strings. */\nfunction wordsOfValue(value: unknown): string[] {\n if (Array.isArray(value)) return value.filter((v): v is string => typeof v === \"string\");\n return typeof value === \"string\" && value !== \"\" ? [value] : [];\n}\n/** Terms that take no value: the column alone is the question. */\nconst VALUELESS_OPS: ReadonlySet<string> = new Set([\"present\", \"is_empty\", \"is_not_empty\"]);\n\n/** Where a linked column's id and the id of the field of the table it points at are joined in a picker value. */\nconst LINK_SEP = \">\";\n\n/**\n * A FIELD OF A LINKED TABLE (lane NOTION-Q): \"Client › Client Type is not Past Client\". The clause is the store's\n * `linked` node — {\"op\": \"linked\", \"match\": \"any\" | \"none\", \"args\": [{\"field\": <relation>}, <condition on the\n * linked table>]}. \"is\" means some linked record is it; \"is not\" means no linked record is, so a post with no\n * client stays (Notion's \"none of\"). Other matches (`every`) are the agent's and are read out, not drawn.\n */\nexport function linkedNode(viaId: string, innerId: string, op: \"eq\" | \"ne\", value: unknown): RuleExpression {\n return {\n op: \"linked\",\n match: op === \"eq\" ? \"any\" : \"none\",\n args: [{ field: viaId }, { op: \"eq\", args: [{ field: innerId }, { const: value }] }],\n } as unknown as RuleExpression;\n}\n\n/** The parts of a linked clause this row can draw, or null when it is any other clause. */\nexport function linkedOf(expr: unknown): { via: string; inner: string; op: \"eq\" | \"ne\"; value: unknown } | null {\n const node = asNode(expr);\n if (!node || node[\"op\"] !== \"linked\") return null;\n const [rel, cond] = argsOf(node) as Array<Record<string, unknown> | undefined>;\n const innerNode = asNode(cond);\n const [a, b] = innerNode ? (argsOf(innerNode) as Array<Record<string, unknown> | undefined>) : [];\n const match = node[\"match\"] ?? \"any\";\n if (!rel || typeof rel[\"field\"] !== \"string\" || !innerNode || innerNode[\"op\"] !== \"eq\") return null;\n if (!a || typeof a[\"field\"] !== \"string\" || !b || !(\"const\" in b)) return null;\n if (match !== \"any\" && match !== \"none\") return null;\n return { via: rel[\"field\"], inner: a[\"field\"], op: match === \"any\" ? \"eq\" : \"ne\", value: b[\"const\"] };\n}\n\n/**\n * THE TERMS ONLY A VIEW'S FILTER KNOWS (lane NOTION-SMALL-2). A list is asked at the moment it is read,\n * so a filter can say \"is Me\" (whoever is reading) and \"is today / this week / in the next 7 days\" (the\n * day it is read). A stage gate or a form question judges one record being written and has no such\n * words, so the builder offers them only where the view's filter mounts it (`FilterTermsContext`).\n */\nexport const FilterTermsContext = createContext(false);\n\nexport const RELATIVE_DAY_TERMS: ReadonlyArray<{ kind: string; label: string; takesDays?: boolean }> = [\n { kind: \"today\", label: \"is today\" },\n { kind: \"tomorrow\", label: \"is tomorrow\" },\n { kind: \"yesterday\", label: \"is yesterday\" },\n { kind: \"this_week\", label: \"is this week\" },\n { kind: \"next_week\", label: \"is next week\" },\n { kind: \"last_week\", label: \"is last week\" },\n { kind: \"this_month\", label: \"is this month\" },\n { kind: \"next_month\", label: \"is next month\" },\n { kind: \"last_month\", label: \"is last month\" },\n { kind: \"before_today\", label: \"is before today\" },\n { kind: \"next_days\", label: \"is in the next … days\", takesDays: true },\n { kind: \"past_days\", label: \"is in the past … days\", takesDays: true },\n];\n\n/** A date column asked about a day range worked out when the list is read. */\nexport function relativeDayNode(fieldId: string, kind: string, days?: number): RuleExpression {\n const zone = getPersonTimeZone();\n const window: Record<string, unknown> = { relative: kind };\n if (RELATIVE_DAY_TERMS.find((t) => t.kind === kind)?.takesDays) window[\"n\"] = days ?? 7;\n if (zone) window[\"tz\"] = zone;\n return { op: \"within\", args: [{ field: fieldId }, { const: window }] } as RuleExpression;\n}\n\n/** The relative day range a clause holds, or null when it is any other clause. */\nexport function relativeDayOf(expr: unknown): { kind: string; days: number | null; field: string } | null {\n const node = asNode(expr);\n if (!node || node[\"op\"] !== \"within\") return null;\n const [a, b] = argsOf(node) as Array<Record<string, unknown> | undefined>;\n const window = asNode(b?.[\"const\"]);\n if (!a || typeof a[\"field\"] !== \"string\" || !window || typeof window[\"relative\"] !== \"string\") return null;\n const days = typeof window[\"n\"] === \"number\" ? window[\"n\"] : null;\n return { kind: window[\"relative\"], days, field: a[\"field\"] };\n}\n\n/** A person column asked about whoever is reading. */\nexport function meNode(fieldId: string, negate: boolean): RuleExpression {\n return { op: negate ? \"ne\" : \"eq\", args: [{ field: fieldId }, { const: { me: true } }] } as RuleExpression;\n}\n\n/** \"me\" / \"not_me\" when a clause compares a column with the reader, else null. */\nexport function meOf(expr: unknown): { which: \"me\" | \"not_me\"; field: string } | null {\n const node = asNode(expr);\n if (!node || (node[\"op\"] !== \"eq\" && node[\"op\"] !== \"ne\")) return null;\n const [a, b] = argsOf(node) as Array<Record<string, unknown> | undefined>;\n const value = asNode(b?.[\"const\"]);\n if (!a || typeof a[\"field\"] !== \"string\" || !value || value[\"me\"] !== true) return null;\n return { which: node[\"op\"] === \"eq\" ? \"me\" : \"not_me\", field: a[\"field\"] };\n}\n\n/**\n * A column this condition may speak about, by id — which is how the store names them.\n *\n * 🚨 IT CARRIES THE FIELD NOW, AND THAT IS A DEFECT BEING FIXED (lane RELATION-DISPLAY-2,\n * 2026-09-21). This was `{id, key, label}` and nothing else, so the builder could not know\n * that a column POINTS AT ANOTHER RECORD. A relation clause therefore rendered the same\n * plain text box every other clause gets — and since a relation's stored value is the\n * other record's id (FLD-6 / REL-1), the only way to write a true one was for a person to\n * find and TYPE A UUID. Nobody does that, which means \"only jobs for this customer\" was a\n * gate a non-technical person could not write at all, on a builder whose whole purpose is\n * that they can.\n *\n * `field` is OPTIONAL and everything still works without it: a caller that passes only the\n * three strings gets exactly the old behavior. Both callers in this package already hold\n * the whole `Field` and were throwing it away one line before handing it over.\n */\nexport interface ConditionField {\n id: string;\n key: string;\n label: string;\n /**\n * The Field itself, when the caller has it. Present, a relation clause picks a record BY\n * ITS DISPLAYED WORDS through `RelationPicker` — the same picker the cell uses, reading\n * the same `relation_words_many` the cell reads, so what a person chooses in a filter and\n * what they see in the column are the same string. It writes the ID, which is what the\n * store compares.\n */\n field?: Field;\n /**\n * Set when this entry is a field of the table a relation column POINTS AT (lane NOTION-Q): `id` is\n * `<relation field id>><field id>` and `via` names the relation. Offered only by a view's filter.\n */\n via?: { id: string; fieldId: string } | undefined;\n}\n\n/** Does this clause compare against a record rather than a typed value? */\nfunction pointsAtARecord(f: ConditionField | undefined): f is ConditionField & { field: Field } {\n return !!f?.field && f.field.type === \"relation\" && !!f.field.relation_target;\n}\n\n/** Is this a column of choices (a pick-list, one or many)? */\nfunction isChoiceColumn(f: ConditionField | undefined): f is ConditionField & { field: Field } {\n if (!f?.field) return false;\n const kind = String(editorKindFor(f.field));\n return kind === \"select\" || kind === \"multi_select\";\n}\n\n/**\n * A CHOICE COLUMN IS COMPARED BY ONE OF ITS CHOICES, picked from the column's own list: \"Status\n * is [Scheduled]\" never asks a person to type the word and hope it matches. A column whose\n * choices cannot be read (no store on this screen, or a refusal) keeps the typed box.\n */\n/**\n * SEVERAL CHOICES OF ONE COLUMN (ROLLUP-FILTER): every choice the column has, as a chip the person switches on or off.\n * A choice already written by key or by a different case still reads as switched on; a word the column does not\n * have is kept and shown, never dropped. The value is the list of words, in the column's order, then any others.\n */\nfunction ChoiceValues({ field, value, onChange }: { field: Field; value: string[]; onChange: (words: string[]) => void }) {\n const client = useOptionalRecordsClient();\n const [choices, setChoices] = useState<Array<{ key: string; label: string }> | null>(null);\n useEffect(() => {\n if (!client) return;\n let cancelled = false;\n void fieldOptionsOnce(client, field.id).then((got) => {\n if (cancelled) return;\n setChoices(got.ok ? (got.data ?? []).map((o) => ({ key: optionKey(o), label: optionLabel(o) ?? \"\" })).filter((c) => c.label !== \"\") : []);\n });\n return () => {\n cancelled = true;\n };\n }, [client, field.id]);\n const lower = value.map((w) => w.toLowerCase());\n const isOn = (c: { key: string; label: string }) => lower.includes(c.key.toLowerCase()) || lower.includes(c.label.toLowerCase());\n const known = (choices ?? []).flatMap((c) => [c.key.toLowerCase(), c.label.toLowerCase()]);\n const strays = value.filter((w) => !known.includes(w.toLowerCase()));\n const toggle = (c: { key: string; label: string }) => {\n const rest = value.filter((w) => w.toLowerCase() !== c.key.toLowerCase() && w.toLowerCase() !== c.label.toLowerCase());\n const next = isOn(c) ? rest : [...rest, c.label];\n const order = (choices ?? []).map((x) => x.label);\n onChange([...next].sort((a, b) => (order.indexOf(a) === -1 ? 1e6 : order.indexOf(a)) - (order.indexOf(b) === -1 ? 1e6 : order.indexOf(b))));\n };\n if (!choices || choices.length === 0) {\n return (\n <BasicInput\n className=\"h-8 w-40 text-xs\"\n aria-label=\"Condition values, separated by commas\"\n value={value.join(\", \")}\n onChange={(e) => onChange(e.target.value.split(\",\").map((w) => w.trim()).filter((w) => w !== \"\"))}\n />\n );\n }\n return (\n <span className=\"inline-flex flex-wrap items-center gap-1\" data-records-condition-choices=\"\" data-pick-values={value.join(\"|\")}>\n {choices.map((c) => (\n <Button\n key={c.key}\n type=\"button\"\n size=\"sm\"\n variant={isOn(c) ? \"default\" : \"outline\"}\n className=\"h-7 px-2 text-xs\"\n aria-pressed={isOn(c)}\n aria-label={`${c.label} for ${field.label || field.key}`}\n onClick={() => toggle(c)}\n >\n {c.label}\n </Button>\n ))}\n {strays.map((w) => (\n <Button key={`stray-${w}`} type=\"button\" size=\"sm\" variant=\"default\" className=\"h-7 px-2 text-xs\" aria-pressed aria-label={`${w} (not a choice of this column)`} onClick={() => onChange(value.filter((x) => x !== w))}>\n {w}\n </Button>\n ))}\n </span>\n );\n}\n\nfunction ChoiceValue({ field, value, onChange }: { field: Field; value: string; onChange: (word: string) => void }) {\n const client = useOptionalRecordsClient();\n const [choices, setChoices] = useState<Array<{ key: string; label: string }> | null>(null);\n const [open, setOpen] = useState(false);\n const [search, setSearch] = useState(\"\");\n useEffect(() => {\n if (!client) return;\n let cancelled = false;\n void fieldOptionsOnce(client, field.id).then((got) => {\n if (cancelled) return;\n setChoices(\n got.ok\n ? (got.data ?? [])\n .map((o) => ({ key: optionKey(o), label: optionLabel(o) ?? \"\" }))\n .filter((c) => c.label !== \"\")\n : [],\n );\n });\n return () => {\n cancelled = true;\n };\n }, [client, field.id]);\n if (!choices || choices.length === 0) {\n return (\n <BasicInput\n className=\"h-8 w-28 text-xs\"\n aria-label=\"Condition value\"\n value={value}\n onChange={(e) => onChange(e.target.value)}\n />\n );\n }\n // THE SAME COLORED, SEARCHABLE LIST AS THE CELL EDITOR (lane CELL-EDITORS, night walk 2026-10-06): the\n // filter's value was a bare text list with no search and no colors. It is the one pick list\n // (`PickOrAdd`), each choice the chip its column wears (`choiceChipLookOf`).\n const shown = rankTypedMatches(choices, search.trim(), (c) => c.label);\n return (\n <span className=\"inline-flex min-w-0\" data-records-condition-choice=\"\" data-pick-value={value}>\n <PickOrAdd\n triggerSize=\"compact\"\n triggerLabel={`Choice for ${field.label || field.key}`}\n // THE CHOICE'S WORDS, NEVER ITS KEY (TYPEFORM-2): a condition written by an agent or a form\n // holds the option key; it is shown by the label the person reads.\n triggerText={choices.find((c) => c.key === value || c.label === value)?.label ?? (value || \"Choose\")}\n open={open}\n onOpenChange={(next) => {\n setOpen(next);\n if (!next) setSearch(\"\");\n }}\n search={search}\n onSearch={setSearch}\n items={shown.map((c) => ({\n id: c.key,\n label: c.label,\n chip: choiceChipLookOf(field, c.key, c.label).className,\n picked: c.label === value || c.key === value,\n attrs: { \"data-pick-value\": c.label },\n }))}\n onPick={(key) => {\n const picked = choices.find((c) => c.key === key);\n if (picked) onChange(picked.label);\n setOpen(false);\n setSearch(\"\");\n }}\n empty={<p className=\"p-2 text-xs text-muted-foreground\">No match</p>}\n />\n </span>\n );\n}\n\nexport interface ConditionRowProps {\n /** The words before the row: \"Ask only when\", \"When\". */\n lead: string;\n /** The expression as it stands, or null for \"no condition at all\". */\n expr: RuleExpression | Record<string, unknown> | null | undefined;\n fields: ConditionField[];\n onChange: (next: RuleExpression | null) => void;\n /** What the empty option says: \"always\" on a form question, \"every card\" on a gate. */\n emptyLabel?: string;\n className?: string | undefined;\n}\n\n/**\n * CAN THIS ROW DRAW THAT CONDITION? The builder writes ONE clause — a field, a comparison\n * and a value — and the store's Rule language is bigger than that. A node it cannot draw\n * (a `sibling_count`, an `and`/`or`, a comparison between two columns) rendered as an empty\n * picker is a screen SAYING there is no condition when there is one, and it invites somebody\n * to replace a rule they cannot see. Every caller asks this first and says so instead.\n *\n * Found by a screenshot: the homeowner's own rule — \"a second quote from a DIFFERENT\n * contractor\", a `sibling_count` — opened in the editor as \"— pick a column —\".\n */\nexport function conditionIsSimple(expr: RuleExpression | Record<string, unknown> | null | undefined): boolean {\n if (expr === null || expr === undefined) return true;\n if (relativeDayOf(expr) !== null || meOf(expr) !== null || linkedOf(expr) !== null) return true;\n const node = expr as { op?: unknown; args?: unknown };\n if (\n typeof node.op !== \"string\" ||\n !(CONDITION_OPS.some((c) => c.op === node.op) || LIST_TERMS.some((c) => c.op === node.op) || CHOICE_LIST_OPS.has(node.op))\n ) {\n return false;\n }\n if (!Array.isArray(node.args)) return false;\n const first = node.args[0] as { field?: unknown } | undefined;\n if (!first || typeof first.field !== \"string\") return false;\n if (VALUELESS_OPS.has(node.op)) return node.args.length === 1;\n const second = node.args[1] as { const?: unknown } | undefined;\n return node.args.length === 2 && !!second && \"const\" in second;\n}\n\n/**\n * What a condition this row cannot draw actually ASKS, in the words the store uses for it.\n * Not a pretty-printer for the whole Rule language — enough that a person reading a rule\n * they cannot edit here still knows what it does before deciding to replace it.\n */\nexport function conditionInWords(\n expr: RuleExpression | Record<string, unknown> | null | undefined,\n fields: ConditionField[],\n): string {\n const name = (id: unknown) => {\n const f = fields.find((x) => x.id === id);\n return f ? f.label || f.key : \"a column\";\n };\n const said: Record<string, string> = {\n eq: \"is\", ne: \"is not\", gt: \"is more than\", lt: \"is less than\",\n gte: \"is at least\", lte: \"is at most\", and: \"and\", or: \"or\",\n matches: \"matches\", contains: \"contains\", not_contains: \"does not contain\",\n has_any: \"has any of\", has_all: \"has all of\", has_none: \"has none of\", is_exactly: \"is exactly\",\n };\n const walk = (node: unknown): string => {\n if (node === null || node === undefined) return \"nothing\";\n const n = node as Record<string, unknown>;\n if (\"const\" in n) return JSON.stringify(n[\"const\"]);\n if (typeof n[\"field\"] === \"string\" && !(\"op\" in n)) return name(n[\"field\"]);\n const op = typeof n[\"op\"] === \"string\" ? n[\"op\"] : \"\";\n if (op === \"previous\" && typeof n[\"field\"] === \"string\") return `what ${name(n[\"field\"])} used to say`;\n if (op === \"sibling_count\") {\n const same = (n[\"same\"] as unknown[] | undefined) ?? [];\n const differs = (n[\"differs\"] as unknown[] | undefined) ?? [];\n const sameWords = same.length > 0 ? ` for the same ${same.map(name).join(\" and \")}` : \"\";\n const diffWords = differs.length > 0 ? ` from a different ${differs.map(name).join(\" and \")}` : \"\";\n return `how many others there are${sameWords}${diffWords}`;\n }\n if (op === \"stage_count\") return \"how many are in that column already\";\n if (op === \"actor_at_least\") return `whoever is moving it is at least ${String(n[\"level\"] ?? \"somebody\")}`;\n const args = Array.isArray(n[\"args\"]) ? (n[\"args\"] as unknown[]) : [];\n if (op === \"not\") return `not ${walk(args[0])}`;\n if (op === \"present\") return `${walk(args[0])} has been answered`;\n if (op === \"is_empty\") return `${walk(args[0])} is empty`;\n if (op === \"is_not_empty\") return `${walk(args[0])} is not empty`;\n if (op === \"linked\") {\n const how = n[\"match\"] === \"every\" ? \"every\" : n[\"match\"] === \"none\" ? \"none of\" : \"any\";\n return `${how} linked record in ${walk(args[0])}: ${walk(args[1])}`;\n }\n const dayRange = relativeDayOf(n);\n if (dayRange) {\n const term = RELATIVE_DAY_TERMS.find((t) => t.kind === dayRange.kind);\n const said = term ? term.label.replace(\"…\", String(dayRange.days ?? 7)) : \"is in a day range\";\n return `${name(dayRange.field)} ${said}`;\n }\n const reader = meOf(n);\n if (reader) return `${name(reader.field)} ${reader.which === \"me\" ? \"is me\" : \"is not me\"}`;\n const word = said[op] ?? op;\n if (op === \"and\" || op === \"or\") return args.map(walk).join(` ${word} `);\n if (args.length === 2) return `${walk(args[0])} ${word} ${walk(args[1])}`;\n if (args.length === 1) return `${walk(args[0])} ${word}`;\n return op;\n };\n return walk(expr);\n}\n\n/**\n * A value typed into a text box, as the store should hold it. A number column compared\n * against the text \"5000\" is not the comparison anybody meant, and the store has no way\n * to guess which was intended after the fact.\n */\nexport function conditionValue(typed: string): string | number | boolean {\n const trimmed = typed.trim();\n if (trimmed === \"\") return typed;\n if (trimmed === \"true\") return true;\n if (trimmed === \"false\") return false;\n if (/^-?\\d+(\\.\\d+)?$/.test(trimmed)) {\n const asNumber = Number(trimmed);\n if (Number.isFinite(asNumber)) return asNumber;\n }\n return typed;\n}\n\n/** The one condition row. It writes the store's own Rule expression, by Field id. */\nexport function ConditionRow({ lead, expr, fields, onChange, emptyLabel = \"always\", className }: ConditionRowProps) {\n const node = (expr ?? null) as { op?: string; args?: Array<{ field?: string; const?: unknown }> } | null;\n const filterTerms = useContext(FilterTermsContext);\n const choiceListTerms = useContext(ChoiceListTermsContext) || filterTerms;\n const relative = relativeDayOf(expr);\n const reader = meOf(expr);\n const linked = linkedOf(expr);\n // The comparison the picker shows: a relative day range or \"me\" is a term of its own over `within` / `eq`.\n const op = relative ? `rel:${relative.kind}` : reader ? reader.which : linked ? linked.op : (node?.op ?? \"\");\n const onField = linked ? `${linked.via}${LINK_SEP}${linked.inner}` : (node?.args?.[0]?.field ?? \"\");\n const value = relative || reader ? \"\" : linked ? linked.value : (node?.args?.[1]?.const ?? \"\");\n const chosen = fields.find((f) => f.id === onField);\n const chosenKind = chosen?.field ? String(editorKindFor(chosen.field)) : \"\";\n const choiceTerms = choiceListTerms && !chosen?.via && (chosenKind === \"select\" || chosenKind === \"multi_select\") ? CHOICE_LIST_TERMS : [];\n const extraTerms: Array<{ op: string; label: string }> = [\n ...(!filterTerms || chosen?.via ? [] :\n chosenKind === \"datetime\" ? RELATIVE_DAY_TERMS.map((t) => ({ op: `rel:${t.kind}`, label: t.label })) :\n chosenKind === \"member\" ? [{ op: \"me\", label: \"is me\" }, { op: \"not_me\", label: \"is not me\" }] :\n chosenKind === \"multi_select\" ? LIST_TERMS :\n []),\n ...choiceTerms,\n ];\n // A linked field is asked \"is\" / \"is not\" only: some linked record is it, or none is.\n const baseTerms = chosen?.via ? CONDITION_OPS.filter((c) => c.op === \"eq\" || c.op === \"ne\") : CONDITION_OPS;\n const relativeTerm = relative ? RELATIVE_DAY_TERMS.find((t) => t.kind === relative.kind) : undefined;\n\n function write(next: { op?: string; field?: string; value?: unknown; days?: number }) {\n const picked = next.op;\n const fieldNow = next.field ?? onField;\n if (fieldNow && picked !== undefined && (picked.startsWith(\"rel:\") || picked === \"me\" || picked === \"not_me\")) {\n onChange(picked === \"me\" || picked === \"not_me\" ? meNode(fieldNow, picked === \"not_me\") : relativeDayNode(fieldNow, picked.slice(4), relative?.days ?? undefined));\n return;\n }\n if (fieldNow && next.days !== undefined && relative) {\n onChange(relativeDayNode(fieldNow, relative.kind, next.days));\n return;\n }\n if (next.field !== undefined && (relative || reader || linked)) {\n // A different column starts again at \"is\": the old term may not exist for the new column's kind.\n const target = fields.find((f) => f.id === next.field);\n onChange(\n !next.field ? null :\n target?.via ? linkedNode(target.via.id, target.via.fieldId, \"eq\", \"\") :\n ({ op: CONDITION_OPS[0]!.op, args: [{ field: next.field }, { const: \"\" }] } as RuleExpression),\n );\n return;\n }\n // A FRESH ROW STARTS AT \"is\". Picking a column on an empty row used to write `null` —\n // no comparison had been chosen yet, and no comparison picker is drawn until a column is —\n // so on a row with nothing in it the column picker was a control that did nothing\n // (found by S2-PRIME's \"Add a group\" test). The first comparison in the list is the default.\n const chosenOp = next.op ?? (op || (next.field ? CONDITION_OPS[0]!.op : \"\"));\n const chosenField = next.field ?? onField;\n let chosenValue = next.value ?? value;\n // ONE WORD BECOMES A LIST going to \"any of / none of\", and a list gives its first word back going to \"is\".\n if (CHOICE_LIST_OPS.has(chosenOp)) chosenValue = wordsOfValue(chosenValue);\n else if (Array.isArray(chosenValue)) chosenValue = wordsOfValue(chosenValue)[0] ?? \"\";\n if (!chosenOp || !chosenField) {\n onChange(null);\n return;\n }\n const target = fields.find((f) => f.id === chosenField);\n if (target?.via) {\n onChange(linkedNode(target.via.id, target.via.fieldId, chosenOp === \"ne\" ? \"ne\" : \"eq\", chosenValue));\n return;\n }\n onChange(\n VALUELESS_OPS.has(chosenOp)\n ? ({ op: chosenOp, args: [{ field: chosenField }] } as RuleExpression)\n : ({ op: chosenOp, args: [{ field: chosenField }, { const: chosenValue }] } as RuleExpression),\n );\n }\n\n return (\n <div className={className ?? \"flex flex-wrap items-center gap-1 text-xs\"}>\n <span className=\"text-muted-foreground\">{lead}</span>\n <PickOne\n label=\"Condition field\"\n className=\"h-8 w-auto min-w-[7rem] text-xs\"\n value={onField}\n onChange={(field) => write({ field })}\n options={[{ value: \"\", label: emptyLabel }, ...fields.map((f) => ({ value: f.id, label: f.label || f.key }))]}\n attrs={{ \"data-condition\": \"field\" }}\n />\n {/* A CONDITION ON A QUESTION THAT IS GONE SAYS SO (TYPEFORM-2), never a blank picker. */}\n {onField && !fields.some((f) => f.id === onField) ? (\n <span\n className=\"rounded bg-destructive px-1.5 py-0.5 text-[11px] font-medium text-destructive-foreground\"\n title=\"This condition names a question that is no longer on the form.\"\n data-records-condition-missing=\"\"\n >\n Missing question\n </span>\n ) : null}\n {onField ? (\n <>\n <PickOne\n label=\"Condition comparison\"\n className=\"h-8 w-auto min-w-[6rem] text-xs\"\n value={op}\n onChange={(next) => write({ op: next })}\n options={[...baseTerms, ...extraTerms].map((c) => ({ value: c.op, label: c.label }))}\n attrs={{ \"data-condition\": \"comparison\" }}\n />\n {relative ? (\n relativeTerm?.takesDays ? (\n <BasicInput\n className=\"h-8 w-16 text-xs\"\n type=\"number\"\n min={0}\n aria-label=\"Number of days\"\n value={String(relative.days ?? 7)}\n onChange={(e) => write({ days: Math.max(0, Math.floor(Number(e.target.value) || 0)) })}\n />\n ) : null\n ) : reader || VALUELESS_OPS.has(op) ? null : pointsAtARecord(chosen) ? (\n // A RECORD IS PICKED BY ITS WORDS, NEVER TYPED AS AN ID. The same picker the\n // cell uses, on the same `relation_words_many` the cell reads, so a filter and\n // the column it filters can never disagree about what a record is called. It\n // is asked for ONE record even when the column holds several: a clause compares\n // against one value, and a picker that let somebody choose three would be\n // writing an expression this row cannot draw back.\n <RelationPicker\n field={{ ...chosen.field, multi: false }}\n value={value === \"\" ? null : value}\n onChange={(next) => write({ value: next === null || next === undefined ? \"\" : String(next) })}\n id=\"condition-value-record\"\n className=\"min-w-[8rem]\"\n // PICKING A VALUE TO FILTER BY IS NOT A REASON TO ADD A CUSTOMER TO THE\n // BOOK. Every other relation surface offers \"New <thing>\"; this one is\n // choosing what to LOOK at, and a create here would put a row in the\n // target Table that nobody asked for.\n allowCreate={false}\n />\n ) : isChoiceColumn(chosen) && CHOICE_LIST_OPS.has(op) ? (\n <ChoiceValues field={chosen.field} value={wordsOfValue(value)} onChange={(words) => write({ value: words })} />\n ) : isChoiceColumn(chosen) && (op === \"eq\" || op === \"ne\" || op === \"contains\" || op === \"not_contains\") ? (\n <ChoiceValue field={chosen.field} value={String(value ?? \"\")} onChange={(word) => write({ value: word })} />\n ) : (\n <BasicInput\n className=\"h-8 w-28 text-xs\"\n aria-label=\"Condition value\"\n value={String(value ?? \"\")}\n onChange={(e) => write({ value: conditionValue(e.target.value) })}\n />\n )}\n </>\n ) : null}\n </div>\n );\n}\n\n// ═══════════════════════════════════════════════════════════════════════════════════════\n// GROUPS OF CLAUSES, NESTED AS DEEP AS A PERSON BUILDS THEM.\n// ═══════════════════════════════════════════════════════════════════════════════════════\n\n/**\n * The four ways a group's clauses can be joined, in the words a person chooses between.\n * `none` is NOT(ANY …) and `notall` is NOT(ALL …) — the store's own `not` over its own `or` /\n * `and`, so a group is still nothing but Rule nodes.\n */\nexport type ConditionJoiner = \"and\" | \"or\" | \"none\" | \"notall\";\n\nconst JOINERS: ReadonlyArray<{ op: ConditionJoiner; label: string }> = [\n { op: \"and\", label: \"All of these are true\" },\n { op: \"or\", label: \"Any of these is true\" },\n { op: \"none\", label: \"None of these is true\" },\n { op: \"notall\", label: \"Not all of these are true\" },\n];\n\ntype Node = Record<string, unknown>;\n\nfunction asNode(expr: unknown): Node | null {\n return expr && typeof expr === \"object\" && !Array.isArray(expr) ? (expr as Node) : null;\n}\n\nfunction argsOf(node: Node): unknown[] {\n return Array.isArray(node[\"args\"]) ? (node[\"args\"] as unknown[]) : [];\n}\n\n/**\n * Is this node a group, and which? An `and` / `or` with its arguments; a `not` of an `or` is\n * \"None of these\", a `not` of an `and` is \"Not all of these\", and a `not` of one clause is\n * \"None of these\" with one clause in it — which is exactly what \"priority is not Low, as a group\"\n * reads as.\n */\nexport function conditionGroupOf(expr: unknown): { joiner: ConditionJoiner; args: unknown[] } | null {\n const node = asNode(expr);\n if (!node) return null;\n const op = node[\"op\"];\n if (op === \"and\" || op === \"or\") return { joiner: op, args: argsOf(node) };\n if (op === \"not\") {\n const inner = asNode(argsOf(node)[0]);\n if (!inner) return null;\n if (inner[\"op\"] === \"or\") return { joiner: \"none\", args: argsOf(inner) };\n if (inner[\"op\"] === \"and\") return { joiner: \"notall\", args: argsOf(inner) };\n if (conditionIsSimple(inner)) return { joiner: \"none\", args: [inner] };\n }\n return null;\n}\n\n/**\n * CAN THE BUILDER DRAW THIS CONDITION? — the question every caller asks before it renders,\n * and the reason a rule somebody cannot see is never silently saved over.\n *\n * Drawable means: nothing; one clause; or a group of drawable members, to any depth. `depth`\n * still limits it for a caller that wants a shallower builder (0 = one level of clauses and no\n * nested group). `conditionIsSimple` is still the leaf test and still exported.\n */\nexport function conditionIsDrawable(\n expr: RuleExpression | Record<string, unknown> | null | undefined,\n depth = Number.POSITIVE_INFINITY,\n): boolean {\n if (expr === null || expr === undefined) return true;\n const group = conditionGroupOf(expr);\n if (!group) return conditionIsSimple(expr);\n if (group.args.length === 0) return true;\n return group.args.every((arg) => {\n const node = asNode(arg);\n if (node === null) return false;\n return conditionIsSimple(node) || (depth > 0 && conditionIsDrawable(node, depth - 1));\n });\n}\n\n/** The clauses of an expression, as the group editor holds them: always a list. */\nfunction clausesOf(expr: RuleExpression | Record<string, unknown> | null | undefined): {\n joiner: ConditionJoiner;\n args: unknown[];\n} {\n const group = conditionGroupOf(expr);\n if (group) return group;\n return { joiner: \"and\", args: expr === null || expr === undefined ? [] : [expr] };\n}\n\n/**\n * The store's expression for a group. ONE clause of an ALL / ANY is written as that clause and\n * never as a one-armed `and` — a person who writes one condition and reads back\n * `{\"op\":\"and\",\"args\":[…]}` has been given something they did not type — unless `keep` says the\n * person is holding a group open (they just made it, or just changed its joiner). A NOT group\n * always keeps its `not`, because dropping it would reverse the question.\n */\nexport function writeConditionGroup(joiner: ConditionJoiner, args: unknown[], keep = false): RuleExpression | null {\n const kept = args.filter((a) => a !== null && a !== undefined);\n if (kept.length === 0) return null;\n if (joiner === \"none\" || joiner === \"notall\") {\n const inner = kept.length === 1 && joiner === \"none\"\n ? kept[0]\n : { op: joiner === \"none\" ? \"or\" : \"and\", args: kept };\n return { op: \"not\", args: [inner] } as unknown as RuleExpression;\n }\n if (kept.length === 1 && !keep) return kept[0] as RuleExpression;\n return { op: joiner, args: kept } as unknown as RuleExpression;\n}\n\nexport interface ConditionGroupProps {\n /** The words before the condition: \"When\", \"Ask only when\", \"Show jobs where\". */\n lead: string;\n expr: RuleExpression | Record<string, unknown> | null | undefined;\n fields: ConditionField[];\n onChange: (next: RuleExpression | null) => void;\n /** What the empty option says: \"always\", \"every card\". */\n emptyLabel?: string;\n /**\n * false draws one level of clauses and no \"Add a group\". Left out, groups nest as deep as a\n * person builds them — the depth the store compiles.\n */\n allowNesting?: boolean;\n /**\n * How many levels of groups a person may make below the whole condition (Notion's advanced\n * filter: 2 — a group, and a group inside it). Left out, no limit. A deeper saved question still\n * draws; only \"Add a group\" stops at the limit.\n */\n maxDepth?: number | undefined;\n /** How deep this group sits (0 = the whole condition). Set by the builder itself. */\n depth?: number;\n /** A nested group can take itself away; the outermost one cannot. */\n onRemove?: (() => void) | undefined;\n className?: string | undefined;\n}\n\n/**\n * THE ONE CONDITION BUILDER. One clause reads exactly as it always has — a single row, no\n * joiner, no chrome — and the joiner appears once there is something to join, so a person\n * writing one condition never meets a control for a problem they do not have. A nested group\n * always shows its joiner: it is a box with its own and / or, and that is the whole point of it.\n */\nexport function ConditionGroup({\n lead,\n expr,\n fields,\n onChange,\n emptyLabel = \"always\",\n allowNesting = true,\n maxDepth,\n depth = 0,\n onRemove,\n className,\n}: ConditionGroupProps) {\n const { joiner, args } = clausesOf(expr);\n // A CLAUSE BEING TYPED IS NOT YET A CLAUSE. Pressing \"Add another condition\" or \"Add a group\"\n // opens an empty row; it joins the expression the moment it says something. Appending a `null`\n // to the saved expression instead would either write a half-clause the store cannot read or\n // vanish on the next render, which is a button that does nothing. AN EMPTY GROUP IS NEVER\n // WRITTEN either: `{\"op\":\"or\",\"args\":[]}` is a rule that refuses nobody (STAGE-RULES-2 found\n // exactly that standing in for a real house rule), so a new group is born with its first clause.\n const [drafting, setDrafting] = useState<\"clause\" | \"group\" | null>(null);\n\n const nested = depth > 0;\n const replaceAt = (index: number, next: unknown) => {\n const nextArgs = args.slice();\n if (next === null || next === undefined) nextArgs.splice(index, 1);\n else nextArgs[index] = next;\n onChange(writeConditionGroup(joiner, nextArgs, nested));\n };\n const joinWord = (index: number) =>\n index === 0 ? lead : joiner === \"or\" || joiner === \"none\" ? \"or\" : \"and\";\n const showJoiner = nested || args.length > 1 || joiner === \"none\" || joiner === \"notall\";\n /** The joiner a new group starts with: the other one, which is why anybody makes a group. */\n const opposite: ConditionJoiner = joiner === \"or\" || joiner === \"none\" ? \"and\" : \"or\";\n\n return (\n <div\n className={className ?? \"flex flex-col gap-1 text-xs\"}\n data-testid={nested ? \"condition-nested-group\" : \"condition-group\"}\n data-depth={depth}\n >\n {showJoiner ? (\n <div className=\"flex items-center gap-1\">\n <span className=\"text-muted-foreground\">{nested ? \"Group:\" : lead}</span>\n <PickOne\n label={nested ? `How the conditions in this group are joined (level ${depth + 1})` : \"How these conditions are joined\"}\n className=\"h-8 w-auto min-w-[9rem] text-xs\"\n value={joiner}\n onChange={(next) => onChange(writeConditionGroup(next as ConditionJoiner, args, true))}\n options={JOINERS.map((j) => ({ value: j.op, label: j.label }))}\n attrs={{ \"data-condition\": \"joiner\" }}\n />\n {nested && onRemove ? (\n <Button\n size=\"sm\"\n variant=\"ghost\"\n className=\"h-6 px-1 text-xs\"\n data-testid=\"condition-remove-group\"\n onClick={onRemove}\n >\n Remove this group\n </Button>\n ) : null}\n </div>\n ) : null}\n\n {args.length === 0 ? (\n <ConditionRow\n lead={lead}\n emptyLabel={emptyLabel}\n expr={null}\n fields={fields}\n onChange={(next) => onChange(next)}\n />\n ) : (\n args.map((arg, index) => {\n const group = conditionGroupOf(arg);\n const key = `clause-${index}`;\n if (group && allowNesting) {\n return (\n <div key={key} className=\"ml-4 rounded border border-dashed p-1\">\n <ConditionGroup\n lead={joinWord(index)}\n expr={arg as RuleExpression}\n fields={fields}\n onChange={(next) => replaceAt(index, next)}\n onRemove={() => replaceAt(index, null)}\n emptyLabel={emptyLabel}\n maxDepth={maxDepth}\n depth={depth + 1}\n />\n </div>\n );\n }\n return (\n <ConditionRow\n key={key}\n lead={showJoiner || args.length > 1 ? joinWord(index) : lead}\n emptyLabel={emptyLabel}\n expr={arg as RuleExpression}\n fields={fields}\n onChange={(next) => replaceAt(index, next)}\n />\n );\n })\n )}\n\n {drafting ? (\n <div className={drafting === \"group\" ? \"ml-4 rounded border border-dashed p-1\" : undefined}>\n <ConditionRow\n lead={drafting === \"group\" ? `${joinWord(1)}, a group where` : joinWord(1)}\n emptyLabel={emptyLabel}\n expr={null}\n fields={fields}\n onChange={(next) => {\n if (next === null) return;\n const born = drafting === \"group\" ? writeConditionGroup(opposite, [next], true) : next;\n setDrafting(null);\n onChange(writeConditionGroup(joiner, [...args, born], nested || drafting === \"group\"));\n }}\n />\n </div>\n ) : null}\n\n {args.length > 0 && !drafting ? (\n <div className=\"flex items-center gap-1\">\n <Button\n size=\"sm\"\n variant=\"ghost\"\n className=\"h-6 px-1 text-xs\"\n data-testid=\"condition-add-clause\"\n onClick={() => setDrafting(\"clause\")}\n >\n Add another condition\n </Button>\n {allowNesting && (maxDepth === undefined || depth < maxDepth) ? (\n <Button\n size=\"sm\"\n variant=\"ghost\"\n className=\"h-6 px-1 text-xs\"\n data-testid=\"condition-add-group\"\n onClick={() => setDrafting(\"group\")}\n >\n Add a group\n </Button>\n ) : null}\n </div>\n ) : null}\n </div>\n );\n}\n","\"use client\";\n\n// src/FieldRetype.tsx — @ai-matrx/records-ui\n//\n// CHANGE WHAT A COLUMN HOLDS (merged-grid review 2, 2026-09-27, C3).\n//\n// The field panel used to say \"What a column holds cannot be changed here… add a new column and move\n// the values across\" — while the store has always been able to do it: `custom.migrate_retype`\n// converts every value that converts and keeps each one that does not in that record's `_retired`,\n// with the reason (FLD-4 / T12). The older /data grid reached it through its seam\n// (`changeFieldType`). This carries it into the package's panel, Airtable's \"change field type\",\n// bettered in the two places Airtable is weakest:\n// · BEFORE anything changes, the panel says how many values convert and how many will be kept\n// aside, with examples — counted by the store running the change itself and rolling it back\n// (`custom.field_retype_preview`; a person column still uses the mirror, `previewRetype`);\n// · nothing is ever cleared: a value that does not fit stays with its record, with the reason.\n// A refusal from the store is shown in its own words, and nothing was changed.\n\nimport { useEffect, useState } from \"react\";\nimport { previewRetype, type Field, type FieldPatch, type RecordsError, type RetypePreview, type Uuid } from \"@ai-matrx/records\";\nimport { tableShapeChanged, useRecordsClient } from \"@ai-matrx/records/react\";\nimport { Button, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@ai-matrx/design-system\";\nimport { editorKindFor } from \"./parity\";\nimport { fieldName } from \"./names\";\nimport { RefusalNotice } from \"./Refusal\";\nimport { useRecordsUi } from \"./host\";\nimport { refusalSentence } from \"./plainWords\";\nimport { useMemberRoster } from \"./memberNames\";\nimport { previewPersonWords, readPersonColumn, forgetWrittenWords, personWordsWritten, resolvePeople, writePersonWords, writeRecordPatches, type PersonColumnRow, type PersonWords } from \"./personRetype\";\nimport type { KeptPerson } from \"./memberNames\";\n\n/** What a column can be changed INTO here, in the words the add-column menu uses. */\n/** The pick waits this long before the store is asked what the change would do (ADV-2 D2). */\nexport const RETYPE_PREVIEW_DEBOUNCE_MS = 300;\n\n/** Run `ask` once, `RETYPE_PREVIEW_DEBOUNCE_MS` after it is called; the returned cancel drops it (an effect cleanup on the next pick). */\nexport function scheduleRetypePreview(ask: () => void, ms: number = RETYPE_PREVIEW_DEBOUNCE_MS): () => void {\n const timer = setTimeout(ask, ms);\n return () => clearTimeout(timer);\n}\n\nexport const RETYPE_TARGETS = [\n { id: \"text\", behaviour: \"text\", kind: null, label: \"Text\", holds: \"words\", via: \"behaviour\" },\n { id: \"number\", behaviour: \"range\", kind: \"number\", label: \"Number\", holds: \"a number\", via: \"behaviour\" },\n // A DATE is a `range` of kind date: `migrate_retype` alone cannot say \"date\" (it keeps the old\n // kind, so every date would be kept aside), so this one goes through `custom.field_update`'s own\n // retype arm (`parity_type: datetime`), which converts on the SAME trigger and keeps what does not\n // fit in `_retired` with the reason — measured on the live store 2026-09-28.\n { id: \"date\", behaviour: \"range\", kind: \"date\", label: \"Date\", holds: \"a date\", via: \"kind\", parity: \"datetime\" },\n { id: \"checkbox\", behaviour: \"boolean\", kind: null, label: \"Yes / no\", holds: \"a yes or a no\", via: \"behaviour\" },\n // THE REST OF WHAT THE STORE'S RETYPE TAKES (walk 2026-10-10: a text column could only become Number,\n // Date or Yes/no, so it could not become a Choice, Phone, Email or Link — the Sheet allowed any\n // kind the values convert to). All go through `custom.field_update`'s `parity_type` arm, the same\n // conversion trigger, which keeps what does not fit in `_retired` with the reason.\n { id: \"email\", behaviour: \"text\", kind: null, label: \"Email address\", holds: \"email addresses\", via: \"kind\", parity: \"email\" },\n { id: \"phone\", behaviour: \"text\", kind: null, label: \"Phone number\", holds: \"phone numbers\", via: \"kind\", parity: \"phone\" },\n { id: \"url\", behaviour: \"text\", kind: null, label: \"Link\", holds: \"web addresses\", via: \"kind\", parity: \"url\" },\n { id: \"currency\", behaviour: \"range\", kind: \"number\", label: \"Money\", holds: \"an amount of money\", via: \"kind\", parity: \"currency\" },\n { id: \"percent\", behaviour: \"range\", kind: \"number\", label: \"Percentage\", holds: \"a percentage\", via: \"kind\", parity: \"percent\" },\n { id: \"select\", behaviour: \"text\", kind: null, label: \"Choice\", holds: \"one choice from a list\", via: \"kind\", parity: \"select\" },\n] as const;\n\ntype Target = (typeof RETYPE_TARGETS)[number];\n\n/**\n * Which columns this panel can change. A choice list or a link stores record ids, and a worked-out\n * column stores nothing typed, so changing any of them to words or numbers would keep ids nobody can\n * read — those are left to their own panels and say so.\n */\nexport function retypeableFrom(field: Field): boolean {\n // A PERSON COLUMN CAN BE CHANGED (lane PERSON-SWEEP): to words (names), to emails, and to any other\n // kind with the values it cannot hold kept aside by name — never an id on screen.\n if (isPersonField(field)) return true;\n const behaviour = String(field.type);\n return behaviour === \"text\" || behaviour === \"range\" || behaviour === \"boolean\";\n}\n\n/**\n * WHY THIS COLUMN'S KIND IS NOT CHANGED HERE, in its own kind's words (lane VIEWS-AND-FIELDS W1-B\n * item 7a). One sentence for every kind `retypeableFrom` turns away — a plain choice column used\n * to be told it \"holds records picked from a list or another table… record ids\". The why behind\n * all of them (the store keeps ids or works the value out) is the author's, kept above.\n */\nexport function whyNotRetypeable(field: Field): string {\n const kind = String(editorKindFor(field));\n if (kind === \"select\" || kind === \"multi_select\") return \"A choice column. Its choices are edited below.\";\n if (kind === \"member\") return \"Holds people, so its kind is not changed here.\";\n if (kind === \"attachment\") return \"Holds files, so its kind is not changed here.\";\n if (kind === \"relation\" || kind === \"entity_reference\") return \"Links to records, so its kind is not changed here.\";\n if (kind === \"formula\" || kind === \"lookup\" || kind === \"rollup\" || String(field.type) === \"formula\") {\n return \"Calculated by the table, so its kind is not changed here.\";\n }\n return \"Its kind is not changed here.\";\n}\n\n/** A column that holds people (Person records of the organization). */\nexport function isPersonField(field: Field): boolean {\n return String(editorKindFor(field)) === \"member\";\n}\n\n/**\n * The ONE patch a target sends to `custom.field_update` — for the preview and for the change alike. A\n * behavior target is the word `custom.migrate_retype` itself hands `field_update` (range -> number,\n * boolean -> checkbox), so the preview of a Number / Yes-no / Text change is the same change too.\n */\nexport function retypePatch(to: Target): FieldPatch {\n if (to.via === \"kind\") return { parity_type: to.parity } as FieldPatch;\n const word = to.behaviour === \"range\" ? \"number\" : to.behaviour === \"boolean\" ? \"checkbox\" : \"text\";\n return { type: word } as FieldPatch;\n}\n\n/** What this column holds now, as one of the targets' ids. */\nfunction currentTarget(field: Field): string {\n if (isPersonField(field)) return \"person\";\n const kind = String(editorKindFor(field));\n if (String(field.type) === \"boolean\") return \"checkbox\";\n if (kind === \"datetime\" || kind === \"date\") return \"date\";\n if (kind === \"email\" || kind === \"phone\" || kind === \"url\" || kind === \"currency\" || kind === \"percent\") return kind;\n if (String(field.type) === \"range\") return \"number\";\n return \"text\";\n}\n\n/** A failure of ours (not the store's) in the store's own refusal shape. */\nfunction failure(e: unknown, fallback: string): RecordsError {\n return { code: \"internal\", message: e instanceof Error && e.message ? e.message : fallback };\n}\n\nexport function FieldRetype({ field, tableId, onRetyped }: { field: Field; tableId: Uuid; onRetyped?: (() => void) | undefined }) {\n const client = useRecordsClient();\n const notify = useRecordsUi().notify;\n const [to, setTo] = useState<Target | null>(null);\n const [preview, setPreview] = useState<RetypePreview | null>(null);\n const [asking, setAsking] = useState(false);\n // The store would not run the change ahead on a column this big (or a busy table): the count is the values held.\n const [limitedHeld, setLimitedHeld] = useState<number | null>(null);\n const [refusal, setRefusal] = useState<RecordsError | null>(null);\n const [busy, setBusy] = useState(false);\n const [said, setSaid] = useState<string | null>(null);\n const roster = useMemberRoster();\n const person = isPersonField(field);\n const [read, setRead] = useState<{ rows: PersonColumnRow[]; people: Map<string, KeptPerson> } | null>(null);\n const name = fieldName(field);\n const targets = RETYPE_TARGETS.filter((t) => t.id !== currentTarget(field));\n\n // THE COUNT BEFORE THE CHANGE: the store groups the column's values; the mirror judges each.\n useEffect(() => {\n if (!to) return;\n let cancelled = false;\n setPreview(null);\n setLimitedHeld(null);\n setRefusal(null);\n setAsking(true);\n if (person) {\n // A person column: the people are read and named first, so the preview speaks of names, never ids.\n if (!roster) return;\n void readPersonColumn(client, tableId, field.key)\n .then(async (rows) => {\n const people = await resolvePeople(client, rows, roster);\n if (cancelled) return;\n setRead({ rows, people });\n setAsking(false);\n if (to.id === \"text\" || to.id === \"email\") {\n setPreview(previewPersonWords(rows, people, to.id === \"email\" ? \"email\" : \"name\"));\n return;\n }\n const groups = rows.map((r) => ({ value: r.ids.map((id) => people.get(id)?.name ?? \"\").join(\", \"), count: 1 }));\n setPreview(previewRetype({ type: to.behaviour, kind: to.kind }, groups, false));\n })\n .catch((e: unknown) => {\n if (cancelled) return;\n setAsking(false);\n setRefusal(failure(e, \"The people could not be read\"));\n });\n return () => {\n cancelled = true;\n };\n }\n // THE STORE'S OWN COUNT (lane F2, D11). The mirror judged every \"kind\" target by its behavior word, so a\n // change to Choice, Email, Phone, Link, Money, Percentage or Date was promised as converting while the store\n // kept the values aside. `fieldRetypePreview` runs the very patch `change` sends, and rolls it back.\n // Debounced (ADV-2 D2): each pick runs the real change in the store and rolls it back, so a person\n // stepping through the targets asks once, for the one they stop on.\n const cancelAsk = scheduleRetypePreview(() => {\n void client.fieldRetypePreview({ field_id: field.id as Uuid, patch: retypePatch(to) }).then((answer) => {\n if (cancelled) return;\n setAsking(false);\n if (!answer.ok) {\n setRefusal(answer.error);\n return;\n }\n if (answer.data.limited || answer.data.converts === null || answer.data.kept_aside === null) {\n setLimitedHeld(answer.data.held_before);\n setPreview({ converts: answer.data.held_before, keptAside: 0, examples: [], partial: false });\n return;\n }\n setLimitedHeld(null);\n setPreview({ converts: answer.data.converts, keptAside: answer.data.kept_aside, examples: answer.data.examples, partial: false });\n });\n });\n return () => {\n cancelled = true;\n cancelAsk();\n };\n }, [client, tableId, field.key, to, person, roster]);\n\n if (!retypeableFrom(field)) {\n return (\n <p className=\"text-[11px] text-muted-foreground\" data-records-retype=\"not-here\">\n {whyNotRetypeable(field)}\n </p>\n );\n }\n\n const change = async () => {\n if (!to) return;\n setBusy(true);\n setRefusal(null);\n let holding: number;\n let aside: number;\n // UNDO, AT ONCE (TABLE-ACTIONS wave 5, T5.2): the store recorded the change as a Migration;\n // `custom.migrate_undo` puts the column's whole shape back and the trigger converts the values again.\n // What this change wrote into the column after the store retyped it (record id -> words), so its Undo takes out exactly those.\n let wordsWritten: Record<string, string> | undefined;\n const offerUndo = (migration: string | null | undefined) => {\n if (!migration || !notify?.reversible) return;\n const wasPerson = person && read && (to.id === \"text\" || (to.id as string) === \"email\") ? read : null;\n notify.reversible({\n verb: \"change\",\n noun: \"column\",\n subject: name,\n undo: async () => {\n const back = await client.migrateUndo({ migration_id: migration as Uuid });\n if (!back.ok) throw new Error(refusalSentence(back.error));\n // The words written over the people go back to the people (the same records, the same ids).\n if (wasPerson) {\n await writeRecordPatches(\n client,\n tableId,\n wasPerson.rows.map((r) => ({ recordId: r.recordId, patch: { [field.key]: field.multi ? r.ids : (r.ids[0] ?? null) } })),\n );\n // …and the words the undo's re-check set aside are taken out of the kept-aside lists — only those exact words.\n if (wordsWritten) await forgetWrittenWords(client, tableId, field.key, wordsWritten);\n }\n tableShapeChanged(tableId);\n onRetyped?.();\n },\n });\n };\n if (to.via !== \"behaviour\") {\n const done = await client.fieldUpdate({ field_id: field.id as Uuid, patch: retypePatch(to) });\n setBusy(false);\n if (!done.ok) {\n setRefusal(done.error);\n return;\n }\n holding = preview?.converts ?? 0;\n aside = preview?.keptAside ?? 0;\n // field_update answers the field, not the Migration; the conversion recorded one, newest first.\n const recorded = await client.migrations({ target_id: field.id as Uuid, limit: 1 });\n const newest = recorded.ok ? recorded.data[0] : undefined;\n if (newest && !newest.undone_at) offerUndo(newest.id);\n } else {\n const done = await client.migrateRetype({ field_id: field.id as Uuid, to: to.behaviour });\n setBusy(false);\n if (!done.ok) {\n setRefusal(done.error);\n return;\n }\n holding = done.data.records_still_holding_a_value ?? 0;\n aside = done.data.values_in_retired_for_this_field ?? 0;\n offerUndo(done.data.migration_id);\n }\n if (person && read && (to.id === \"text\" || (to.id as string) === \"email\")) {\n const as: PersonWords = (to.id as string) === \"email\" ? \"email\" : \"name\";\n try {\n wordsWritten = personWordsWritten(read.rows, read.people, as);\n const written = await writePersonWords(client, tableId, read.rows, read.people, field.key, as);\n holding = written;\n aside = read.rows.length - written;\n } catch (e) {\n setRefusal(failure(e, \"The words could not be written\"));\n return;\n }\n }\n if (limitedHeld !== null && to.via !== \"behaviour\") {\n setSaid(`${name} now holds ${to.holds}. Values that did not fit were kept with their records, with the reason.`);\n } else\n setSaid(\n `${name} now holds ${to.holds}. ${holding} ${holding === 1 ? \"record holds\" : \"records hold\"} a value` +\n (aside > 0 ? `; ${aside} ${aside === 1 ? \"value that did not fit was\" : \"values that did not fit were\"} kept with ${aside === 1 ? \"its record\" : \"their records\"}, with the reason.` : \".\"),\n );\n setTo(null);\n setPreview(null);\n tableShapeChanged(tableId);\n onRetyped?.();\n };\n\n return (\n <div className=\"flex flex-col gap-1.5\" data-records-retype=\"\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <Select value={to?.id ?? \"\"} onValueChange={(next) => setTo(targets.find((t) => t.id === next) ?? null)}>\n <SelectTrigger size=\"sm\" aria-label=\"Change what this column holds\" className=\"w-auto min-w-[12rem]\">\n <SelectValue placeholder=\"Change what this column holds\" />\n </SelectTrigger>\n <SelectContent>\n {targets.map((t) => (\n <SelectItem key={t.id} value={t.id}>\n {t.label}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n {to ? (\n <Button size=\"sm\" disabled={busy || asking || preview === null} onClick={() => void change()} data-records-retype-go=\"\">\n {busy ? \"Changing…\" : `Change to ${to.label}`}\n </Button>\n ) : null}\n {to ? (\n <Button size=\"sm\" variant=\"ghost\" onClick={() => setTo(null)} disabled={busy}>\n Cancel\n </Button>\n ) : null}\n </div>\n {to && asking ? <p className=\"text-[11px] text-muted-foreground\">Counting {name}'s values…</p> : null}\n {to && preview && limitedHeld !== null ? (\n <p className=\"text-[11px] text-muted-foreground\" data-records-retype-preview=\"\" data-records-retype-limited=\"\">\n About {limitedHeld.toLocaleString()} values to change to {to.label.toLowerCase()}; any that do not fit are kept aside with their records, with the reason — nothing is deleted.\n </p>\n ) : to && preview ? (\n <p className=\"text-[11px] text-muted-foreground\" data-records-retype-preview=\"\">\n {preview.converts} {preview.converts === 1 ? \"value converts\" : \"values convert\"} to {to.label.toLowerCase()}\n {preview.keptAside > 0\n ? `; ${preview.keptAside} ${preview.keptAside === 1 ? \"value does\" : \"values do\"} not fit and will be kept aside with ${preview.keptAside === 1 ? \"its record\" : \"their records\"}, with the reason — nothing is deleted` +\n (preview.examples.length > 0 ? ` (for example ${preview.examples.map((e) => `“${e}”`).join(\", \")})` : \"\")\n : \"\"}\n {preview.partial ? \". Counted over the first 1,000 different values.\" : \".\"}\n </p>\n ) : null}\n {refusal ? <RefusalNotice error={refusal} /> : null}\n {said ? (\n <p role=\"status\" className=\"text-[11px] text-muted-foreground\" data-records-retype-done=\"\">\n {said}\n </p>\n ) : null}\n </div>\n );\n}\n","// src/personRetype.ts — @ai-matrx/records-ui · lane PERSON-SWEEP\n//\n// CHANGING A PERSON COLUMN INTO WORDS (Airtable lets any field change type with a preview). A Person\n// column stores Person ROW ids; the store's own retype keeps ids it cannot read. So for Text (their\n// names) and Email (their emails) the screen resolves the people first (`resolveKeptPerson`, the one\n// resolver), lets the store retype the column (so the change is a recorded Migration with its undo),\n// and then writes each record's words in place of the id the store left. A person with no email is\n// not guessed: their record keeps the value aside, shown by name.\n\nimport type { Uuid } from \"@ai-matrx/records\";\nimport type { RecordsClient } from \"@ai-matrx/records/core\";\nimport { changeRecordsAt, type VersionedChange } from \"./recordVersions\";\nimport { refusalSentence } from \"./plainWords\";\nimport type { OrganizationMember } from \"./host\";\nimport { isUuidShape } from \"@ai-matrx/kit/uuid\";\nimport { resolveKeptPerson, type KeptPerson } from \"./memberNames\";\n\nexport type PersonWords = \"name\" | \"email\";\n\nexport interface PersonColumnRow {\n recordId: Uuid;\n ids: string[];\n}\n\nconst PAGE = 500;\nconst CEILING = 20_000;\n\nfunction idsIn(value: unknown): string[] {\n return (Array.isArray(value) ? value : [value]).filter(isUuidShape);\n}\n\n/** Every record's person ids for a column, read through the store's list door (the held value, else the one kept aside). */\nexport async function readPersonColumn(client: Pick<RecordsClient, \"list\">, tableId: Uuid, key: string): Promise<PersonColumnRow[]> {\n const out: PersonColumnRow[] = [];\n for (let offset = 0; offset < CEILING; offset += PAGE) {\n const page = await client.list({ table_id: tableId, limit: PAGE, offset });\n if (!page.ok) throw new Error(refusalSentence(page.error));\n for (const row of page.data.rows) {\n const doc = (row.document ?? {}) as Record<string, unknown>;\n let ids = idsIn(doc[key]);\n if (ids.length === 0 && Array.isArray(doc[\"_retired\"])) {\n const kept = (doc[\"_retired\"] as Array<{ key?: unknown; value?: unknown }>).filter((e) => e.key === key);\n const last = kept[kept.length - 1];\n if (last) ids = idsIn(last.value);\n }\n if (ids.length > 0) out.push({ recordId: row.id, ids });\n }\n if (page.data.rows.length < PAGE) break;\n }\n return out;\n}\n\n/** Resolve the distinct people a column holds. */\nexport async function resolvePeople(\n client: Pick<RecordsClient, \"recordRead\">,\n rows: readonly PersonColumnRow[],\n roster: ReadonlyMap<string, OrganizationMember>,\n): Promise<Map<string, KeptPerson>> {\n const distinct = [...new Set(rows.flatMap((r) => r.ids))];\n const people = await Promise.all(distinct.map((id) => resolveKeptPerson(client, id, roster)));\n return new Map(people.map((p) => [p.id, p] as const));\n}\n\n/** A record's words: the names (or emails) of the people it holds, null when none has any. */\nexport function wordsFor(ids: readonly string[], people: ReadonlyMap<string, KeptPerson>, as: PersonWords): string | null {\n const said = ids\n .map((id) => (as === \"name\" ? people.get(id)?.name : people.get(id)?.email))\n .filter((w): w is string => typeof w === \"string\" && w.trim() !== \"\" && !w.startsWith(\"A person no longer\"));\n return said.length > 0 ? said.join(\", \") : null;\n}\n\n/** The preview a person column's change to words shows, in the shape every retype preview has. */\nexport function previewPersonWords(rows: readonly PersonColumnRow[], people: ReadonlyMap<string, KeptPerson>, as: PersonWords) {\n let converts = 0;\n let keptAside = 0;\n const examples: string[] = [];\n for (const row of rows) {\n if (wordsFor(row.ids, people, as) !== null) converts += 1;\n else {\n keptAside += 1;\n const who = people.get(row.ids[0] ?? \"\")?.name;\n if (who && examples.length < 5 && !examples.includes(who)) examples.push(who);\n }\n }\n return { converts, keptAside, examples, partial: false };\n}\n\n/**\n * Each record's version, read now. A retype is a migration that bumps every record it touches, so a\n * version read before it is stale; the words are written against what the record is now.\n */\nexport async function versionsNow(client: Pick<RecordsClient, \"recordHeaders\">, ids: readonly Uuid[]): Promise<Map<string, number>> {\n const out = new Map<string, number>();\n for (let i = 0; i < ids.length; i += 200) {\n const got = await client.recordHeaders({ ids: ids.slice(i, i + 200) as Uuid[] });\n if (!got.ok) throw new Error(refusalSentence(got.error));\n for (const h of got.data ?? []) if (typeof h.version === \"number\") out.set(h.id, h.version);\n }\n return out;\n}\n\n/** One transaction per hundred records, each update against the version the record has now. */\nexport async function writeRecordPatches(\n client: Pick<RecordsClient, \"recordChangeMany\" | \"recordHeaders\">,\n tableId: Uuid,\n patches: ReadonlyArray<{ recordId: Uuid; patch: Record<string, unknown> }>,\n): Promise<void> {\n const versions = await versionsNow(client, patches.map((p) => p.recordId));\n for (let i = 0; i < patches.length; i += 100) {\n const changes: VersionedChange[] = patches.slice(i, i + 100).map((p) => ({\n op: \"update\",\n record_id: p.recordId,\n patch: p.patch,\n expected_version: versions.get(p.recordId) ?? null,\n }));\n const done = await changeRecordsAt(client, { table_id: tableId, changes });\n if (!done.ok) throw new Error(refusalSentence(done.error));\n }\n}\n\n/** After the store retyped the column: write each record's words where the id was left. Returns how many records were written. */\nexport async function writePersonWords(\n client: Pick<RecordsClient, \"recordChangeMany\" | \"recordHeaders\">,\n tableId: Uuid,\n rows: readonly PersonColumnRow[],\n people: ReadonlyMap<string, KeptPerson>,\n key: string,\n as: PersonWords,\n): Promise<number> {\n const patches = personWordsPatches(rows, people, key, as);\n await writeRecordPatches(client, tableId, patches);\n return patches.length;\n}\n\n/** The words each record is given (record id -> words): what the retype's undo is told it wrote, so it takes out exactly these. */\nexport function personWordsWritten(rows: readonly PersonColumnRow[], people: ReadonlyMap<string, KeptPerson>, as: PersonWords): Record<string, string> {\n const out: Record<string, string> = {};\n for (const row of rows) {\n const words = wordsFor(row.ids, people, as);\n if (words !== null) out[row.recordId] = words;\n }\n return out;\n}\n\nfunction personWordsPatches(rows: readonly PersonColumnRow[], people: ReadonlyMap<string, KeptPerson>, key: string, as: PersonWords) {\n return Object.entries(personWordsWritten(rows, people, as)).map(([recordId, words]) => ({ recordId: recordId as Uuid, patch: { [key]: words } as Record<string, unknown> }));\n}\n\n/**\n * AFTER AN UNDO: take out of each record's kept-aside list exactly the words this change wrote there.\n * The undo's re-check sets those words aside (a name is not a person), and they would sit in the list as\n * clutter — and be counted by the next retype. A value a person typed afterwards differs from the word\n * written, so it is never touched: it stays kept aside and visible.\n */\nexport async function forgetWrittenWords(\n client: Pick<RecordsClient, \"list\" | \"recordChangeMany\" | \"recordHeaders\">,\n tableId: Uuid,\n key: string,\n written: Readonly<Record<string, string>>,\n): Promise<number> {\n const patches: Array<{ recordId: Uuid; patch: Record<string, unknown> }> = [];\n for (let offset = 0; offset < CEILING; offset += PAGE) {\n const page = await client.list({ table_id: tableId, limit: PAGE, offset });\n if (!page.ok) throw new Error(refusalSentence(page.error));\n for (const row of page.data.rows) {\n const word = written[row.id];\n const kept = (row.document ?? {})[\"_retired\"];\n if (word === undefined || !Array.isArray(kept)) continue;\n const rest = kept.filter((e: { key?: unknown; value?: unknown }) => !(e?.key === key && e?.value === word));\n if (rest.length !== kept.length) patches.push({ recordId: row.id, patch: { _retired: rest } });\n }\n if (page.data.rows.length < PAGE) break;\n }\n await writeRecordPatches(client, tableId, patches);\n return patches.length;\n}\n","\"use client\";\n\n// src/FieldRulePreview.tsx — @ai-matrx/records-ui · lane 10 P4c (V13 #4)\n//\n// THE COUNT BEFORE A CHECK TIGHTENS. Saving a smaller largest, a larger smallest, a shorter\n// longest, a new pattern or a lower top star sets aside every value already written that no longer\n// fits — kept in its record with the reason, never deleted. A person is told how many, with\n// examples, before pressing Save: the same question and the same sentence `FieldRetype` asks\n// before a retype (the store groups the column's values; the mirror `previewRuleChange` judges\n// each group). The store still decides on Save.\n\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport { previewRuleChange, type Field, type FieldRule, type RecordsError, type RetypePreview, type Uuid } from \"@ai-matrx/records\";\nimport { useRecordsClient } from \"@ai-matrx/records/react\";\nimport { RefusalNotice } from \"./Refusal\";\nimport { fieldName } from \"./names\";\nimport { refusalFromThrown } from \"./refusals\";\n\nconst PREVIEW_GROUPS = 1000;\n\n/** The checks as the store compares them: kind, value, shortest. Order does not matter. */\nfunction ruleWords(rules: ReadonlyArray<FieldRule>): string {\n return rules\n .map((r) => JSON.stringify([r.kind, r.value === undefined || r.value === \"\" ? null : String(r.value), r.min ?? null, r.example ?? null]))\n .sort()\n .join(\"|\");\n}\n\n/** True when the edited checks differ from what the column holds now. */\nexport function rulesChanged(was: ReadonlyArray<FieldRule>, now: ReadonlyArray<FieldRule>): boolean {\n return ruleWords(was) !== ruleWords(now);\n}\n\n/** A column the store keeps numbers in (`range` is the store's one number type). */\nfunction holdsNumbers(field: Field): boolean {\n return field.type === \"range\";\n}\n\n/**\n * THE GROUP AS THE COLUMN HOLDS IT. The store groups by the value's TEXT (`data ->> key`), so a\n * number column's 0 comes back as \"0\" — and the mirror judges `min` / `max` on numbers only, so\n * \"at least 1\" over a stored 0 was counted as fitting while the store then set the 0 aside (live\n * walk, 2026-10-05). On a number column a group that reads as a number is judged as that number.\n */\nexport function groupValue(value: unknown, numbers: boolean): unknown {\n if (!numbers || typeof value !== \"string\") return value;\n const text = value.trim();\n return /^-?(\\d+\\.?\\d*|\\.\\d+)([eE][-+]?\\d+)?$/.test(text) ? Number(text) : value;\n}\n\nexport function FieldRulePreview({ field, tableId, rules }: { field: Field; tableId: Uuid; rules: ReadonlyArray<FieldRule> }) {\n const client = useRecordsClient();\n const [preview, setPreview] = useState<RetypePreview | null>(null);\n const [refusal, setRefusal] = useState<RecordsError | null>(null);\n const key = useMemo(() => ruleWords(rules), [rules]);\n // `key` stands for `rules` by value, so typing the same check twice asks once; the ref is what is judged.\n const latest = useRef(rules);\n latest.current = rules;\n const name = fieldName(field);\n\n useEffect(() => {\n let cancelled = false;\n setPreview(null);\n setRefusal(null);\n const timer = setTimeout(() => {\n void client\n .recordAggregate({ table_id: tableId, groupBy: [field.key], measures: [{ op: \"count\" }], limit: PREVIEW_GROUPS })\n .then((answer) => {\n if (cancelled) return;\n if (!answer.ok) {\n setRefusal(answer.error);\n return;\n }\n const numbers = holdsNumbers(field);\n const groups = answer.data.map((row) => ({ value: groupValue(row.groups[field.key] ?? null, numbers), count: row.row_count }));\n setPreview(previewRuleChange(latest.current, groups, answer.data.length >= PREVIEW_GROUPS));\n })\n // A count that THREW (a dropped connection, a door the host never bound) is said as a\n // refusal, never left \"Counting…\" forever over an unhandled rejection.\n .catch((thrown: unknown) => {\n if (cancelled) return;\n setRefusal(refusalFromThrown(thrown, `${name}'s values could not be counted.`, \"The check still applies when you save.\"));\n });\n }, 300);\n return () => {\n cancelled = true;\n clearTimeout(timer);\n };\n }, [client, tableId, field.key, key]);\n\n if (refusal) return <RefusalNotice error={refusal} />;\n if (!preview) {\n return (\n <p className=\"text-[11px] text-muted-foreground\" data-records-rule-preview=\"counting\">\n Counting {name}'s values…\n </p>\n );\n }\n if (preview.keptAside === 0) {\n return (\n <p className=\"text-[11px] text-muted-foreground\" data-records-rule-preview=\"fits\">\n Every value already in {name} still fits{preview.partial ? \" (counted over the first 1,000 different values)\" : \"\"}.\n </p>\n );\n }\n return (\n <p className=\"text-[11px] text-amber-700 dark:text-amber-400\" role=\"status\" data-records-rule-preview=\"sets-aside\">\n {preview.keptAside} {preview.keptAside === 1 ? \"value no longer fits and will be\" : \"values no longer fit and will be\"} kept aside with{\" \"}\n {preview.keptAside === 1 ? \"its record\" : \"their records\"}, with the reason — nothing is deleted\n {preview.examples.length > 0 ? ` (for example ${preview.examples.map((e) => `“${e}”`).join(\", \")})` : \"\"}\n {preview.partial ? \". Counted over the first 1,000 different values.\" : \".\"}\n </p>\n );\n}\n","\"use client\";\n\n// src/ColumnLook.tsx — @ai-matrx/records-ui · merge tranche 6a (column settings)\n//\n// HOW A COLUMN LOOKS, SET IN ITS OWN SETTINGS: each choice's color (drawn on each row of the one\n// choice editor, `ChoiceListEditor.tsx`; this file turns those rows into the Field's document), and what a plain column\n// \"shows as\" (money, a percent, a star rating, a date style…). The older /data grid kept both in\n// its Column settings dialog (`ColumnSettingsDialog.tsx`, `ChoiceOptionsEditor.tsx`,\n// `FieldFormatPicker.tsx`); the store keeps both ON THE FIELD as its `display_format`, written by\n// `custom.field_update`'s settings arm — the same document the /data Sheet's seam writes, so\n// the colors a person set on either grid are the colors the other one draws.\n//\n// Colors are names from the design-system palette (`STYLE_COLORS`), never a raw hex; the\n// swatches are the design-system's own classes.\n\nimport type { Field } from \"@ai-matrx/records\";\nimport type { StyleColor } from \"@ai-matrx/design-system/data-table\";\n\nimport type { ChoiceListRow } from \"./ChoiceListEditor\";\nimport { choiceLooksOf, choiceWord, displayFormatOf } from \"./choiceLooks\";\nimport { editorKindFor } from \"./parity\";\n\n/** One choice and the color it wears (null: none). */\nexport interface ChoiceColorRow {\n value: string;\n color: StyleColor | null;\n}\n\n/** The words a choice option record keeps (`title` for a list the store made, `name` for a moved one). */\nexport function optionWords(options: ReadonlyArray<{ data?: Record<string, unknown> | null } | Record<string, unknown>>): string[] {\n const out: string[] = [];\n for (const option of options) {\n const data = ((option as { data?: Record<string, unknown> | null }).data ?? option) as Record<string, unknown>;\n const word = [data[\"title\"], data[\"name\"], data[\"label\"]].find((w) => typeof w === \"string\" && w.trim() !== \"\");\n if (typeof word === \"string\" && !out.includes(word.trim())) out.push(word.trim());\n }\n return out;\n}\n\n/** The rows the color editor starts from: every option, with the color the Field keeps for it. */\nexport function startingChoiceColors(field: Field, words: readonly string[]): ChoiceColorRow[] {\n const looks = choiceLooksOf(field);\n const rows: ChoiceColorRow[] = words.map((value) => {\n const look = looks.find((l) => choiceWord(l.value) === choiceWord(value) || (l.label && choiceWord(l.label) === choiceWord(value)));\n return { value, color: look?.color ?? null };\n });\n // A color kept for a word that is no longer an option stays in the list, so saving never drops it.\n for (const look of looks) {\n if (!rows.some((r) => choiceWord(r.value) === choiceWord(look.value))) rows.push({ value: look.value, color: look.color ?? null });\n }\n return rows;\n}\n\n/**\n * THE DISPLAY DOCUMENT A SAVE SENDS for a choice column: the Field's own document with its\n * choices' colors replaced — every other option it carries (labels, groups, help) kept. `null`\n * means nothing changed and nothing is sent.\n */\nexport function choiceDisplayPatch(field: Field, rows: readonly ChoiceColorRow[]): { id: string; options: Record<string, unknown> } | null {\n const held = displayFormatOf(field);\n const before = choiceLooksOf(field);\n const changed = rows.some((row) => {\n const was = before.find((l) => choiceWord(l.value) === choiceWord(row.value))?.color ?? null;\n return was !== row.color;\n });\n if (!changed) return null;\n const heldChoices = Array.isArray(held?.options[\"choices\"]) ? (held!.options[\"choices\"] as Array<Record<string, unknown>>) : [];\n const choices = rows\n .map((row) => {\n const kept = heldChoices.find((c) => typeof c[\"value\"] === \"string\" && choiceWord(c[\"value\"]) === choiceWord(row.value)) ?? {};\n const { color: _old, ...rest } = kept;\n return { ...rest, value: typeof kept[\"value\"] === \"string\" ? kept[\"value\"] : row.value, ...(row.color ? { color: row.color } : {}) };\n })\n .filter((c) => Object.keys(c).length > 1);\n const id = held?.id ?? (editorKindFor(field) === \"multi_select\" ? \"multi_choice\" : \"choice\");\n return { id, options: { ...(held?.options ?? {}), choices } };\n}\n\n/**\n * A RE-WORDED CHOICE KEEPS ITS LOOK (lane CHOICE-COLUMN-EDIT). The color is kept on the Field by\n * the choice's WORDS, so re-wording \"Cusor\" to \"Cursor\" in place left the color on words no choice\n * has any more. `renames` is old words → new words; the look (the one being saved, else the one the\n * Field holds) follows each re-worded choice. Null when there is nothing to carry.\n */\nexport function lookFollowsRenames(\n field: Field,\n look: { id: string; options: Record<string, unknown> } | null,\n renames: ReadonlyMap<string, string>,\n): { id: string; options: Record<string, unknown> } | null {\n if (renames.size === 0) return look;\n const base = look ?? displayFormatOf(field);\n const choices = base && Array.isArray(base.options[\"choices\"]) ? (base.options[\"choices\"] as Array<Record<string, unknown>>) : null;\n if (!base || !choices) return look;\n let moved = false;\n const next = choices.map((c) => {\n const was = typeof c[\"value\"] === \"string\" ? c[\"value\"] : null;\n const now = was === null ? undefined : [...renames].find(([old]) => choiceWord(old) === choiceWord(was))?.[1];\n if (now === undefined) return c;\n moved = true;\n return { ...c, value: now };\n });\n if (!moved) return look;\n return { id: base.id, options: { ...base.options, choices: next } };\n}\n\n/**\n * THE LOOK A SAVE SENDS FOR AN EXISTING CHOICE COLUMN, from the ONE choice editor's rows\n * (`ChoiceListEditor` — each row carries its color; lane VIEWS-AND-FIELDS W1-B). The colors\n * are kept by WORDS, so the rows are compared under the words the store held (`start`), then the\n * look follows each re-worded choice (`lookFollowsRenames`). A color kept for a choice that was\n * removed, or for words no option has, stays — a save never drops a color nobody touched.\n * Null: nothing about the look changed.\n */\nexport function choiceLookFromList(\n field: Field,\n start: readonly ChoiceListRow[],\n rows: readonly ChoiceListRow[],\n): { id: string; options: Record<string, unknown> } | null {\n const base = startingChoiceColors(field, start.map((r) => r.words.trim()).filter((w) => w !== \"\"));\n const colorRows: ChoiceColorRow[] = base.map((row) => {\n const was = start.find((r) => choiceWord(r.words) === choiceWord(row.value));\n const now = was?.id ? rows.find((r) => r.id === was.id) : undefined;\n return now ? { value: row.value, color: now.color ?? null } : row;\n });\n for (const r of rows) {\n if (r.id !== null || r.words.trim() === \"\") continue;\n if (colorRows.some((c) => choiceWord(c.value) === choiceWord(r.words))) continue;\n colorRows.push({ value: r.words.trim(), color: r.color ?? null });\n }\n const renames = new Map<string, string>();\n for (const was of start) {\n const now = was.id ? rows.find((r) => r.id === was.id) : undefined;\n if (now && now.words.trim() !== \"\" && now.words.trim() !== was.words.trim()) renames.set(was.words.trim(), now.words.trim());\n }\n return lookFollowsRenames(field, choiceDisplayPatch(field, colorRows), renames);\n}\n\n/** THE LOOK A NEW CHOICE COLUMN IS MADE WITH: its rows' colors, or null when none wears one. */\nexport function choiceLookForNewList(\n multi: boolean,\n rows: readonly ChoiceListRow[],\n): { id: string; options: { choices: Array<{ value: string; color: StyleColor }> } } | null {\n const choices = rows.flatMap((r) => (r.words.trim() !== \"\" && r.color ? [{ value: r.words.trim(), color: r.color }] : []));\n return choices.length === 0 ? null : { id: multi ? \"multi_choice\" : \"choice\", options: { choices } };\n}\n\n// \"Shows as\" for a plain column lives in `FieldFormatPicker.tsx` (merge tranche 6e): the whole\n// registry, grouped, with \"Other kinds\".\n","\"use client\";\n\n// src/NewerKindQuestions.tsx — @ai-matrx/records-ui\n//\n// WHAT THE COLUMN PANEL ASKS ABOUT THREE OF THE NEWER KINDS (lane 10 P4). Airtable asks a rating\n// how many stars it goes to; Notion's Status asks which group each option sits in; a barcode may\n// name the code it holds. Each answer goes to the store as a word it judges\n// (`custom._field_document_for` / `custom.field_update`): `max`, `status_groups`, `symbology`.\n\nimport {\n BARCODE_SYMBOLOGIES,\n STATUS_GROUPS,\n STATUS_GROUP_WORDS,\n statusGroupOf,\n type Field,\n type FieldRule,\n type StatusGroup,\n} from \"@ai-matrx/records\";\nimport { Label, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@ai-matrx/design-system\";\nimport { STATUS_GROUP_MARK } from \"./newerKindValues\";\n\n/** A new Status column starts with Notion's three, one in each group. */\nexport const STATUS_STARTING_CHOICES: ReadonlyArray<{ words: string; group: StatusGroup }> = [\n { words: \"Not started\", group: \"todo\" },\n { words: \"In progress\", group: \"in_progress\" },\n { words: \"Done\", group: \"done\" },\n];\n\n/** The group a choice's words most plainly name; anything else starts as To do. */\nexport function guessStatusGroup(words: string): StatusGroup {\n const w = words.toLowerCase().replace(/[^a-z]/g, \"\");\n if ([\"done\", \"complete\", \"completed\", \"closed\", \"finished\", \"discharged\", \"cancelled\", \"canceled\"].includes(w)) return \"done\";\n if ([\"inprogress\", \"doing\", \"started\", \"active\", \"inreview\", \"review\"].includes(w)) return \"in_progress\";\n return \"todo\";\n}\n\n/** One choice's row in the groups question: how the store names it, its words, its group. */\nexport type StatusGroupRow = { ref: string; words: string; group: StatusGroup };\n\n/**\n * Each choice's group, for the choices this panel is showing (V8 #3). A choice the column already\n * keeps is named by its OPTION ID — the store keys groups by the choice's stored key, which a\n * rename never changes, and reads the group from there; a choice being added is named by its words.\n * `changed` holds only what the person picked here, by the same name.\n */\nexport function statusGroupRows(\n field: Field | undefined,\n rows: ReadonlyArray<{ id: string | null; words: string }>,\n keyOfId: Readonly<Record<string, string>>,\n changed: Readonly<Record<string, StatusGroup>>,\n): StatusGroupRow[] {\n const out: StatusGroupRow[] = [];\n for (const r of rows) {\n const words = r.words.trim();\n if (words === \"\") continue;\n const ref = r.id ?? words;\n const key = r.id ? keyOfId[r.id] : undefined;\n const held = field && key ? statusGroupOf(field, key) : undefined;\n out.push({ ref, words, group: changed[ref] ?? held ?? guessStatusGroup(words) });\n }\n return out;\n}\n\nexport function StatusGroupsQuestion({\n rows,\n onGroup,\n}: {\n rows: readonly StatusGroupRow[];\n onGroup: (ref: string, next: StatusGroup) => void;\n}) {\n if (rows.length === 0) return null;\n return (\n <div className=\"flex flex-col gap-1\" data-records-status-groups=\"\">\n <Label className=\"text-xs\">Groups</Label>\n {rows.map((r) => (\n <div key={r.ref} className=\"flex items-center gap-2\">\n <span className=\"min-w-0 flex-1 truncate text-sm\">{r.words}</span>\n <Select value={r.group} onValueChange={(next) => onGroup(r.ref, next as StatusGroup)}>\n <SelectTrigger size=\"sm\" className=\"w-36\" aria-label={`Group for ${r.words}`}>\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {STATUS_GROUPS.map((g) => (\n <SelectItem key={g} value={g}>\n {STATUS_GROUP_MARK[g]} {STATUS_GROUP_WORDS[g]}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </div>\n ))}\n </div>\n );\n}\n\n/** A rating's top star, 1 to 10. */\nexport function RatingMaxQuestion({ value, onChange }: { value: number; onChange: (next: number) => void }) {\n return (\n <label className=\"flex max-w-[16rem] flex-col gap-1\">\n <Label className=\"text-xs\">Out of</Label>\n <Select value={String(value)} onValueChange={(next) => onChange(Number(next))}>\n <SelectTrigger size=\"sm\" aria-label=\"Out of\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n {Array.from({ length: 10 }, (_, i) => i + 1).map((n) => (\n <SelectItem key={n} value={String(n)}>\n {n} {n === 1 ? \"star\" : \"stars\"}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </label>\n );\n}\n\n/** The rules with a rating's 0..max in place of whatever min and max they held. */\nexport function rulesWithRatingMax(rules: readonly FieldRule[], max: number): FieldRule[] {\n return [\n ...rules.filter((r) => r.kind !== \"min\" && r.kind !== \"max\"),\n { kind: \"min\", value: 0 } as FieldRule,\n { kind: \"max\", value: max } as FieldRule,\n ];\n}\n\nconst SYMBOLOGY_WORDS: Record<(typeof BARCODE_SYMBOLOGIES)[number], string> = {\n code128: \"Code 128\",\n code39: \"Code 39\",\n ean13: \"EAN-13\",\n ean8: \"EAN-8\",\n upc_a: \"UPC-A\",\n upc_e: \"UPC-E\",\n itf: \"ITF\",\n qr: \"QR code\",\n data_matrix: \"Data Matrix\",\n pdf417: \"PDF417\",\n};\n\n/** Which code a barcode holds; \"Any code\" takes whatever a scanner reads. */\nexport function BarcodeSymbologyQuestion({ value, onChange }: { value: string; onChange: (next: string) => void }) {\n return (\n <label className=\"flex max-w-[16rem] flex-col gap-1\">\n <Label className=\"text-xs\">Code type</Label>\n <Select value={value === \"\" ? \"any\" : value} onValueChange={(next) => onChange(next === \"any\" ? \"\" : next)}>\n <SelectTrigger size=\"sm\" aria-label=\"Code type\">\n <SelectValue />\n </SelectTrigger>\n <SelectContent>\n <SelectItem value=\"any\">Any code</SelectItem>\n {BARCODE_SYMBOLOGIES.map((s) => (\n <SelectItem key={s} value={s}>\n {SYMBOLOGY_WORDS[s]}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n </label>\n );\n}\n","\"use client\";\n\n// src/FieldFormatPicker.tsx — @ai-matrx/records-ui · merge tranche 6e (formats)\n//\n// \"SHOWS AS\" — THE WHOLE PLATFORM REGISTRY, GROUPED THE WAY THE OLDER /data GRID GROUPED IT\n// (`lib/field-formats/FieldFormatPicker.tsx`, rewritten onto `Field`). The formats that fit what\n// the column already stores come first, in the registry's own groups (Text, Numbers, Dates,\n// Choice, Structured); then \"Other kinds · changes what the column holds\" — every other kind of\n// data a person thinks in (a Time on a date column, Attachments on a text column), which retypes\n// the column and sets its look in the SAME `custom.field_update`. Never offered: the two raw\n// structural formats (JSON, a raw list) and the worked-out ones (a formula, a record number, the\n// stamps), which are made as columns of their own, not chosen as a look.\n//\n// Each format's own options follow it — currency, how a percent is kept (45 or 0.45: read from\n// the Field, never guessed), decimals, the unit of a duration, what a rating is out of, a date's\n// style, a prefix or suffix, thousands separators — and nothing else.\n//\n// Every pick is the package's own `PickOne` (never a native <select> — lane VIEWS-AND-FIELDS W1-B):\n// the long \"Shows as\" list is searchable, each format named with its group.\n\nimport type { ReactNode } from \"react\";\nimport type { Field } from \"@ai-matrx/records\";\nimport { Label } from \"@ai-matrx/design-system\";\nimport {\n FIELD_FORMAT_LIST,\n getFieldFormat,\n groupedFormatsForBase,\n type FieldFormatConfig,\n type FieldFormatDef,\n type FieldFormatOptions,\n} from \"@ai-matrx/design-system/field-formats\";\nimport { PickOne } from \"./PickOne\";\n\nimport { displayFormatOf } from \"./choiceLooks\";\nimport { editorKindFor } from \"./parity\";\n\n/** What the picker holds: the look, and — for an Other kind — the store's word for what the column becomes. */\nexport interface FormatChoice {\n format: FieldFormatConfig | null;\n /** `custom.field_update`'s `type` word when this choice retypes the column; null when it does not. */\n retype: string | null;\n}\n\n/** A format that makes a column a different KIND of thing in the store (a list, a link, a person, files). */\nconst KIND_WORD: Partial<Record<string, string>> = {\n choice: \"select\",\n multi_choice: \"multi_select\",\n tags: \"multi_select\",\n relation: \"relation\",\n person: \"member\",\n attachment: \"attachment\",\n};\n\n/** A plain column's storage → the store's plain kind word. */\nconst PLAIN_WORD: Partial<Record<string, string>> = {\n string: \"text\",\n number: \"number\",\n integer: \"number\",\n boolean: \"checkbox\",\n date: \"datetime\",\n datetime: \"datetime\",\n};\n\n/** What an Other kind makes the column hold, in a person's words. */\nfunction storesWord(def: FieldFormatDef): string {\n if (KIND_WORD[def.id]) return def.label;\n return BASE_WORDS[def.base] ?? def.base;\n}\n\nconst BASE_WORDS: Record<string, string> = {\n string: \"Text\",\n number: \"Number\",\n integer: \"Whole number\",\n boolean: \"Yes / no\",\n date: \"Date\",\n datetime: \"Date & time\",\n array: \"List\",\n};\n\n/** Never chosen as a look: made as a column of their own, or raw structure. */\nfunction neverALook(def: FieldFormatDef): boolean {\n return def.editor === \"computed\" || def.id === \"json\" || def.id === \"array\";\n}\n\n/**\n * THE STORAGE A COLUMN'S VALUES HAVE, for the list of formats that fit it — `formula` for a\n * worked-out column (its result can wear any plain look, and it is never retyped here), `null`\n * for a column whose value the record renderer draws itself (a list, a link, a person, files).\n */\nexport function storageOf(field: Field): string | null {\n switch (String(editorKindFor(field))) {\n case \"text\":\n case \"long_text\":\n case \"email\":\n case \"url\":\n case \"phone\":\n return \"string\";\n case \"number\":\n case \"currency\":\n case \"percent\":\n case \"rating\":\n return \"number\";\n case \"checkbox\":\n case \"boolean\":\n return \"boolean\";\n case \"datetime\":\n return String(field.config?.[\"kind\"] ?? \"\") === \"date\" ? \"date\" : \"datetime\";\n case \"formula\":\n return \"formula\";\n default:\n return null;\n }\n}\n\n/** The formats offered for this column: its own, grouped, and the Other kinds (each with its retype word). */\nexport function formatMenu(field: Field): {\n groups: Array<{ group: string; formats: FieldFormatDef[] }>;\n otherKinds: Array<{ def: FieldFormatDef; word: string }>;\n} {\n const base = storageOf(field);\n if (base === null) return { groups: [], otherKinds: [] };\n if (base === \"formula\") {\n const groups: Array<{ group: string; formats: FieldFormatDef[] }> = [];\n for (const def of FIELD_FORMAT_LIST) {\n if (neverALook(def) || KIND_WORD[def.id] || def.id === \"boolean\") continue;\n const bucket = groups.find((g) => g.group === def.group);\n if (bucket) bucket.formats.push(def);\n else groups.push({ group: def.group, formats: [def] });\n }\n return { groups, otherKinds: [] };\n }\n const groups = groupedFormatsForBase(base)\n .map((g) => ({ group: g.group as string, formats: g.formats.filter((d) => !neverALook(d) && !KIND_WORD[d.id]) }))\n .filter((g) => g.formats.length > 0);\n const own = new Set(groups.flatMap((g) => g.formats.map((d) => d.id as string)));\n const otherKinds: Array<{ def: FieldFormatDef; word: string }> = [];\n for (const def of FIELD_FORMAT_LIST) {\n if (own.has(def.id) || neverALook(def)) continue;\n const word = KIND_WORD[def.id] ?? PLAIN_WORD[def.base];\n if (word) otherKinds.push({ def, word });\n }\n return { groups, otherKinds };\n}\n\n/** What the picker opens on: the look the Field keeps. */\nexport function startingChoice(field: Field): FormatChoice {\n const held = displayFormatOf(field);\n if (!held || !getFieldFormat(held.id) || held.id === \"formula\") return { format: null, retype: null };\n return {\n format: Object.keys(held.options).length > 0 ? ({ id: held.id, options: held.options } as FieldFormatConfig) : ({ id: held.id } as FieldFormatConfig),\n retype: null,\n };\n}\n\nfunction sameLook(a: FieldFormatConfig | null, b: FieldFormatConfig | null): boolean {\n const norm = (c: FieldFormatConfig | null) =>\n c ? JSON.stringify([c.id, Object.entries(c.options ?? {}).sort(([x], [y]) => x.localeCompare(y))]) : \"\";\n return norm(a) === norm(b);\n}\n\n/**\n * THE KEYS A SAVE SENDS for this choice, or `undefined` when nothing changed. The look travels as\n * `display_format` (null clears it); an Other kind adds its `type` word beside it.\n */\nexport function formatPatch(field: Field, choice: FormatChoice): Record<string, unknown> | undefined {\n const before = startingChoice(field).format;\n if (!choice.retype && sameLook(before, choice.format)) return undefined;\n const display = choice.format\n ? { id: choice.format.id, ...(choice.format.options && Object.keys(choice.format.options).length > 0 ? { options: choice.format.options } : {}) }\n : null;\n return {\n ...(choice.retype ? { type: choice.retype } : {}),\n ...(choice.retype === \"multi_select\" && choice.format?.id === \"tags\" ? { allow_other: true } : {}),\n display_format: display,\n };\n}\n\nconst CURRENCIES = [\"USD\", \"EUR\", \"GBP\", \"CAD\", \"AUD\", \"JPY\", \"CHF\", \"CNY\", \"INR\", \"MXN\", \"BRL\"];\nconst SELECT = \"h-8 w-full\";\nconst BOX = \"h-8 w-full rounded border bg-background px-2 text-xs\";\n\n/** THE PICKER. `value` is controlled; the caller sends `formatPatch` with its save. */\nexport function FieldFormatPicker({\n field,\n value,\n onValue,\n}: {\n field: Field;\n value: FormatChoice;\n onValue: (next: FormatChoice) => void;\n}) {\n const { groups, otherKinds } = formatMenu(field);\n if (groups.length === 0 && otherKinds.length === 0) return null;\n const active = value.format ? getFieldFormat(value.format.id) : null;\n const options: FieldFormatOptions = value.format?.options ?? {};\n const optionKeys = active?.optionKeys ?? [];\n const retypedTo = value.retype ? otherKinds.find((k) => k.def.id === value.format?.id) : undefined;\n\n const setOption = <K extends keyof FieldFormatOptions>(key: K, next: FieldFormatOptions[K] | undefined) => {\n if (!value.format) return;\n const merged: FieldFormatOptions = { ...options };\n if (next === undefined || (next as unknown) === \"\" || (typeof next === \"number\" && !Number.isFinite(next))) delete merged[key];\n else merged[key] = next as FieldFormatOptions[K];\n onValue({ ...value, format: Object.keys(merged).length > 0 ? { id: value.format.id, options: merged } : { id: value.format.id } });\n };\n\n const option = (key: keyof FieldFormatOptions, label: string, control: ReactNode) =>\n optionKeys.includes(key) ? (\n <label key={key} className=\"flex min-w-[6rem] flex-col gap-0.5 text-[11px] text-muted-foreground\">\n {label}\n {control}\n </label>\n ) : null;\n\n return (\n <div className=\"flex flex-col gap-1\" data-records-format-picker=\"\">\n <Label className=\"text-xs\" htmlFor={`records-shows-as-${field.id}`}>\n Shows as\n </Label>\n <PickOne\n id={`records-shows-as-${field.id}`}\n label=\"Shows as\"\n className={SELECT}\n value={value.format?.id ?? \"\"}\n onChange={(id) => {\n if (id === \"\") {\n onValue({ format: null, retype: null });\n return;\n }\n const other = otherKinds.find((k) => k.def.id === id);\n onValue({ format: { id: id as FieldFormatConfig[\"id\"] }, retype: other ? other.word : null });\n }}\n options={[\n { value: \"\", label: \"As it is stored\" },\n ...groups.flatMap((g) => g.formats.map((d) => ({ value: d.id, label: d.label, group: g.group }))),\n ...otherKinds.map(({ def }) => ({\n value: def.id,\n label: `${def.label} · holds ${storesWord(def)}`,\n group: \"Other kinds · changes what the column holds\",\n })),\n ]}\n />\n <p className=\"text-[11px] text-muted-foreground\">\n {retypedTo\n ? `This changes what the column holds, to ${storesWord(retypedTo.def)}. Each value that can convert does; you are told before anything that cannot is lost.`\n : active\n ? active.description\n : \"How every value in this column is written, wherever it appears.\"}\n </p>\n {optionKeys.length > 0 ? (\n <div className=\"flex flex-wrap items-end gap-2\">\n {option(\n \"currency\",\n \"Currency\",\n <PickOne\n label=\"Currency\"\n attrs={{ \"data-records-format-option\": \"currency\" }}\n className={SELECT}\n value={options.currency ?? \"USD\"}\n onChange={(picked) => setOption(\"currency\", picked)}\n options={CURRENCIES.map((c) => ({ value: c, label: c }))}\n />,\n )}\n {option(\n \"percentScale\",\n \"Stored as\",\n <PickOne\n label=\"Stored as\"\n attrs={{ \"data-records-format-option\": \"percentScale\" }}\n className={SELECT}\n value={options.percentScale ?? \"whole\"}\n onChange={(picked) => setOption(\"percentScale\", picked as \"whole\" | \"fraction\")}\n options={[\n { value: \"whole\", label: \"45 means 45%\" },\n { value: \"fraction\", label: \"0.45 means 45%\" },\n ]}\n />,\n )}\n {option(\n \"durationUnit\",\n \"Unit\",\n <PickOne\n label=\"Unit\"\n attrs={{ \"data-records-format-option\": \"durationUnit\" }}\n className={SELECT}\n value={options.durationUnit ?? \"seconds\"}\n onChange={(picked) => setOption(\"durationUnit\", picked as NonNullable<FieldFormatOptions[\"durationUnit\"]>)}\n options={[\n { value: \"milliseconds\", label: \"Milliseconds\" },\n { value: \"seconds\", label: \"Seconds\" },\n { value: \"minutes\", label: \"Minutes\" },\n { value: \"hours\", label: \"Hours\" },\n ]}\n />,\n )}\n {option(\n \"precision\",\n \"Decimals\",\n <input\n data-records-format-option=\"precision\"\n type=\"number\"\n min={0}\n max={10}\n placeholder=\"auto\"\n className={BOX}\n value={options.precision ?? \"\"}\n onChange={(e) => setOption(\"precision\", e.target.value === \"\" ? undefined : Number(e.target.value))}\n />,\n )}\n {option(\n \"ratingMax\",\n \"Out of\",\n <input\n data-records-format-option=\"ratingMax\"\n type=\"number\"\n min={1}\n max={10}\n className={BOX}\n value={options.ratingMax ?? 5}\n onChange={(e) => setOption(\"ratingMax\", e.target.value === \"\" ? undefined : Math.max(1, Math.min(10, Number(e.target.value))))}\n />,\n )}\n {option(\n \"dateStyle\",\n \"Style\",\n <PickOne\n label=\"Style\"\n attrs={{ \"data-records-format-option\": \"dateStyle\" }}\n className={SELECT}\n value={options.dateStyle ?? \"medium\"}\n onChange={(picked) => setOption(\"dateStyle\", picked as \"short\" | \"medium\" | \"long\")}\n options={[\n { value: \"short\", label: \"Short\" },\n { value: \"medium\", label: \"Medium\" },\n { value: \"long\", label: \"Long\" },\n ]}\n />,\n )}\n {option(\n \"prefix\",\n \"Prefix\",\n <input data-records-format-option=\"prefix\" className={BOX} value={options.prefix ?? \"\"} onChange={(e) => setOption(\"prefix\", e.target.value)} />,\n )}\n {option(\n \"suffix\",\n \"Suffix\",\n <input data-records-format-option=\"suffix\" className={BOX} placeholder=\"e.g. kg\" value={options.suffix ?? \"\"} onChange={(e) => setOption(\"suffix\", e.target.value)} />,\n )}\n {optionKeys.includes(\"useGrouping\") ? (\n <label className=\"flex items-center gap-1.5 pb-1 text-[11px] text-muted-foreground\">\n <input\n type=\"checkbox\"\n data-records-format-option=\"useGrouping\"\n checked={options.useGrouping !== false}\n onChange={(e) => setOption(\"useGrouping\", e.target.checked)}\n />\n Thousands separators\n </label>\n ) : null}\n </div>\n ) : null}\n </div>\n );\n}\n","// src/archiveWords.ts — @ai-matrx/records-ui · lane V25-UI-FIXES\n//\n// THE ONE ARCHIVE SENTENCE, in this package. Archived custom tables, records and saved views are\n// listed by personal and Organization Trash (lane TRASH-TABLES), so every confirm in front of an\n// archive says the same three facts the app's own confirms say: what happens (it is archived, not\n// destroyed), what the person will notice (it leaves this list), and where it comes back from\n// (the Archived view — platform ruling, 2026-10-03: a store surface never sends a person to \"Trash\").\n// The words are the app's `archiveConfirmSentence` (matrx-frontend\n// `features/trash/archiveCopy.ts`) exactly — one sentence across the platform; this package cannot\n// import the app, so it carries the same function and the test pins the words.\n//\n// Before: the table's confirm said \"The store keeps them for 365 days, so it can still be brought\n// back.\" without saying from where (VERIFIER-25, outside the list), and the record's said \"waits in\n// Archived items\" — true, and silent about Trash.\n\n/**\n * \"This archives the table \"Vendor contracts\". It leaves this list, and you can restore it from Trash.\"\n *\n * `what` is the thing as a person would say it — `the table \"Vendor contracts\"`, `\"Summit Janitorial\"`.\n */\nimport { formatCount } from \"@ai-matrx/kit/format\";\n\nexport function archiveConfirmSentence(what: string): string {\n const subject = what.trim() || \"it\";\n return `This archives ${subject}. It leaves this list, and you can restore it from the Archived view.`;\n}\n\n/** Where a table's archive run is, for {@link tableArchiveSentence}. */\nexport interface TableArchiveState {\n progress: { remaining: number; total: number; archived_total: number; in_progress?: boolean | undefined } | null;\n running: boolean;\n /** The last run ended with records still live (stopped, or a pass refused). */\n interrupted: boolean;\n /** The run ended on a refusal. */\n failed: boolean;\n slowedDown: boolean;\n /** Passes made on this screen since it opened (0 after a reload). */\n passesHere?: number;\n}\n\nconst recordsWord = (n: number) => `${formatCount(n)} record${n === 1 ? \"\" : \"s\"}`;\n\n/**\n * ONE SENTENCE FOR A TABLE'S ARCHIVE RUN (BREAKER-1 B-F13, lane DATA-V2-BASICS-2). The panel used to\n * stack the confirm's count, \"N of M put away so far\" and \"Stopped. …\"; and a reload in the middle of\n * a run showed a fresh button with no word that half the records were already put away. A run the\n * store says is still open (`in_progress`) reads as one to carry on. The rows it has already put\n * away are always named — it never says nothing happened.\n */\nexport function tableArchiveSentence(s: TableArchiveState): string {\n const p = s.progress;\n if (!p) return \"Every record in it goes with it.\";\n const done = p.total - p.remaining;\n const sofar = `${formatCount(done)} of ${recordsWord(p.total)} ${done === 1 ? \"is\" : \"are\"} put away`;\n if (s.running) {\n return `Archiving — ${formatCount(done)} of ${recordsWord(p.total)} put away.${s.slowedDown ? \" Busy, so it is taking smaller passes; it will still finish.\" : \"\"}`;\n }\n if (p.in_progress && !s.failed && !(s.passesHere ?? 0)) {\n return `Archiving this table was started and not finished: ${sofar}. Carry on and it picks up where it stopped.`;\n }\n if (s.interrupted && s.failed) return `That pass did not finish: ${sofar} and nothing was lost. Carry on and it picks up where it stopped.`;\n if (s.interrupted) return `Stopped: ${sofar}. Carry on whenever you like; it picks up where it stopped.`;\n return `Its ${recordsWord(p.remaining)} ${p.remaining === 1 ? \"goes\" : \"go\"} with it.`;\n}\n\n/**\n * \"2 rollups on Patients read through this.\" The ONE sentence both link-archive confirms use (the\n * back-link dialog and Column settings' Remove on a link column), so a person is told what else\n * goes \"Source archived\" before the click. Empty when nothing reads through it.\n */\nexport function readersSentence(count: number, tableName: string | null): string {\n if (count <= 0) return \"\";\n const rollups = count === 1 ? \"1 rollup\" : `${count} rollups`;\n return `${rollups} on ${tableName ?? \"this table\"} read through this.`;\n}\n","// src/reversePrefix.ts — the id prefix of a back-link grid column. Kept apart from ReverseColumns.tsx\n// so the pure column helpers (gridMenus, gridColumns) can know a back-link id without its React deps.\n\n/** A reverse column's grid id starts with this. Never a Field key: a Field key cannot hold a colon. */\nexport const REVERSE_COLUMN_PREFIX = \"linked:\";\n","// src/gridPage.ts — @ai-matrx/records-ui · merge tranche 6k (server search, sort and paging)\n//\n// THE MERGED GRID ASKS THE STORE FOR ITS PAGE (`custom.read_records_page` through `useRecordPage`).\n//\n// The classic grid read one page and then searched, filtered and sorted THAT page in the browser —\n// the readiness audit searched a 1,000-row table for a record on page six and found nothing, and a\n// sort ordered fifty rows while claiming to order the table. Here the grid's own query state (the\n// data table's search box, its column filters, its header sort, its page) is translated into the\n// store's one question and the store answers it: sorted over the whole table, searched over every\n// column this reader may see, filtered in its own WHERE clause, counted.\n//\n// These are the pure halves: the sort in the store's shape, and the column filters in the store's\n// one filter shape. A filter the store cannot ask is NEVER applied in the browser to the page it\n// happens to hold (that is the lie this tranche removes) — it is refused by name, and the grid\n// says so.\n\nimport type { Field, RecordFilter, RecordsError, RuleExpression, StoreFilter } from \"@ai-matrx/records\";\nimport { isRuleFilter } from \"@ai-matrx/records\";\nimport { dateFilterBounds, dateFilterDayBounds, dayInstantWindow } from \"@ai-matrx/design-system/data-table\";\nimport { getPersonTimeZone } from \"./personTime\";\nimport type { ColumnFilterValue, ColumnFiltersState } from \"@ai-matrx/design-system/data-table/types\";\nimport { editorKindFor } from \"./parity\";\nimport { fieldName } from \"./names\";\n\n/**\n * 🚨 WHY THE STORE CANNOT SORT BY THIS COLUMN, or `null` when it can (merged-grid review\n * 2026-09-26). A column worked out on every read (`type: \"formula\"`, `compute_on: \"read\"` — the\n * default, and what a lookup or a rollup is) keeps no value in the record, so\n * `custom.read_records_page` refuses to order the whole table by it. The header offered \"Sort\n * ascending\" anyway; the refused page then emptied the grid. The screen asks this ONE question\n * before offering a sort, and says the store's own reason instead.\n */\nexport function sortRefusal(f: Field): string | null {\n if (!computedOnRead(f)) return null;\n return `${fieldName(f)} is worked out each time it is read, so the whole table cannot be sorted by it. Sort by a column it is worked out from.`;\n}\n\n/**\n * THE HEADER MENU'S ONE LINE for a column that can neither sort nor filter (walk 2026-10-17, D4: the line\n * spoke only of sorting while the Filter was gone with no word). The store's WHERE clause and ORDER BY read\n * kept values, and `read_records_page` / `record_aggregate` keep none for a column worked out on read.\n */\nexport function sortAndFilterRefusal(f: Field): string | null {\n if (sortRefusal(f) === null) return null;\n return `${fieldName(f)} is worked out each time it is read, so it can be neither sorted nor filtered. Use a column it is worked out from.`;\n}\n\n/** The same fact for a filter: the store's WHERE clause reads kept values, and this column keeps none. */\nexport function filterRefusal(f: Field): string | null {\n if (!computedOnRead(f)) return null;\n return `${fieldName(f)} is worked out each time it is read, so the whole table cannot be filtered by it. Filter by a column it is worked out from.`;\n}\n\nfunction computedOnRead(f: Field): boolean {\n const kind = String(editorKindFor(f));\n return (\n (f.type === \"formula\" || kind === \"formula\" || kind === \"lookup\" || kind === \"rollup\") &&\n String((f as { compute_on?: unknown }).compute_on ?? \"read\") === \"read\"\n );\n}\n\n// The sort halves (`holdsNumbers`, `sortAsFor`, `pageSortFor`) moved to `@ai-matrx/records/first-page` (step 10):\n// the server's first-page seed asks with the very same arguments.\nimport { holdsNumbers } from \"@ai-matrx/records/first-page\";\nexport { holdsNumbers, pageSortFor, sortAsFor } from \"@ai-matrx/records/first-page\";\n\n/** A text a person typed, as a case-insensitive \"contains\" pattern — records' one definition (`records/data`). */\nimport { containsPattern } from \"@ai-matrx/records/data\";\nexport { containsPattern };\n\nexport interface StoreQuestion {\n /** The whole question: the view's own filter AND every column filter the store can ask. */\n filter: StoreFilter | undefined;\n /** Column filters the store cannot ask, each as a sentence naming the column. Never applied locally. */\n refused: string[];\n}\n\ntype Clause = { flat: RecordFilter } | { rule: RuleExpression };\n\n/**\n * THE DATA TABLE'S \"(empty)\" TICK, as it writes it into a select filter's `values`\n * (`SELECT_EMPTY_VALUE` in the design system's filter engine). Asked of the store as \"has not been\n * answered\". `a-text-column-filters-by-its-values-counted-by-the-store.test.tsx` ticks the real\n * checklist, so this word drifting from the table's is a red test, not a silent no-op.\n */\nexport const BLANK_VALUE = \"__empty__\";\n\nconst field = (f: Field): RuleExpression => ({ field: f.id });\nconst constant = (value: unknown): RuleExpression => ({ const: value });\n/** A column's moment is in the half-open window `{from, to}` — the store's `within` node. */\nconst withinWindow = (f: Field, window: { from?: string; to?: string }): RuleExpression =>\n ({ op: \"within\", args: [field(f), constant(window)] }) as unknown as RuleExpression;\nconst op = (name: string, ...args: RuleExpression[]): RuleExpression =>\n ({ op: name, args }) as unknown as RuleExpression;\n\n/** One column filter, as a store clause — or the sentence saying why the store cannot ask it. */\nexport function clauseFor(f: Field, value: ColumnFilterValue, now: Date = new Date()): Clause | string | null {\n const name = fieldName(f);\n const refused = filterRefusal(f);\n if (refused) return refused;\n const not = (rule: RuleExpression): RuleExpression => op(\"not\", rule);\n switch (value.kind) {\n case \"text\": {\n const mode = value.mode ?? \"contains\";\n if (mode === \"empty\" || mode === \"null\") return value.negated ? { rule: op(\"present\", field(f)) } : { rule: not(op(\"present\", field(f))) };\n if (mode === \"not_empty\" || mode === \"not_null\") return value.negated ? { rule: not(op(\"present\", field(f))) } : { rule: op(\"present\", field(f)) };\n const text = value.value.trim();\n if (text === \"\") return null;\n const kind = String(editorKindFor(f));\n if (kind === \"number\" || kind === \"currency\" || kind === \"percent\" || kind === \"checkbox\") {\n return `${name} holds numbers, so it is filtered by a range, not by words.`;\n }\n const matches = op(\"matches\", field(f), constant(containsPattern(text)));\n return { rule: value.negated ? not(matches) : matches };\n }\n case \"select\": {\n // \"Is any of\" the ticked values; \"(empty)\" ticked (`BLANK_VALUE`) is \"has not been answered\";\n // Exclude is everything else — a blank row is not one of the ticked values, so Exclude keeps it\n // unless \"(empty)\" is ticked too (the Sheet's \"Exclude these instead\", slice C).\n const ticked = value.values ?? (value.value === \"\" ? [] : [value.value]);\n const blank = ticked.includes(BLANK_VALUE);\n const words = ticked.filter((w) => w !== BLANK_VALUE);\n if (!blank && words.length === 0) return value.negated ? null : { rule: constant(false) };\n const present = op(\"present\", field(f));\n const kind = String(editorKindFor(f));\n if (kind === \"datetime\" || kind === \"date\") {\n // TICKED DAYS: each is a half-open window, asked as the store's one `within` leaf. One day\n // alone stays a flat window (what a dashboard number asks); several days are an ANY of\n // them, a day beside \"(empty)\" adds the unanswered, and Exclude is NOT — the same shapes\n // every other value list makes, kept by a saved view in the one filter grammar.\n if (words.length === 0) return { rule: value.negated ? present : not(present) };\n const holdsDays = String(((f.config ?? {}) as Record<string, unknown>)[\"kind\"] ?? \"\") === \"date\";\n if (words.length === 1 && !blank && !value.negated) return { flat: { [f.key]: dayWindow(words[0]!, holdsDays) } };\n const leaves = words.map((day) => withinWindow(f, dayWindow(day, holdsDays)));\n const anyDay = leaves.length === 1 ? leaves[0]! : op(\"or\", ...leaves);\n if (!value.negated) return { rule: blank ? op(\"or\", not(present), anyDay) : anyDay };\n return { rule: blank ? op(\"and\", present, not(anyDay)) : not(anyDay) };\n }\n // The list's words are text; a number or yes/no column is asked in its own kind.\n const asStored = (w: string): unknown =>\n holdsNumbers(f) || kind === \"rating\"\n ? Number.isFinite(Number(w)) ? Number(w) : w\n : kind === \"checkbox\" && (w === \"true\" || w === \"false\") ? w === \"true\" : w;\n const stored = words.map(asStored);\n const anyWord =\n stored.length === 0 ? null : stored.length === 1 ? op(\"eq\", field(f), constant(stored[0])) : op(\"or\", ...stored.map((w) => op(\"eq\", field(f), constant(w))));\n if (!value.negated) {\n if (!blank && stored.length === 1) return { flat: { [f.key]: stored[0] as string | number | boolean } };\n if (!blank) return { rule: anyWord! };\n return { rule: anyWord ? op(\"or\", not(present), anyWord) : not(present) };\n }\n if (blank) return { rule: anyWord ? op(\"and\", present, not(anyWord)) : present };\n return { rule: op(\"or\", not(present), not(anyWord!)) };\n }\n case \"boolean\":\n return value.negated ? { rule: op(\"ne\", field(f), constant(value.value)) } : { flat: { [f.key]: value.value } };\n case \"number\": {\n // The number filter's operators (lane C): =, ≠, <, >, empty, not empty; \"between\" below.\n // The header's Exclude (slice C) turns every one of them round, never only \"between\".\n const turned = (rule: RuleExpression): Clause => ({ rule: value.negated ? not(rule) : rule });\n if (value.op === \"empty\") return turned(not(op(\"present\", field(f))));\n if (value.op === \"not_empty\") return turned(op(\"present\", field(f)));\n if (value.op === \"eq\" || value.op === \"ne\") {\n if (typeof value.min !== \"number\") return null;\n return turned(op(value.op, field(f), constant(value.min)));\n }\n if (value.op === \"lt\") return typeof value.max === \"number\" ? turned(op(\"lt\", field(f), constant(value.max))) : null;\n if (value.op === \"gt\") return typeof value.min === \"number\" ? turned(op(\"gt\", field(f), constant(value.min))) : null;\n const parts: RuleExpression[] = [];\n if (typeof value.min === \"number\") parts.push(op(\"gte\", field(f), constant(value.min)));\n if (typeof value.max === \"number\") parts.push(op(\"lte\", field(f), constant(value.max)));\n if (parts.length === 0) return null;\n const range = parts.length === 1 ? parts[0]! : op(\"and\", ...parts);\n return { rule: value.negated ? not(range) : range };\n }\n case \"date\": {\n // A relative preset (\"Today\", \"Last hour\") is worked out at the moment the question is asked,\n // in the viewer's own clock, and sent as exact bounds (grids review 3, lane H item 3). A saved\n // view's \"Today\" is today when it is opened — never the day somebody first picked it. A\n // column that holds a DAY is asked in days, never compared with an instant.\n // The window is read in the PERSON'S zone (setPersonTimeZone), so \"Today\" here is what the calendar calls today.\n const zone = getPersonTimeZone() ?? undefined;\n const moments = dateFilterBounds(value.preset ? { ...value, anchor: now.toISOString() } : value, now, zone);\n const holdsDays = String(((f.config ?? {}) as Record<string, unknown>)[\"kind\"] ?? \"\") === \"date\";\n const bounds = holdsDays ? dateFilterDayBounds(moments, zone) : moments;\n if (bounds.since === undefined && bounds.until === undefined) return null;\n return {\n flat: {\n [f.key]: {\n ...(bounds.since === undefined ? {} : { from: bounds.since }),\n ...(bounds.until === undefined ? {} : { to: bounds.until }),\n },\n },\n };\n }\n default:\n return `${name} cannot be filtered that way.`;\n }\n}\n\n/**\n * ONE DAY AS A HALF-OPEN WINDOW. A column that holds DAYS is asked in days (\"2026-09-01\" up to\n * \"2026-09-02\"); a column of moments is asked from the viewer's own midnight to the next.\n */\nexport function dayWindow(day: string, holdsDays: boolean): { from: string; to: string } {\n if (!holdsDays) return dayInstantWindow(day, getPersonTimeZone() ?? undefined);\n const [y, m, d] = day.split(\"-\").map(Number);\n const ymd = (t: Date) => `${t.getUTCFullYear()}-${String(t.getUTCMonth() + 1).padStart(2, \"0\")}-${String(t.getUTCDate()).padStart(2, \"0\")}`;\n return { from: ymd(new Date(Date.UTC(y!, (m ?? 1) - 1, d ?? 1))), to: ymd(new Date(Date.UTC(y!, (m ?? 1) - 1, (d ?? 1) + 1))) };\n}\n\n/**\n * THE VIEW'S QUESTION AND THE COLUMN FILTERS, AS ONE STORE QUESTION.\n *\n * Flat clauses (an equality, `null`, a date window) stay flat when nothing else needs a Rule, so a\n * plain \"Status is Scheduled\" is the same question a dashboard number asks. When any clause needs a\n * Rule (words that contain, a range, several choices, NOT), the flat equalities become `eq` nodes of\n * one ALL group. A date window becomes a `within` leaf of that group.\n */\nexport function storeQuestion(\n fields: readonly Field[],\n base: StoreFilter | undefined,\n columnFilters: ColumnFiltersState,\n now: Date = new Date(),\n): StoreQuestion {\n const refused: string[] = [];\n const flat: RecordFilter = {};\n const rules: RuleExpression[] = [];\n if (base && isRuleFilter(base)) rules.push(base);\n else if (base) Object.assign(flat, base);\n for (const [key, value] of Object.entries(columnFilters)) {\n if (!value) continue;\n const f = fields.find((candidate) => candidate.key === key);\n if (!f) continue;\n const clause = clauseFor(f, value, now);\n if (clause === null) continue;\n if (typeof clause === \"string\") {\n refused.push(clause);\n continue;\n }\n if (\"flat\" in clause) Object.assign(flat, clause.flat);\n else rules.push(clause.rule);\n }\n const flatKeys = Object.keys(flat);\n if (rules.length === 0) return { filter: flatKeys.length > 0 ? flat : undefined, refused };\n for (const key of flatKeys) {\n const f = fields.find((candidate) => candidate.key === key);\n const value = flat[key];\n if (!f) continue;\n if (value !== null && typeof value === \"object\") {\n rules.push(withinWindow(f, value as { from?: string; to?: string }));\n continue;\n }\n rules.push(value === null ? op(\"not\", op(\"present\", field(f))) : op(\"eq\", field(f), constant(value)));\n }\n return { filter: rules.length === 1 ? rules[0]! : op(\"and\", ...rules), refused };\n}\n\n/**\n * 🚨 THE STORE'S SENTENCE, WITH ITS COLUMNS CALLED BY THEIR NAMES (merged-grid review 2026-09-26).\n * A refused page read names the column by its KEY (\"The column \\\"visit_total\\\" is worked out each\n * time it is read…\"), and the refusal formatter — rightly — drops a sentence carrying a machine\n * key, so the grid printed only \"That was not accepted\" and \"Nothing was read.\": a red fragment.\n * The key is the grid's to translate: every Field key the sentence names becomes that column's\n * name, and the store's sentence is then said whole.\n */\nexport function inColumnWords(error: RecordsError, fields: readonly Field[]): RecordsError {\n const say = (text: string | null | undefined): string | null | undefined => {\n if (!text) return text;\n let out = text;\n for (const f of [...fields].sort((a, b) => b.key.length - a.key.length)) {\n const key = f.key.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n out = out.replace(new RegExp(`([\"“'])${key}([\"”'])`, \"g\"), `$1${fieldName(f)}$2`);\n }\n return out;\n };\n return { ...error, message: say(error.message) ?? error.message, ...(error.hint ? { hint: say(error.hint) ?? error.hint } : {}) };\n}\n","// src/tableJson.ts — @ai-matrx/records-ui · TABLE-PARITY item 1 (the older Sheet's ExportTableModal):\n// A TABLE AS JSON, two ways, beside CSV, XLSX and Markdown.\n//\n// exportJson the rows alone: an array of objects, each column's name -> its value (what a script reads).\n// exportFullSchema the table whole: its columns (name, key, kind, list-ness, required, choices), its settings and\n// its rows — enough to read the table back into another one.\n//\n// Pure. Both take the SAME `ExportRow`s the CSV is written from (`toRows` / `rowsForFile`), so a JSON file carries\n// exactly the columns and rows the screen shows, with the same words for a withheld or never-asked value.\n// A column's kind is the classifier's (`editorKindFor` and the field's `multi`), never its raw stored type.\n\nimport type { Field, ReadValue } from \"@ai-matrx/records\";\nimport { exportCellText, type ExportRow } from \"@ai-matrx/records/core\";\nimport { toDelimited } from \"@ai-matrx/kit/delimited\";\nimport { editorKindFor } from \"./parity\";\nimport { fieldName } from \"./names\";\n\n/** The id column's header in a round-trip file. */\nexport const ROW_ID_NAME = \"Row ID\";\n\n/** The stored values of rows, in the export shape (the value as kept, never the words a cell draws). */\nexport function storedExportRows(fields: readonly Field[], rows: ReadonlyArray<{ document?: unknown }>): ExportRow[] {\n return rows.map((row) => {\n const document = (row.document ?? {}) as Record<string, unknown>;\n return Object.fromEntries(fields.map((f) => [f.key, { field_key: f.key, value: document[f.key] ?? null, absent_reason: null } as ReadValue]));\n });\n}\n\n/** CSV whose first column is each record's id: copy it, edit it, paste it back, and the same records change. */\nexport function exportCsvWithRowIds(fields: readonly Field[], rows: readonly ExportRow[], ids: readonly string[]): string {\n const head = [ROW_ID_NAME, ...uniqueNames(fields)];\n const body = rows.map((row, at) => [ids[at] ?? \"\", ...fields.map((f) => exportCellText(f, row[f.key]))]);\n return toDelimited([head, ...body]);\n}\n\n/** One cell as JSON: the value as stored; the store's absence word when it was withheld or never asked. */\nfunction jsonCell(value: ReadValue | undefined): unknown {\n if (!value) return null;\n if (value.absent_reason) return `(${value.absent_reason})`;\n return value.value === undefined ? null : value.value;\n}\n\n/** The rows alone: `[ { \"Client\": \"…\", \"Retainer\": 4000 }, … ]`, columns in the order given. */\nexport function exportJson(fields: readonly Field[], rows: readonly ExportRow[], ids?: readonly string[]): string {\n const names = uniqueNames(fields);\n const objects = rows.map((row, at) => ({\n // A round-trip file leads with each record's id, so a re-import updates the record instead of adding a copy.\n ...(ids ? { [ROW_ID_NAME]: ids[at] ?? null } : {}),\n ...Object.fromEntries(fields.map((f, i) => [names[i]!, jsonCell(row[f.key])])),\n }));\n return JSON.stringify(objects, null, 2) + \"\\n\";\n}\n\n/** A column as it is described in a full-schema file. */\nexport interface SchemaColumn {\n key: string;\n name: string;\n /** What the column holds, by the field-kind classifier (never the raw stored type). */\n kind: string;\n /** Holds several values (a list). */\n multi: boolean;\n required: boolean;\n /** The choices of a choice column, when it has them. */\n choices?: unknown;\n}\n\nexport function schemaColumnOf(field: Field): SchemaColumn {\n const config = (field.config ?? {}) as Record<string, unknown>;\n const choices = config[\"options\"] ?? config[\"choices\"];\n return {\n key: field.key,\n name: fieldName(field),\n kind: String(editorKindFor(field)),\n multi: field.multi === true,\n required: field.required === true,\n ...(choices !== undefined ? { choices } : {}),\n };\n}\n\nexport interface FullSchemaTable {\n name: string;\n /** The table's own settings worth carrying (label words, icon, row label column, …). */\n settings?: Record<string, unknown> | undefined;\n}\n\n/** The table whole: `{ table, settings, columns, rows }`, rows keyed by column KEY so they read back exactly. */\nexport function exportFullSchema(table: FullSchemaTable, fields: readonly Field[], rows: readonly ExportRow[], ids?: readonly string[]): string {\n return (\n JSON.stringify(\n {\n table: { name: table.name },\n settings: table.settings ?? {},\n columns: fields.map(schemaColumnOf),\n rows: rows.map((row, at) => ({\n ...(ids ? { id: ids[at] ?? null } : {}),\n ...Object.fromEntries(fields.map((f) => [f.key, jsonCell(row[f.key])])),\n })),\n },\n null,\n 2,\n ) + \"\\n\"\n );\n}\n\n/** Column names made unique (two columns called \"Notes\" must not overwrite each other in one object). */\nfunction uniqueNames(fields: readonly Field[]): string[] {\n const seen = new Map<string, number>();\n return fields.map((f) => {\n const base = fieldName(f);\n const n = (seen.get(base) ?? 0) + 1;\n seen.set(base, n);\n return n === 1 ? base : `${base} (${n})`;\n });\n}\n\n/** The table settings a full-schema file carries, picked from the store's table record. */\nexport function settingsOfTable(table: Record<string, unknown> | null | undefined): Record<string, unknown> {\n if (!table) return {};\n const keep = [\"label_singular\", \"label_plural\", \"icon\", \"color\", \"type\", \"title_field\", \"ordered\", \"display\"];\n return Object.fromEntries(keep.filter((k) => table[k] !== undefined && table[k] !== null).map((k) => [k, table[k]]));\n}\n","// src/gridLook.ts — @ai-matrx/records-ui · lane DEFAULT-GRID-PARITY\n//\n// WHAT THE STORE ALREADY SAYS ABOUT HOW A TABLE OPENS, READ IN ONE PLACE.\n//\n// The owner, on his real table's new page (2026-09-23): \"none of my advanced features are\n// copied over.\" Each of the things below was IN THE STORE and the default grid never read\n// it (`common-docs/systems/data/custom-data/HANDOFF.md`, rows D1 D3 D4 D5 D6\n// S2 F1 R3). They are pure functions on purpose — the grid is a large component and every\n// one of these answers is a question a test must be able to ask without mounting it:\n//\n// · the table's DEFAULT SORT (`data.default_sort`, `[{field, direction}]`), which the store\n// keeps and nothing read;\n// · the LAYOUT the grid opens with: the platform, then the organization's knob\n// (`custom/grid_layout`, read through `custom.grid_layout`), then THIS VIEW's own choice —\n// three layers, in that order, and the view always wins;\n// · the SUMMARY measures a column may offer, from the store's own list\n// (`custom.agg_operations`), filtered to what the column can mean;\n// · a REFERENCE a person pastes into a prompt — the `table` / `table_row` reference nouns.\n\nimport type { AggregateOperation, Field, GridLayout, GridLayoutMode, GridRowHeight, ReadRow } from \"@ai-matrx/records\";\nimport type { MatrxDataTableCopyConfig } from \"@ai-matrx/design-system/data-table/types\";\n\nimport { fieldName } from \"./names\";\nimport { shownValue, type LabelLookup } from \"./labels\";\nimport { editorKindFor } from \"./parity\";\nimport { exportCsvWithRowIds, exportFullSchema, exportJson, settingsOfTable, storedExportRows } from \"./tableJson\";\n\n// ── the default sort ─────────────────────────────────────────────────────────────────────\n\n// The table's own sort moved to `@ai-matrx/records/first-page` (step 10): the server's first page reads it too.\nexport { defaultSortOf, type ColumnSort as DefaultSort } from \"@ai-matrx/records/first-page\";\n\n// ── the layout ───────────────────────────────────────────────────────────────────────────\n\n/** A view's own layout choices — the per-view override of the organization's knob. */\nexport interface ViewLook {\n /** px, the grid's existing per-view row height. */\n rowHeight?: number | undefined;\n /** The view's own frozen columns, by key (the grid's existing per-view freeze). */\n frozen?: string[] | undefined;\n wrap?: boolean | undefined;\n /** Column titles on two lines, the view's own choice. */\n headerWrap?: boolean | undefined;\n fit?: GridLayoutMode | undefined;\n /**\n * \"Freeze the first column\", said by THIS VIEW — `false` is an explicit NO over an\n * organization whose knob freezes it, which an empty `frozen` list cannot say (an empty\n * list is how a view that never chose reads).\n */\n freezeFirst?: boolean | undefined;\n}\n\n/**\n * The row heights, in the pixels the grid's primitive takes. Airtable's four: short is the primitive's\n * own one-line density (kept as an explicit 36 when a view chooses it), medium 2 lines, tall 4,\n * extra tall 6. `compact` / `normal` are the older words. A px is the ONE thing a view stores\n * (`presentation.rowHeight`), so the line count is read back from it: see `rowLines`.\n */\nexport const ROW_HEIGHT_PX: Record<GridRowHeight, number | undefined> = {\n compact: 28,\n short: undefined,\n normal: undefined,\n medium: 56,\n tall: 96,\n extra_tall: 136,\n};\n\n/** The four words the Layout menu offers, in order. */\nexport const ROW_HEIGHT_WORDS = [\"short\", \"medium\", \"tall\", \"extra_tall\"] as const;\n\n/** The px a view remembers, read back as one of the menu's four words (older words fold into short). */\nexport function rowHeightWord(px: number | undefined): GridRowHeight {\n if (px === undefined || px < 46) return \"short\";\n if (px < 76) return \"medium\";\n if (px < 116) return \"tall\";\n return \"extra_tall\";\n}\n\n/** A stored word as the menu's word: compact and normal are one-line rows, i.e. short. */\nexport function menuRowHeightWord(word: GridRowHeight): (typeof ROW_HEIGHT_WORDS)[number] {\n return word === \"compact\" || word === \"normal\" ? \"short\" : word;\n}\n\n/** How many lines of text a row of this height shows: 1, 2, 4 or 6. */\nexport function rowLines(px: number | undefined): 1 | 2 | 4 | 6 {\n const word = rowHeightWord(px);\n return word === \"extra_tall\" ? 6 : word === \"tall\" ? 4 : word === \"medium\" ? 2 : 1;\n}\n\nexport interface ResolvedLook {\n rowHeight: number | undefined;\n rowHeightWord: GridRowHeight;\n wrap: boolean;\n /** Column titles on two lines instead of one. */\n headerWrap: boolean;\n /** What the table does with its width: fit it, or keep natural widths and scroll. */\n fit: \"fit\" | \"scroll\";\n /** The choice as stored — `auto` resolves to fit or scroll by the column count. */\n fitChoice: GridLayoutMode;\n frozen: string[];\n /** Where each of the four came from, so the menu can say \"your organization's\". */\n from: { rowHeight: Source; wrap: Source; fit: Source; frozen: Source };\n}\n\nexport type Source = \"view\" | \"organization\" | \"platform\";\n\nfunction storeSource(layout: GridLayout | null, key: string): Source {\n const said = layout?.source?.[key];\n return said === \"organization\" ? \"organization\" : \"platform\";\n}\n\n/**\n * THE COLUMN ORDER THE LOOK READS \"FIRST\" FROM: the Fields' own order, with the column that names\n * each record (`title_field`) leading — \"freeze the first column\" freezes the record's name, as\n * Airtable's primary field is always the one that stays (merged-grid review 2, D1: the menu said\n * \"Freeze Title\" and pinned whichever column sorted first). Pure.\n */\nexport function lookColumnKeys(orderedKeys: readonly string[], titleField: string | null | undefined): string[] {\n return titleField && orderedKeys.includes(titleField)\n ? [titleField, ...orderedKeys.filter((k) => k !== titleField)]\n : [...orderedKeys];\n}\n\n/**\n * THE LOOK THE GRID OPENS WITH: the view's own choice over the organization's knob over the\n * platform. `columnKeys` is the grid's column order, because \"freeze the first column\" is a\n * statement about whichever column is first, and \"automatic\" fit is a statement about how\n * many columns there are (`fit_max_columns`).\n *\n * `layout` null means the store's answer has not arrived or was refused; the grid then opens\n * exactly as it always did — the knob is an override, never the only thing that makes a\n * table readable.\n */\nexport function resolveLook(\n layout: GridLayout | null,\n view: ViewLook,\n columnKeys: readonly string[],\n): ResolvedLook {\n const stored = layout?.layout;\n const rowHeight =\n view.rowHeight !== undefined ? view.rowHeight : stored ? ROW_HEIGHT_PX[stored.row_height] : undefined;\n const wrap = view.wrap ?? stored?.wrap ?? true;\n const headerWrap = view.headerWrap ?? false;\n const fitChoice: GridLayoutMode = view.fit ?? stored?.mode ?? \"auto\";\n const max = stored?.fit_max_columns ?? 8;\n const fit: \"fit\" | \"scroll\" =\n fitChoice === \"fit\" ? \"fit\" : fitChoice === \"scroll\" ? \"scroll\" : columnKeys.length <= max ? \"fit\" : \"scroll\";\n const freezeFirst = view.freezeFirst ?? stored?.freeze_first_column ?? false;\n const frozen =\n view.frozen && view.frozen.length > 0\n ? view.frozen\n : freezeFirst && columnKeys[0]\n ? [columnKeys[0]]\n : [];\n return {\n rowHeight,\n rowHeightWord: menuRowHeightWord(view.rowHeight !== undefined ? rowHeightWord(view.rowHeight) : (stored?.row_height ?? \"normal\")),\n wrap,\n headerWrap,\n fit,\n fitChoice,\n frozen,\n from: {\n rowHeight: view.rowHeight !== undefined ? \"view\" : storeSource(layout, \"row_height\"),\n wrap: view.wrap !== undefined ? \"view\" : storeSource(layout, \"wrap\"),\n fit: view.fit !== undefined ? \"view\" : storeSource(layout, \"mode\"),\n frozen:\n (view.frozen && view.frozen.length > 0) || view.freezeFirst !== undefined\n ? \"view\"\n : storeSource(layout, \"freeze_first_column\"),\n },\n };\n}\n\n// ── the summary bar ──────────────────────────────────────────────────────────────────────\n\n/** What each of the store's measures is called on screen. */\nexport const MEASURE_LABEL: Record<string, string> = {\n count: \"Count\",\n sum: \"Sum\",\n avg: \"Average\",\n min: \"Smallest\",\n max: \"Largest\",\n median: \"Median\",\n filled: \"Filled\",\n empty: \"Empty\",\n unique: \"Unique\",\n percent_empty: \"Percent empty\",\n percent_filled: \"Percent filled\",\n range: \"Range\",\n} satisfies Record<AggregateOperation, string>;\n\n/**\n * NOTION'S CALCULATE MENU (Spaces N6) — the embedded grid's footer offers Notion's list, in Notion's\n * order and words, each answered by one of the store's measures. `footer` is what the footer cell\n * says before the value (\"Sum 1,240\"). Count all counts records, so every column offers it.\n */\nexport const NOTION_CALCULATIONS: ReadonlyArray<{ op: string; menu: string; footer: string }> = [\n { op: \"count\", menu: \"Count all\", footer: \"Count\" },\n { op: \"unique\", menu: \"Count unique values\", footer: \"Unique\" },\n { op: \"empty\", menu: \"Count empty\", footer: \"Empty\" },\n { op: \"filled\", menu: \"Count not empty\", footer: \"Not empty\" },\n { op: \"percent_empty\", menu: \"Percent empty\", footer: \"Empty\" },\n { op: \"percent_filled\", menu: \"Percent not empty\", footer: \"Not empty\" },\n { op: \"sum\", menu: \"Sum\", footer: \"Sum\" },\n { op: \"avg\", menu: \"Average\", footer: \"Average\" },\n { op: \"median\", menu: \"Median\", footer: \"Median\" },\n { op: \"min\", menu: \"Min\", footer: \"Min\" },\n { op: \"max\", menu: \"Max\", footer: \"Max\" },\n { op: \"range\", menu: \"Range\", footer: \"Range\" },\n];\n\n/** Notion's calculations this column can mean, among those the store offers. */\nexport function calculationsFor(field: Field, storeOps: readonly string[]): Array<{ op: string; menu: string; footer: string }> {\n const offered = new Set(measuresFor(field, storeOps, true));\n return NOTION_CALCULATIONS.filter((c) => offered.has(c.op));\n}\n\nconst NUMERIC_ONLY = new Set([\"sum\", \"avg\", \"median\"]);\nconst ARITHMETIC = new Set([\n \"add\", \"sub\", \"mul\", \"div\", \"mod\", \"power\", \"sum\", \"average\", \"round\", \"abs\", \"min\", \"max\", \"ceiling\", \"floor\",\n]);\nconst ORDERED = new Set([\"min\", \"max\", \"range\"]);\n\n/** Is this a column whose values are numbers the store can add up? */\nexport function isNumericField(field: Field): boolean {\n const kind = editorKindFor(field);\n if (kind === \"number\" || kind === \"currency\" || kind === \"percent\" || kind === \"rollup\") return true;\n // A worked-out column is a number when its expression is arithmetic — `{Visit fee} -\n // {Deposit taken}` is stored as `{\"op\":\"fx.sub\",…}`. A joined label is not.\n if (kind !== \"formula\") return false;\n const expr = ((field.config ?? {}) as Record<string, unknown>)[\"expr\"] as { op?: unknown } | undefined;\n const op = typeof expr?.op === \"string\" ? expr.op.replace(/^fx\\./, \"\") : \"\";\n return ARITHMETIC.has(op);\n}\n\nfunction isOrderedField(field: Field): boolean {\n return isNumericField(field) || editorKindFor(field) === \"datetime\";\n}\n\n/**\n * THE MEASURES THIS COLUMN MAY OFFER — the store's own list (`custom.agg_operations`),\n * narrowed to what the column can mean. A sum of a text column is not a number the store\n * would refuse; it is a number that means nothing, which is worse, so it is never offered.\n * `count` counts records and belongs to no column, so it is offered once, on the first.\n */\nexport function measuresFor(field: Field, storeOps: readonly string[], firstColumn: boolean): string[] {\n return storeOps.filter((op) => {\n if (op === \"count\") return firstColumn;\n if (NUMERIC_ONLY.has(op)) return isNumericField(field);\n if (ORDERED.has(op)) return isOrderedField(field);\n return true;\n });\n}\n\n// ── a reference for a prompt ─────────────────────────────────────────────────────────────\n\n/**\n * THE GRID'S COPY, WITH ITS REFERENCES (TABLE-PARITY R3).\n *\n * The data table's Copy already offers the rows as text and as agent JSON; what it could not\n * offer is a REFERENCE — the pointer an agent expands itself (`table` and `table_row`, the\n * reference nouns the server resolves, and which follow a moved table into the record store).\n * The primitive takes references only on an explicit copy config, so this is that config: the\n * same text and JSON the primitive's own default writes (every column that reads a value, in\n * the view's order, by its own name), plus the two references. A row reference is NAMED by\n * the table's row label so it reads as a name. The host's content-transfer port decides\n * whether it can build them; where none is installed, the reference choice is simply absent.\n */\nexport function gridCopyConfig(args: {\n tableId: string;\n tableName: string;\n fields: readonly Field[];\n rowLabel: (row: ReadRow) => string;\n /**\n * WHAT A REFERENCE IS CALLED — the grid's own resolver (`useRecordLabels`). Copy and Copy for\n * AI carry the words the cell shows (\"Ojeda residence\"), never the id the store keeps.\n */\n labels?: LabelLookup;\n /** The store's table record, for the settings a full-schema copy carries. */\n table?: Record<string, unknown> | null | undefined;\n /**\n * The rows of the view as the grid holds them NOW (the store's page: its filter and sort applied), read when a file is\n * picked. Absent, the table's own files are not offered. Read lazily on purpose: an `export` hook that declared the\n * rows as a parameter would redraw the toolbar with every row edit (`copyDrawsFromRows`).\n */\n viewRows?: (() => ReadRow[]) | undefined;\n}): MatrxDataTableCopyConfig<ReadRow> {\n const { tableId, tableName, fields, rowLabel, labels, table, viewRows } = args;\n const shown = (row: ReadRow) => {\n const document = (row.document ?? {}) as Record<string, unknown>;\n const out: Record<string, unknown> = {};\n for (const field of fields) {\n if (document[field.key] !== undefined) out[fieldName(field)] = shownValue(field, document[field.key], labels);\n }\n return out;\n };\n const text = (value: unknown): string =>\n value === null || value === undefined ? \"\" : typeof value === \"object\" ? JSON.stringify(value) : String(value);\n /** The table's own files, written from the rows of THIS VIEW (its filter and sort), ids first where a round trip needs them. */\n const stored = (rows: ReadRow[]) => storedExportRows(fields, rows);\n const ids = (rows: ReadRow[]) => rows.map((r) => r.id as string);\n return {\n label: tableName,\n listLabel: tableName,\n // THE OLDER SHEET'S TABLE COPY, KEPT (TABLE-PARITY item 4): the rows with their ids (a copy that pastes back onto the\n // same records), the table as JSON, and the full schema (columns, settings, rows).\n ...(viewRows ? { export: () => { const visible = viewRows(); return {\n items: [\n { id: \"csv-row-ids\", label: \"CSV with row IDs\", build: () => ({ content: exportCsvWithRowIds(fields, stored(visible), ids(visible)), extension: \"csv\", mime: \"text/csv;charset=utf-8\", filename: `${tableName} with row IDs` }) },\n { id: \"table-json\", label: \"JSON with row IDs\", build: () => ({ content: exportJson(fields, stored(visible), ids(visible)), extension: \"json\", mime: \"application/json;charset=utf-8\", filename: tableName }) },\n { id: \"full-schema\", label: \"Full schema (JSON)\", build: () => ({ content: exportFullSchema({ name: tableName, settings: settingsOfTable(table) }, fields, stored(visible), ids(visible)), extension: \"json\", mime: \"application/json;charset=utf-8\", filename: `${tableName} full schema` }) },\n ],\n }; } } : {}),\n location: tableName,\n rowKind: \"table-row\",\n listKind: \"table-view\",\n listDescription: `${tableName} — the records on this page, filtered and sorted as shown.`,\n humanRow: (row) =>\n Object.entries(shown(row))\n .map(([name, value]) => `${name}: ${text(value)}`)\n .join(\"\\n\"),\n agentRow: (row) => shown(row),\n rowReferences: (row) => [\n {\n id: `table_row:${tableId}:${row.id}`,\n label: rowLabel(row),\n noun: \"table_row\",\n items: [{ table_id: tableId, row_id: row.id, table_name: tableName, row_label: rowLabel(row) }],\n },\n ],\n references: () => [\n {\n id: `table:${tableId}`,\n label: tableName,\n noun: \"table\",\n items: [{ table_id: tableId, table_name: tableName }],\n },\n ],\n };\n}\n","// src/gridMenus.ts — @ai-matrx/records-ui · merge tranches 6a + 6b\n//\n// THE OLDER /data GRID'S MENUS, REWRITTEN ONTO `Field`.\n//\n// Two menus a spreadsheet person reaches for without thinking: the column header's own menu\n// (rename, insert a column beside it, hide, delete, its settings, use it as the row label) and\n// the right-click menu, which is four menus decided by where the pointer was — the cell, its row,\n// its column, the table (`@ai-matrx/design-system/data-table` `menu-targets.ts`). The /data grid\n// had both (`components/user-generated-table-data/ColumnHeaderMenu.tsx`,\n// `features/data-tables/grid-context-menu.ts`); this is the same vocabulary — the same section\n// titles, the same verbs, a disabled item that SAYS WHY — built from the store's own Field records\n// and aimed at the grid's own data paths, never at a second write path.\n//\n// Pure: no React, no store. Every \"do\" is a function the grid hands in, so the builders can be\n// asserted item by item and the grid decides what each press reaches.\n\nimport type { Field } from \"@ai-matrx/records\";\nimport type { MatrxTableMenuItem, MatrxTableMenuSection } from \"@ai-matrx/design-system/data-table\";\nimport type { MatrxDataTableContextMenuConfig } from \"@ai-matrx/design-system/data-table/types\";\n\nimport { fieldName } from \"./names\";\nimport { REVERSE_COLUMN_PREFIX } from \"./reversePrefix\";\nimport { sortRefusal } from \"./gridPage\";\nimport { isNumericField } from \"./gridLook\";\nimport { editorKindFor } from \"./parity\";\nimport { retypeableFrom, whyNotRetypeable } from \"./FieldRetype\";\n\n/** Why a menu item whose handler this grid did not hand in does nothing here. */\nconst NOT_HERE = \"Not available here\";\n\n/**\n * WHAT A SORT IS CALLED ON THIS COLUMN (merged-grid review 2, C1: a number column read \"Sort A→Z\").\n * The words say what the order IS for the values the column holds, as Sheets and Airtable do:\n * numbers 1→9, dates oldest→newest, words A→Z. Pure.\n */\n/** Why a record cannot be renamed from the grid: its table names records by no typed column. */\nexport const NO_NAME_CELL = \"This table names records by no typed column\";\n\nexport function sortWords(field: Field | undefined): { asc: string; desc: string } {\n if (field) {\n const kind = String(editorKindFor(field));\n if (isNumericField(field) || kind === \"autonumber\") return { asc: \"1→9\", desc: \"9→1\" };\n if (kind === \"datetime\" || kind === \"date\") return { asc: \"oldest→newest\", desc: \"newest→oldest\" };\n }\n return { asc: \"A→Z\", desc: \"Z→A\" };\n}\n\n/** What the data table hands a `contextMenu.sections` resolver for the level that was clicked. */\nexport type MatrxTableMenuPayload = Parameters<NonNullable<MatrxDataTableContextMenuConfig<unknown>[\"sections\"]>>[0];\n\n/** Everything the menus may do, each through a path the grid already owns. */\nexport interface GridMenuActions {\n copyText: (text: string, what: string) => void;\n pasteInto: (rowId: string, columnId: string) => void;\n /** \"Paste over n cells\": the clipboard goes over the selected block through the grid's one paste door; absent, the item says why. */\n pasteOver?: (() => void) | undefined;\n clearCells: (cells: Array<{ rowId: string; columnId: string }>) => void;\n fillDown: (rowIds: string[], columnIds: string[]) => void;\n newRecord: () => void;\n /** Present only on a hand-ordered view, where a row HAS a place; absent, the items say why. */\n insertRow?: ((rowId: string, side: \"above\" | \"below\") => void) | undefined;\n duplicateRow: (rowId: string) => void;\n archiveRow: (rowId: string) => void;\n openRecord?: ((rowId: string) => void) | undefined;\n askWhoChanged?: ((columnId: string, rowId: string) => void) | undefined;\n sortBy: (columnId: string, direction: \"asc\" | \"desc\" | null) => void;\n filterBy: (columnId: string, value: unknown) => void;\n hideColumn: (columnId: string) => void;\n renameColumn: (columnId: string) => void;\n insertColumn: (columnId: string, side: \"left\" | \"right\") => void;\n columnSettings: (columnId: string) => void;\n deleteColumn: (columnId: string) => void;\n useAsRowLabel: (columnId: string) => void;\n addColumn?: (() => void) | undefined;\n /** Rename the record: its name cell opens in place (v7 TABLE-EXPERIENCE item 5); absent, the item says why. */\n renameRow?: ((rowId: string) => void) | undefined;\n /** Keep this row's values as a row template (\"New from template\"); absent, the item is not drawn. */\n saveAsTemplate?: ((rowId: string) => void) | undefined;\n /** Copy the link to the record's own page; absent, the item is not drawn. */\n copyRecordLink?: ((rowId: string) => void) | undefined;\n /** Merge another record of the table into this row (`MergeRecordDialog`); absent, the item says why. */\n mergeRow?: ((rowId: string) => void) | undefined;\n /** Move some of this row's values to a new record (`SplitRecordDialog`); absent, the item says why. */\n splitRow?: ((rowId: string) => void) | undefined;\n /** Copy values up into a new parent record (`ExtractParentDialog`); absent, the item says why. */\n extractParentRow?: ((rowId: string) => void) | undefined;\n /** Print this row through one of the table's saved layouts (`PrintWithLayoutDialog`); absent, the item says why. */\n printRow?: ((rowId: string) => void) | undefined;\n /** Open the host's one record picker pointed at this row (`RecordsUiHost.linkRecord`). */\n linkRow?: ((rowId: string) => void) | undefined;\n /** Change what the column holds (`FieldRetype`, with Undo); absent, the item says why. */\n changeType?: ((columnId: string) => void) | undefined;\n /** Tidy the column's text across every row (`ColumnCleanDialog`); absent, the item says why. */\n cleanColumn?: ((columnId: string) => void) | undefined;\n /** Tidy ONE cell's text, with the same review (`ColumnCleanDialog` on one row); absent, the item is not drawn. */\n cleanCell?: ((rowId: string, columnId: string) => void) | undefined;\n /** Freeze or unfreeze the column on the view (the Layout menu's freeze, per column); absent, the item says why. */\n freezeColumn?: ((columnId: string) => void) | undefined;\n /** Drop the column's saved width so it takes its kind's width again; absent, the item says why. */\n autoFitColumn?: ((columnId: string) => void) | undefined;\n /** Move the column one place left or right in the view's order; absent, the items say why. */\n moveColumn?: ((columnId: string, side: \"left\" | \"right\") => void) | undefined;\n}\n\n/** What this person may do here, each with the sentence that says why not. */\nexport interface GridMenuContext {\n fields: readonly Field[];\n /** The table's row label column (`title_field`). */\n titleField: string | null;\n /** May this person change records here at all, and this row in particular. */\n mayWriteRow: (rowId: string) => boolean;\n whyNotWrite: (rowId?: string) => string;\n /** May this person archive (delete) this row: a higher rung than changing it (`remove` asks `editor`). */\n mayRemoveRow?: ((rowId: string) => boolean) | undefined;\n whyNotRemove?: ((rowId?: string) => string) | undefined;\n /** A row action the person's level refuses is left out of the menu instead of drawn disabled. */\n hideRefusedRowActions?: boolean | undefined;\n /** May this person add a record to the table. */\n mayAddRecord: boolean;\n whyNotAdd: string;\n /** May this person change the table's shape (columns, row label). */\n mayStructure: boolean;\n whyNotStructure: string;\n /** The columns frozen on this view (the \"Freeze column\" item reads Unfreeze for these). */\n frozenColumns?: ReadonlySet<string> | undefined;\n /** The visible columns in the order drawn (the move items stop at the ends). */\n columnOrder?: readonly string[] | undefined;\n /** Whether a column holds plain text a clean can tidy (`isTextColumn`). */\n cleanable?: ((field: Field) => boolean) | undefined;\n /** Which columns take a typed value (a worked-out column never does). */\n typeable: (columnId: string) => boolean;\n /** The column's current sort, when it is the one the grid is sorted by. */\n sortedBy: { id: string; direction: \"asc\" | \"desc\" } | null;\n actions: GridMenuActions;\n /**\n * A READ-ONLY GRID (a picker's preview, `editable={false}`, a host whose `rights` port says\n * read): every item that writes is ABSENT — not disabled with a reason — because the grid is\n * not a place where writing happens at all (merged-grid leftovers, 2026-09-28). See `READS`.\n */\n readOnly?: boolean | undefined;\n /**\n * MORE ITEMS FROM THE MERGED GRID'S OTHER CONTROLS (tranches 6g, 6h, 6i) — color, summary,\n * highlight, row label — each built where its data lives and slotted into the one vocabulary.\n */\n extras?: GridMenuExtras | undefined;\n}\n\n/** Items the grid's color, summary and row-label controls add to the menus. */\nexport interface GridMenuExtras {\n header?: ((columnId: string) => MatrxTableMenuItem[]) | undefined;\n cell?: ((rowId: string, columnId: string) => MatrxTableMenuItem[]) | undefined;\n row?: ((rowId: string) => MatrxTableMenuItem[]) | undefined;\n table?: (() => MatrxTableMenuItem[]) | undefined;\n /** Items for a multi-cell selection (the color door's \"Highlight n cells\"). */\n selection?: ((cells: Array<{ rowId: string; columnId: string }>) => MatrxTableMenuItem[]) | undefined;\n /** The row's own name (the table's row label), for the Row section's heading. */\n rowTitle?: ((rowId: string) => string | null) | undefined;\n}\n\nfunction fieldOf(ctx: GridMenuContext, columnId: string): Field | undefined {\n return ctx.fields.find((f) => f.key === columnId);\n}\n\nfunction columnWords(ctx: GridMenuContext, columnId: string): string {\n const field = fieldOf(ctx, columnId);\n return field ? fieldName(field) : columnId;\n}\n\n/** Only a column a person types can name a record: the store names records by stored words. */\nexport function rowLabelRefusal(field: Field | undefined): string | undefined {\n if (!field) return \"This column is not one of the table's own.\";\n const kind = String(field.type);\n if (kind === \"formula\" || kind === \"lookup\" || kind === \"rollup\") {\n return `${fieldName(field)} is calculated, and a record is named by a column people fill in.`;\n }\n if (kind === \"relation\") return `${fieldName(field)} points at other records; a record is named by its own words.`;\n return undefined;\n}\n\n/**\n * A formula column's own formula text, when it can name a record by it (the row-label formula,\n * `tableRowLabelSet`). Undefined for every other column, and for a formula column that holds no text.\n */\nexport function rowLabelFormulaOf(field: Field | undefined): string | undefined {\n if (!field || String(field.type) !== \"formula\") return undefined;\n const text = String(((field.config ?? {}) as Record<string, unknown>)[\"formula_text\"] ?? \"\").trim();\n return text === \"\" ? undefined : text;\n}\n\n/** Why the header menu's \"Use as row label\" is not offered on this column; a formula column is offered. */\nexport function useAsRowLabelRefusal(field: Field | undefined): string | undefined {\n if (field && String(field.type) === \"formula\") {\n return rowLabelFormulaOf(field) ? undefined : `${fieldName(field)} has no formula text to name a record by.`;\n }\n return rowLabelRefusal(field);\n}\n\n/**\n * WHAT A READ-ONLY GRID'S MENUS KEEP — THE ONE LIST (merged-grid leftovers, 2026-09-28: the\n * tables picker's preview offered Duplicate, Paste, Insert and Delete). An ALLOW-list on purpose:\n * an item added later is hidden from a read-only grid until someone decides it only reads, so a\n * new write item can never leak into a preview. Printing a record through a layout reads it (the\n * store withholds masked columns, so a viewer prints what they may see: Airtable lets anyone who sees a\n * base print with a layout; AT-REVIEW-3). Copying, opening, filtering, sorting and hiding a\n * column on your own screen read; everything else writes to the table, its records or its look.\n */\nexport const READS: ReadonlySet<string> = new Set([\n \"cell-copy\",\n \"cell-history\",\n \"cell-filter\",\n \"row-open\",\n \"row-print-layout\",\n \"row-history\",\n \"row-copy\",\n \"col-sort-asc\",\n \"col-sort-desc\",\n \"col-sort-clear\",\n \"col-hide\",\n \"sel-copy\",\n]);\n\n/** A read-only grid's items: only what reads (`READS`). */\nfunction readsOnly(items: MatrxTableMenuItem[], ctx: GridMenuContext): MatrxTableMenuItem[] {\n return ctx.readOnly ? items.filter((item) => READS.has(item.id)) : items;\n}\n\n/**\n * THE COLUMN HEADER'S OWN MENU — drawn by the data table under its built-in sort and filter\n * (`MatrxColumnDef.headerMenu`), so a column's actions live in the one place a person looks.\n */\n/** A back-link column's grid id starts here (`ReverseColumns.tsx` `REVERSE_COLUMN_PREFIX`). */\nconst BACK_LINK_COLUMN = \"linked:\";\n/** Why a back-link column is not renamed or retyped here: it mirrors a column of another table. */\nexport const BACK_LINK_COLUMN_MIRRORS = \"This column mirrors a link column on another table. Change it there.\";\n\nexport function headerMenuItems(columnId: string, ctx: GridMenuContext): MatrxTableMenuItem[] {\n // A BACK-LINK (REL-9, virtual) has no Field of its own: its settings say which link column it\n // mirrors, and removing it archives that column (CHAIR-UI-STORE item 2) — never a silent no-op.\n if (columnId.startsWith(BACK_LINK_COLUMN)) {\n const a = ctx.actions;\n return readsOnly([\n { id: \"col-settings\", label: \"Column settings…\", icon: \"settings\", onSelect: () => a.columnSettings(columnId) },\n { id: \"col-rename\", label: \"Rename column\", icon: \"pencil\", disabledReason: BACK_LINK_COLUMN_MIRRORS, onSelect: () => undefined },\n { id: \"col-hide\", label: \"Hide column\", icon: \"eye-off\", onSelect: () => a.hideColumn(columnId) },\n {\n id: \"col-delete\",\n label: \"Delete column…\",\n icon: \"trash\",\n destructive: true,\n separatorBefore: true,\n disabledReason: ctx.mayStructure ? undefined : ctx.whyNotStructure,\n onSelect: () => a.deleteColumn(columnId),\n },\n ], ctx);\n }\n const field = fieldOf(ctx, columnId);\n const shape = ctx.mayStructure ? undefined : ctx.whyNotStructure;\n const isLabel = ctx.titleField === columnId;\n const labelRefusal = shape ?? (isLabel ? \"Records are already named by this column.\" : useAsRowLabelRefusal(field));\n const a = ctx.actions;\n return readsOnly([\n { id: \"col-rename\", label: \"Rename column\", icon: \"pencil\", disabledReason: shape, onSelect: () => a.renameColumn(columnId) },\n { id: \"col-settings\", label: \"Column settings…\", icon: \"settings\", disabledReason: shape, onSelect: () => a.columnSettings(columnId) },\n {\n id: \"col-retype\",\n label: \"Change type…\",\n disabledReason:\n shape ??\n (!a.changeType ? NOT_HERE : field && !retypeableFrom(field) ? whyNotRetypeable(field) : undefined),\n onSelect: () => a.changeType?.(columnId),\n },\n {\n id: \"col-clean\",\n label: \"Clean column…\",\n icon: \"paintbrush\",\n disabledReason:\n !a.cleanColumn\n ? NOT_HERE\n : !ctx.typeable(columnId)\n ? `${columnWords(ctx, columnId)} is calculated; nobody types it.`\n : field && !ctx.cleanable?.(field)\n ? \"Only a text column can be cleaned.\"\n : undefined,\n onSelect: () => a.cleanColumn?.(columnId),\n },\n {\n id: \"col-freeze\",\n label: ctx.frozenColumns?.has(columnId) ? \"Unfreeze column\" : \"Freeze column\",\n disabledReason: a.freezeColumn ? undefined : NOT_HERE,\n onSelect: () => a.freezeColumn?.(columnId),\n },\n { id: \"col-autofit\", label: \"Auto-fit width\", disabledReason: a.autoFitColumn ? undefined : NOT_HERE, onSelect: () => a.autoFitColumn?.(columnId) },\n {\n id: \"col-move-left\",\n label: \"Move left\",\n disabledReason: !a.moveColumn ? NOT_HERE : ctx.columnOrder?.[0] === columnId ? \"This column is already first.\" : undefined,\n onSelect: () => a.moveColumn?.(columnId, \"left\"),\n },\n {\n id: \"col-move-right\",\n label: \"Move right\",\n disabledReason: !a.moveColumn ? NOT_HERE : ctx.columnOrder?.[ctx.columnOrder.length - 1] === columnId ? \"This column is already last.\" : undefined,\n onSelect: () => a.moveColumn?.(columnId, \"right\"),\n },\n { id: \"col-insert-left\", label: \"Insert column left…\", icon: \"panel-left\", disabledReason: shape, onSelect: () => a.insertColumn(columnId, \"left\") },\n { id: \"col-insert-right\", label: \"Insert column right…\", icon: \"panel-right\", disabledReason: shape, onSelect: () => a.insertColumn(columnId, \"right\") },\n {\n id: \"col-row-label\",\n label: isLabel ? \"Names each record\" : \"Use as row label\",\n icon: \"tag\",\n disabledReason: labelRefusal,\n onSelect: () => a.useAsRowLabel(columnId),\n },\n ...(ctx.extras?.header?.(columnId) ?? []),\n { id: \"col-hide\", label: \"Hide column\", icon: \"eye-off\", onSelect: () => a.hideColumn(columnId) },\n {\n id: \"col-delete\",\n label: \"Delete column…\",\n icon: \"trash\",\n destructive: true,\n separatorBefore: true,\n disabledReason: shape ?? (isLabel ? \"Records are named by this column; pick another row label first.\" : undefined),\n onSelect: () => a.deleteColumn(columnId),\n },\n ], ctx);\n}\n\nfunction cellSection(\n payload: Extract<MatrxTableMenuPayload, { level: \"cell\" }>,\n ctx: GridMenuContext,\n): MatrxTableMenuSection {\n const a = ctx.actions;\n const { rowId, columnId } = payload;\n const mayWrite = ctx.mayWriteRow(rowId);\n const typeable = ctx.typeable(columnId);\n const why = !mayWrite\n ? ctx.whyNotWrite(rowId)\n : !typeable\n ? `${columnWords(ctx, columnId)} is calculated; nobody types it.`\n : undefined;\n const items: MatrxTableMenuItem[] = [\n {\n id: \"cell-cut\",\n label: \"Cut cell\",\n icon: \"scissors\",\n shortcut: \"⌘X\",\n disabledReason: why,\n onSelect: () => {\n a.copyText(payload.text, \"The cell\");\n a.clearCells([{ rowId, columnId }]);\n },\n },\n { id: \"cell-copy\", label: \"Copy cell\", icon: \"copy\", shortcut: \"⌘C\", onSelect: () => a.copyText(payload.text, \"The cell\") },\n { id: \"cell-paste\", label: \"Paste\", icon: \"clipboard-paste\", shortcut: \"⌘V\", disabledReason: why, onSelect: () => a.pasteInto(rowId, columnId) },\n { id: \"cell-clear\", label: \"Clear cell\", icon: \"eraser\", destructive: true, disabledReason: why, onSelect: () => a.clearCells([{ rowId, columnId }]) },\n ];\n // THE PER-CELL CLEAN (the older Sheet's cell button): the column's operations on this one value, with the review.\n // ALWAYS OFFERED, like the header's \"Clean column…\": a cell it cannot clean says why (a member walk on\n // 2026-10-10 found the item silently absent from the cell menu while the header showed its sibling).\n const cellField = fieldOf(ctx, columnId);\n items.push({\n id: \"cell-clean\",\n label: \"Clean cell…\",\n icon: \"paintbrush\",\n disabledReason:\n why ??\n (!a.cleanCell ? NOT_HERE : cellField && !ctx.cleanable?.(cellField) ? \"Only a text cell can be cleaned.\" : undefined),\n onSelect: () => a.cleanCell?.(rowId, columnId),\n });\n if (a.askWhoChanged) {\n items.push({ id: \"cell-history\", label: \"Who changed this?\", icon: \"history\", shortcut: \"⌥⇧H\", onSelect: () => a.askWhoChanged?.(columnId, rowId) });\n }\n const empty = payload.value === null || payload.value === undefined || payload.value === \"\";\n items.push({\n id: \"cell-filter\",\n label: empty ? \"Show rows where this is empty\" : \"Show rows with this value\",\n icon: \"filter\",\n onSelect: () => a.filterBy(columnId, payload.value),\n });\n items.push(...(ctx.extras?.cell?.(rowId, columnId) ?? []));\n return { id: \"cell\", title: payload.columnLabel || \"Cell\", items };\n}\n\nfunction rowSection(rowId: string, ctx: GridMenuContext, rowText: string | null): MatrxTableMenuSection {\n // THE RECORD'S MENU, NOTION'S ORDER (v7 TABLE-EXPERIENCE item 5): open, rename, duplicate, copy\n // link, then what reaches other records, then where a row goes, then Archive alone and last.\n const a = ctx.actions;\n const mayWrite = ctx.mayWriteRow(rowId);\n const items: MatrxTableMenuItem[] = [];\n if (a.openRecord) {\n items.push({ id: \"row-open\", label: \"Open record\", icon: \"panel-right\", shortcut: \"Space\", onSelect: () => a.openRecord?.(rowId) });\n }\n items.push({\n id: \"row-rename\",\n label: \"Rename\",\n icon: \"pencil\",\n disabledReason: !mayWrite ? ctx.whyNotWrite(rowId) : a.renameRow ? undefined : NO_NAME_CELL,\n onSelect: () => a.renameRow?.(rowId),\n });\n const noPlace =\n \"This view is sorted, so a new record lands where its sort puts it. Reorder places rows by hand; New record adds one.\";\n const insertWhy = !ctx.mayAddRecord ? ctx.whyNotAdd : a.insertRow ? undefined : noPlace;\n items.push({\n id: \"row-duplicate\",\n label: \"Duplicate\",\n icon: \"copy-plus\",\n disabledReason: ctx.mayAddRecord ? undefined : ctx.whyNotAdd,\n onSelect: () => a.duplicateRow(rowId),\n });\n if (a.copyRecordLink) {\n items.push({ id: \"row-copy-link\", label: \"Copy link\", icon: \"link\", onSelect: () => a.copyRecordLink?.(rowId) });\n }\n if (rowText !== null) {\n items.push({ id: \"row-copy\", label: \"Copy row\", icon: \"copy\", onSelect: () => a.copyText(rowText, \"The row\") });\n }\n if (a.saveAsTemplate) {\n items.push({ id: \"row-save-template\", label: \"Save as template\", icon: \"copy-plus\", onSelect: () => a.saveAsTemplate?.(rowId) });\n }\n items.push(\n {\n id: \"row-merge\",\n label: \"Merge with…\",\n separatorBefore: true,\n disabledReason: !mayWrite ? ctx.whyNotWrite(rowId) : a.mergeRow ? undefined : NOT_HERE,\n onSelect: () => a.mergeRow?.(rowId),\n },\n {\n id: \"row-split\",\n label: \"Split…\",\n disabledReason: !mayWrite ? ctx.whyNotWrite(rowId) : a.splitRow ? undefined : NOT_HERE,\n onSelect: () => a.splitRow?.(rowId),\n },\n {\n id: \"row-extract-parent\",\n label: \"Extract parent…\",\n disabledReason: !mayWrite ? ctx.whyNotWrite(rowId) : a.extractParentRow ? undefined : NOT_HERE,\n onSelect: () => a.extractParentRow?.(rowId),\n },\n {\n id: \"row-print-layout\",\n label: \"Print with layout…\",\n separatorBefore: true,\n // Reading a record to print it never needs write access.\n disabledReason: a.printRow ? undefined : NOT_HERE,\n onSelect: () => a.printRow?.(rowId),\n },\n {\n id: \"row-link\",\n label: \"Link a record…\",\n icon: \"link\",\n disabledReason: a.linkRow ? undefined : NOT_HERE,\n onSelect: () => a.linkRow?.(rowId),\n },\n { id: \"row-insert-above\", label: \"Insert row above\", icon: \"plus\", separatorBefore: true, disabledReason: insertWhy, onSelect: () => a.insertRow?.(rowId, \"above\") },\n { id: \"row-insert-below\", label: \"Insert row below\", icon: \"plus\", disabledReason: insertWhy, onSelect: () => a.insertRow?.(rowId, \"below\") },\n );\n if (a.openRecord) {\n items.push({ id: \"row-history\", label: \"Row history\", icon: \"history\", onSelect: () => a.openRecord?.(rowId) });\n }\n items.push(...(ctx.extras?.row?.(rowId) ?? []));\n // ARCHIVE IN ITS OWN GROUP, LAST (DATA-V2-BASICS-2): one slip from Duplicate must not cost a row.\n // It asks `remove` (editor), not `write` (edit_content): a content editor changes rows but the door\n // refuses their archive, so the item says so — or, for a host that hides what the level refuses\n // (`hideRefusedRowActions`), is not drawn at all.\n const mayRemove = mayWrite && (ctx.mayRemoveRow ? ctx.mayRemoveRow(rowId) : true);\n if (mayRemove || !ctx.hideRefusedRowActions) {\n items.push({\n id: \"row-archive\",\n label: \"Archive record\",\n icon: \"trash\",\n destructive: true,\n separatorBefore: true,\n disabledReason: mayRemove ? undefined : !mayWrite ? ctx.whyNotWrite(rowId) : ctx.whyNotRemove?.(rowId) ?? ctx.whyNotWrite(rowId),\n onSelect: () => a.archiveRow(rowId),\n });\n }\n // THE ROW IS CALLED BY ITS NAME (tranche 6i): the table's row label, as the older grid's\n // right-click heading was.\n return { id: \"row\", title: ctx.extras?.rowTitle?.(rowId) || \"Row\", items };\n}\n\nfunction columnSection(columnId: string, columnLabel: string, ctx: GridMenuContext): MatrxTableMenuSection {\n const a = ctx.actions;\n const sorted = ctx.sortedBy?.id === columnId ? ctx.sortedBy.direction : null;\n // A sort the store would refuse is said, never offered (`sortRefusal`, merged-grid review 2026-09-26).\n const field = fieldOf(ctx, columnId);\n const refused = field ? sortRefusal(field) ?? undefined : undefined;\n const words = sortWords(field);\n return {\n id: \"column\",\n title: columnLabel || columnWords(ctx, columnId),\n items: [\n { id: \"col-sort-asc\", label: `Sort ${words.asc}`, icon: \"arrow-up-a-z\", disabledReason: refused ?? (sorted === \"asc\" ? `Already sorted ${words.asc}.` : undefined), onSelect: () => a.sortBy(columnId, \"asc\") },\n { id: \"col-sort-desc\", label: `Sort ${words.desc}`, icon: \"arrow-down-a-z\", disabledReason: refused ?? (sorted === \"desc\" ? `Already sorted ${words.desc}.` : undefined), onSelect: () => a.sortBy(columnId, \"desc\") },\n ...(sorted ? [{ id: \"col-sort-clear\", label: \"Clear sort\", icon: \"arrow-up-down\" as const, onSelect: () => a.sortBy(columnId, null) }] : []),\n ...headerMenuItems(columnId, ctx),\n ],\n };\n}\n\nfunction tableSection(ctx: GridMenuContext): MatrxTableMenuSection {\n const a = ctx.actions;\n const items: MatrxTableMenuItem[] = [\n { id: \"table-new-record\", label: \"New record\", icon: \"plus\", disabledReason: ctx.mayAddRecord ? undefined : ctx.whyNotAdd, onSelect: () => a.newRecord() },\n ];\n if (a.addColumn) {\n items.push({\n id: \"table-add-column\",\n label: \"Add column…\",\n icon: \"plus\",\n disabledReason: ctx.mayStructure ? undefined : ctx.whyNotStructure,\n onSelect: () => a.addColumn?.(),\n });\n }\n items.push(...(ctx.extras?.table?.() ?? []));\n return { id: \"table\", title: \"Table\", items };\n}\n\n/**\n * THE RIGHT-CLICK MENU — the section for what was aimed at first (`primary`), then the wider\n * things it sits in, exactly as the /data grid ordered them: a cell's menu also carries its row,\n * its column and the table.\n */\nexport function gridMenuSections(\n payload: MatrxTableMenuPayload,\n ctx: GridMenuContext,\n rowText: (rowId: string) => string | null = () => null,\n): MatrxTableMenuSection[] {\n const sections = allSections(payload, ctx, rowText);\n if (!ctx.readOnly) return sections;\n // A read-only grid: only what reads, and a section left with nothing is not drawn.\n const kept = sections\n .map((section) => ({ ...section, items: readsOnly(section.items, ctx) }))\n .filter((section) => section.items.length > 0);\n if (kept.length > 0 && !kept.some((section) => section.primary)) kept[0] = { ...kept[0]!, primary: true };\n return kept;\n}\n\nfunction allSections(\n payload: MatrxTableMenuPayload,\n ctx: GridMenuContext,\n rowText: (rowId: string) => string | null,\n): MatrxTableMenuSection[] {\n switch (payload.level) {\n case \"cell\":\n // A RIGHT-CLICK ON A CELL IS THE RECORD'S MENU FIRST (Airtable, Notion; v7 item 5): the cell's\n // own verbs (copy, paste, clear — all on the keyboard too) follow.\n return [\n { ...rowSection(payload.rowId, ctx, rowText(payload.rowId)), primary: true },\n cellSection(payload, ctx),\n columnSection(payload.columnId, payload.columnLabel, ctx),\n tableSection(ctx),\n ];\n case \"row\":\n return [{ ...rowSection(payload.rowId, ctx, rowText(payload.rowId)), primary: true }, tableSection(ctx)];\n case \"column\":\n return [{ ...columnSection(payload.columnId, payload.columnLabel, ctx), primary: true }, tableSection(ctx)];\n case \"selection\": {\n const n = payload.cellCount;\n const blocked = payload.rowIds.find((id) => !ctx.mayWriteRow(id));\n const untypeable = payload.columnIds.find((id) => !ctx.typeable(id));\n const why = blocked\n ? ctx.whyNotWrite(blocked)\n : untypeable\n ? `${columnWords(ctx, untypeable)} is calculated; nobody types it.`\n : undefined;\n const cells = payload.rowIds.flatMap((rowId) => payload.columnIds.map((columnId) => ({ rowId, columnId })));\n return [\n {\n id: \"selection\",\n title: `${n} ${n === 1 ? \"cell\" : \"cells\"}`,\n primary: true,\n items: [\n {\n id: \"sel-cut\",\n label: `Cut ${n} cells`,\n icon: \"scissors\",\n shortcut: \"⌘X\",\n disabledReason: why,\n onSelect: () => {\n ctx.actions.copyText(payload.tsv, `${n} cells`);\n ctx.actions.clearCells(cells);\n },\n },\n { id: \"sel-copy\", label: `Copy ${n} cells`, icon: \"copy\", shortcut: \"⌘C\", onSelect: () => ctx.actions.copyText(payload.tsv, `${n} cells`) },\n {\n id: \"sel-paste\",\n label: `Paste over ${n} cells`,\n icon: \"clipboard-paste\",\n shortcut: \"⌘V\",\n disabledReason: why ?? (ctx.actions.pasteOver ? undefined : NOT_HERE),\n onSelect: () => ctx.actions.pasteOver?.(),\n },\n { id: \"sel-clear\", label: `Clear ${n} cells`, icon: \"eraser\", destructive: true, disabledReason: why, onSelect: () => ctx.actions.clearCells(cells) },\n {\n id: \"sel-fill-down\",\n label: \"Fill down\",\n icon: \"arrow-down-to-line\",\n shortcut: \"⌘D\",\n disabledReason: why ?? (payload.rowIds.length < 2 ? \"Select at least two rows to fill down.\" : undefined),\n onSelect: () => ctx.actions.fillDown(payload.rowIds, payload.columnIds),\n },\n ...(ctx.extras?.selection?.(cells) ?? []),\n ],\n },\n tableSection(ctx),\n ];\n }\n case \"table\":\n return [{ ...tableSection(ctx), primary: true }];\n }\n}\n\n/**\n * WHERE A NEW COLUMN GOES in the view's column order: beside the one it was inserted from.\n * Pure. `order` is the order on screen; the new key is taken out first so a repeat is a move.\n */\nexport function placeColumn(order: readonly string[], newKey: string, anchor: string, side: \"left\" | \"right\"): string[] {\n const rest = order.filter((k) => k !== newKey);\n const at = rest.indexOf(anchor);\n if (at < 0) return [...rest, newKey];\n const index = side === \"left\" ? at : at + 1;\n return [...rest.slice(0, index), newKey, ...rest.slice(index)];\n}\n\n/**\n * THE COLUMNS IN THE ORDER A PERSON LEFT THEM: the view's kept order first (keys whose Field is\n * gone are skipped), then every column it does not name, in the Fields' own order. Pure.\n */\nexport function columnsInKeptOrder(fieldKeys: readonly string[], kept: readonly string[] | undefined): string[] {\n if (!kept || kept.length === 0) return [...fieldKeys];\n const known = new Set(fieldKeys);\n // A kept back-link column (`linked:…`) keeps its place like a Field's (ReverseColumns.tsx).\n const named = kept.filter((k, i) => (known.has(k) || k.startsWith(REVERSE_COLUMN_PREFIX)) && kept.indexOf(k) === i);\n const namedSet = new Set(named);\n return [...named, ...fieldKeys.filter((k) => !namedSet.has(k))];\n}\n\n/**\n * THE ORDER THE COLUMNS TAKE WHEN NOBODY MOVED ONE (lane C, review 2026-09-26 C5): a Field's own\n * `sort`, then the order the columns were MADE in, and the key only as the last word. Ordering by\n * key put a new column in the alphabetical slot of its internal key (\"New columns land in\n * alphabetical order of their internal key\"). Pure.\n */\nexport function compareFieldOrder(\n a: Pick<Field, \"sort\" | \"key\"> & { created_at?: string | null },\n b: Pick<Field, \"sort\" | \"key\"> & { created_at?: string | null },\n): number {\n const bySort = (a.sort ?? 100) - (b.sort ?? 100);\n if (bySort !== 0) return bySort;\n const made = String(a.created_at ?? \"\").localeCompare(String(b.created_at ?? \"\"));\n if (made !== 0) return made;\n return a.key.localeCompare(b.key);\n}\n\n/**\n * THE `sort` A NEW COLUMN IS DECLARED WITH: one past the last column, so it lands at the END of\n * the table in every view and every client, never in the middle. Pure.\n */\nexport function nextFieldSort(fields: readonly Pick<Field, \"sort\">[] | null | undefined): number {\n let last = 0;\n for (const f of fields ?? []) last = Math.max(last, f.sort ?? 100);\n return last + 1;\n}\n","// src/ButtonSettings.tsx — @ai-matrx/records-ui\n//\n// A BUTTON COLUMN'S SETTINGS (lane NOTION-PROPS-3), drawn inside the column settings panel (`FieldEditor`):\n// its label, its color, and what a press does — open a link (with the row's values in it), set fields\n// (one of the table's row actions) or run one of the table's automations. Saved through the column's one\n// save (`custom.field_declare` / `custom.field_update`'s `button`); the store judges it on the way in.\n\nimport { useEffect, useState } from \"react\";\nimport { BasicInput, Button, Label } from \"@ai-matrx/design-system\";\nimport { STYLE_COLORS } from \"@ai-matrx/design-system/data-table\";\nimport { buttonUrlPlaceholders, type ButtonDoes, type ButtonSettings, type Field, type PortalAccent, type RecordsError, type RowAction, type Uuid } from \"@ai-matrx/records\";\nimport { useOptionalRecordsClient } from \"@ai-matrx/records/react\";\nimport { AccentSwatches } from \"./AccentSwatches\";\nimport { PickOne } from \"./PickOne\";\nimport { AddRowSettings } from \"./AddRowSettings\";\nimport { fieldName } from \"./names\";\nimport { RefusalLine } from \"./Refusal\";\nimport { editorKindFor } from \"./parity\";\n\nconst DOES_WORDS: Record<ButtonDoes | \"none\", string> = {\n none: \"Nothing yet\",\n open_url: \"Open a link\",\n run_action: \"Set fields\",\n run_automation: \"Run an automation\",\n add_row: \"Add a row\",\n};\n\n/** A link with each {{field id}} shown as the column's name, so the person reads what it will hold. */\nexport function buttonUrlInWords(url: string, fields: readonly Field[]): string {\n let out = url;\n for (const id of buttonUrlPlaceholders(url)) {\n const f = fields.find((x) => x.id === id || x.key === id);\n if (f) out = out.split(`{{${id}}}`).join(`{${fieldName(f)}}`);\n }\n return out;\n}\n\nexport function ButtonSettingsEditor({\n value,\n onChange,\n tableId,\n fields,\n}: {\n value: ButtonSettings;\n onChange: (next: ButtonSettings) => void;\n tableId: Uuid | null;\n fields: readonly Field[];\n}) {\n const client = useOptionalRecordsClient();\n // The table's row actions as the store holds them: a new one is declared WITH them, never instead.\n const [actions, setActions] = useState<RowAction[] | null>(null);\n const [actionsRefused, setActionsRefused] = useState<RecordsError | null>(null);\n const [automations, setAutomations] = useState<Array<{ id: string; name: string }> | null>(null);\n useEffect(() => {\n if (!client || !tableId) return;\n let live = true;\n if (value.do === \"run_action\" && actions === null) {\n void client.rowActions({ table_id: tableId }).then((got) => {\n if (!live) return;\n // A read that failed says so; it is never drawn as \"no row actions yet\" (walk 2026-10-08 D1).\n if (!got.ok) return setActionsRefused(got.error);\n setActions((got.data?.actions ?? []).filter((a) => a.id));\n });\n }\n if (value.do === \"run_automation\" && automations === null) {\n void client.automations({ table_id: tableId }).then((got) => {\n if (live) setAutomations(got.ok ? (got.data?.automations ?? []).filter((a) => !a.archived_at).map((a) => ({ id: a.id, name: a.name })) : []);\n });\n }\n return () => {\n live = false;\n };\n }, [client, tableId, value.do, actions, automations]);\n\n const set = (patch: Partial<ButtonSettings>) => onChange({ ...value, ...patch });\n const columns = fields.filter((f) => !(f.type === \"text\" && f.format === \"button\"));\n\n return (\n <div className=\"flex flex-col gap-2 rounded-md border p-2\" data-records-button-settings=\"\">\n <div className=\"grid gap-2 sm:grid-cols-2\">\n <label className=\"flex flex-col gap-1\">\n <Label className=\"text-xs\">Button label</Label>\n <BasicInput className=\"h-8 text-xs\" value={value.label} data-records-button-label=\"\" onChange={(e) => set({ label: e.target.value })} />\n </label>\n <div className=\"flex flex-col gap-1\">\n <Label className=\"text-xs\">Does</Label>\n <PickOne\n label=\"What a press does\"\n value={value.do ?? \"none\"}\n attrs={{ \"data-records-button-does\": \"\" }}\n onChange={(next) => set({ do: next === \"none\" ? undefined : (next as ButtonDoes) })}\n options={([\"none\", \"open_url\", \"run_action\", \"run_automation\", \"add_row\"] as const).map((d) => ({ value: d, label: DOES_WORDS[d] }))}\n />\n </div>\n </div>\n <div className=\"flex flex-col gap-1\">\n <Label className=\"text-xs\">Color</Label>\n <AccentSwatches\n value={(value.color ?? \"\") as PortalAccent | \"\"}\n options={STYLE_COLORS as unknown as readonly PortalAccent[]}\n noneLabel=\"Plain\"\n onChange={(next) => set({ color: next === \"\" ? undefined : next })}\n />\n </div>\n {value.do === \"open_url\" ? (\n <div className=\"flex flex-col gap-1\">\n <Label className=\"text-xs\">Link</Label>\n <div className=\"flex gap-1\">\n <BasicInput\n className=\"h-8 flex-1 font-mono text-xs\"\n placeholder=\"https://\"\n data-records-button-url=\"\"\n value={value.url ?? \"\"}\n onChange={(e) => set({ url: e.target.value })}\n />\n {columns.length > 0 ? (\n <PickOne\n label=\"Add a column's value\"\n className=\"h-8 w-36 text-xs\"\n value=\"\"\n placeholder=\"Add value\"\n attrs={{ \"data-records-button-insert\": \"\" }}\n onChange={(id) => set({ url: `${value.url ?? \"\"}{{${id}}}` })}\n options={columns.map((f) => ({ value: f.id, label: fieldName(f) }))}\n />\n ) : null}\n </div>\n {value.url && buttonUrlPlaceholders(value.url).length > 0 ? (\n <p className=\"truncate text-[11px] text-muted-foreground\" data-records-button-url-words=\"\">\n {buttonUrlInWords(value.url, fields)}\n </p>\n ) : null}\n </div>\n ) : null}\n {value.do === \"add_row\" ? <AddRowSettings value={value} onChange={onChange} tableId={tableId} fields={fields} /> : null}\n {value.do === \"run_action\" ? (\n !tableId ? (\n <p className=\"text-xs text-muted-foreground\">Row actions belong to a table</p>\n ) : actionsRefused ? (\n <RefusalLine error={actionsRefused} />\n ) : (\n <div className=\"flex flex-col gap-2\" data-records-button-action=\"\">\n {actions === null || actions.length > 0 ? (\n <PickOne\n label=\"Row action\"\n value={value.action_id ?? \"\"}\n placeholder={actions ? \"Choose a row action\" : \"Reading row actions…\"}\n attrs={{ \"data-records-button-action-pick\": \"\" }}\n onChange={(id) => set({ action_id: id as Uuid })}\n options={(actions ?? []).map((a) => ({ value: a.id as string, label: a.name }))}\n />\n ) : null}\n {actions !== null ? (\n <NewRowAction\n tableId={tableId}\n label={value.label}\n actions={actions}\n columns={columns}\n onMade={(made, all) => {\n setActions(all);\n set({ action_id: made });\n }}\n />\n ) : null}\n </div>\n )\n ) : null}\n {value.do === \"run_automation\" ? (\n automations && automations.length === 0 ? (\n <p className=\"text-xs text-muted-foreground\">No automations yet. Add one in Table ⋯ → Automations.</p>\n ) : (\n <PickOne\n label=\"Automation\"\n value={value.automation_id ?? \"\"}\n placeholder={automations ? \"Choose an automation\" : \"Reading automations…\"}\n onChange={(id) => set({ automation_id: id as Uuid })}\n options={(automations ?? []).map((a) => ({ value: a.id, label: a.name }))}\n />\n )\n ) : null}\n </div>\n );\n}\n\n/** The columns a row action can set: ones a person types, never a worked-out or button column. */\nfunction settableColumns(columns: readonly Field[]): Field[] {\n return columns.filter((f) => {\n const kind = editorKindFor(f);\n return f.type !== \"formula\" && kind !== \"formula\" && kind !== \"lookup\" && kind !== \"rollup\" && !(f.type === \"text\" && f.format === \"button\");\n });\n}\n\n/**\n * SET FIELDS, MADE RIGHT HERE (walk 2026-10-08 D1). \"Set fields\" used to send a person to Table settings\n * to make a row action first and saved nothing meanwhile. The row action is made inline: one column and\n * the value a press sets, declared with the table's other row actions (`custom.action_declare`) and picked\n * for this button. A refusal is said, here.\n */\nfunction NewRowAction({\n tableId,\n label,\n actions,\n columns,\n onMade,\n}: {\n tableId: Uuid;\n label: string;\n actions: RowAction[];\n columns: readonly Field[];\n onMade: (made: Uuid, all: RowAction[]) => void;\n}) {\n const client = useOptionalRecordsClient();\n const settable = settableColumns(columns);\n const [fieldId, setFieldId] = useState(\"\");\n const [setTo, setSetTo] = useState(\"\");\n const [busy, setBusy] = useState(false);\n const [refused, setRefused] = useState<RecordsError | null>(null);\n if (settable.length === 0) return <p className=\"text-xs text-muted-foreground\">No column to set</p>;\n const make = async () => {\n if (!client || fieldId === \"\") return;\n setBusy(true);\n setRefused(null);\n const name = label.trim() || \"Set fields\";\n const kept = actions.map((a) => ({ ...(a.id ? { id: a.id } : {}), name: a.name, kind: a.kind ?? \"update\", ...(a.color !== undefined ? { color: a.color } : {}), ...(a.icon ? { icon: a.icon } : {}), ...(a.confirm !== undefined ? { confirm: a.confirm } : {}), ...(a.steps ? { steps: a.steps } : {}), ...(a.prompt ? { prompt: a.prompt } : {}) }));\n const declared = await client.actionDeclare({\n table_id: tableId,\n actions: [...kept, { name, kind: \"update\", confirm: false, steps: [setTo === \"\" ? { field: fieldId as Uuid, set: \"clear\" } : { field: fieldId as Uuid, set: \"value\", value: setTo }] }] as RowAction[],\n });\n if (!declared.ok) {\n setBusy(false);\n return setRefused(declared.error);\n }\n const reread = await client.rowActions({ table_id: tableId });\n setBusy(false);\n if (!reread.ok) return setRefused(reread.error);\n const all = (reread.data?.actions ?? []).filter((a) => a.id);\n const before = new Set(actions.map((a) => a.id));\n const made = all.find((a) => !before.has(a.id) && a.name === name) ?? all.find((a) => !before.has(a.id));\n if (!made?.id) return setRefused({ code: \"internal\", message: \"The row action was saved but could not be read back.\", hint: \"Reopen this column's settings and pick it from the list.\" } as RecordsError);\n onMade(made.id, all);\n };\n return (\n <div className=\"flex flex-col gap-1\" data-records-button-new-action=\"\">\n <Label className=\"text-xs\">New row action</Label>\n <div className=\"flex flex-wrap items-center gap-1\">\n <PickOne\n label=\"Column to set\"\n className=\"h-8 w-40 text-xs\"\n value={fieldId}\n placeholder=\"Column\"\n attrs={{ \"data-records-button-action-field\": \"\" }}\n onChange={setFieldId}\n options={settable.map((f) => ({ value: f.id, label: fieldName(f) }))}\n />\n <BasicInput className=\"h-8 w-32 text-xs\" placeholder=\"Value\" aria-label=\"Value\" data-records-button-action-value=\"\" value={setTo} onChange={(e) => setSetTo(e.target.value)} />\n <Button type=\"button\" size=\"sm\" variant=\"outline\" disabled={busy || fieldId === \"\"} data-records-button-action-make=\"\" onClick={() => void make()}>\n {busy ? \"Making…\" : \"Make\"}\n </Button>\n </div>\n {refused ? <RefusalLine error={refused} /> : null}\n </div>\n );\n}\n","\"use client\";\n\n// src/AccentSwatches.tsx — @ai-matrx/records-ui\n//\n// THE ONE COLOR PICKER FOR A LOOK. A portal's look (`PortalLookEditor`) and a form's look\n// (`FormBuilder`, MAKE-HOME W5) choose their color here, from the SAME seven names the table\n// highlights use (`custom.portal_accents()`), so an organization's portal and its forms can never\n// be offered two palettes. \"App colour\" is the empty choice: the look falls back to the\n// organization's (a form) or the app's (a portal).\n\nimport type { PortalAccent } from \"@ai-matrx/records\";\nimport { PORTAL_ACCENTS } from \"@ai-matrx/records\";\nimport { cn } from \"@ai-matrx/design-system\";\nimport { STYLE_COLOR_LABELS, SWATCH_CLASS } from \"@ai-matrx/design-system/data-table\";\n\nexport interface AccentSwatchesProps {\n value: PortalAccent | \"\";\n onChange: (accent: PortalAccent | \"\") => void;\n /** The colors the store accepts. Defaults to the shared seven. */\n options?: readonly PortalAccent[] | undefined;\n /** The words on the empty choice. */\n noneLabel?: string | undefined;\n}\n\nexport function AccentSwatches({ value, onChange, options = PORTAL_ACCENTS, noneLabel = \"App color\" }: AccentSwatchesProps) {\n return (\n <div className=\"flex flex-wrap gap-1.5\" role=\"radiogroup\" aria-label=\"Color\">\n <button\n type=\"button\"\n role=\"radio\"\n aria-checked={value === \"\"}\n onClick={() => onChange(\"\")}\n className={cn(\n \"h-7 rounded border px-2 text-xs\",\n value === \"\" ? \"border-foreground\" : \"border-border text-muted-foreground\",\n )}\n >\n {noneLabel}\n </button>\n {options.map((c) => (\n <button\n key={c}\n type=\"button\"\n role=\"radio\"\n aria-checked={value === c}\n aria-label={STYLE_COLOR_LABELS[c]}\n title={STYLE_COLOR_LABELS[c]}\n onClick={() => onChange(c)}\n className={cn(\"h-7 w-7 rounded-full border-2\", SWATCH_CLASS[c], value === c ? \"border-foreground\" : \"border-transparent\")}\n />\n ))}\n </div>\n );\n}\n","// src/AddRowSettings.tsx — @ai-matrx/records-ui\n//\n// W2-A 2 (TEMPLATE-GAPS): AN \"ADD A ROW\" BUTTON'S SETTINGS. Which table the new row goes in (this one, or any other\n// table here) and what it starts with: for each of the new row's columns, one of the pressed row's columns or the\n// pressed row itself (a link back). `custom.button_press` makes the row through the store's create door and the\n// cell opens it.\n\nimport { Label } from \"@ai-matrx/design-system\";\nimport type { ButtonSettings, Field, Uuid } from \"@ai-matrx/records\";\nimport { useFields, useOptionalRecordsClient } from \"@ai-matrx/records/react\";\nimport { useEffect, useState } from \"react\";\nimport { usePickerTables } from \"./tablePicking\";\nimport { isKeptTable, isValueSet } from \"./tablePickerEntries\";\nimport { PickOne } from \"./PickOne\";\n\n/** The pick value for \"the pressed row itself\", stored as `@row`. */\nexport const THIS_ROW = \"@row\";\nconst NOTHING = \"\";\n\n/** The prefill after one column's choice: NOTHING removes the column, anything else maps it. */\nexport function prefillWith(prefill: Record<string, string> | undefined, key: string, from: string): Record<string, string> | undefined {\n const next = { ...(prefill ?? {}) };\n if (from === NOTHING) delete next[key];\n else next[key] = from;\n return Object.keys(next).length ? next : undefined;\n}\n\nexport function AddRowSettings({ value, onChange, tableId, fields }: { value: ButtonSettings; onChange: (next: ButtonSettings) => void; tableId: Uuid | null; fields: readonly Field[] }) {\n // The canonical picker list (G3): a value set or a table the platform keeps is never a place to add a row.\n const tables = usePickerTables();\n const target = (value.table_id ?? tableId) as Uuid | null;\n const targetFields = useFields(target);\n const typed = (targetFields.data ?? []).filter((f) => f.type !== \"formula\" && typeof f.config?.[\"system\"] !== \"string\");\n const sources = [{ value: NOTHING, label: \"Nothing\" }, { value: THIS_ROW, label: \"This row\" }, ...fields.map((f) => ({ value: f.key, label: f.label }))];\n // TEMPLATE-GAPS R3: the new row may start from one of the target table's row templates (\"New 1:1\").\n const client = useOptionalRecordsClient();\n const [templates, setTemplates] = useState<Array<{ template_id: string; name: string }>>([]);\n useEffect(() => {\n if (!client || !target) return;\n let live = true;\n void client.rowTemplates({ table_id: target }).then((got) => live && setTemplates(got.ok ? got.data : []));\n return () => {\n live = false;\n };\n }, [client, target]);\n return (\n <div className=\"flex flex-col gap-2\" data-records-button-add-row=\"\">\n <div className=\"flex flex-col gap-1\">\n <Label className=\"text-xs\">Adds to</Label>\n <PickOne\n label=\"Table the new row goes in\"\n value={value.table_id ?? tableId ?? \"\"}\n attrs={{ \"data-records-button-add-row-table\": \"\" }}\n onChange={(id) => onChange({ ...value, table_id: id === tableId ? undefined : (id as Uuid), prefill: undefined, template_id: undefined })}\n options={tables.data.filter((t) => !isValueSet(t) && !isKeptTable(t)).map((t) => ({ value: t.id as string, label: t.id === tableId ? `${t.label_plural ?? t.name} (this table)` : (t.label_plural ?? t.name) }))}\n />\n </div>\n {templates.length || value.template_id ? (\n <div className=\"flex flex-col gap-1\">\n <Label className=\"text-xs\">Starts from</Label>\n <PickOne\n label=\"Row template the new row starts from\"\n value={value.template_id ?? NOTHING}\n attrs={{ \"data-records-button-add-row-template\": \"\" }}\n onChange={(id) => onChange({ ...value, template_id: id ? (id as Uuid) : undefined })}\n options={[{ value: NOTHING, label: \"A blank row\" }, ...templates.map((t) => ({ value: t.template_id, label: t.name }))]}\n />\n </div>\n ) : null}\n {typed.length ? (\n <div className=\"grid grid-cols-[auto_1fr] items-center gap-x-2 gap-y-1\">\n {typed.map((f) => (\n <div key={f.id} className=\"contents\">\n <span className=\"text-sm\">{f.label}</span>\n <PickOne\n label={`${f.label} starts with`}\n value={value.prefill?.[f.key] ?? NOTHING}\n attrs={{ \"data-records-button-prefill\": f.key }}\n onChange={(from) => onChange({ ...value, prefill: prefillWith(value.prefill, f.key, from) })}\n options={sources}\n />\n </div>\n ))}\n </div>\n ) : null}\n </div>\n );\n}\n","// src/standardFieldChoices.ts — @ai-matrx/records-ui · what a field of a standard table can be, with no React\n//\n// Pure, so `/helpers` carries `CUSTOM_FIELD_ADDABLE_TYPES` and a host settings page lists the\n// addable types before it loads any screen (records-ui front door, 2026-10-16). `FieldEditor.tsx`\n// and `CustomFieldsSection.tsx` re-export these.\n\nimport { DECLARABLE_FIELD_KINDS } from \"@ai-matrx/records/field-kinds\";\nimport { FIELD_TYPE_CHOICES, isSystemFieldKind, type FieldTypeChoice } from \"./fieldTypes\";\n\n/**\n * WHAT A FIELD OF A STANDARD TABLE CAN BE — every kind that HOLDS a value there (lane 7 W1, fix\n * round 1). The store's own kind registry (`custom.field_kinds()`, generated into\n * `DECLARABLE_FIELD_KINDS`) says what each kind is made of; a kind whose behavior is `formula` —\n * Borrowed value, Total, Count, Worked out, and the stamps (Record number, Created / Last changed\n * time), which are formula words — is worked out by `custom.rule_eval` over a custom record, and a\n * standard row is never worked out. Measured on the clone 2026-10-02 (a CRM company; every kind\n * declared, a realistic value written through `custom.entity_row_write`, read back through\n * `custom.entity_record_read`): every other kind came back holding its value; every formula kind\n * came back null. So a record page offers exactly the kinds that hold a value, read from the\n * store's registry — one source, no hand list. A kind the registry does not publish is not offered.\n */\nconst STORE_BEHAVIOUR = new Map<string, string>(DECLARABLE_FIELD_KINDS.map((row) => [row.kind as string, row.behavior as string]));\n\n/** True when a field of this kind holds a value on a standard table's row. */\nexport function holdsAValueOnAStandardTable(kind: string): boolean {\n if (isSystemFieldKind(kind)) return false;\n const behaviour = STORE_BEHAVIOUR.get(kind);\n return behaviour !== undefined && behaviour !== \"formula\";\n}\n\n/** What a record page's Add field offers: `fieldTypes.ts`'s choices, less what cannot hold a value there. */\nexport const STANDARD_TABLE_FIELD_CHOICES: FieldTypeChoice[] = FIELD_TYPE_CHOICES.filter((c) =>\n holdsAValueOnAStandardTable(c.id),\n);\n\n\n/**\n * WHAT A PERSON CAN ADD FROM A RECORD PAGE: EVERYTHING A TABLE'S COLUMN CAN BE.\n *\n * 🚨 G3 — ONE PALETTE (lane 7 STANDARD-TABLES, wave 1). This used to be a hand-kept list of\n * eleven types (`ADDABLE_TYPE_IDS`) \"that need nothing more than a name\", so a CRM contact could\n * not get a Choice, a Yes / no or a link to another record, and none of the column's governance —\n * while `custom.entity_field_declare` resolves its spec through the very `custom._field_document_for`\n * a custom table's column goes through. A standard table and a custom table are one primitive, so\n * the record page opens the table's own `FieldEditor` and offers `fieldTypes.ts`'s pickable set\n * less the kinds that cannot hold a value on a standard row (`STANDARD_TABLE_FIELD_CHOICES`, read\n * from the store's kind registry). `a-record-page-adds-a-field-with-the-tables-own-palette.test.tsx`\n * fails the moment this list and that set differ.\n */\nexport const ADDABLE_TYPES = STANDARD_TABLE_FIELD_CHOICES.map((choice) => ({\n value: choice.id as string,\n label: choice.label,\n}));\n","/**\n * A TYPED VALUE'S REFUSAL FLOATS WHERE IT CAN BE READ (walk 4, 2026-10-07).\n *\n * \"Enter a valid phone number\" was in the DOM but clipped inside a 114 px grid cell (the cell, the\n * sticky header and the scroller all clip what an absolutely placed note tries to draw past them),\n * and on the record page the same note covered the Email value under Phone. The note is now drawn\n * in a layer on <body>, anchored to the open editor, so nothing clips it and it moves nothing:\n * · in a grid cell — directly above the cell, left-aligned with it (below it when there is no\n * room above), the way every other note an open cell says floats;\n * · in a record's field — inside the field's own box, at its right end, so it covers no other field.\n * The anchor is the open editor (`data-matrx-cell-editor`), else the note's own parent.\n */\nimport { useLayoutEffect, useRef, useState, type CSSProperties } from \"react\";\nimport { createPortal } from \"react-dom\";\n\nconst GAP = 4;\n\nfunction placeFor(anchor: Element, note: HTMLElement | null): CSSProperties {\n const a = anchor.getBoundingClientRect();\n const inGrid = anchor.closest(\"td\") !== null;\n const height = note?.offsetHeight ?? 20;\n const width = note?.offsetWidth ?? 0;\n if (inGrid) {\n const above = a.top - GAP - height;\n const top = above >= 0 ? above : a.bottom + GAP;\n const left = Math.max(GAP, Math.min(a.left, window.innerWidth - width - GAP));\n return { position: \"fixed\", top, left };\n }\n // A record's field: inside its own box, right end, vertically centered.\n return { position: \"fixed\", top: a.top + (a.height - height) / 2, left: Math.max(a.left, a.right - width - 8) };\n}\n\nexport function FloatingRefusal({ text, why }: { text: string; why?: string | undefined }) {\n const spot = useRef<HTMLSpanElement | null>(null);\n const note = useRef<HTMLSpanElement | null>(null);\n const [style, setStyle] = useState<CSSProperties | null>(null);\n // Only an OPEN CELL'S editor (a grid cell, a record's field in place) floats its note; a form's\n // box keeps it in flow under the box, as it always did.\n const [floating, setFloating] = useState(false);\n useLayoutEffect(() => {\n const here = spot.current;\n if (!here) return;\n const anchor = here.closest(\"[data-matrx-cell-editor]\");\n setFloating(anchor !== null);\n if (!anchor) return;\n const place = () => setStyle(placeFor(anchor, note.current));\n place();\n // Measured once more after the note has its own size, then on every scroll or resize.\n const frame = requestAnimationFrame(place);\n window.addEventListener(\"scroll\", place, true);\n window.addEventListener(\"resize\", place);\n return () => {\n cancelAnimationFrame(frame);\n window.removeEventListener(\"scroll\", place, true);\n window.removeEventListener(\"resize\", place);\n };\n }, [text]);\n if (!floating) {\n return (\n <span ref={spot} data-records-typed-refusal=\"\" role=\"status\" title={why} className=\"text-[11px] leading-snug text-amber-700 dark:text-amber-400\">\n {text}\n </span>\n );\n }\n return (\n <>\n <span ref={spot} data-records-refusal-anchor=\"\" hidden />\n {typeof document === \"undefined\"\n ? null\n : createPortal(\n <span\n ref={note}\n data-records-typed-refusal=\"\"\n data-records-floating-refusal=\"\"\n role=\"status\"\n title={why}\n style={{ ...(style ?? { position: \"fixed\", top: -9999, left: -9999 }), zIndex: 60 }}\n className=\"pointer-events-none w-max max-w-[24rem] rounded-md border bg-popover px-1.5 py-0.5 text-[11px] leading-snug text-amber-700 shadow-md dark:text-amber-400\"\n >\n {text}\n </span>,\n document.body,\n )}\n </>\n );\n}\n","\"use client\";\n\n// src/formatControls.tsx — @ai-matrx/records-ui · merge tranche 6e (formats)\n//\n// THE FORMAT-AWARE EDITOR — the older /data grid's `FormatAwareInput` and `RatingInput`,\n// rewritten onto the platform registry. A column that shows as money takes \"$1,250.50\"; a percent\n// kept as a fraction is typed as the percent a person reads (45, or \"45%\") and kept as 0.45; a\n// rating is its stars; a time of day, a color, an email, a link, a phone number get the input\n// that fits them. Parsing is the registry's own (`parseFieldInput`), so what the cell shows and\n// what the editor reads are one vocabulary.\n//\n// `formatControl` answers `null` for a format with no opinion about its input — the caller keeps\n// the kind's own control (THE FALLBACK LAW applied to editing: a format may add a better input,\n// never take a working one away).\n\nimport { useEffect, useRef, useState, type ReactNode } from \"react\";\nimport { BasicInput, BasicTextarea } from \"@ai-matrx/design-system\";\nimport { getFieldFormat, parseFieldInput, type FieldFormatConfig } from \"@ai-matrx/design-system/field-formats\";\n\nimport { RatingStars } from \"./formattedValue\";\nimport { fieldLookFor } from \"./looks\";\n\ninterface FormatControlArgs {\n format: FieldFormatConfig;\n value: unknown;\n onChange: (value: unknown) => void;\n disabled?: boolean | undefined;\n id: string;\n label: string;\n /** A page nobody is signed into: the browser may offer the person's own email and phone. */\n ownDetails?: boolean | undefined;\n}\n\n/** Number formats typed as text, so a symbol, a comma or a percent sign is read, never refused by the browser. */\nconst TYPED_NUMBERS = new Set([\"currency\", \"percent\", \"progress\", \"decimal\", \"duration\", \"file_size\", \"integer\"]);\n\n/** A percent kept as a fraction is shown and typed ×100. */\nfunction scaled(format: FieldFormatConfig): boolean {\n return (format.id === \"percent\" || format.id === \"progress\") && format.options?.percentScale === \"fraction\";\n}\n\n/** What the box starts holding for a stored value. */\nexport function typedText(format: FieldFormatConfig, value: unknown): string {\n if (value === null || value === undefined) return \"\";\n if (typeof value === \"number\" && scaled(format)) return String(Math.round(value * 100 * 1e6) / 1e6);\n return String(value);\n}\n\n/** What a typed text is kept as, in this format. Null for an empty box. */\nexport function keptValue(format: FieldFormatConfig, raw: string): unknown {\n if (raw.trim() === \"\") return null;\n const parsed = parseFieldInput(raw, format);\n if (typeof parsed === \"number\" && scaled(format)) return Math.round((parsed / 100) * 1e9) / 1e9;\n return parsed;\n}\n\nfunction NumberInFormat({ format, value, onChange, disabled, id }: FormatControlArgs) {\n const [text, setText] = useState(() => typedText(format, value));\n // A value that moves under the box (a reload, a seed) is shown — unless it is what was just typed.\n const lastSent = useRef<unknown>(undefined);\n useEffect(() => {\n if (value === lastSent.current) return;\n setText(typedText(format, value));\n }, [value, format]);\n return (\n <BasicInput\n id={id}\n inputMode=\"decimal\"\n className=\"tabular-nums\"\n value={text}\n disabled={disabled}\n placeholder={format.id === \"currency\" ? \"$0.00\" : format.id === \"percent\" || format.id === \"progress\" ? \"45%\" : undefined}\n onChange={(e) => {\n setText(e.target.value);\n const next = keptValue(format, e.target.value);\n lastSent.current = next;\n onChange(next);\n }}\n />\n );\n}\n\n/** The input a format supplies, or null when the kind's own control is the right one. */\nexport function formatControl(args: FormatControlArgs): ReactNode | null {\n const def = getFieldFormat(args.format.id);\n if (!def) return null;\n const { format, value, onChange, disabled, id, label, ownDetails } = args;\n // A PLUG-IN LOOK's own editor comes first (`looks/`).\n const look = fieldLookFor(def.id);\n if (look?.Editor) {\n const Editor = look.Editor;\n return <Editor value={value} format={format} onChange={onChange} disabled={disabled} id={id} label={label} />;\n }\n const text = value === null || value === undefined ? \"\" : String(value);\n const commit = (raw: string) => onChange(raw === \"\" ? null : parseFieldInput(raw, format));\n\n if (def.id === \"rating\") {\n return disabled ? (\n <RatingStars value={value} max={format.options?.ratingMax ?? 5} label={label} />\n ) : (\n <span id={id} className=\"inline-flex\">\n <RatingStars value={value} max={format.options?.ratingMax ?? 5} label={label} onRate={(n) => onChange(n)} />\n </span>\n );\n }\n if (TYPED_NUMBERS.has(def.id)) return <NumberInFormat {...args} />;\n switch (def.editor) {\n // A TIME OF DAY is not this file's: `FieldControl` draws the typed box and its helper\n // (`TypedWordsControl`), never the browser's time control (grids review 3, 2026-09-30).\n case \"email\":\n case \"url\":\n case \"tel\":\n return (\n <BasicInput\n id={id}\n type={def.editor}\n // THE RIGHT KEYBOARD (TYPEFORM-2): @ for an email, the dial pad for a phone, .com for a link.\n inputMode={def.editor}\n {...(ownDetails ? { autoComplete: def.editor } : {})}\n value={text}\n disabled={disabled}\n onChange={(e) => commit(e.target.value)}\n />\n );\n case \"color\":\n return (\n <span className=\"flex items-center gap-2\">\n <BasicInput\n id={`${id}-swatch`}\n type=\"color\"\n aria-label={`${label} — pick a color`}\n className=\"h-8 w-12 p-1\"\n value={/^#[0-9a-fA-F]{6}$/.test(text) ? text : \"#000000\"}\n disabled={disabled}\n onChange={(e) => commit(e.target.value)}\n />\n <BasicInput id={id} value={text} placeholder=\"#3b82f6\" disabled={disabled} onChange={(e) => commit(e.target.value)} />\n </span>\n );\n case \"textarea\":\n return <BasicTextarea id={id} rows={4} value={text} disabled={disabled} onChange={(e) => commit(e.target.value)} />;\n default:\n return null;\n }\n}\n","\"use client\";\n\n// src/typedDateHelper.tsx — @ai-matrx/records-ui\n//\n// THE SMALL CALENDAR AND CLOCK BESIDE A TYPED DATE — A HELPER THAT NEVER OWNS THE KEYS.\n//\n// 🚨 WHY (grids review 3, 2026-09-30, a BLOCKER). Double-click, Enter or F2 on a date & time cell\n// opened the BROWSER'S OWN picker (`<input type=\"datetime-local\">`): Space dropped its calendar,\n// typing `10/03/2026 1200PM` landed in its segments one at a time and the time was lost, and Enter\n// saved the moment it was pressed — Sep 30, 1:36 AM. A cell opened by typing already worked.\n//\n// THE RULE (Google Sheets and Airtable): every way into a date, a time or a date-and-time editor is\n// ONE plain text box, read ONCE on commit by the one reader (`@ai-matrx/records` `readTypedDate` /\n// `readTypedTime`). Beside it sits this: a calendar (and, for a moment, a list of times) for the\n// person who would rather point. It is a mouse helper only — it takes no focus, it is not in the Tab\n// order, a press in it never blurs the box (so it never commits the cell), and a pick writes WORDS\n// into the box, the same words a person could have typed; the reader still decides.\n\nimport { useState } from \"react\";\nimport { Popover, PopoverContent, PopoverTrigger, cn } from \"@ai-matrx/design-system\";\nimport { readTypedDate, readTypedTime, typedDateText, typedTimeText } from \"@ai-matrx/records\";\nimport { personWallNow, usePersonTimeZone } from \"./personTime\";\n\n/** What the helper offers: a calendar, a list of times, or both. */\nexport type DateHelperKind = \"date\" | \"datetime\" | \"time\";\n\nconst WEEK = [\"Su\", \"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\"];\nconst MONTHS = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n\nfunction pad(n: number): string {\n return String(n).padStart(2, \"0\");\n}\n\n/** The day and the time the box's words read as right now, when they read at all. */\nfunction readBox(text: string, kind: DateHelperKind): { day: string | null; time: { h: number; m: number } | null } {\n if (kind === \"time\") {\n const t = readTypedTime(text);\n if (!t.ok) return { day: null, time: null };\n const [h, m] = t.value.split(\":\").map(Number);\n return { day: null, time: { h: h!, m: m! } };\n }\n const read = readTypedDate(text, { withTime: kind === \"datetime\" });\n if (!read.ok) return { day: null, time: null };\n if (kind === \"datetime\" && read.instant) {\n const at = new Date(read.instant);\n return { day: read.day, time: { h: at.getHours(), m: at.getMinutes() } };\n }\n return { day: read.day, time: null };\n}\n\n/** The words the box takes for a day and a time, in the reader's own order. */\nfunction wordsFor(kind: DateHelperKind, day: string | null, time: { h: number; m: number } | null): string {\n if (kind === \"time\") return time ? typedTimeText(time.h, time.m) : \"\";\n if (!day) return \"\";\n const dayText = typedDateText(day);\n return kind === \"datetime\" && time ? `${dayText} ${typedTimeText(time.h, time.m)}` : dayText;\n}\n\n/** Keeps the pointer from ever taking focus off the text box — the helper never owns the keys. */\nconst keepFocus = { onMouseDown: (e: { preventDefault: () => void }) => e.preventDefault(), tabIndex: -1 } as const;\n\nfunction CalendarGlyph() {\n return (\n <svg aria-hidden=\"true\" viewBox=\"0 0 24 24\" width=\"14\" height=\"14\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <rect x=\"3\" y=\"4\" width=\"18\" height=\"18\" rx=\"2\" />\n <path d=\"M16 2v4M8 2v4M3 10h18\" />\n </svg>\n );\n}\nfunction ClockGlyph() {\n return (\n <svg aria-hidden=\"true\" viewBox=\"0 0 24 24\" width=\"14\" height=\"14\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" strokeLinejoin=\"round\">\n <circle cx=\"12\" cy=\"12\" r=\"10\" />\n <path d=\"M12 6v6l4 2\" />\n </svg>\n );\n}\n\n/**\n * `onPicked`: a pick that completes the value (a day for a date, a time for a time or a moment) is\n * a finished edit, as in Notion — the host saves and closes. Typing in the box is untouched.\n */\nexport function TypedDateHelper({\n kind,\n text,\n onText,\n label,\n onPicked,\n startOpen = false,\n}: {\n kind: DateHelperKind;\n text: string;\n onText: (text: string) => void;\n label: string;\n onPicked?: (() => void) | undefined;\n /**\n * OPEN FROM THE FIRST FRAME (Arman 2026-10-08: a date took three clicks to reach its calendar).\n * A cell opened by a click, Enter or F2 shows its calendar at once beside the box (Notion,\n * Airtable); the box still holds the keyboard, so typing a date needs no further click. A cell\n * opened by typing keeps it closed — that person is already typing.\n */\n startOpen?: boolean | undefined;\n}) {\n const [open, setOpen] = useState(startOpen);\n const held = readBox(text, kind);\n usePersonTimeZone();\n const today = personWallNow();\n const start = held.day ? new Date(Number(held.day.slice(0, 4)), Number(held.day.slice(5, 7)) - 1, 1) : new Date(today.getFullYear(), today.getMonth(), 1);\n const [month, setMonth] = useState<{ y: number; m: number } | null>(null);\n const shown = month ?? { y: start.getFullYear(), m: start.getMonth() };\n const first = new Date(shown.y, shown.m, 1).getDay();\n const days = new Date(shown.y, shown.m + 1, 0).getDate();\n const cells: Array<number | null> = [...Array.from({ length: first }, () => null), ...Array.from({ length: days }, (_, i) => i + 1)];\n const todayKey = `${today.getFullYear()}-${pad(today.getMonth() + 1)}-${pad(today.getDate())}`;\n const times = Array.from({ length: 48 }, (_, i) => ({ h: Math.floor(i / 2), m: (i % 2) * 30 }));\n const pickDay = (d: number) => {\n const day = `${shown.y}-${pad(shown.m + 1)}-${pad(d)}`;\n onText(wordsFor(kind, day, held.time));\n if (kind === \"date\") {\n setOpen(false);\n onPicked?.();\n }\n };\n const pickTime = (t: { h: number; m: number }) => {\n const day = kind === \"datetime\" ? (held.day ?? todayKey) : null;\n onText(wordsFor(kind, day, t));\n setOpen(false);\n onPicked?.();\n };\n const turn = (by: number) => {\n const at = new Date(shown.y, shown.m + by, 1);\n setMonth({ y: at.getFullYear(), m: at.getMonth() });\n };\n return (\n <Popover open={open} onOpenChange={setOpen}>\n <PopoverTrigger asChild>\n <button\n type=\"button\"\n {...keepFocus}\n data-records-date-helper=\"\"\n aria-label={kind === \"time\" ? `Pick a time for ${label}` : `Pick a date for ${label}`}\n title={kind === \"time\" ? \"Pick a time\" : \"Pick a date\"}\n className=\"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground\"\n >\n {kind === \"time\" ? <ClockGlyph /> : <CalendarGlyph />}\n </button>\n </PopoverTrigger>\n <PopoverContent\n sizing=\"content\"\n align=\"start\"\n className=\"p-2\"\n data-matrx-cell-editor=\"\"\n data-records-date-helper-panel=\"\"\n // THE BOX KEEPS THE KEYBOARD: the helper opens without taking focus and never hands it back\n // somewhere else when it closes.\n onOpenAutoFocus={(e) => e.preventDefault()}\n onCloseAutoFocus={(e) => e.preventDefault()}\n >\n <div className=\"flex gap-2\">\n {kind === \"time\" ? null : (\n <div className=\"flex flex-col gap-1\" role=\"grid\" aria-label={`${MONTHS[shown.m]} ${shown.y}`}>\n <div className=\"flex items-center justify-between text-xs font-medium\">\n <button type=\"button\" {...keepFocus} aria-label=\"Previous month\" className=\"rounded px-1.5 hover:bg-muted\" onClick={() => turn(-1)}>\n ‹\n </button>\n <span>\n {MONTHS[shown.m]} {shown.y}\n </span>\n <button type=\"button\" {...keepFocus} aria-label=\"Next month\" className=\"rounded px-1.5 hover:bg-muted\" onClick={() => turn(1)}>\n ›\n </button>\n </div>\n <div className=\"grid grid-cols-7 gap-0.5 text-center text-[11px]\">\n {WEEK.map((w) => (\n <span key={w} className=\"text-muted-foreground\">\n {w}\n </span>\n ))}\n {cells.map((d, i) => {\n if (d === null) return <span key={`blank-${i}`} />;\n const key = `${shown.y}-${pad(shown.m + 1)}-${pad(d)}`;\n return (\n <button\n key={key}\n type=\"button\"\n {...keepFocus}\n data-records-date-helper-day={key}\n className={cn(\n \"h-6 w-6 rounded tabular-nums hover:bg-muted\",\n key === held.day ? \"bg-primary text-primary-foreground hover:bg-primary\" : \"\",\n key === todayKey && key !== held.day ? \"ring-1 ring-ring\" : \"\",\n )}\n onClick={() => pickDay(d)}\n >\n {d}\n </button>\n );\n })}\n </div>\n </div>\n )}\n {kind === \"date\" ? null : (\n <div className=\"flex max-h-48 flex-col overflow-y-auto pr-1 text-[11px]\" aria-label=\"Times\">\n {times.map((t) => (\n <button\n key={`${t.h}:${t.m}`}\n type=\"button\"\n {...keepFocus}\n data-records-date-helper-time={`${pad(t.h)}:${pad(t.m)}`}\n className={cn(\n \"whitespace-nowrap rounded px-2 py-0.5 text-left tabular-nums hover:bg-muted\",\n held.time && held.time.h === t.h && held.time.m === t.m ? \"bg-primary text-primary-foreground\" : \"\",\n )}\n onClick={() => pickTime(t)}\n >\n {typedTimeText(t.h, t.m)}\n </button>\n ))}\n </div>\n )}\n </div>\n </PopoverContent>\n </Popover>\n );\n}\n","// src/dataSource.ts — @ai-matrx/records-ui (pure; also served alone by `@ai-matrx/records-ui/helpers`)\n//\n// The two helpers every host calls before it draws anything: who is acting (`personActor`) and the\n// store's data seam over a supabase-js client (`recordsDataSource`). No React and no screen here, so\n// a service, a registry or a server module that needs only these never pulls the package's screens.\n// `RecordsMount` re-exports both, so the root entry keeps them.\n\nimport type { RecordsActor, RecordsDataSource, Uuid } from \"@ai-matrx/records\";\nimport { globalSlot } from \"@ai-matrx/kit/global-slot\";\n\nexport function personActor(userId: Uuid | null | undefined): RecordsActor {\n return userId ? { actor: \"user\", user_id: userId } : { actor: \"user\" };\n}\n\n/**\n * A supabase-js client AS this package's data seam.\n *\n * `RecordsDataSource` is deliberately a small structural subset of\n * `SupabaseClient` — the package holds no key and opens no connection, the host\n * hands it a client that already carries the person's session.\n *\n * IT IS NOT AN IDENTITY CAST, and it cost a live screen to learn why\n * (2026-09-19, /data's first load): the port's `rpc(fn, args, { schema })`\n * says the schema OUT LOUD, because every door of this store is `custom.<name>`\n * and every door of the trust layer is `iam.<name>`. supabase-js's own\n * `rpc(fn, args, options)` has no `schema` option at all — its third argument is\n * `{ head, get, count }` — so a client passed straight through silently asked\n * its default PostgREST profile and the store answered, correctly and uselessly,\n * \"Could not find the function public.table_kernel_id ... PGRST202\". The schema\n * is chosen the one way supabase-js offers: `client.schema(name).rpc(...)`.\n *\n * `schema(name).from(table)` already agrees structurally and is passed through.\n *\n * `fallbackSchema` is the profile a call that says NOTHING is sent to. No caller\n * in `@ai-matrx/records` omits the option — `callDoor` always says `custom` and\n * `trustDoor` always says `iam` — so it never fires today; it exists so that a\n * call which one day forgets lands on the store rather than silently on\n * `public`. It is a FALLBACK and not the answer: a version of this adapter that\n * sent EVERY door to one fixed schema would route the `iam` trust doors (the\n * external principal, the publish binding) into `custom` and get a PGRST202\n * naming the wrong schema.\n *\n * The cast itself stays HERE, once, where it is explained: a generated\n * `Database` type makes `schema().from().select()` enormous, and a host app that\n * passes its client straight into `config` gets `TS2589: Type instantiation is\n * excessively deep and possibly infinite` in its own build (matrx-frontend,\n * 2026-09-18, on all three campaign routes at once).\n */\n/*\n * ONE DATA SOURCE PER SUPABASE CLIENT (owner, 2026-10-02). The record store's data layer keys its\n * cache by the data source object, so a host that builds this adapter again on every mount (a\n * board tile woken or brought back by Undo) must get the SAME object back for the same client —\n * otherwise every remount is a stranger to the answers the last mount read.\n */\n// One cache per realm, never per bundle copy: this module ships in BOTH the root entry and\n// `@ai-matrx/records-ui/helpers` (`splitting: false`), and a module `let` would split it in two.\nconst dataSources = globalSlot(\"ai-matrx.records-ui.data-sources\", () => new WeakMap<object, Map<string, RecordsDataSource>>());\n\nexport function recordsDataSource(client: object, fallbackSchema = \"custom\"): RecordsDataSource {\n let bySchema = dataSources.get(client);\n if (!bySchema) {\n bySchema = new Map();\n dataSources.set(client, bySchema);\n }\n const held = bySchema.get(fallbackSchema);\n if (held) return held;\n const made = makeRecordsDataSource(client, fallbackSchema);\n bySchema.set(fallbackSchema, made);\n return made;\n}\n\nfunction makeRecordsDataSource(client: object, fallbackSchema: string): RecordsDataSource {\n const supabase = client as unknown as {\n rpc: (fn: string, args: Record<string, unknown>) => PromiseLike<unknown>;\n schema: (name: string) => {\n rpc: (fn: string, args: Record<string, unknown>) => PromiseLike<unknown>;\n from: (table: string) => unknown;\n };\n auth?: { getSession?: () => Promise<{ data?: { session?: unknown } | null }> };\n };\n return {\n // PAGE-BUNDLE: the real adapter opens a table page with one `custom.table_page_bundle` call.\n opensInOneCall: true,\n async rpc(fn, args, options) {\n const schema = options?.schema ?? fallbackSchema;\n // 🚨 NO STORE DOOR LEAVES WITHOUT A PERSON (lane MONITOR-TRIAGE, 2026-10-01). `anon` holds\n // no USAGE on schema `custom`, so a door called with no session can only come back\n // \"42501 permission denied for schema custom\" (HTTP 401) — seven of them per signed-out\n // /data load (inbox, counts, home, portals…), every one a red row in ops.system_error.\n // A `custom` door with no session is answered HERE, with the store's own signed-out\n // sentence and no network call. Other schemas (`iam`, `platform`) serve guests by design\n // and are never short-circuited. A client without `auth` (a server or test seam) is\n // passed straight through.\n if (schema === \"custom\" && supabase.auth?.getSession && !(await hasSession(supabase.auth.getSession))) {\n return { data: null, error: SIGNED_OUT } as Awaited<ReturnType<RecordsDataSource[\"rpc\"]>>;\n }\n const on = supabase.schema(schema);\n return (await on.rpc(fn, args)) as Awaited<ReturnType<RecordsDataSource[\"rpc\"]>>;\n },\n schema(name) {\n return supabase.schema(name) as ReturnType<RecordsDataSource[\"schema\"]>;\n },\n };\n}\n\n/** The read door's own sentence for a call with nobody signed in (`custom.read_records_page`, DOOR-1). */\nconst SIGNED_OUT = {\n code: \"42501\",\n message: \"Nobody is signed in, so there is nothing to read.\",\n hint: \"Sign in, then try again.\",\n details: null,\n} as const;\n\nasync function hasSession(getSession: () => Promise<{ data?: { session?: unknown } | null }>): Promise<boolean> {\n try {\n const answer = await getSession();\n return Boolean(answer?.data?.session);\n } catch {\n // Auth could not say: let the request go and the database's answer stand.\n return true;\n }\n}\n","\"use client\";\n\n// src/RecordsMount.tsx — @ai-matrx/records-ui\n//\n// THE ONE LINE A HOST ROUTE WRITES. `<RecordsProvider>` from @ai-matrx/records\n// and `<RecordsUiProvider>` from this package are two providers that must be\n// nested in one order, every time — so a route that got the order wrong would\n// fail with \"useRecordsClient was called outside <RecordsProvider>\" at the\n// bottom of a screen nobody was looking at. This mounts both, in the one order\n// that is correct, so a route file stays a mount and nothing more.\n//\n// THE RIGHTS QUESTION — AND THE ANSWER THAT USED TO BE HERE.\n//\n// `storeDecidesRights` returned `{admin: true, comment: true, write: true}` for\n// every non-kernel table, for everybody, on the reasoning that the doors are\n// the authority and a refusal would be shown verbatim when it came. The\n// sixth-pass verdict measured the cost of that reasoning: a colleague at viewer\n// double-clicked a cell, got a live editor, typed a value, pressed Enter, and\n// was told only then that she may not write. \"The permission is right; the\n// screen told her she could.\"\n//\n// It is not a guess any more. The read door has always answered the reader's\n// level on the table and the client now carries it (`Table.your_level`), so\n// this function ASKS instead of assuming, `letTheStoreDecideRights` still means\n// what it says, and a host that binds nothing gets the same honest answer\n// rather than every control absent. Kernel Tables (REC-27) keep their own\n// exclusion: the nine Tables the platform ships are not administered from a\n// person's screen at any level.\n\nimport { useRef, type ReactNode } from \"react\";\nimport type { RecordsConfig, Table } from \"@ai-matrx/records\";\nexport { personActor, recordsDataSource } from \"./dataSource\";\nimport { RecordsProvider } from \"@ai-matrx/records/react\";\nimport { RecordLabelProvider } from \"./labels\";\n\nimport { PersonNamesBridge } from \"./PersonNamesBridge\";\nimport { NO_RIGHTS, RecordsUiProvider, type RecordsUiHost, type TableRights } from \"./host\";\n\nexport const STORE_DECIDES_REASON =\n \"This host offers exactly what this person may do, so a control they cannot use is never drawn in the first place.\";\n\nexport { KERNEL_REASON } from \"./rights\";\n\n/**\n * DEPRECATED, and kept only so a host that imported it still compiles.\n *\n * It used to answer yes to everything for every non-kernel table. It cannot\n * answer honestly at all, because the honest answer needs a door call and this\n * signature is synchronous — which is exactly why the guess was here. Binding\n * it now would be binding a port that OVERRIDES the store's real answer, so it\n * returns the not-yet-answered set and every caller should simply stop passing\n * a `rights` port: unbound is the honest path (`useTableRights`).\n */\nexport function storeDecidesRights(_table: Table): TableRights {\n return NO_RIGHTS;\n}\n\nexport interface RecordsMountProps {\n /** The store config: the host's session-carrying client, the actor, the organization. */\n config: RecordsConfig;\n /** What this host binds on top — links, toasts, uploads, rights. */\n host?: RecordsUiHost | undefined;\n /**\n * Use `storeDecidesRights` when the host binds no `rights` of its own. Left\n * off, an unbound host gets `NO_RIGHTS` and every administering control is\n * absent with its reason.\n */\n letTheStoreDecideRights?: boolean | undefined;\n children: ReactNode;\n}\n\nexport function RecordsMount({\n config,\n host,\n letTheStoreDecideRights,\n children,\n}: RecordsMountProps) {\n // `letTheStoreDecideRights` means what it says and now needs no port at all:\n // with nothing bound, `useTableRights` asks `custom.my_levels` and draws what\n // the answer allows. A port bound here would OVERRIDE that answer.\n const bound = useShallowStableHost(host);\n void letTheStoreDecideRights;\n return (\n <RecordsProvider config={config}>\n <RecordsUiProvider value={bound}>\n {/* WHAT AN ID IS CALLED. A choice and a relation are stored as the id of\n another record, so every read-only surface needs the same answer to\n \"what is that record called\" — resolved once here rather than once\n per cell, and never drawn as the id itself. */}\n <RecordLabelProvider>\n <PersonNamesBridge />\n {children}\n </RecordLabelProvider>\n </RecordsUiProvider>\n </RecordsProvider>\n );\n}\n\n/**\n * The actor a signed-in person is. `user` is the store's own word (the closed\n * ACTOR_VOCABULARY is `user` · `agent` · `system`), and AGT-N-4 means an agent\n * acting for this person carries exactly this authority and no other.\n */\n/**\n * THE HOST, AS ONE IDENTITY FOR AS LONG AS ITS PARTS ARE THE SAME (lane RENDER-AUDIT, 2026-09-26).\n *\n * This used to be `{ ...(host ?? {}) }` — a NEW object on every render of the mount — and it is the\n * value of the host context every screen of this package reads (`useRecordsUi`: the table page,\n * the grid, the view bar, every rail). So any render of whatever sits above the mount (a search\n * parameter moving, the organization list arriving, a toast) re-rendered the whole table page and\n * every cell in it, with nothing on the table having changed. Measured on /data with the React\n * profiler hook: 11 host-context renders of `TablePage` during one page load.\n *\n * The host a caller builds is a bag of ports and values; it is the SAME host when every part is the\n * same part. So the previous object is kept until a part changes identity, and a host that builds\n * the bag inline on every render (the common case) costs nothing.\n */\nfunction useShallowStableHost(host: RecordsUiHost | undefined): RecordsUiHost {\n const held = useRef<RecordsUiHost | null>(null);\n const next = host ?? {};\n const previous = held.current;\n if (previous !== null && sameParts(previous, next)) return previous;\n const bound: RecordsUiHost = { ...next };\n held.current = bound;\n return bound;\n}\n\nfunction sameParts(a: RecordsUiHost, b: RecordsUiHost): boolean {\n const aKeys = Object.keys(a) as (keyof RecordsUiHost)[];\n const bKeys = Object.keys(b) as (keyof RecordsUiHost)[];\n if (aKeys.length !== bKeys.length) return false;\n for (const key of aKeys) if (a[key] !== b[key]) return false;\n return true;\n}\n","\"use client\";\n\n// src/PersonNamesBridge.tsx — @ai-matrx/records-ui · lane PERSON-SWEEP\n// Binds the one person resolver (`resolveKeptPerson`) to this mount's store client and the host roster.\n\nimport { useEffect } from \"react\";\nimport { useOptionalRecordsClient } from \"@ai-matrx/records/react\";\nimport { PERSON_NOT_IN_ORGANIZATION, resolveKeptPerson, useMemberRoster } from \"./memberNames\";\nimport { setPersonOpener, setPersonResolver } from \"./personNames\";\n\nexport function PersonNamesBridge() {\n const client = useOptionalRecordsClient();\n const roster = useMemberRoster();\n useEffect(() => {\n if (!roster) return;\n setPersonResolver(async (id) => {\n const who = await resolveKeptPerson(client, id, roster);\n return who.name === PERSON_NOT_IN_ORGANIZATION ? null : who.name;\n });\n setPersonOpener(async (id) => {\n const who = await resolveKeptPerson(client, id, roster);\n return who.recordId ? { recordId: who.recordId, userId: who.userId ?? null, email: who.email ?? null, name: who.name } : null;\n });\n return () => {\n setPersonResolver(null);\n setPersonOpener(null);\n };\n }, [client, roster]);\n return null;\n}\n","\"use client\";\n\n// src/TablePickers.tsx — @ai-matrx/records-ui · lane 3 INTEGRATION W1.1 (2026-10-02)\n//\n// PICK BY NAME, NEVER BY ID. The one table picker, column/value row editor and record picker for\n// any host screen that STORES a table id, a record id or `{column key: value}` but must SHOW names:\n// the workflow studio's data steps first (`data.table.*`, `records.*` declare `table_picker`,\n// `column_values`, `record_picker`), every other builder after. Before this a workflow step asked\n// a person to paste a table uuid and hand-write `{\"status\": \"low\"}` as JSON.\n//\n// THE LIST is `custom.data_home_tables()` with no organization — every Table the person can open in\n// every organization she can reach (law: common-docs/policies/access-ladder.md),\n// one flat list, each row naming its organization. The chosen Table's columns and records are read\n// in the organization the Table lives in (`TableScope`), never the active one.\n//\n// WHAT IS STORED is unchanged: the table id, the record id, and `{field.key: stored value}` — the\n// exact keys `custom` record documents carry, so a saved workflow from before this file reads back\n// and runs unchanged. A key that is no longer a column is shown as itself, marked, never dropped.\n\nimport { useEffect, useMemo, useState, type ReactNode } from \"react\";\nimport type { Field, RecordsDataSource, Uuid } from \"@ai-matrx/records\";\nimport { RecordsProvider, useFields, useRecords, useTable } from \"@ai-matrx/records/react\";\nimport { Button, CreatablePicker, type CreatableOption } from \"@ai-matrx/design-system\";\nimport { FieldControl } from \"./editors\";\nimport { fieldName, rowNameIn } from \"./names\";\nimport { personActor } from \"./RecordsMount\";\nimport { tablePickerEntries } from \"./tablePicking\";\nimport { RefusalLine } from \"./Refusal\";\nimport { refusal as refusalOf } from \"./refusals\";\nimport { refusalSentence } from \"./plainWords\";\n\n/** One row of `custom.data_home_tables()`. */\nexport interface TableAnywhere {\n table_id: Uuid;\n table_name: string;\n organization_id: Uuid;\n organization_name: string;\n kind: string | null;\n platform_owned: boolean;\n /** When the table last changed (the door's own column) — what tells two same-named tables apart. */\n updated_at?: string | null;\n /** Who made it, when the door says. */\n created_by_name?: string | null;\n}\n\nexport interface TablesAnywhere {\n loading: boolean;\n /** The store's own sentence when the list was refused. */\n error: string | null;\n rows: TableAnywhere[];\n}\n\n// ONE READ PER DATA SOURCE (W1.1, 2026-10-02). Every TableScope / table name on a screen used to\n// read `data_home_tables` for itself — a Find Records result of 20 rows fired 20 identical reads,\n// and when they failed every row sat on \"…\". Reads in flight (and a just-read list, briefly) are\n// shared per data source; a failed read is never kept, so the next mount asks again.\nconst SHARED_FOR_MS = 5_000;\nconst sharedReads = new WeakMap<RecordsDataSource, { at: number; read: Promise<TablesAnywhere> }>();\n\nfunction readTablesAnywhere(dataSource: RecordsDataSource): Promise<TablesAnywhere> {\n const held = sharedReads.get(dataSource);\n if (held && Date.now() - held.at < SHARED_FOR_MS) return held.read;\n const read = Promise.resolve(dataSource.rpc(\"data_home_tables\", {}, { schema: \"custom\" })).then(\n ({ data, error }): TablesAnywhere => {\n if (error) {\n return {\n loading: false,\n error: refusalSentence({ message: String(error[\"message\"] ?? \"\") }) || \"Tables could not be read.\",\n rows: [],\n };\n }\n const rows = (Array.isArray(data) ? (data as TableAnywhere[]) : []).slice();\n rows.sort((a, b) => a.table_name.localeCompare(b.table_name));\n return { loading: false, error: null, rows };\n },\n (thrown: unknown): TablesAnywhere => ({\n loading: false,\n error: String((thrown as Error)?.message ?? thrown) || \"Tables could not be read.\",\n rows: [],\n }),\n );\n sharedReads.set(dataSource, { at: Date.now(), read });\n void read.then((result) => {\n if (result.error && sharedReads.get(dataSource)?.read === read) sharedReads.delete(dataSource);\n });\n return read;\n}\n\n/** Every Table the person can open, in every organization, sorted by name. */\nexport function useTablesAnywhere(dataSource: RecordsDataSource): TablesAnywhere {\n const [state, setState] = useState<TablesAnywhere>({ loading: true, error: null, rows: [] });\n useEffect(() => {\n let live = true;\n void readTablesAnywhere(dataSource).then((result) => {\n if (live) setState(result);\n });\n return () => {\n live = false;\n };\n }, [dataSource]);\n return state;\n}\n\nexport interface TablePickerProps {\n dataSource: RecordsDataSource;\n value: string | null;\n onChange: (tableId: string) => void;\n disabled?: boolean;\n /** Hand in an already-read list to skip a second read. */\n tables?: TablesAnywhere;\n}\n\n/** Pick a Table by its name; the id is what `onChange` hands back. */\nexport function TablePicker({ dataSource, value, onChange, disabled, tables }: TablePickerProps) {\n const own = useTablesAnywhere(dataSource);\n const list = tables ?? own;\n // Tables the app keeps for itself (choice lists, ledgers) stay out of the list unless chosen —\n // the one rule every table picker uses (`tablePicking.ts`).\n const options = tablePickerEntries(\n list.rows.map((t) => ({ ...t, id: t.table_id, name: t.table_name })),\n { keep: value },\n ).entries.map(({ table: t }) => t);\n // Two tables of one name in one organization are told apart by a second line: who made it and\n // when it last changed (the organization hint cannot tell them apart).\n const sameName = new Map<string, number>();\n for (const t of options) {\n const key = `${t.organization_id}|${t.table_name.trim().toLowerCase()}`;\n sameName.set(key, (sameName.get(key) ?? 0) + 1);\n }\n const pickerOptions: CreatableOption[] = options.map((t) => {\n const twin = (sameName.get(`${t.organization_id}|${t.table_name.trim().toLowerCase()}`) ?? 0) > 1;\n const row = t as typeof t & TableAnywhere;\n const secondOf = (r: typeof row) =>\n [r.created_by_name ? `by ${r.created_by_name}` : null, r.updated_at ? `changed ${new Date(r.updated_at).toLocaleDateString()}` : null]\n .filter(Boolean)\n .join(\" · \");\n const base = secondOf(row);\n // Twins whose second line is the same too (made by one person on one day) are told apart by a short code.\n const alike = options.filter((o) => o.organization_id === t.organization_id && o.table_name.trim().toLowerCase() === t.table_name.trim().toLowerCase() && secondOf(o as typeof row) === base).length;\n const second = alike > 1 ? [base, `#${t.table_id.slice(0, 4)}`].filter(Boolean).join(\" · \") : base;\n return {\n value: t.table_id,\n // The organization hint already tells two same-named tables apart across organizations.\n label: t.table_name,\n hint: t.organization_name,\n keywords: t.organization_name,\n ...(twin && second\n ? {\n render: (\n <span className=\"flex min-w-0 flex-col\">\n <span className=\"truncate\">{t.table_name}</span>\n <span className=\"truncate text-[11px] text-muted-foreground\">{second}</span>\n </span>\n ),\n }\n : {}),\n };\n });\n const missing = Boolean(value) && !list.loading && !list.error && !list.rows.some((t) => t.table_id === value);\n return (\n <div className=\"flex flex-col gap-1\">\n <CreatablePicker\n value={value || null}\n options={pickerOptions}\n onSelect={onChange}\n placeholder={missing ? \"Table not available\" : \"Choose a table\"}\n searchPlaceholder=\"Search tables\"\n noun=\"table\"\n loading={list.loading}\n {...(disabled ? { disabled: true } : {})}\n ariaLabel=\"Table\"\n />\n {list.error && <RefusalLine error={refusalOf(\"door\", list.error, \"Try again in a moment.\")} />}\n {missing && <p className=\"text-[11px] text-destructive\">This table is archived or not shared with you.</p>}\n </div>\n );\n}\n\nexport interface TableScopeProps {\n dataSource: RecordsDataSource;\n /** The signed-in person — the actor every read runs as. */\n userId: Uuid | null;\n tableId: string | null;\n children: ReactNode;\n /** Shown while the Table's organization is unknown, or when no Table is chosen. */\n fallback?: ReactNode;\n /** Shown when the list of Tables could not be read, or the Table is not one this person can\n * open — a scope that never resolves must say so, never wait forever. Defaults to `fallback`. */\n unavailable?: ReactNode;\n tables?: TablesAnywhere;\n}\n\n/** The record store, bound to the organization the chosen Table lives in. */\nexport function TableScope({ dataSource, userId, tableId, children, fallback = null, unavailable, tables }: TableScopeProps) {\n const own = useTablesAnywhere(dataSource);\n const list = tables ?? own;\n const organizationId = list.rows.find((t) => t.table_id === tableId)?.organization_id ?? null;\n if (tableId && !organizationId && !list.loading) return <>{unavailable ?? fallback}</>;\n if (!tableId || !organizationId) return <>{fallback}</>;\n return (\n <RecordsProvider config={{ dataSource, actor: personActor(userId), organizationId }}>\n {children}\n </RecordsProvider>\n );\n}\n\nexport interface ColumnValuesEditorProps {\n tableId: string;\n /** `{field key: stored value}` — what the step matches on or writes. */\n value: Record<string, unknown>;\n onChange: (next: Record<string, unknown>) => void;\n disabled?: boolean;\n /** The add button's label: \"Add a condition\" for a lookup, \"Add a value\" for a write. */\n addLabel: string;\n}\n\n/** Column / value rows for one Table. Must sit inside a `TableScope`. */\nexport function ColumnValuesEditor({ tableId, value, onChange, disabled, addLabel }: ColumnValuesEditorProps) {\n const fields = useFields(tableId);\n const all = useMemo(() => fields.data ?? [], [fields.data]);\n const byKey = useMemo(() => new Map(all.map((f) => [f.key, f])), [all]);\n const keys = Object.keys(value);\n // A row whose column is not chosen yet lives here until it is.\n const [adding, setAdding] = useState(false);\n\n const optionsFor = (current: string | null): CreatableOption[] =>\n all\n .filter((f) => f.key === current || !(f.key in value))\n .map((f) => ({ value: f.key, label: fieldName(f) }));\n\n const rename = (from: string, to: string) => {\n if (from === to) return;\n const next: Record<string, unknown> = {};\n for (const k of keys) next[k === from ? to : k] = k === from ? null : value[k];\n onChange(next);\n };\n const remove = (key: string) => {\n const { [key]: _gone, ...rest } = value;\n void _gone;\n onChange(rest);\n };\n\n return (\n <div className=\"flex flex-col gap-2\">\n {fields.error && <RefusalLine error={fields.error} />}\n {keys.map((key) => {\n const field = byKey.get(key);\n return (\n <ColumnValueRow\n key={key}\n columnKey={key}\n field={field}\n loading={fields.loading}\n options={optionsFor(key)}\n value={value[key]}\n disabled={disabled}\n onColumn={(to) => rename(key, to)}\n onValue={(v) => onChange({ ...value, [key]: v })}\n onRemove={() => remove(key)}\n />\n );\n })}\n {adding && (\n <ColumnValueRow\n columnKey={null}\n field={undefined}\n loading={fields.loading}\n options={optionsFor(null)}\n value={null}\n disabled={disabled}\n onColumn={(to) => {\n setAdding(false);\n onChange({ ...value, [to]: null });\n }}\n onValue={() => undefined}\n onRemove={() => setAdding(false)}\n />\n )}\n {!disabled && !adding && keys.length < all.length && (\n <Button type=\"button\" variant=\"outline\" size=\"sm\" className=\"self-start\" onClick={() => setAdding(true)}>\n {addLabel}\n </Button>\n )}\n </div>\n );\n}\n\nfunction ColumnValueRow({\n columnKey,\n field,\n loading,\n options,\n value,\n disabled,\n onColumn,\n onValue,\n onRemove,\n}: {\n columnKey: string | null;\n field: Field | undefined;\n loading: boolean;\n options: CreatableOption[];\n value: unknown;\n disabled?: boolean | undefined;\n onColumn: (key: string) => void;\n onValue: (value: unknown) => void;\n onRemove: () => void;\n}) {\n // A saved key that is no longer a column keeps its own words and says so.\n const orphan = columnKey !== null && !loading && field === undefined;\n const shown = orphan ? [{ value: columnKey, label: columnKey, hint: \"Not a column\" }, ...options] : options;\n return (\n <div className=\"flex flex-col gap-1 rounded-md border border-border/60 p-2\">\n <div className=\"flex items-center gap-2\">\n <div className=\"min-w-0 flex-1\">\n <CreatablePicker\n value={columnKey}\n options={shown}\n onSelect={onColumn}\n placeholder=\"Choose a column\"\n searchPlaceholder=\"Search columns\"\n noun=\"column\"\n loading={loading}\n {...(disabled ? { disabled: true } : {})}\n ariaLabel=\"Column\"\n />\n </div>\n {!disabled && (\n <Button type=\"button\" variant=\"ghost\" size=\"sm\" aria-label=\"Remove\" onClick={onRemove}>\n ✕\n </Button>\n )}\n </div>\n {field ? (\n <FieldControl field={field} value={value} onChange={onValue} disabled={disabled} />\n ) : orphan ? (\n <p className=\"text-[11px] text-muted-foreground\">{value === null || value === undefined ? \"—\" : String(value)}</p>\n ) : null}\n </div>\n );\n}\n\nexport interface RecordPickerProps {\n tableId: string;\n value: string | null;\n onChange: (recordId: string) => void;\n disabled?: boolean;\n}\n\n/** Pick one record of a Table by its name. Must sit inside a `TableScope`. */\nexport function RecordPicker({ tableId, value, onChange, disabled }: RecordPickerProps) {\n const table = useTable(tableId);\n const records = useRecords(tableId, { pageSize: 200 });\n const rows = records.data?.rows ?? [];\n const options: CreatableOption[] = rows.map((row) => ({\n value: row.id,\n label: rowNameIn(table.data ?? null, row),\n }));\n const missing = Boolean(value) && !records.loading && !records.error && !rows.some((r) => r.id === value);\n return (\n <div className=\"flex flex-col gap-1\">\n <CreatablePicker\n value={value || null}\n options={options}\n onSelect={onChange}\n placeholder={missing ? \"Record not in this table\" : \"Choose a record\"}\n searchPlaceholder=\"Search records\"\n noun=\"record\"\n loading={records.loading}\n {...(disabled ? { disabled: true } : {})}\n ariaLabel=\"Record\"\n />\n {records.error && <RefusalLine error={records.error} />}\n </div>\n );\n}\n","\"use client\";\n\n// src/DataBindingPicker.tsx — @ai-matrx/records-ui · lane 3 INTEGRATION W1.1 (2026-10-02)\n//\n// \"FROM MY DATA\" — ONE PICKER FOR EVERY BINDING. A value that is filled from a person's own table\n// when something runs: an agent variable (matrx-frontend's CustomDataBindingPicker, the first\n// author of this shape and these words) and a workflow input (the studio's Collect Inputs field)\n// bind through the SAME declaration, resolved server-side by the SAME merge-field resolver\n// (aidream `conversation_context.merge_field_bindings`). This file is that picker's portable\n// half: table (every Table the person can open, in every organization), shape (whole table /\n// one record / one field of a record), the record, the field, the row template with clickable\n// placeholders, the row limit and what happens when nothing is found — all by NAME.\n//\n// THE SHAPE IS THE MERGE-FIELD DECLARATION, verbatim (`DataBinding` mirrors @ai-matrx/chat's\n// `CustomDataBinding`): `{kind: \"merge_field\", source: \"record\", semantic_type, table_id,\n// record_id?, field_key?, limit?, transform?: {name: \"list\", template, join?, max?}, missing,\n// override_policy: \"shown_locked\"}`.\n\nimport { useEffect, useMemo } from \"react\";\nimport type { Field, RecordsDataSource, Table, Uuid } from \"@ai-matrx/records\";\nimport { isEntityReferenceConfig } from \"@ai-matrx/records\";\nimport { useFields, useTable } from \"@ai-matrx/records/react\";\nimport { BasicInput, Button, CreatablePicker, cn, type CreatableOption } from \"@ai-matrx/design-system\";\nimport { fieldName } from \"./names\";\nimport { RecordPicker, TablePicker, TableScope, useTablesAnywhere } from \"./TablePickers\";\n\nexport interface DataBinding {\n kind: \"merge_field\";\n source: \"record\";\n semantic_type: \"collection\" | \"reference\" | \"value\";\n table_id: string;\n record_id?: string;\n field_key?: string;\n match?: Record<string, string | number | boolean | null>;\n limit?: number;\n transform?: { name: \"list\"; template: string; join?: string; max?: number };\n missing: \"absent\" | \"block\";\n override_policy: \"shown_locked\";\n}\n\nexport type DataBindingShape = DataBinding[\"semantic_type\"];\n\nexport const DATA_BINDING_SHAPES: { value: DataBindingShape; label: string }[] = [\n { value: \"collection\", label: \"The whole table\" },\n { value: \"reference\", label: \"One record\" },\n { value: \"value\", label: \"One field of a record\" },\n];\n\nexport const DATA_BINDING_MISSING: { value: DataBinding[\"missing\"]; label: string }[] = [\n { value: \"absent\", label: \"Say it's missing\" },\n { value: \"block\", label: \"Stop the run\" },\n];\n\n/** A fresh, empty whole-table binding. */\nexport function emptyDataBinding(): DataBinding {\n return {\n kind: \"merge_field\",\n source: \"record\",\n semantic_type: \"collection\",\n table_id: \"\",\n missing: \"absent\",\n override_policy: \"shown_locked\",\n };\n}\n\n/** True when a value is a merge-field binding (the one shape this picker reads and writes). */\nexport function isDataBinding(value: unknown): value is DataBinding {\n return Boolean(value) && typeof value === \"object\" && (value as { kind?: unknown }).kind === \"merge_field\";\n}\n\n/** Ready to run only when the shape has everything it needs. */\nexport function isCompleteDataBinding(binding: DataBinding): boolean {\n if (!binding.table_id) return false;\n if (binding.semantic_type === \"collection\") return true;\n if (!binding.record_id) return false;\n return binding.semantic_type === \"value\" ? Boolean(binding.field_key) : true;\n}\n\n/** The placeholders one column offers; an entity reference offers its words and its id apart. */\nexport function bindingPlaceholdersFor(field: Field): { token: string; label: string }[] {\n const label = fieldName(field);\n if (isEntityReferenceConfig(field.config)) {\n return [\n { token: `{${field.key}.name}`, label: `${label} · name` },\n { token: `{${field.key}.id}`, label: `${label} · id` },\n ];\n }\n return [{ token: `{${field.key}}`, label }];\n}\n\nconst NAME_LIKE = /(^|_)(name|title|label)$/;\nconst DESCRIPTIVE = /(desc|description|summary|notes?|details?|about|why|purpose|role|category|type|group|status)/;\n\n/** The starting row template: the table's name column, then one or two describing columns. */\nexport function defaultBindingTemplate(table: Pick<Table, \"title_field\"> | null, fields: readonly Field[]): string {\n const first = fields[0];\n if (!first) return \"- {name}\";\n const declared = table?.title_field;\n const title =\n (declared ? fields.find((f) => f.key === declared || f.id === declared) : undefined) ??\n fields.find((f) => NAME_LIKE.test(f.key)) ??\n first;\n const token = (f: Field) => bindingPlaceholdersFor(f)[0]?.token ?? `{${f.key}}`;\n const rest = fields.filter((f) => f.id !== title.id);\n const [a, b] = [...rest.filter((f) => DESCRIPTIVE.test(f.key)), ...rest.filter((f) => !DESCRIPTIVE.test(f.key))];\n if (!a) return `- ${token(title)}`;\n return b ? `- ${token(title)}: ${token(a)} (${token(b)})` : `- ${token(title)}: ${token(a)}`;\n}\n\nexport interface DataBindingPickerProps {\n dataSource: RecordsDataSource;\n /** The signed-in person — every read runs as them. */\n userId: Uuid | null;\n binding: DataBinding;\n onChange: (binding: DataBinding) => void;\n disabled?: boolean;\n /** The host's starting row cap for a whole-table read (a knob the host reads), if any. */\n defaultRowLimit?: number | null;\n}\n\n/** \"From my data\": table → shape → record / field → template → when it's missing. */\nexport function DataBindingPicker({ dataSource, userId, binding, onChange, disabled, defaultRowLimit = null }: DataBindingPickerProps) {\n const tables = useTablesAnywhere(dataSource);\n const tableId = binding.table_id || null;\n const selectTable = (id: string) => {\n if (id === binding.table_id) return;\n onChange({\n kind: \"merge_field\",\n source: \"record\",\n semantic_type: binding.semantic_type,\n table_id: id,\n missing: binding.missing,\n override_policy: \"shown_locked\",\n ...(binding.semantic_type === \"collection\" && defaultRowLimit ? { limit: defaultRowLimit } : {}),\n });\n };\n return (\n <div className=\"flex flex-col gap-2\">\n <TablePicker dataSource={dataSource} value={tableId} onChange={selectTable} disabled={Boolean(disabled)} tables={tables} />\n <TableScope dataSource={dataSource} userId={userId} tableId={tableId} tables={tables}>\n {tableId && (\n <BindingDetails\n tableId={tableId}\n binding={binding}\n onChange={onChange}\n disabled={disabled}\n defaultRowLimit={defaultRowLimit}\n />\n )}\n </TableScope>\n </div>\n );\n}\n\nfunction BindingDetails({\n tableId,\n binding,\n onChange,\n disabled,\n defaultRowLimit,\n}: {\n tableId: string;\n binding: DataBinding;\n onChange: (binding: DataBinding) => void;\n disabled?: boolean | undefined;\n defaultRowLimit: number | null;\n}) {\n const table = useTable(tableId);\n const fields = useFields(tableId);\n const fieldList = useMemo(() => fields.data ?? [], [fields.data]);\n const shape = binding.semantic_type;\n\n // PREFILL: a table or record read starts from the table's own name column + its next ones.\n useEffect(() => {\n if (disabled || shape === \"value\" || binding.transform || fields.loading || fieldList.length === 0) return;\n onChange({\n ...binding,\n transform: {\n name: \"list\",\n template: defaultBindingTemplate(table.data ?? null, fieldList),\n join: \"\\n\",\n ...(shape === \"collection\" && binding.limit !== undefined ? { max: binding.limit } : {}),\n },\n });\n }, [disabled, shape, binding, fields.loading, fieldList, table.data, onChange]);\n\n const selectShape = (next: DataBindingShape) => {\n if (next === shape) return;\n const base: DataBinding = {\n kind: \"merge_field\",\n source: \"record\",\n semantic_type: next,\n table_id: binding.table_id,\n missing: binding.missing,\n override_policy: \"shown_locked\",\n };\n if (next !== \"collection\" && binding.record_id) base.record_id = binding.record_id;\n if (next === \"value\" && binding.field_key) base.field_key = binding.field_key;\n if (next === \"collection\") {\n const limit = binding.limit ?? defaultRowLimit;\n if (limit) base.limit = limit;\n }\n if (next !== \"value\" && binding.transform) {\n base.transform = {\n name: \"list\",\n template: binding.transform.template,\n ...(binding.transform.join !== undefined ? { join: binding.transform.join } : {}),\n ...(next === \"collection\" && base.limit !== undefined ? { max: base.limit } : {}),\n };\n }\n onChange(base);\n };\n\n const fieldOptions: CreatableOption[] = fieldList.map((f) => ({ value: f.key, label: fieldName(f) }));\n const template = binding.transform?.template ?? \"\";\n const setTemplate = (next: string) =>\n onChange({ ...binding, transform: { join: \"\\n\", ...binding.transform, name: \"list\", template: next } });\n\n return (\n <div className=\"flex flex-col gap-2\">\n <div className=\"flex flex-wrap gap-1\" role=\"radiogroup\" aria-label=\"What to read\">\n {DATA_BINDING_SHAPES.map((s) => (\n <Button\n key={s.value}\n type=\"button\"\n size=\"sm\"\n variant={s.value === shape ? \"default\" : \"outline\"}\n role=\"radio\"\n aria-checked={s.value === shape}\n disabled={disabled}\n onClick={() => selectShape(s.value)}\n >\n {s.label}\n </Button>\n ))}\n </div>\n {shape !== \"collection\" && (\n <RecordPicker\n tableId={tableId}\n value={binding.record_id ?? null}\n onChange={(id) => onChange({ ...binding, record_id: id })}\n disabled={Boolean(disabled)}\n />\n )}\n {shape === \"value\" && (\n <CreatablePicker\n value={binding.field_key ?? null}\n options={fieldOptions}\n onSelect={(key) => onChange({ ...binding, field_key: key })}\n placeholder=\"Choose a column\"\n searchPlaceholder=\"Search columns\"\n noun=\"column\"\n loading={fields.loading}\n {...(disabled ? { disabled: true } : {})}\n ariaLabel=\"Column\"\n />\n )}\n {shape !== \"value\" && (\n <div className=\"flex flex-col gap-1\">\n <textarea\n className={cn(\n \"min-h-[3.5rem] w-full rounded-md border border-border bg-background px-2 py-1.5 font-mono text-xs\",\n )}\n aria-label=\"Each row reads as\"\n value={template}\n disabled={disabled}\n onChange={(e) => setTemplate(e.target.value)}\n />\n {!disabled && (\n <div className=\"flex flex-wrap gap-1\">\n {fieldList.flatMap(bindingPlaceholdersFor).map((p) => (\n <Button\n key={p.token}\n type=\"button\"\n size=\"sm\"\n variant=\"ghost\"\n className=\"h-6 px-1.5 text-[11px]\"\n onClick={() => setTemplate(template + p.token)}\n >\n {p.label}\n </Button>\n ))}\n </div>\n )}\n </div>\n )}\n {shape === \"collection\" && (\n <label className=\"flex items-center gap-2 text-xs text-muted-foreground\">\n Up to\n <BasicInput\n type=\"number\"\n min={1}\n className=\"h-7 w-20 text-xs\"\n value={binding.limit ?? \"\"}\n disabled={disabled}\n onChange={(e) => {\n const n = Number.parseInt(e.target.value, 10);\n if (!Number.isFinite(n) || n < 1) return;\n onChange({ ...binding, limit: n, ...(binding.transform ? { transform: { ...binding.transform, max: n } } : {}) });\n }}\n />\n rows\n </label>\n )}\n <div className=\"flex flex-wrap items-center gap-1\" role=\"radiogroup\" aria-label=\"If nothing is found\">\n <span className=\"text-xs text-muted-foreground\">If nothing is found</span>\n {DATA_BINDING_MISSING.map((m) => (\n <Button\n key={m.value}\n type=\"button\"\n size=\"sm\"\n variant={m.value === binding.missing ? \"default\" : \"outline\"}\n role=\"radio\"\n aria-checked={m.value === binding.missing}\n disabled={disabled}\n onClick={() => onChange({ ...binding, missing: m.value })}\n >\n {m.label}\n </Button>\n ))}\n </div>\n </div>\n );\n}\n","\"use client\";\n\n// src/PickedSummaries.tsx — @ai-matrx/records-ui · lane 3 INTEGRATION W1.1 (2026-10-02)\n//\n// WHAT A PICKER CHOSE, READ BACK IN WORDS. A host that stores a table id, a record id or\n// `{column key: value}` (the workflow studio's step cards first) shows it as the table's name and\n// \"Stock status is Backordered\" — never the id, the key or the JSON. Each one reads through the\n// same doors the pickers use (`TablePickers.tsx`), and a value reads through the store's own\n// `renderValue`, so a choice shows its words, a relation its record's name.\n\nimport type { ReactNode } from \"react\";\nimport type { RecordsDataSource, Uuid } from \"@ai-matrx/records\";\nimport { useFields, useRecord, useTable } from \"@ai-matrx/records/react\";\nimport { RecordLabelProvider, useRecordLabels } from \"./labels\";\nimport { fieldName, recordName } from \"./names\";\nimport { TableScope, useTablesAnywhere } from \"./TablePickers\";\nimport { renderValue } from \"./values\";\n\n/** The chosen table's name, or `—` when it is not one this person can open. */\nexport function TableNameText({ dataSource, tableId }: { dataSource: RecordsDataSource; tableId: string | null }) {\n const tables = useTablesAnywhere(dataSource);\n if (!tableId) return <>—</>;\n if (tables.loading) return <>…</>;\n // A failed read says it failed — never \"—\", which reads as \"no table\".\n if (tables.error) return <>Couldn't load the table's name</>;\n return <>{tables.rows.find((t) => t.table_id === tableId)?.table_name ?? \"—\"}</>;\n}\n\n/** `{column key: value}` as \"Column is value, Other is value\" for one table. */\nexport function ColumnValuesText({\n dataSource,\n userId,\n tableId,\n value,\n}: {\n dataSource: RecordsDataSource;\n userId: Uuid | null;\n tableId: string | null;\n value: Record<string, unknown>;\n}) {\n if (!tableId) return <>—</>;\n return (\n <TableScope\n dataSource={dataSource}\n userId={userId}\n tableId={tableId}\n fallback={<>…</>}\n unavailable={<>Couldn't load this table's columns</>}\n >\n <RecordLabelProvider>\n <ColumnValuesWords tableId={tableId} value={value} />\n </RecordLabelProvider>\n </TableScope>\n );\n}\n\nfunction ColumnValuesWords({ tableId, value }: { tableId: string; value: Record<string, unknown> }) {\n const fields = useFields(tableId);\n // A choice is stored by its key; the label resolver reads it back as its words.\n const labels = useRecordLabels(fields.data ?? undefined);\n if (fields.loading) return <>…</>;\n // A failed read says it failed — never \"A removed column is —\", which lies about the table.\n if (fields.error) return <>Couldn't load this table's columns</>;\n const parts: ReactNode[] = [];\n for (const [key, stored] of Object.entries(value)) {\n // The store's own envelope keys (`_source`, `_values`, `_choices`…) ride on a record's\n // document; they are bookkeeping, never a column a person named.\n if (key.startsWith(\"_\")) continue;\n const field = (fields.data ?? []).find((f) => f.key === key);\n if (parts.length) parts.push(<span key={`${key}-sep`}>, </span>);\n parts.push(\n <span key={key}>\n {field ? fieldName(field) : \"A removed column\"} is {field ? renderValue(field, stored, undefined, labels) : \"—\"}\n </span>,\n );\n }\n return parts.length ? <>{parts}</> : <>—</>;\n}\n\n/** One record of a table, read back as its name. */\nexport function RecordNameText({\n dataSource,\n userId,\n tableId,\n recordId,\n}: {\n dataSource: RecordsDataSource;\n userId: Uuid | null;\n tableId: string | null;\n recordId: string | null;\n}) {\n if (!tableId || !recordId) return <>—</>;\n return (\n <TableScope\n dataSource={dataSource}\n userId={userId}\n tableId={tableId}\n fallback={<>…</>}\n unavailable={<>Couldn't load this record</>}\n >\n <RecordNameWords tableId={tableId} recordId={recordId} />\n </TableScope>\n );\n}\n\nfunction RecordNameWords({ tableId, recordId }: { tableId: string; recordId: string }) {\n const table = useTable(tableId);\n const record = useRecord(recordId);\n if (record.loading || table.loading) return <>…</>;\n if (record.error) return <>Couldn't load this record</>;\n if (!record.data) return <>A record you cannot open</>;\n return <>{recordName(record.data.document, table.data?.title_field ?? null)}</>;\n}\n","\"use client\";\n\n// src/HeldChangeDecision.tsx — @ai-matrx/records-ui · lane 3 INTEGRATION W1.1 (2026-10-02)\n//\n// APPROVE OR REFUSE A HELD CHANGE — for any host that is not the record pages. A workflow step\n// whose write the organization holds for a person PAUSES its run with the store's wait\n// (`matrx_records.held.held_interrupt_payload`: `held_write` + the `matrx_held_write` marker).\n// The server resumes such a run ONLY once the queue row is decided (`resolve_held_resume`\n// refuses a still-pending one with \"Approve or refuse it on the card first\"), so a host that\n// shows the pause as an ordinary question — a text box — leaves the person with no way through:\n// the W1.1 verifier typed \"Approve\", got a 409, and the run stayed stuck.\n//\n// This is the decision itself: `custom.work_approval_may_decide` decides whether the buttons are\n// drawn at all (a person who may not decide is told so, never shown a dead button), and\n// `custom.work_approval_decide` approves (APPLYING the change, as the person) or refuses. One\n// decision on the one queue row the chat, the table's page and the run page decide too.\n\nimport { useEffect, useState } from \"react\";\nimport type { RecordsDataSource, RecordsError, Uuid } from \"@ai-matrx/records\";\nimport { RecordsProvider, useRecordsClient } from \"@ai-matrx/records/react\";\nimport { Button } from \"@ai-matrx/design-system\";\nimport { personActor } from \"./RecordsMount\";\nimport { RefusalLine } from \"./Refusal\";\n\nexport interface HeldChangeDecisionProps {\n dataSource: RecordsDataSource;\n userId: Uuid | null;\n /** The organization the held change lives in (the marker's `organization_id`). */\n organizationId: Uuid;\n approvalId: Uuid;\n /** Told once the store took the decision; `approved` says which way. */\n onDecided: (approved: boolean) => void;\n /**\n * What approving does next, in the button's words. Default \"Approve\"; a host whose approval also\n * moves something on says so — a paused workflow run passes \"Approve and continue\".\n */\n approveLabel?: string;\n}\n\nexport function HeldChangeDecision({ dataSource, userId, organizationId, approvalId, onDecided, approveLabel }: HeldChangeDecisionProps) {\n return (\n <RecordsProvider config={{ dataSource, actor: personActor(userId), organizationId }}>\n <Decision approvalId={approvalId} onDecided={onDecided} approveLabel={approveLabel ?? \"Approve\"} />\n </RecordsProvider>\n );\n}\n\nfunction Decision({\n approvalId,\n onDecided,\n approveLabel,\n}: {\n approvalId: Uuid;\n onDecided: (approved: boolean) => void;\n approveLabel: string;\n}) {\n const client = useRecordsClient();\n const [may, setMay] = useState<boolean | null>(null);\n const [busy, setBusy] = useState<\"approve\" | \"refuse\" | null>(null);\n const [error, setError] = useState<RecordsError | null>(null);\n\n useEffect(() => {\n let live = true;\n void client.workApprovalMayDecide({ approval_id: approvalId }).then((res) => {\n if (!live) return;\n if (res.ok) setMay(res.data);\n else {\n setMay(false);\n setError(res.error);\n }\n });\n return () => {\n live = false;\n };\n }, [client, approvalId]);\n\n const decide = async (approve: boolean) => {\n setBusy(approve ? \"approve\" : \"refuse\");\n setError(null);\n const res = await client.workApprovalDecide({ approval_id: approvalId, approve });\n setBusy(null);\n if (res.ok) onDecided(approve);\n else setError(res.error);\n };\n\n if (may === null) return <p className=\"text-xs text-muted-foreground\">Checking who can decide…</p>;\n return (\n <div className=\"flex flex-col gap-1.5\">\n {may ? (\n <div className=\"flex gap-2\">\n <Button type=\"button\" size=\"sm\" disabled={busy !== null} onClick={() => void decide(true)}>\n {busy === \"approve\" ? \"Approving…\" : approveLabel}\n </Button>\n <Button type=\"button\" size=\"sm\" variant=\"outline\" disabled={busy !== null} onClick={() => void decide(false)}>\n {busy === \"refuse\" ? \"Refusing…\" : \"Refuse\"}\n </Button>\n </div>\n ) : (\n !error && <p className=\"text-xs text-muted-foreground\">An owner or admin of this organization decides this.</p>\n )}\n {error ? <RefusalLine error={error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OAAO;AAAA,QACxB,UAAS,IAAI,KAAK;AAAA,EACzB;AAEA,MAAI,QAAQ,KAAM,QAAO,gBAAAL,MAAC,OAAE,WAAU,iCAAgC,2CAAwB;AAC9F,SACE,gBAAAC,OAAC,SAAI,WAAU,yBACZ;AAAA,UACC,gBAAAA,OAAC,SAAI,WAAU,cACb;AAAA,sBAAAD,MAACM,UAAA,EAAO,MAAK,UAAS,MAAK,MAAK,UAAU,SAAS,MAAM,SAAS,MAAM,KAAK,OAAO,IAAI,GACrF,mBAAS,YAAY,oBAAe,cACvC;AAAA,MACA,gBAAAN,MAACM,UAAA,EAAO,MAAK,UAAS,MAAK,MAAK,SAAQ,WAAU,UAAU,SAAS,MAAM,SAAS,MAAM,KAAK,OAAO,KAAK,GACxG,mBAAS,WAAW,mBAAc,UACrC;AAAA,OACF,IAEA,CAAC,SAAS,gBAAAN,MAAC,OAAE,WAAU,iCAAgC,kEAAoD;AAAA,IAE5G,QAAQ,gBAAAA,MAAC,eAAY,OAAc,IAAK;AAAA,KAC3C;AAEJ;","names":["document","asked","useState","cn","jsx","jsxs","said","own","useEffect","useRef","useState","Button","jsx","jsxs","useState","shown","useRef","useEffect","Button","jsx","useEffect","useState","readColorPair","readMotion","readOpacity","readShadowPair","readTypeStyle","shadowCss","typeStyleCss","jsx","jsxs","numberOf","field","readColorPair","readShadowPair","shadowCss","readOpacity","readTypeStyle","typeStyleCss","readMotion","useEffect","useState","useEffect","useRef","useState","jsx","field","names","useState","asked","useRef","useEffect","useCallback","useEffect","useMemo","useRef","useState","useOptionalRecordsClient","cn","Fragment","jsx","jsxs","field","useOptionalRecordsClient","useState","useRef","useCallback","useMemo","useEffect","cn","recordName","own","id","useMemo","useState","useFields","useRecordsClient","Button","Select","SelectContent","SelectItem","SelectTrigger","SelectValue","BasicInput","cn","Fragment","jsx","jsxs","document","useFields","useMemo","useRecordsClient","useState","Button","cn","BasicInput","Select","SelectTrigger","SelectValue","SelectContent","SelectItem","useEffect","useRef","useState","optionLabel","useRecordsClient","BasicInput","Button","Label","Popover","PopoverContent","PopoverTrigger","Select","SelectContent","SelectItem","SelectTrigger","SelectValue","cn","STYLE_COLORS","STYLE_COLOR_LABELS","SWATCH_CLASS","useState","useOptionalRecordsClient","Button","jsx","jsxs","field","useOptionalRecordsClient","useState","Button","useCallback","useEffect","useLayoutEffect","useRef","useState","isButtonField","newerKindOf","optionKey","rankTypedMatches","readTypedTime","typedDateText","typedTimeText","useOptionalRecordsClient","BasicInput","BasicTextarea","Badge","Button","Checkbox","Label","Popover","PopoverContent","PopoverTrigger","Select","SelectContent","SelectItem","SelectTrigger","SelectValue","cn","useEffect","useRef","useState","BasicInput","cn","Fragment","jsx","jsxs","field","document","said","useCallback","useEffect","useMemo","useRef","useState","rankTypedMatches","useOptionalRecordsClient","BasicInput","Button","cn","nameOf","Fragment","jsx","jsxs","field","useOptionalRecordsClient","useState","useRef","useCallback","useMemo","useEffect","target","id","said","refusalOf","cn","rankTypedMatches","BasicInput","Button","useContext","useEffect","useRef","useState","Button","Dialog","ErrorBox","DialogContent","DialogHeader","DialogTitle","Popover","PopoverContent","PopoverTrigger","cn","buttonNeeds","buttonOf","useOptionalRecordsClient","useTable","createContext","Fragment","jsx","jsxs","nameOf","useEffect","useMemo","useRef","useState","tableShapeChanged","useFields","useRecords","useRecordsClient","useTable","BasicInput","Button","Checkbox","Label","Select","SelectContent","SelectItem","SelectTrigger","SelectValue","cn","Checkbox","Label","jsx","jsxs","field","same","useEffect","useMemo","useRef","useState","useRecordsClient","BasicTextarea","Button","Label","cn","jsx","jsxs","useRecordsClient","useState","useEffect","useRef","asked","useMemo","cn","Label","BasicTextarea","Button","useMemo","useState","BasicInput","Checkbox","Label","cn","Fragment","jsx","jsxs","useState","useMemo","cn","Label","BasicInput","Checkbox","useCallback","useEffect","useState","Button","useRecordsClient","formatFieldValue","field","jsx","field","Badge","cn","useMemo","useState","useEntityReferenceKinds","useOptionalRecordsClient","Badge","Button","cn","Fragment","jsx","jsxs","field","useOptionalRecordsClient","useMemo","useState","useEntityReferenceKinds","Button","own","cn","Badge","useEffect","useState","BasicTextarea","OutboundLink","jsx","jsxs","useState","useEffect","field","BasicTextarea","formatPhone","useRef","formatFieldValue","cn","OutboundLink","useEffect","useRef","useState","Fragment","jsx","jsxs","useState","useRef","useEffect","shown","jsx","jsxs","own","numberOf","useRef","shown","said","cn","OutboundLink","formatFieldValue","useEffect","useRef","useState","useOptionalRecordsClient","Badge","Button","cn","OutboundLink","jsx","jsxs","field","useOptionalRecordsClient","useState","useEffect","cn","Badge","Button","useRef","refusalOf","entityRefsOf","Badge","Skeleton","cn","jsx","jsxs","own","field","entityRefsOf","Skeleton","cn","Badge","useCallback","useRef","useState","Popover","PopoverContent","PopoverTrigger","cn","jsx","jsxs","shown","names","i","field","op","document","state","autonumberPrefixOf","autonumberWords","sourceArchivedOf","isUuidShape","useSyncExternalStore","useSyncExternalStore","useState","useRecordsClient","Button","isUuidShape","useEffect","useMemo","useState","useOptionalRecordsClient","isUuidShape","useState","useEffect","useOptionalRecordsClient","useMemo","isUuidShape","jsx","jsxs","document","useRecordsClient","useState","said","version","field","shown","isUuidShape","Button","isUuidShape","jsx","document","field","shown","isUuidShape","said","OutboundLink","useState","Badge","Button","Dialog","DialogContent","DialogHeader","DialogTitle","Popover","PopoverContent","PopoverTrigger","cn","OutboundLink","jsx","jsxs","NAME_KEYS","nameOf","names","shown","jsx","OutboundLink","cn","jsxs","useState","shown","Button","NAME_KEYS","Badge","Dialog","DialogContent","DialogHeader","DialogTitle","Popover","PopoverTrigger","PopoverContent","Fragment","jsx","jsxs","field","document","state","sourceArchivedOf","Badge","cn","OutboundLink","formatPhone","isImageUrl","isUuidShape","autonumberPrefixOf","autonumberWords","said","formatFieldValue","shown","jsx","jsxs","state","useRecordsClient","useState","useCallback","useEffect","Button","createContext","useContext","useEffect","useState","BasicInput","Button","optionKey","rankTypedMatches","useOptionalRecordsClient","Fragment","jsx","jsxs","createContext","op","window","field","useOptionalRecordsClient","useState","useEffect","optionKey","BasicInput","Button","shown","rankTypedMatches","said","same","useContext","target","useEffect","useState","tableShapeChanged","useRecordsClient","Button","Select","SelectContent","SelectItem","SelectTrigger","SelectValue","isUuidShape","isUuidShape","said","jsx","jsxs","field","useRecordsClient","useState","said","useEffect","tableShapeChanged","Select","SelectTrigger","SelectValue","SelectContent","SelectItem","Button","useEffect","useMemo","useRef","useState","useRecordsClient","jsx","jsxs","field","useRecordsClient","useState","useMemo","useRef","useEffect","field","STATUS_GROUP_WORDS","statusGroupOf","Label","Select","SelectContent","SelectItem","SelectTrigger","SelectValue","jsx","jsxs","field","statusGroupOf","Label","Select","SelectTrigger","SelectValue","SelectContent","SelectItem","STATUS_GROUP_WORDS","jsxs","jsx","Label","Select","SelectTrigger","SelectValue","SelectContent","SelectItem","Label","getFieldFormat","jsx","jsxs","field","groups","own","getFieldFormat","Label","humanizeIdentifier","tableName","holdsNumbers","window","matches","holdsNumbers","document","names","field","said","field","ARITHMETIC","op","tableName","shown","document","field","a","autonumberPrefixOf","useEffect","useState","BasicInput","Button","Label","useOptionalRecordsClient","cn","SWATCH_CLASS","jsx","jsxs","Label","useFields","useOptionalRecordsClient","useEffect","useState","jsx","jsxs","useFields","useOptionalRecordsClient","useState","useEffect","Label","jsx","jsxs","useOptionalRecordsClient","useState","useEffect","Label","BasicInput","Button","optionKey","Fragment","jsx","jsxs","field","useTable","useFields","useRecordsClient","useState","useMemo","autonumberPrefixOf","useEffect","optionKey","useRef","cn","tableShapeChanged","written","Label","BasicInput","Select","SelectTrigger","SelectValue","SelectContent","SelectItem","Button","Checkbox","refusalOf","state","op","useRecords","humanizeIdentifier","OutboundLink","openOutbound","Fragment","jsx","jsxs","document","shown","value","stop","field","useOptionalRecordsClient","buttonOf","useState","said","useContext","useTable","useRef","useEffect","Button","cn","buttonNeeds","answers","Popover","PopoverTrigger","PopoverContent","ErrorBox","Dialog","DialogContent","DialogHeader","DialogTitle","useLayoutEffect","useRef","useState","Fragment","jsx","jsxs","GAP","useEffect","useRef","useState","BasicInput","BasicTextarea","getFieldFormat","jsx","jsxs","useState","useRef","useEffect","BasicInput","getFieldFormat","BasicTextarea","useState","Popover","PopoverContent","PopoverTrigger","cn","jsx","jsxs","wordsFor","useState","shown","Popover","PopoverTrigger","PopoverContent","cn","Fragment","jsx","jsxs","field","Button","Label","newerKindOf","isButtonField","read","readTypedTime","typedTimeText","typedDateText","useRef","useState","useLayoutEffect","useOptionalRecordsClient","useEffect","BasicInput","optionKey","shown","own","BasicTextarea","Checkbox","Popover","PopoverTrigger","PopoverContent","Select","SelectTrigger","SelectValue","SelectContent","SelectItem","useCallback","rankTypedMatches","add","Badge","cn","Fragment","jsx","jsxs","field","optionLabel","same","useRecordsClient","useState","useRef","useEffect","Label","BasicInput","Button","Select","SelectTrigger","SelectValue","SelectContent","SelectItem","Popover","PopoverTrigger","STYLE_COLOR_LABELS","cn","SWATCH_CLASS","PopoverContent","STYLE_COLORS","globalSlot","useRef","useEffect","useOptionalRecordsClient","useOptionalRecordsClient","useEffect","jsx","jsxs","bound","useRef","useEffect","useMemo","useState","RecordsProvider","useFields","useRecords","useTable","Button","Fragment","jsx","jsxs","state","useState","useEffect","own","refusalOf","RecordsProvider","useFields","useMemo","field","Button","shown","useTable","useRecords","useEffect","useMemo","useFields","useTable","BasicInput","Button","CreatablePicker","cn","jsx","jsxs","field","useTable","useFields","useMemo","useEffect","Button","CreatablePicker","cn","BasicInput","useFields","useTable","Fragment","jsx","jsxs","useFields","field","useTable","useEffect","useState","RecordsProvider","useRecordsClient","Button","jsx","jsxs","RecordsProvider","useRecordsClient","useState","useEffect","Button"]}
|