fsanyoto commited on
Commit
a44526d
Β·
verified Β·
1 Parent(s): a878ebb

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
Files changed (3) hide show
  1. RELEASES.json +1 -1
  2. VERSION +1 -1
  3. web/src/customer-grid/display.ts +683 -669
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "75ff9d9",
3
  "releases": [
4
  {
5
  "version": "v24",
 
1
  {
2
+ "current": "3970056",
3
  "releases": [
4
  {
5
  "version": "v24",
VERSION CHANGED
@@ -1 +1 @@
1
- 75ff9d9
 
1
+ 3970056
web/src/customer-grid/display.ts CHANGED
@@ -1,669 +1,683 @@
1
- // ---------------------------------------------------------------------------
2
- // customer-grid / display.ts
3
- // The pure DISPLAY-STRING half of cells.ts, split out in wave 7 (item W2): the
4
- // export builders run under node in the verify gates, and importing them
5
- // through cells.ts dragged the whole glide-data-grid package into a plain
6
- // script. Everything here depends only on types.ts. cells.ts re-exports these
7
- // names, so every existing import keeps working; the formatting is the same
8
- // bytes it was β€” this is a move, not a change.
9
- // ---------------------------------------------------------------------------
10
-
11
- import type { Field, FieldFormat } from "./types";
12
- import { ratingMax } from "./types";
13
-
14
- export type CellValue = string | number | null | undefined;
15
-
16
- // --- C-AVATAR (wave-14 item 11): the two PURE halves of the assignee avatar ---
17
- // They live here rather than in cells.ts for this module's founding reason: cells.ts imports
18
- // glide, so nothing in it can be reached by a node gate. The canvas drawing stays there; the
19
- // arithmetic and the string handling β€” the parts that can be wrong in ways a screenshot of one
20
- // avatar will not show β€” are here, and `cells.ts` re-exports both.
21
-
22
- /**
23
- * Up to two letters for the fallback circle.
24
- *
25
- * ⚠ The LOCAL PART only. Usernames in this tenant are email-shaped, and splitting
26
- * "fsanyoto@gmail.com" on its separators gives ["fsanyoto@gmail", "com"] β†’ "FC" β€” a person's
27
- * avatar reading as their mail provider. Cutting at "@" first gives "FS".
28
- *
29
- * ⚠ A HYPHEN IS NOT A SEPARATOR. Space, dot and underscore divide a given name from a family
30
- * name in a username; a hyphen almost always JOINS a compound one β€” Jo-Anne, Marie-Claire,
31
- * Al-Rashid. Treating it as a separator turns "jo-anne_smith" into "JA", which is not that
32
- * person's initials and is wrong in the one way nobody can spot: it looks like initials.
33
- */
34
- export function avatarInitials(name: string): string {
35
- const local = name.split("@")[0];
36
- const parts = local.trim().split(/[\s._]+/).filter(Boolean);
37
- if (parts.length === 0) return "?";
38
- if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
39
- return (parts[0][0] + parts[1][0]).toUpperCase();
40
- }
41
-
42
- /**
43
- * The avatar's diameter for a row of `height` px: 22 on a comfortable row, never larger, and
44
- * never so small it stops being a face. Bounded on BOTH sides on purpose β€” a `tall` row (48px)
45
- * must not grow a 42px portrait, and a `short` one (28px) must not shrink to a dot.
46
- */
47
- export function avatarSize(height: number): number {
48
- return Math.max(14, Math.min(22, height - 6));
49
- }
50
-
51
- export interface UserCellData {
52
- kind: "aios-user";
53
- /** The assignee's username. "" = unassigned; the cell then paints nothing at all. */
54
- name: string;
55
- /** C-AVATAR data URL, when the workspace served one for this user. */
56
- photo?: string;
57
- }
58
-
59
- /**
60
- * The `user` cell's payload β€” HERE rather than inline in `cells.ts` for one reason: `copyData`.
61
- *
62
- * ⚠ R6 removed the NAME from the cell, so the cell renders no text at all. glide's copy and
63
- * export take `copyData`, which means an assignee column silently copies and exports as EMPTY
64
- * unless it is set β€” a real regression that appears in no screenshot, because the screenshot
65
- * shows the avatar working perfectly. `cells.ts` imports glide and is therefore unreachable from
66
- * a node gate; this is, so the claim can actually be asserted.
67
- */
68
- export function userCellPayload(
69
- name: string,
70
- userAvatars?: Record<string, string>
71
- ): { data: UserCellData; copyData: string } {
72
- return {
73
- data: { kind: "aios-user", name, photo: userAvatars?.[name] },
74
- copyData: name,
75
- };
76
- }
77
-
78
- export function num(v: CellValue): number {
79
- const n = typeof v === "number" ? v : Number(v);
80
- return Number.isFinite(n) ? n : 0;
81
- }
82
-
83
- /**
84
- * β›” W29-T81 β€” HAS THIS NUMERIC CELL NOTHING TO SHOW? Blank, or a stored value that is not a
85
- * number at all.
86
- *
87
- * `num()` above answers **0** for anything unparseable, which is a measurement where there was
88
- * none. That is survivable for a column only this app writes; it stopped being survivable when
89
- * the import door began accepting rows from a spreadsheet β€” a `qty` column holding
90
- * "seventeen-ish" painted `0` on the canvas while the record panel honestly showed an em-dash.
91
- * Two surfaces disagreeing about the same cell, and the one that looks authoritative is the one
92
- * making the number up.
93
- *
94
- * ⚠ The FOLD was already right (`aggregations.numOf` skips what will not parse), so the totals
95
- * row never counted these β€” it is the painted cell alone. Same family as `formulaIsText` below,
96
- * asked of the RAW value for the same reason.
97
- * ⚠ `" "` is blank, not a zero: `Number(" ")` is 0, which is how a whitespace cell becomes a
98
- * number nobody typed.
99
- */
100
- export function numericIsBlank(v: CellValue): boolean {
101
- return numericOrUndefined(v) === undefined;
102
- }
103
-
104
- /**
105
- * β›”β›” THE ONE NUMERIC READING OF A STORED CELL, and it has to be one.
106
- *
107
- * `numericIsBlank` decides whether the CANVAS paints anything; `aggregations.numOf` decides
108
- * whether the TOTALS ROW counts it. They were written separately and normalised differently β€”
109
- * this one trimmed, that one stripped `$`, `,` and spaces β€” so `"1,234.50"` painted BLANK in the
110
- * cell and was COUNTED in the total underneath it. That is T81's own defect ("two surfaces
111
- * disagreeing about one cell") reintroduced in the opposite direction, by the fix for it, and no
112
- * test could see it because every value in the legs was comma-free.
113
- *
114
- * ⚠ Human spellings are ACCEPTED here on purpose. `coerceClipboardValue` canonicalises what the
115
- * UI writes, but the import door refuses-without-rewriting by design, so a `"$45"` posted by curl
116
- * is storable β€” and the honest reading of that cell is 45 on BOTH surfaces, never 45 in the total
117
- * and nothing in the cell ([[one-evaluator-per-question]]).
118
- */
119
- export function numericOrUndefined(v: CellValue): number | undefined {
120
- if (v === null || v === undefined || v === "") return undefined;
121
- if (typeof v === "number") return Number.isFinite(v) ? v : undefined;
122
- const cleaned = String(v).replace(/[$,\s]/g, "");
123
- if (cleaned === "") return undefined; // " " is blank, not the zero `Number("")` gives
124
- const n = Number(cleaned);
125
- return Number.isFinite(n) ? n : undefined;
126
- }
127
-
128
- /**
129
- * β›” IS THIS FORMULA RESULT TEXT? β€” and it must be asked of the RAW value.
130
- *
131
- * A formula may return text since 2026-07-31 (owner item 2: CONCATENATE, `&`, TEXT(),
132
- * TRUE/FALSE, and any `IF(cond, "yes", "no")`). Both renderers tried to detect that with
133
- * `!Number.isFinite(num(v))` β€” and `num()` above returns **0** for anything non-finite, so the
134
- * test was `Number.isFinite(0)`, which is always true. The text branch therefore never ran in
135
- * EITHER renderer, and every text-returning formula printed as `0`: on the canvas, in the list,
136
- * on kanban cards, in the record panel and in all four export formats.
137
- *
138
- * The feature had never worked. It surfaced by rendering the owner's own Buy signal formula
139
- * through the shipped bundle rather than by asking whether the code looked right.
140
- *
141
- * ONE function, exported, called by both `formatDisplay` and `makeCell` β€” they are meant to be
142
- * one rendering, and the way they drifted was each holding its own copy of this test.
143
- * `Number("")` is 0, so the empty case is excluded explicitly rather than relied upon.
144
- *
145
- * A TYPE PREDICATE, not a bare boolean: `makeCell` builds a `TextCell` from the value straight
146
- * after this test, and without the narrowing the caller has to re-assert the string it just
147
- * proved β€” which is the kind of cast that outlives the reason for it.
148
- */
149
- export function formulaIsText(v: CellValue): v is string {
150
- return typeof v === "string" && v.trim() !== "" && !Number.isFinite(Number(v));
151
- }
152
-
153
- /**
154
- * β›” AND THE BLANK TEST HAS TO AGREE WITH IT, or a value falls between the two.
155
- *
156
- * `formulaIsText` excludes whitespace-only strings (a `" "` result is not TEXT worth painting).
157
- * The callers' own blank guard was `v === ""`, which does not catch `" "` β€” so a formula
158
- * returning a space matched NEITHER, fell through to the numeric path, and printed `0`, because
159
- * `Number(" ")` is 0. The exact bug this pair was written to fix, surviving in a narrower case.
160
- *
161
- * A formula's result is therefore one of exactly three things, and these two predicates make the
162
- * three TOTAL: blank (null, empty, or whitespace), text, or a number. Reachable in practice β€”
163
- * `CONCATENATE(" ", "")` is a space, and so is `TRIM()` of one.
164
- */
165
- export function formulaIsBlank(v: CellValue): boolean {
166
- return v == null || (typeof v === "string" && v.trim() === "");
167
- }
168
-
169
- /** A checkbox cell's boolean, out of the overlay's '1'-or-empty contract. */
170
- export function checkboxOn(v: CellValue | boolean): boolean {
171
- return v === "1" || v === 1 || v === true;
172
- }
173
-
174
- /**
175
- * Item 10 β€” the number DISPLAY string. With no format: exactly the pre-wave-5
176
- * rendering (toLocaleString). `abbrev` wins over decimals when the magnitude
177
- * calls for it (34.0M β€” one decimal, k/M/B); `thousands: false` drops the
178
- * separators; `decimals` fixes 0..4 places.
179
- */
180
- export function numberText(v: number, fmt: FieldFormat | undefined): string {
181
- if (fmt?.abbrev && Math.abs(v) >= 1000) {
182
- const abs = Math.abs(v);
183
- const [div, suffix] =
184
- abs >= 1e9 ? [1e9, "B"] : abs >= 1e6 ? [1e6, "M"] : [1e3, "k"];
185
- return (v / div).toFixed(1) + suffix;
186
- }
187
- const d =
188
- fmt && Number.isInteger(fmt.decimals) && (fmt.decimals as number) >= 0 &&
189
- (fmt.decimals as number) <= 4
190
- ? (fmt.decimals as number)
191
- : null;
192
- const thousands = fmt?.thousands !== false;
193
- if (d != null)
194
- return thousands
195
- ? v.toLocaleString(undefined, {
196
- minimumFractionDigits: d,
197
- maximumFractionDigits: d,
198
- })
199
- : v.toFixed(d);
200
- return thousands ? v.toLocaleString() : String(v);
201
- }
202
-
203
- /**
204
- * Parse a stored date/datetime string. Odoo datetimes arrive as
205
- * "YYYY-MM-DD HH:MM:SS" and are UTC by Odoo convention, so a time-carrying
206
- * value with no zone gets a Z; a bare date keeps today's parse (UTC midnight)
207
- * so format-less rendering stays byte-identical to the pre-wave-5 path.
208
- *
209
- * ⭐ EXPORTED in wave 29 (W29-T30) because the xlsx writer needs a Date to turn
210
- * into an Excel serial, and the alternative was a SECOND date parser in
211
- * `export.ts` β€” two evaluators for one question, which is how the two drift and
212
- * a stamp exports as a different day than it renders
213
- * ([[one-evaluator-per-question]]). It stays the only parser in this module.
214
- */
215
- export function parseStamp(raw: string): Date | null {
216
- const s = raw.includes(" ") ? raw.replace(" ", "T") : raw;
217
- const iso =
218
- /T\d{2}:\d{2}/.test(s) && !/(?:[zZ]|[+-]\d{2}:?\d{2})$/.test(s) ? s + "Z" : s;
219
- const d = new Date(iso);
220
- return Number.isNaN(d.getTime()) ? null : d;
221
- }
222
-
223
- /** A BARE calendar day: the shape Odoo sends for a `date`, and the shape wave 26's migration
224
- * converted the Instagram preset stamps into. `parseStamp` gives it UTC midnight. */
225
- const BARE_DAY = /^\d{4}-\d{2}-\d{2}$/;
226
-
227
- /**
228
- * Is this stored value a calendar DAY rather than an INSTANT? β€” the question that decides which
229
- * clock renders it (see `dateTimeText`).
230
- *
231
- * Exported, and it is the whole reason the test for this is worth anything: the alternative is
232
- * asserting a rendered string, which depends on the machine's timezone β€” so the check would pass
233
- * on the owner's box (+07:00, where the two clocks agree on the day) and could only ever go red
234
- * somewhere else. A predicate is the same decision with no ambient state in it.
235
- *
236
- * ⚠ The SHAPE OF THE RAW STRING, never `field.type`: wave 26 re-typed columns that hold full ISO
237
- * stamps to `date`, so one `date` field can carry both shapes at once during a migration.
238
- */
239
- export function isBareDay(v: CellValue): boolean {
240
- return BARE_DAY.test(String(v ?? "").trim());
241
- }
242
-
243
- /**
244
- * ⭐ Wave-26 item 3 (owner, R3) β€” the day, spelled. `Aug 5, 2026`, never `8/5/2026` and never
245
- * the raw stamp. One vocabulary for the date half whether or not a time follows it, so a
246
- * `date` column and a `created_time` column in the same table read alike.
247
- */
248
- const DAY_PARTS = { year: "numeric", month: "short", day: "numeric" } as const;
249
-
250
- /**
251
- * Item 10 β€” the date DISPLAY string. `time` includes the time of day
252
- * (created_time defaults to true β€” a creation stamp without its time reads as
253
- * a duplicate of nothing); `tz: 'utc'` renders the tenant-neutral clock.
254
- * Unparseable input renders VERBATIM rather than "Invalid Date" β€” the raw
255
- * string is at least true.
256
- *
257
- * ⭐ WAVE 26 ITEM 3 (owner, via R3). The complaint was literal: cells read
258
- * `2026-08-05T14:03:11+07:00`. SESSION A's half re-typed the Instagram preset
259
- * columns from `text` to `date` (which is what routed them here at all) and
260
- * migrated the stored cells to bare `YYYY-MM-DD`; this half is that a date must
261
- * READ as one. Two changes, and the second is the one that is not cosmetic:
262
- *
263
- * β›” **A BARE `YYYY-MM-DD` IS A CALENDAR DAY, NOT AN INSTANT, so it renders in
264
- * UTC.** `parseStamp` gives a bare date UTC midnight, so rendering it in the
265
- * viewer's local zone shows the PREVIOUS DAY to everyone west of Greenwich β€” a
266
- * value stored as the 5th reading as the 4th, silently, for a whole hemisphere.
267
- * `ui/fmt.ts:date()` already refused to inherit this and its comment names this
268
- * function as the holdout; it is no longer one. The tenant runs at +07:00, where
269
- * the two agree, which is exactly why it could sit here unnoticed β€” and why the
270
- * US market in COMMERCIALIZATION_PLAN C1b would have met it first.
271
- *
272
- * A value that CARRIES a time is a real instant and keeps the existing zone
273
- * behaviour (local, or UTC when the field says so): shifting those to UTC would
274
- * introduce the same off-by-a-day from the other direction.
275
- */
276
- export function dateTimeText(
277
- // ⚠ STRUCTURAL, not `Field`: this reads exactly two members, and item 8's post rows hold a
278
- // raw `posted_at` with no column behind it. Widening the parameter (rather than fabricating a
279
- // fake Field at the call site) is what lets the posts list render its days through the SAME
280
- // formatter as a date cell instead of growing a second one. Every existing caller passes a
281
- // `Field`, which is assignable.
282
- field: { type: Field["type"]; format?: FieldFormat },
283
- v: CellValue
284
- ): string {
285
- if (v == null || v === "") return "";
286
- const raw = String(v);
287
- const d = parseStamp(raw);
288
- if (!d) return raw;
289
- const fmt = field.format;
290
- const withTime = fmt?.time ?? field.type === "created_time";
291
- const utc = fmt?.tz === "utc" || isBareDay(raw);
292
- const zone = utc ? { timeZone: "UTC" as const } : undefined;
293
- return withTime
294
- ? d.toLocaleString(undefined, {
295
- ...DAY_PARTS,
296
- hour: "numeric",
297
- minute: "2-digit",
298
- second: "2-digit",
299
- ...zone,
300
- })
301
- : d.toLocaleDateString(undefined, { ...DAY_PARTS, ...zone });
302
- }
303
-
304
- /**
305
- * The plain-string rendering of one (field, value), mirroring makeCell's
306
- * displayData. Reused by the record-detail panel and the W2 export builders so
307
- * a value reads identically on the canvas, in the panel and in a file. Returns
308
- * "" for empty so callers can substitute their own placeholder.
309
- */
310
- /**
311
- * Wave-18 C5-AUTOFIELD β€” the STATE word of an automation cell.
312
- *
313
- * An automation cell holds one machine-written line: `state Β· when Β· detail`, e.g.
314
- * `ok Β· 2026-08-03 14:10 Β· 12 posts`. The state is the first token, and every surface that
315
- * paints the cell β€” canvas tint, record modal, the rail β€” reads it through HERE rather than
316
- * re-splitting the string, because two parsers of one format is how the canvas and the panel
317
- * end up disagreeing about whether a run succeeded (the exact way `formula` broke above).
318
- *
319
- * `"none"` is the honest answer for a cell nothing has written yet β€” NOT "ok". A column that
320
- * has never run must not look like a column that ran and found nothing.
321
- */
322
- export type AutomationState = "ok" | "partial" | "error" | "blocked" | "queued" | "none";
323
-
324
- const AUTOMATION_STATES: AutomationState[] = ["ok", "partial", "error", "blocked", "queued"];
325
-
326
- export function automationState(v: CellValue): AutomationState {
327
- const head = String(v ?? "").split("Β·")[0].trim().toLowerCase();
328
- return (AUTOMATION_STATES as string[]).includes(head)
329
- ? (head as AutomationState)
330
- : "none";
331
- }
332
-
333
- /** Everything after the state word β€” the timestamp and the run's own detail. */
334
- export function automationDetail(v: CellValue): string {
335
- const parts = String(v ?? "").split("Β·");
336
- return parts.length > 1 ? parts.slice(1).join("Β·").trim() : "";
337
- }
338
-
339
- /** Sentence-cased state, for anywhere a word reads better than a token. */
340
- export function automationStateLabel(v: CellValue): string {
341
- const s = automationState(v);
342
- return s === "none" ? "Not run yet" : s[0].toUpperCase() + s.slice(1);
343
- }
344
-
345
- /**
346
- * ⭐ Wave-23 C7 (owner item 5) β€” THE JSON PREVIEW: what a 200px cell says about a document.
347
- *
348
- * `MAX_JSON_BYTES` is the contract's ceiling, mirrored from the host's write validation so the
349
- * viewer can refuse a paste with the same number the server would (a client that lets you type
350
- * 40 KB and then shows you a server refusal has wasted the edit).
351
- *
352
- * The four cases, and each one is a decision rather than a formatting preference:
353
- * Β· **a single-pair object shows THE PAIR.** `{handle: "royalimports"}` is more useful than
354
- * "1 key" and it is the shape most machine writes actually have. Past one pair the pairs
355
- * stop fitting and the honest answer is the count.
356
- * Β· **many keys / many items β†’ `{…} N keys` / `[…] N items`.** Showing the FIRST pair of a
357
- * twelve-key object would let a reader take one arbitrary value β€” whichever key the writer's
358
- * serializer happened to emit first β€” for the cell's content.
359
- * Β· **a bare scalar renders as itself.** `12`, `"ok"`, `true` and `null` are all valid JSON
360
- * documents, and wrapping them in braces would describe a shape they do not have.
361
- * Β· β›” **text that does not parse renders AS ITSELF, never as a shape.** The host validates on
362
- * write, so this only happens to a value that predates the validation or arrived another
363
- * way β€” and the one thing the preview must never do is claim a document is well-formed. The
364
- * viewer's raw tab is where such a value gets read and repaired.
365
- *
366
- * Blank stays blank: an empty json cell is a document nobody has written, and `{}` is a document
367
- * somebody wrote that is empty. Two different facts, two different cells.
368
- */
369
- export const MAX_JSON_BYTES = 32 * 1024;
370
-
371
- /** Does this text parse as JSON? The ONE test, shared by the preview, the cell and the viewer's
372
- * save β€” three copies of a try/catch is how they end up disagreeing about `""` or `NaN`. */
373
- export function jsonParse(v: CellValue): { ok: boolean; value?: unknown } {
374
- const s = String(v ?? "").trim();
375
- if (s === "") return { ok: false };
376
- try {
377
- return { ok: true, value: JSON.parse(s) as unknown };
378
- } catch {
379
- return { ok: false };
380
- }
381
- }
382
-
383
- /**
384
- * ⭐ WAVE-27 item 13 (R13) β€” one compact line for a CODE cell.
385
- *
386
- * Deliberately NOT `jsonPreview`, and the difference is the whole reason `code` is its own kind:
387
- * a json preview SUMMARISES a parsed document ("{…} 5 keys"), which it can only do because the
388
- * value is guaranteed to parse. A snippet has no structure to summarise and often does not parse
389
- * at all β€” half-written SQL is the normal state of one β€” so the honest preview is the first
390
- * non-blank LINE, clipped, plus the line count when there is more underneath. That way the cell
391
- * says what the snippet starts with AND that there is more, instead of inventing a shape for it.
392
- */
393
- export function codePreview(v: CellValue): string {
394
- const raw = String(v ?? "");
395
- if (raw.trim() === "") return "";
396
- const lines = raw.split("\n");
397
- const firstIdx = lines.findIndex((l) => l.trim() !== "");
398
- const first = clip((lines[firstIdx < 0 ? 0 : firstIdx] ?? "").trim(), 60);
399
- // The count is of REAL lines, so a snippet padded with blank lines does not claim depth it
400
- // does not have β€” and it is checkable against what opening the editor shows
401
- // ([[no-unverifiable-aggregates]]).
402
- const n = lines.filter((l) => l.trim() !== "").length;
403
- return n > 1 ? `${first} +${n - 1} more` : first;
404
- }
405
-
406
- /** One compact line for a json cell. See the note above for why each case reads as it does. */
407
- export function jsonPreview(v: CellValue): string {
408
- const raw = String(v ?? "").trim();
409
- if (raw === "") return "";
410
- const parsed = jsonParse(raw);
411
- // ⚠ First line only, and clipped: an unparseable value is often a whole pasted response, and
412
- // a cell is not where a 4 KB blob gets read. It is shown rather than hidden because the
413
- // reader has to be able to see that the column holds something the app could not open.
414
- if (!parsed.ok) return clip(raw.split("\n")[0], 60);
415
- const value = parsed.value;
416
- // ⭐ ITEM 8 β€” a posts window says what it holds. Before wave 26 this document fell through to
417
- // the generic object branch and every creator's `posts` cell read `{…} 4 keys`, which is true
418
- // about JSON and says nothing about the record.
419
- // ⚠ The ARRAY LENGTH, never the document's own `n`: the count in a cell has to be checkable
420
- // against what opening it shows ([[no-unverifiable-aggregates]]).
421
- const shown = postsWindowOf(value);
422
- if (shown)
423
- return shown.posts.length === 0
424
- ? "No posts"
425
- : `${shown.posts.length} post${shown.posts.length === 1 ? "" : "s"}`;
426
- if (Array.isArray(value))
427
- return value.length === 0 ? "[]" : `[…] ${value.length} item${value.length === 1 ? "" : "s"}`;
428
- if (value !== null && typeof value === "object") {
429
- const keys = Object.keys(value as Record<string, unknown>);
430
- if (keys.length === 0) return "{}";
431
- if (keys.length === 1)
432
- return clip(`{${keys[0]}: ${scalarText((value as Record<string, unknown>)[keys[0]])}}`, 60);
433
- return `{…} ${keys.length} keys`;
434
- }
435
- return clip(scalarText(value), 60);
436
- }
437
-
438
- /** The day, spelled, for a caller holding a raw value and no column β€” the posts list's
439
- * `posted_at`. Routed through `dateTimeText` so it can never drift from a date CELL. */
440
- export function dayText(v: CellValue): string {
441
- return dateTimeText({ type: "date" }, v);
442
- }
443
-
444
- /* ═══ ⭐ WAVE 26 ITEM 8 (contract C2) β€” THE `posts` WINDOW ═══
445
- The preset `posts` cell holds ONE object written by the engine's `posts_window`:
446
-
447
- { n, metrics, as_of, posts: [{ shortcode, url, posted_at, type, caption,
448
- views?, likes?, comments? }] }
449
-
450
- Two laws come with it and both are enforced below rather than in the components:
451
-
452
- β›” `metrics: false` β‡’ views/likes/comments are ABSENT KEYS, NEVER 0. A reader must render an
453
- absent metric as NOTHING. Coercing it to a number here β€” `Number(p.views) || 0` is the
454
- natural thing to type β€” would fabricate a measurement, which is the engine's own
455
- blank-never-zero law broken at the display seam, silently and plausibly (a creator with no
456
- metrics bought would read as a creator with no engagement).
457
-
458
- β›” IT IS A WINDOW, NOT THE HISTORY. `ut_ig_posts` / `ut_ig_post_snapshots` accumulate; this
459
- cell is the last N (R1/R3 β€” "one store for one series"). So nothing here may present the
460
- cell as a total.
461
-
462
- ⚠ DETECTED BY SHAPE, never by the field's key. A user may name a column `posts`, and the
463
- preset key is not a contract the renderer can see from the value alone. An object carrying a
464
- `posts` ARRAY OF OBJECTS is what makes "3 posts" a true sentence about it, whoever wrote it.
465
- ═══ */
466
- export interface PostSummary {
467
- shortcode?: string;
468
- url?: string;
469
- posted_at?: string;
470
- type?: string;
471
- caption?: string;
472
- /** β›” `undefined` when the metric was not bought. Never 0 β€” see the note above. */
473
- views?: number;
474
- likes?: number;
475
- comments?: number;
476
- }
477
-
478
- export interface PostsWindow {
479
- /** The engine's own count. May differ from `posts.length`; readers show the LENGTH, because
480
- * that is the number a reader can check against what is in front of them. */
481
- n: number;
482
- metrics: boolean;
483
- as_of?: string;
484
- posts: PostSummary[];
485
- }
486
-
487
- function str(v: unknown): string | undefined {
488
- return typeof v === "string" && v !== "" ? v : undefined;
489
- }
490
-
491
- /** β›” A number ONLY when the key really holds one. `undefined` for absent, for null, and for a
492
- * non-numeric β€” anything else invents a measurement. */
493
- function metric(v: unknown): number | undefined {
494
- return typeof v === "number" && Number.isFinite(v) ? v : undefined;
495
- }
496
-
497
- /** The window behind an ALREADY-PARSED value, or null when this is not one. */
498
- export function postsWindowOf(value: unknown): PostsWindow | null {
499
- if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
500
- const doc = value as Record<string, unknown>;
501
- const rows = doc.posts;
502
- if (!Array.isArray(rows)) return null;
503
- if (!rows.every((r) => r !== null && typeof r === "object" && !Array.isArray(r))) return null;
504
- const posts: PostSummary[] = rows.map((r) => {
505
- const p = r as Record<string, unknown>;
506
- return {
507
- shortcode: str(p.shortcode),
508
- url: str(p.url),
509
- posted_at: str(p.posted_at),
510
- type: str(p.type),
511
- caption: str(p.caption),
512
- views: metric(p.views),
513
- likes: metric(p.likes),
514
- comments: metric(p.comments),
515
- };
516
- });
517
- return {
518
- n: typeof doc.n === "number" ? doc.n : posts.length,
519
- metrics: doc.metrics === true,
520
- as_of: str(doc.as_of),
521
- posts,
522
- };
523
- }
524
-
525
- /** The window behind a stored CELL, or null. */
526
- export function postsWindow(v: CellValue): PostsWindow | null {
527
- const parsed = jsonParse(v);
528
- return parsed.ok ? postsWindowOf(parsed.value) : null;
529
- }
530
-
531
- /** A nested value, small enough to sit inside a one-pair preview. Objects and arrays collapse
532
- * to their own marks rather than recursing β€” a preview that unfolds is not a preview. */
533
- function scalarText(v: unknown): string {
534
- if (v === null) return "null";
535
- if (Array.isArray(v)) return `[…] ${v.length}`;
536
- if (typeof v === "object") return `{…} ${Object.keys(v as object).length}`;
537
- return typeof v === "string" ? v : String(v);
538
- }
539
-
540
- /** ⚠ An ellipsis CHARACTER, not three dots: the grid's canvas measures text and three periods
541
- * are three glyphs wide. Same mark the group-bar fitter uses. */
542
- function clip(s: string, n: number): string {
543
- return s.length <= n ? s : s.slice(0, n - 1) + "…";
544
- }
545
-
546
- /**
547
- * The document, indented for the viewer's pretty tab. Returns the RAW TEXT UNCHANGED when it
548
- * does not parse β€” re-indenting is not repair, and handing a reader a "prettified" version of
549
- * something the app could not read would hide the only thing they need to see.
550
- */
551
- export function jsonPretty(v: CellValue): string {
552
- const raw = String(v ?? "");
553
- const parsed = jsonParse(raw);
554
- return parsed.ok ? JSON.stringify(parsed.value, null, 2) : raw;
555
- }
556
-
557
- /**
558
- * Wave-5 item 11 β€” the actionable link behind a url/email/phone value, or null when the value
559
- * does not parse as one (the raw text still shows; a link that goes nowhere is worse than no
560
- * link). url without a scheme gets https://; `javascript:` can never come out of here.
561
- *
562
- * ⭐ MOVED here from `RecordDetail.tsx` for wave-26 item 11, when the KANBAN CARD became a
563
- * second surface that needs it. Two copies of a scheme guard is how one of them ends up
564
- * accepting `javascript:` β€” the same argument that moved `formatDisplay`'s formula test into one
565
- * function after the canvas and the panel had drifted. It is also the only reason this claim is
566
- * testable at all: both call sites are React components, and this module is glide-free and
567
- * React-free, so a node gate can reach it.
568
- */
569
- export function actionHref(field: Field, v: CellValue): string | null {
570
- const s = String(v ?? "").trim();
571
- if (!s) return null;
572
- if (field.type === "url") {
573
- if (/^https?:\/\//i.test(s)) return s;
574
- if (/^[\w-]+(\.[\w-]+)+/.test(s)) return `https://${s}`;
575
- return null;
576
- }
577
- if (field.type === "email")
578
- return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s) ? `mailto:${s}` : null;
579
- if (field.type === "phone") {
580
- const digits = s.replace(/[\s().-]/g, "");
581
- return /^\+?\d{5,}$/.test(digits) ? `tel:${digits}` : null;
582
- }
583
- return null;
584
- }
585
-
586
- export function formatDisplay(field: Field, v: CellValue): string {
587
- switch (field.type) {
588
- case "currency":
589
- return v == null || v === "" ? "" : "$" + numberText(num(v), field.format);
590
- case "formula": {
591
- // β›” A FORMULA MAY RETURN TEXT (owner item 2, 2026-07-31 β€” CONCATENATE, `&`, TEXT(),
592
- // and any `IF(cond, "yes", "no")`). `makeCell` learned that; this function did not, and
593
- // the two are supposed to be one rendering. So every surface that reads THIS one β€”
594
- // ListView, KanbanView, the calendar's summary cells, the record-detail panel and ALL
595
- // FOUR export formats β€” printed a text result as `0`, because `num("Buy now")` is NaN.
596
- // The canvas showed the words and the file showed a zero, for the same cell.
597
- //
598
- // Found by rendering the owner's own Buy signal formula through the shipped bundle
599
- // (_qa_owner_20260803). The branch below is `makeCell`'s test, verbatim: a non-blank,
600
- // non-numeric STRING is its own display.
601
- // The three states, in the one order that makes them total β€” see `formulaIsBlank`.
602
- if (formulaIsBlank(v)) return "";
603
- if (formulaIsText(v)) return v;
604
- return numberText(num(v), field.format);
605
- }
606
- case "int":
607
- return v == null || v === "" ? "" : numberText(num(v), field.format);
608
- case "pct":
609
- return v == null || v === "" ? "" : num(v).toFixed(1) + "%";
610
- case "date":
611
- case "created_time":
612
- return dateTimeText(field, v);
613
- case "checkbox":
614
- return checkboxOn(v) ? "Checked" : "";
615
- case "rating": {
616
- const n = num(v);
617
- return n >= 1 ? `${Math.round(n)} of ${ratingMax(field)}` : "";
618
- }
619
- case "json":
620
- // Wave-23 C7 β€” the SAME compact line the canvas cell paints. Explicit here rather than
621
- // left to `default` for the reason the `formula` note above records: this function feeds
622
- // ListView, KanbanView, the calendar, the record panel and all four EXPORT formats, and
623
- // falling through would dump a whole 32 KB document into a CSV cell.
624
- return jsonPreview(v);
625
- case "code":
626
- // ⭐ Wave-27 item 13 (R13) β€” the same compact line the canvas cell paints, and explicit
627
- // for `json`'s exact reason: a snippet is multi-LINE, and falling through to `default`
628
- // would put raw newlines into a CSV cell, a kanban card and a calendar chip.
629
- return codePreview(v);
630
- case "automation":
631
- // The machine-written line, verbatim. Explicit rather than left to the `default` branch
632
- // below: `formula` fell through a default once and printed every text result as `0` for
633
- // months, and the lesson recorded there is that a type whose rendering is deliberate
634
- // should SAY so where a reader looks for it.
635
- return String(v ?? "");
636
- case "metric":
637
- // Wave-22 C7 β€” a server-computed number over the master snapshot series. BLANK IS A
638
- // STATE, never zero: the engine sends "" when the window holds no snapshots, and
639
- // rendering that as 0 would fabricate a measurement (the engine's own blank-never-zero
640
- // law, kept at the display seam too).
641
- return v == null || v === "" ? "" : numberText(num(v), field.format);
642
- case "rollup": {
643
- // ⭐ WAVE 29 (W29-T30) β€” THE MISSING CASE. `rollup` fell through to `default` and printed
644
- // its raw fold string, so ONE cell rendered two ways: the canvas showed `1,491,552.43`
645
- // (`cells.ts`'s rollup branch, comma-fixed 2026-08-10 on the owner's instruction) while
646
- // every CSV, PDF, JSON-display and Excel export showed `1491552.43`. Same family as D-121
647
- // (the record panel ignoring a field's format) β€” three surfaces, one concept.
648
- //
649
- // β›” THE BLANK RULE IS THE POINT, and it is why this is a guarded branch and not a call to
650
- // `numberText(num(v), ...)`. `_rollup_fold` returns "" for "no rows to aggregate" and only
651
- // the count family ever returns a real 0, so `num("")` β€” which is 0 β€” would paint the
652
- // measurement the server just refused to invent. A fold that is not a number at all
653
- // (`concatenate`, `arrayunique`, `latest` over text) keeps its own text.
654
- // β‡’ Mirrors `cells.ts`'s branch line for line, deliberately: one concept, one rendering.
655
- const raw = String(v ?? "");
656
- const asNum = raw.trim() === "" ? NaN : Number(raw);
657
- return Number.isFinite(asNum) ? numberText(asNum, field.format) : raw;
658
- }
659
- case "multiselect":
660
- // The comma-joined SET, read back with breathing room ("A, B" not "A,B").
661
- return String(v ?? "")
662
- .split(",")
663
- .map((s) => s.trim())
664
- .filter((s) => s !== "")
665
- .join(", ");
666
- default:
667
- return String(v ?? "");
668
- }
669
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / display.ts
3
+ // The pure DISPLAY-STRING half of cells.ts, split out in wave 7 (item W2): the
4
+ // export builders run under node in the verify gates, and importing them
5
+ // through cells.ts dragged the whole glide-data-grid package into a plain
6
+ // script. Everything here depends only on types.ts. cells.ts re-exports these
7
+ // names, so every existing import keeps working; the formatting is the same
8
+ // bytes it was β€” this is a move, not a change.
9
+ // ---------------------------------------------------------------------------
10
+
11
+ import type { Field, FieldFormat } from "./types";
12
+ import { ratingMax } from "./types";
13
+
14
+ export type CellValue = string | number | null | undefined;
15
+
16
+ // --- C-AVATAR (wave-14 item 11): the two PURE halves of the assignee avatar ---
17
+ // They live here rather than in cells.ts for this module's founding reason: cells.ts imports
18
+ // glide, so nothing in it can be reached by a node gate. The canvas drawing stays there; the
19
+ // arithmetic and the string handling β€” the parts that can be wrong in ways a screenshot of one
20
+ // avatar will not show β€” are here, and `cells.ts` re-exports both.
21
+
22
+ /**
23
+ * Up to two letters for the fallback circle.
24
+ *
25
+ * ⚠ The LOCAL PART only. Usernames in this tenant are email-shaped, and splitting
26
+ * "fsanyoto@gmail.com" on its separators gives ["fsanyoto@gmail", "com"] β†’ "FC" β€” a person's
27
+ * avatar reading as their mail provider. Cutting at "@" first gives "FS".
28
+ *
29
+ * ⚠ A HYPHEN IS NOT A SEPARATOR. Space, dot and underscore divide a given name from a family
30
+ * name in a username; a hyphen almost always JOINS a compound one β€” Jo-Anne, Marie-Claire,
31
+ * Al-Rashid. Treating it as a separator turns "jo-anne_smith" into "JA", which is not that
32
+ * person's initials and is wrong in the one way nobody can spot: it looks like initials.
33
+ */
34
+ export function avatarInitials(name: string): string {
35
+ const local = name.split("@")[0];
36
+ const parts = local.trim().split(/[\s._]+/).filter(Boolean);
37
+ if (parts.length === 0) return "?";
38
+ if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
39
+ return (parts[0][0] + parts[1][0]).toUpperCase();
40
+ }
41
+
42
+ /**
43
+ * The avatar's diameter for a row of `height` px: 22 on a comfortable row, never larger, and
44
+ * never so small it stops being a face. Bounded on BOTH sides on purpose β€” a `tall` row (48px)
45
+ * must not grow a 42px portrait, and a `short` one (28px) must not shrink to a dot.
46
+ */
47
+ export function avatarSize(height: number): number {
48
+ return Math.max(14, Math.min(22, height - 6));
49
+ }
50
+
51
+ export interface UserCellData {
52
+ kind: "aios-user";
53
+ /** The assignee's username. "" = unassigned; the cell then paints nothing at all. */
54
+ name: string;
55
+ /** C-AVATAR data URL, when the workspace served one for this user. */
56
+ photo?: string;
57
+ }
58
+
59
+ /**
60
+ * The `user` cell's payload β€” HERE rather than inline in `cells.ts` for one reason: `copyData`.
61
+ *
62
+ * ⚠ R6 removed the NAME from the cell, so the cell renders no text at all. glide's copy and
63
+ * export take `copyData`, which means an assignee column silently copies and exports as EMPTY
64
+ * unless it is set β€” a real regression that appears in no screenshot, because the screenshot
65
+ * shows the avatar working perfectly. `cells.ts` imports glide and is therefore unreachable from
66
+ * a node gate; this is, so the claim can actually be asserted.
67
+ */
68
+ export function userCellPayload(
69
+ name: string,
70
+ userAvatars?: Record<string, string>
71
+ ): { data: UserCellData; copyData: string } {
72
+ return {
73
+ data: { kind: "aios-user", name, photo: userAvatars?.[name] },
74
+ copyData: name,
75
+ };
76
+ }
77
+
78
+ /**
79
+ * The number to PAINT, with `0` as the fallback every existing caller already relies on.
80
+ *
81
+ * β›”β›” IT MUST PARSE THE SAME WAY THE FOLD DOES, AND FOR ONE COMMIT IT DID NOT. This was a bare
82
+ * `Number(v)`, so `"1,234.50"` β†’ `NaN` β†’ **0**: the canvas painted `$0` while the totals row
83
+ * underneath counted 1,234.5. The T81 fix that introduced `numericIsBlank` made the BLANK
84
+ * decision consistent and left the VALUE on this function, so the cell stopped being blank and
85
+ * started being a fabricated zero β€” the exact defect T81 exists to kill, one step to the right.
86
+ * ⚠ Caught by an adversarial read, NOT by the leg named "the fold counts exactly what the cell
87
+ * shows" β€” which only ever called `computeAggs` and never evaluated what the cell shows. A test
88
+ * whose NAME makes a claim its assertion does not is worse than no test.
89
+ * ⚠ REACHABLE, and by more than one path: the import door refuses-without-rewriting (so `$45`
90
+ * is storable by design, and `api_api` asserts it imports), and `automation_engine._rollup_fold`
91
+ * returns raw source cells as STRINGS for `latest`/`min`/`max`.
92
+ */
93
+ export function num(v: CellValue): number {
94
+ return numericOrUndefined(v) ?? 0;
95
+ }
96
+
97
+ /**
98
+ * β›” W29-T81 β€” HAS THIS NUMERIC CELL NOTHING TO SHOW? Blank, or a stored value that is not a
99
+ * number at all.
100
+ *
101
+ * `num()` above answers **0** for anything unparseable, which is a measurement where there was
102
+ * none. That is survivable for a column only this app writes; it stopped being survivable when
103
+ * the import door began accepting rows from a spreadsheet β€” a `qty` column holding
104
+ * "seventeen-ish" painted `0` on the canvas while the record panel honestly showed an em-dash.
105
+ * Two surfaces disagreeing about the same cell, and the one that looks authoritative is the one
106
+ * making the number up.
107
+ *
108
+ * ⚠ The FOLD was already right (`aggregations.numOf` skips what will not parse), so the totals
109
+ * row never counted these β€” it is the painted cell alone. Same family as `formulaIsText` below,
110
+ * asked of the RAW value for the same reason.
111
+ * ⚠ `" "` is blank, not a zero: `Number(" ")` is 0, which is how a whitespace cell becomes a
112
+ * number nobody typed.
113
+ */
114
+ export function numericIsBlank(v: CellValue): boolean {
115
+ return numericOrUndefined(v) === undefined;
116
+ }
117
+
118
+ /**
119
+ * β›”β›” THE ONE NUMERIC READING OF A STORED CELL, and it has to be one.
120
+ *
121
+ * `numericIsBlank` decides whether the CANVAS paints anything; `aggregations.numOf` decides
122
+ * whether the TOTALS ROW counts it. They were written separately and normalised differently β€”
123
+ * this one trimmed, that one stripped `$`, `,` and spaces β€” so `"1,234.50"` painted BLANK in the
124
+ * cell and was COUNTED in the total underneath it. That is T81's own defect ("two surfaces
125
+ * disagreeing about one cell") reintroduced in the opposite direction, by the fix for it, and no
126
+ * test could see it because every value in the legs was comma-free.
127
+ *
128
+ * ⚠ Human spellings are ACCEPTED here on purpose. `coerceClipboardValue` canonicalises what the
129
+ * UI writes, but the import door refuses-without-rewriting by design, so a `"$45"` posted by curl
130
+ * is storable β€” and the honest reading of that cell is 45 on BOTH surfaces, never 45 in the total
131
+ * and nothing in the cell ([[one-evaluator-per-question]]).
132
+ */
133
+ export function numericOrUndefined(v: CellValue): number | undefined {
134
+ if (v === null || v === undefined || v === "") return undefined;
135
+ if (typeof v === "number") return Number.isFinite(v) ? v : undefined;
136
+ const cleaned = String(v).replace(/[$,\s]/g, "");
137
+ if (cleaned === "") return undefined; // " " is blank, not the zero `Number("")` gives
138
+ const n = Number(cleaned);
139
+ return Number.isFinite(n) ? n : undefined;
140
+ }
141
+
142
+ /**
143
+ * β›” IS THIS FORMULA RESULT TEXT? β€” and it must be asked of the RAW value.
144
+ *
145
+ * A formula may return text since 2026-07-31 (owner item 2: CONCATENATE, `&`, TEXT(),
146
+ * TRUE/FALSE, and any `IF(cond, "yes", "no")`). Both renderers tried to detect that with
147
+ * `!Number.isFinite(num(v))` β€” and `num()` above returns **0** for anything non-finite, so the
148
+ * test was `Number.isFinite(0)`, which is always true. The text branch therefore never ran in
149
+ * EITHER renderer, and every text-returning formula printed as `0`: on the canvas, in the list,
150
+ * on kanban cards, in the record panel and in all four export formats.
151
+ *
152
+ * The feature had never worked. It surfaced by rendering the owner's own Buy signal formula
153
+ * through the shipped bundle rather than by asking whether the code looked right.
154
+ *
155
+ * ONE function, exported, called by both `formatDisplay` and `makeCell` β€” they are meant to be
156
+ * one rendering, and the way they drifted was each holding its own copy of this test.
157
+ * `Number("")` is 0, so the empty case is excluded explicitly rather than relied upon.
158
+ *
159
+ * A TYPE PREDICATE, not a bare boolean: `makeCell` builds a `TextCell` from the value straight
160
+ * after this test, and without the narrowing the caller has to re-assert the string it just
161
+ * proved β€” which is the kind of cast that outlives the reason for it.
162
+ */
163
+ export function formulaIsText(v: CellValue): v is string {
164
+ return typeof v === "string" && v.trim() !== "" && !Number.isFinite(Number(v));
165
+ }
166
+
167
+ /**
168
+ * β›” AND THE BLANK TEST HAS TO AGREE WITH IT, or a value falls between the two.
169
+ *
170
+ * `formulaIsText` excludes whitespace-only strings (a `" "` result is not TEXT worth painting).
171
+ * The callers' own blank guard was `v === ""`, which does not catch `" "` β€” so a formula
172
+ * returning a space matched NEITHER, fell through to the numeric path, and printed `0`, because
173
+ * `Number(" ")` is 0. The exact bug this pair was written to fix, surviving in a narrower case.
174
+ *
175
+ * A formula's result is therefore one of exactly three things, and these two predicates make the
176
+ * three TOTAL: blank (null, empty, or whitespace), text, or a number. Reachable in practice β€”
177
+ * `CONCATENATE(" ", "")` is a space, and so is `TRIM()` of one.
178
+ */
179
+ export function formulaIsBlank(v: CellValue): boolean {
180
+ return v == null || (typeof v === "string" && v.trim() === "");
181
+ }
182
+
183
+ /** A checkbox cell's boolean, out of the overlay's '1'-or-empty contract. */
184
+ export function checkboxOn(v: CellValue | boolean): boolean {
185
+ return v === "1" || v === 1 || v === true;
186
+ }
187
+
188
+ /**
189
+ * Item 10 β€” the number DISPLAY string. With no format: exactly the pre-wave-5
190
+ * rendering (toLocaleString). `abbrev` wins over decimals when the magnitude
191
+ * calls for it (34.0M β€” one decimal, k/M/B); `thousands: false` drops the
192
+ * separators; `decimals` fixes 0..4 places.
193
+ */
194
+ export function numberText(v: number, fmt: FieldFormat | undefined): string {
195
+ if (fmt?.abbrev && Math.abs(v) >= 1000) {
196
+ const abs = Math.abs(v);
197
+ const [div, suffix] =
198
+ abs >= 1e9 ? [1e9, "B"] : abs >= 1e6 ? [1e6, "M"] : [1e3, "k"];
199
+ return (v / div).toFixed(1) + suffix;
200
+ }
201
+ const d =
202
+ fmt && Number.isInteger(fmt.decimals) && (fmt.decimals as number) >= 0 &&
203
+ (fmt.decimals as number) <= 4
204
+ ? (fmt.decimals as number)
205
+ : null;
206
+ const thousands = fmt?.thousands !== false;
207
+ if (d != null)
208
+ return thousands
209
+ ? v.toLocaleString(undefined, {
210
+ minimumFractionDigits: d,
211
+ maximumFractionDigits: d,
212
+ })
213
+ : v.toFixed(d);
214
+ return thousands ? v.toLocaleString() : String(v);
215
+ }
216
+
217
+ /**
218
+ * Parse a stored date/datetime string. Odoo datetimes arrive as
219
+ * "YYYY-MM-DD HH:MM:SS" and are UTC by Odoo convention, so a time-carrying
220
+ * value with no zone gets a Z; a bare date keeps today's parse (UTC midnight)
221
+ * so format-less rendering stays byte-identical to the pre-wave-5 path.
222
+ *
223
+ * ⭐ EXPORTED in wave 29 (W29-T30) because the xlsx writer needs a Date to turn
224
+ * into an Excel serial, and the alternative was a SECOND date parser in
225
+ * `export.ts` β€” two evaluators for one question, which is how the two drift and
226
+ * a stamp exports as a different day than it renders
227
+ * ([[one-evaluator-per-question]]). It stays the only parser in this module.
228
+ */
229
+ export function parseStamp(raw: string): Date | null {
230
+ const s = raw.includes(" ") ? raw.replace(" ", "T") : raw;
231
+ const iso =
232
+ /T\d{2}:\d{2}/.test(s) && !/(?:[zZ]|[+-]\d{2}:?\d{2})$/.test(s) ? s + "Z" : s;
233
+ const d = new Date(iso);
234
+ return Number.isNaN(d.getTime()) ? null : d;
235
+ }
236
+
237
+ /** A BARE calendar day: the shape Odoo sends for a `date`, and the shape wave 26's migration
238
+ * converted the Instagram preset stamps into. `parseStamp` gives it UTC midnight. */
239
+ const BARE_DAY = /^\d{4}-\d{2}-\d{2}$/;
240
+
241
+ /**
242
+ * Is this stored value a calendar DAY rather than an INSTANT? β€” the question that decides which
243
+ * clock renders it (see `dateTimeText`).
244
+ *
245
+ * Exported, and it is the whole reason the test for this is worth anything: the alternative is
246
+ * asserting a rendered string, which depends on the machine's timezone β€” so the check would pass
247
+ * on the owner's box (+07:00, where the two clocks agree on the day) and could only ever go red
248
+ * somewhere else. A predicate is the same decision with no ambient state in it.
249
+ *
250
+ * ⚠ The SHAPE OF THE RAW STRING, never `field.type`: wave 26 re-typed columns that hold full ISO
251
+ * stamps to `date`, so one `date` field can carry both shapes at once during a migration.
252
+ */
253
+ export function isBareDay(v: CellValue): boolean {
254
+ return BARE_DAY.test(String(v ?? "").trim());
255
+ }
256
+
257
+ /**
258
+ * ⭐ Wave-26 item 3 (owner, R3) β€” the day, spelled. `Aug 5, 2026`, never `8/5/2026` and never
259
+ * the raw stamp. One vocabulary for the date half whether or not a time follows it, so a
260
+ * `date` column and a `created_time` column in the same table read alike.
261
+ */
262
+ const DAY_PARTS = { year: "numeric", month: "short", day: "numeric" } as const;
263
+
264
+ /**
265
+ * Item 10 β€” the date DISPLAY string. `time` includes the time of day
266
+ * (created_time defaults to true β€” a creation stamp without its time reads as
267
+ * a duplicate of nothing); `tz: 'utc'` renders the tenant-neutral clock.
268
+ * Unparseable input renders VERBATIM rather than "Invalid Date" β€” the raw
269
+ * string is at least true.
270
+ *
271
+ * ⭐ WAVE 26 ITEM 3 (owner, via R3). The complaint was literal: cells read
272
+ * `2026-08-05T14:03:11+07:00`. SESSION A's half re-typed the Instagram preset
273
+ * columns from `text` to `date` (which is what routed them here at all) and
274
+ * migrated the stored cells to bare `YYYY-MM-DD`; this half is that a date must
275
+ * READ as one. Two changes, and the second is the one that is not cosmetic:
276
+ *
277
+ * β›” **A BARE `YYYY-MM-DD` IS A CALENDAR DAY, NOT AN INSTANT, so it renders in
278
+ * UTC.** `parseStamp` gives a bare date UTC midnight, so rendering it in the
279
+ * viewer's local zone shows the PREVIOUS DAY to everyone west of Greenwich β€” a
280
+ * value stored as the 5th reading as the 4th, silently, for a whole hemisphere.
281
+ * `ui/fmt.ts:date()` already refused to inherit this and its comment names this
282
+ * function as the holdout; it is no longer one. The tenant runs at +07:00, where
283
+ * the two agree, which is exactly why it could sit here unnoticed β€” and why the
284
+ * US market in COMMERCIALIZATION_PLAN C1b would have met it first.
285
+ *
286
+ * A value that CARRIES a time is a real instant and keeps the existing zone
287
+ * behaviour (local, or UTC when the field says so): shifting those to UTC would
288
+ * introduce the same off-by-a-day from the other direction.
289
+ */
290
+ export function dateTimeText(
291
+ // ⚠ STRUCTURAL, not `Field`: this reads exactly two members, and item 8's post rows hold a
292
+ // raw `posted_at` with no column behind it. Widening the parameter (rather than fabricating a
293
+ // fake Field at the call site) is what lets the posts list render its days through the SAME
294
+ // formatter as a date cell instead of growing a second one. Every existing caller passes a
295
+ // `Field`, which is assignable.
296
+ field: { type: Field["type"]; format?: FieldFormat },
297
+ v: CellValue
298
+ ): string {
299
+ if (v == null || v === "") return "";
300
+ const raw = String(v);
301
+ const d = parseStamp(raw);
302
+ if (!d) return raw;
303
+ const fmt = field.format;
304
+ const withTime = fmt?.time ?? field.type === "created_time";
305
+ const utc = fmt?.tz === "utc" || isBareDay(raw);
306
+ const zone = utc ? { timeZone: "UTC" as const } : undefined;
307
+ return withTime
308
+ ? d.toLocaleString(undefined, {
309
+ ...DAY_PARTS,
310
+ hour: "numeric",
311
+ minute: "2-digit",
312
+ second: "2-digit",
313
+ ...zone,
314
+ })
315
+ : d.toLocaleDateString(undefined, { ...DAY_PARTS, ...zone });
316
+ }
317
+
318
+ /**
319
+ * The plain-string rendering of one (field, value), mirroring makeCell's
320
+ * displayData. Reused by the record-detail panel and the W2 export builders so
321
+ * a value reads identically on the canvas, in the panel and in a file. Returns
322
+ * "" for empty so callers can substitute their own placeholder.
323
+ */
324
+ /**
325
+ * Wave-18 C5-AUTOFIELD β€” the STATE word of an automation cell.
326
+ *
327
+ * An automation cell holds one machine-written line: `state Β· when Β· detail`, e.g.
328
+ * `ok Β· 2026-08-03 14:10 Β· 12 posts`. The state is the first token, and every surface that
329
+ * paints the cell β€” canvas tint, record modal, the rail β€” reads it through HERE rather than
330
+ * re-splitting the string, because two parsers of one format is how the canvas and the panel
331
+ * end up disagreeing about whether a run succeeded (the exact way `formula` broke above).
332
+ *
333
+ * `"none"` is the honest answer for a cell nothing has written yet β€” NOT "ok". A column that
334
+ * has never run must not look like a column that ran and found nothing.
335
+ */
336
+ export type AutomationState = "ok" | "partial" | "error" | "blocked" | "queued" | "none";
337
+
338
+ const AUTOMATION_STATES: AutomationState[] = ["ok", "partial", "error", "blocked", "queued"];
339
+
340
+ export function automationState(v: CellValue): AutomationState {
341
+ const head = String(v ?? "").split("Β·")[0].trim().toLowerCase();
342
+ return (AUTOMATION_STATES as string[]).includes(head)
343
+ ? (head as AutomationState)
344
+ : "none";
345
+ }
346
+
347
+ /** Everything after the state word β€” the timestamp and the run's own detail. */
348
+ export function automationDetail(v: CellValue): string {
349
+ const parts = String(v ?? "").split("Β·");
350
+ return parts.length > 1 ? parts.slice(1).join("Β·").trim() : "";
351
+ }
352
+
353
+ /** Sentence-cased state, for anywhere a word reads better than a token. */
354
+ export function automationStateLabel(v: CellValue): string {
355
+ const s = automationState(v);
356
+ return s === "none" ? "Not run yet" : s[0].toUpperCase() + s.slice(1);
357
+ }
358
+
359
+ /**
360
+ * ⭐ Wave-23 C7 (owner item 5) β€” THE JSON PREVIEW: what a 200px cell says about a document.
361
+ *
362
+ * `MAX_JSON_BYTES` is the contract's ceiling, mirrored from the host's write validation so the
363
+ * viewer can refuse a paste with the same number the server would (a client that lets you type
364
+ * 40 KB and then shows you a server refusal has wasted the edit).
365
+ *
366
+ * The four cases, and each one is a decision rather than a formatting preference:
367
+ * Β· **a single-pair object shows THE PAIR.** `{handle: "royalimports"}` is more useful than
368
+ * "1 key" and it is the shape most machine writes actually have. Past one pair the pairs
369
+ * stop fitting and the honest answer is the count.
370
+ * Β· **many keys / many items β†’ `{…} N keys` / `[…] N items`.** Showing the FIRST pair of a
371
+ * twelve-key object would let a reader take one arbitrary value β€” whichever key the writer's
372
+ * serializer happened to emit first β€” for the cell's content.
373
+ * Β· **a bare scalar renders as itself.** `12`, `"ok"`, `true` and `null` are all valid JSON
374
+ * documents, and wrapping them in braces would describe a shape they do not have.
375
+ * Β· β›” **text that does not parse renders AS ITSELF, never as a shape.** The host validates on
376
+ * write, so this only happens to a value that predates the validation or arrived another
377
+ * way β€” and the one thing the preview must never do is claim a document is well-formed. The
378
+ * viewer's raw tab is where such a value gets read and repaired.
379
+ *
380
+ * Blank stays blank: an empty json cell is a document nobody has written, and `{}` is a document
381
+ * somebody wrote that is empty. Two different facts, two different cells.
382
+ */
383
+ export const MAX_JSON_BYTES = 32 * 1024;
384
+
385
+ /** Does this text parse as JSON? The ONE test, shared by the preview, the cell and the viewer's
386
+ * save β€” three copies of a try/catch is how they end up disagreeing about `""` or `NaN`. */
387
+ export function jsonParse(v: CellValue): { ok: boolean; value?: unknown } {
388
+ const s = String(v ?? "").trim();
389
+ if (s === "") return { ok: false };
390
+ try {
391
+ return { ok: true, value: JSON.parse(s) as unknown };
392
+ } catch {
393
+ return { ok: false };
394
+ }
395
+ }
396
+
397
+ /**
398
+ * ⭐ WAVE-27 item 13 (R13) β€” one compact line for a CODE cell.
399
+ *
400
+ * Deliberately NOT `jsonPreview`, and the difference is the whole reason `code` is its own kind:
401
+ * a json preview SUMMARISES a parsed document ("{…} 5 keys"), which it can only do because the
402
+ * value is guaranteed to parse. A snippet has no structure to summarise and often does not parse
403
+ * at all β€” half-written SQL is the normal state of one β€” so the honest preview is the first
404
+ * non-blank LINE, clipped, plus the line count when there is more underneath. That way the cell
405
+ * says what the snippet starts with AND that there is more, instead of inventing a shape for it.
406
+ */
407
+ export function codePreview(v: CellValue): string {
408
+ const raw = String(v ?? "");
409
+ if (raw.trim() === "") return "";
410
+ const lines = raw.split("\n");
411
+ const firstIdx = lines.findIndex((l) => l.trim() !== "");
412
+ const first = clip((lines[firstIdx < 0 ? 0 : firstIdx] ?? "").trim(), 60);
413
+ // The count is of REAL lines, so a snippet padded with blank lines does not claim depth it
414
+ // does not have β€” and it is checkable against what opening the editor shows
415
+ // ([[no-unverifiable-aggregates]]).
416
+ const n = lines.filter((l) => l.trim() !== "").length;
417
+ return n > 1 ? `${first} +${n - 1} more` : first;
418
+ }
419
+
420
+ /** One compact line for a json cell. See the note above for why each case reads as it does. */
421
+ export function jsonPreview(v: CellValue): string {
422
+ const raw = String(v ?? "").trim();
423
+ if (raw === "") return "";
424
+ const parsed = jsonParse(raw);
425
+ // ⚠ First line only, and clipped: an unparseable value is often a whole pasted response, and
426
+ // a cell is not where a 4 KB blob gets read. It is shown rather than hidden because the
427
+ // reader has to be able to see that the column holds something the app could not open.
428
+ if (!parsed.ok) return clip(raw.split("\n")[0], 60);
429
+ const value = parsed.value;
430
+ // ⭐ ITEM 8 β€” a posts window says what it holds. Before wave 26 this document fell through to
431
+ // the generic object branch and every creator's `posts` cell read `{…} 4 keys`, which is true
432
+ // about JSON and says nothing about the record.
433
+ // ⚠ The ARRAY LENGTH, never the document's own `n`: the count in a cell has to be checkable
434
+ // against what opening it shows ([[no-unverifiable-aggregates]]).
435
+ const shown = postsWindowOf(value);
436
+ if (shown)
437
+ return shown.posts.length === 0
438
+ ? "No posts"
439
+ : `${shown.posts.length} post${shown.posts.length === 1 ? "" : "s"}`;
440
+ if (Array.isArray(value))
441
+ return value.length === 0 ? "[]" : `[…] ${value.length} item${value.length === 1 ? "" : "s"}`;
442
+ if (value !== null && typeof value === "object") {
443
+ const keys = Object.keys(value as Record<string, unknown>);
444
+ if (keys.length === 0) return "{}";
445
+ if (keys.length === 1)
446
+ return clip(`{${keys[0]}: ${scalarText((value as Record<string, unknown>)[keys[0]])}}`, 60);
447
+ return `{…} ${keys.length} keys`;
448
+ }
449
+ return clip(scalarText(value), 60);
450
+ }
451
+
452
+ /** The day, spelled, for a caller holding a raw value and no column β€” the posts list's
453
+ * `posted_at`. Routed through `dateTimeText` so it can never drift from a date CELL. */
454
+ export function dayText(v: CellValue): string {
455
+ return dateTimeText({ type: "date" }, v);
456
+ }
457
+
458
+ /* ═══ ⭐ WAVE 26 ITEM 8 (contract C2) β€” THE `posts` WINDOW ═══
459
+ The preset `posts` cell holds ONE object written by the engine's `posts_window`:
460
+
461
+ { n, metrics, as_of, posts: [{ shortcode, url, posted_at, type, caption,
462
+ views?, likes?, comments? }] }
463
+
464
+ Two laws come with it and both are enforced below rather than in the components:
465
+
466
+ β›” `metrics: false` β‡’ views/likes/comments are ABSENT KEYS, NEVER 0. A reader must render an
467
+ absent metric as NOTHING. Coercing it to a number here β€” `Number(p.views) || 0` is the
468
+ natural thing to type β€” would fabricate a measurement, which is the engine's own
469
+ blank-never-zero law broken at the display seam, silently and plausibly (a creator with no
470
+ metrics bought would read as a creator with no engagement).
471
+
472
+ β›” IT IS A WINDOW, NOT THE HISTORY. `ut_ig_posts` / `ut_ig_post_snapshots` accumulate; this
473
+ cell is the last N (R1/R3 β€” "one store for one series"). So nothing here may present the
474
+ cell as a total.
475
+
476
+ ⚠ DETECTED BY SHAPE, never by the field's key. A user may name a column `posts`, and the
477
+ preset key is not a contract the renderer can see from the value alone. An object carrying a
478
+ `posts` ARRAY OF OBJECTS is what makes "3 posts" a true sentence about it, whoever wrote it.
479
+ ═══ */
480
+ export interface PostSummary {
481
+ shortcode?: string;
482
+ url?: string;
483
+ posted_at?: string;
484
+ type?: string;
485
+ caption?: string;
486
+ /** β›” `undefined` when the metric was not bought. Never 0 β€” see the note above. */
487
+ views?: number;
488
+ likes?: number;
489
+ comments?: number;
490
+ }
491
+
492
+ export interface PostsWindow {
493
+ /** The engine's own count. May differ from `posts.length`; readers show the LENGTH, because
494
+ * that is the number a reader can check against what is in front of them. */
495
+ n: number;
496
+ metrics: boolean;
497
+ as_of?: string;
498
+ posts: PostSummary[];
499
+ }
500
+
501
+ function str(v: unknown): string | undefined {
502
+ return typeof v === "string" && v !== "" ? v : undefined;
503
+ }
504
+
505
+ /** β›” A number ONLY when the key really holds one. `undefined` for absent, for null, and for a
506
+ * non-numeric β€” anything else invents a measurement. */
507
+ function metric(v: unknown): number | undefined {
508
+ return typeof v === "number" && Number.isFinite(v) ? v : undefined;
509
+ }
510
+
511
+ /** The window behind an ALREADY-PARSED value, or null when this is not one. */
512
+ export function postsWindowOf(value: unknown): PostsWindow | null {
513
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
514
+ const doc = value as Record<string, unknown>;
515
+ const rows = doc.posts;
516
+ if (!Array.isArray(rows)) return null;
517
+ if (!rows.every((r) => r !== null && typeof r === "object" && !Array.isArray(r))) return null;
518
+ const posts: PostSummary[] = rows.map((r) => {
519
+ const p = r as Record<string, unknown>;
520
+ return {
521
+ shortcode: str(p.shortcode),
522
+ url: str(p.url),
523
+ posted_at: str(p.posted_at),
524
+ type: str(p.type),
525
+ caption: str(p.caption),
526
+ views: metric(p.views),
527
+ likes: metric(p.likes),
528
+ comments: metric(p.comments),
529
+ };
530
+ });
531
+ return {
532
+ n: typeof doc.n === "number" ? doc.n : posts.length,
533
+ metrics: doc.metrics === true,
534
+ as_of: str(doc.as_of),
535
+ posts,
536
+ };
537
+ }
538
+
539
+ /** The window behind a stored CELL, or null. */
540
+ export function postsWindow(v: CellValue): PostsWindow | null {
541
+ const parsed = jsonParse(v);
542
+ return parsed.ok ? postsWindowOf(parsed.value) : null;
543
+ }
544
+
545
+ /** A nested value, small enough to sit inside a one-pair preview. Objects and arrays collapse
546
+ * to their own marks rather than recursing β€” a preview that unfolds is not a preview. */
547
+ function scalarText(v: unknown): string {
548
+ if (v === null) return "null";
549
+ if (Array.isArray(v)) return `[…] ${v.length}`;
550
+ if (typeof v === "object") return `{…} ${Object.keys(v as object).length}`;
551
+ return typeof v === "string" ? v : String(v);
552
+ }
553
+
554
+ /** ⚠ An ellipsis CHARACTER, not three dots: the grid's canvas measures text and three periods
555
+ * are three glyphs wide. Same mark the group-bar fitter uses. */
556
+ function clip(s: string, n: number): string {
557
+ return s.length <= n ? s : s.slice(0, n - 1) + "…";
558
+ }
559
+
560
+ /**
561
+ * The document, indented for the viewer's pretty tab. Returns the RAW TEXT UNCHANGED when it
562
+ * does not parse β€” re-indenting is not repair, and handing a reader a "prettified" version of
563
+ * something the app could not read would hide the only thing they need to see.
564
+ */
565
+ export function jsonPretty(v: CellValue): string {
566
+ const raw = String(v ?? "");
567
+ const parsed = jsonParse(raw);
568
+ return parsed.ok ? JSON.stringify(parsed.value, null, 2) : raw;
569
+ }
570
+
571
+ /**
572
+ * Wave-5 item 11 β€” the actionable link behind a url/email/phone value, or null when the value
573
+ * does not parse as one (the raw text still shows; a link that goes nowhere is worse than no
574
+ * link). url without a scheme gets https://; `javascript:` can never come out of here.
575
+ *
576
+ * ⭐ MOVED here from `RecordDetail.tsx` for wave-26 item 11, when the KANBAN CARD became a
577
+ * second surface that needs it. Two copies of a scheme guard is how one of them ends up
578
+ * accepting `javascript:` β€” the same argument that moved `formatDisplay`'s formula test into one
579
+ * function after the canvas and the panel had drifted. It is also the only reason this claim is
580
+ * testable at all: both call sites are React components, and this module is glide-free and
581
+ * React-free, so a node gate can reach it.
582
+ */
583
+ export function actionHref(field: Field, v: CellValue): string | null {
584
+ const s = String(v ?? "").trim();
585
+ if (!s) return null;
586
+ if (field.type === "url") {
587
+ if (/^https?:\/\//i.test(s)) return s;
588
+ if (/^[\w-]+(\.[\w-]+)+/.test(s)) return `https://${s}`;
589
+ return null;
590
+ }
591
+ if (field.type === "email")
592
+ return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s) ? `mailto:${s}` : null;
593
+ if (field.type === "phone") {
594
+ const digits = s.replace(/[\s().-]/g, "");
595
+ return /^\+?\d{5,}$/.test(digits) ? `tel:${digits}` : null;
596
+ }
597
+ return null;
598
+ }
599
+
600
+ export function formatDisplay(field: Field, v: CellValue): string {
601
+ switch (field.type) {
602
+ case "currency":
603
+ return v == null || v === "" ? "" : "$" + numberText(num(v), field.format);
604
+ case "formula": {
605
+ // β›” A FORMULA MAY RETURN TEXT (owner item 2, 2026-07-31 β€” CONCATENATE, `&`, TEXT(),
606
+ // and any `IF(cond, "yes", "no")`). `makeCell` learned that; this function did not, and
607
+ // the two are supposed to be one rendering. So every surface that reads THIS one β€”
608
+ // ListView, KanbanView, the calendar's summary cells, the record-detail panel and ALL
609
+ // FOUR export formats β€” printed a text result as `0`, because `num("Buy now")` is NaN.
610
+ // The canvas showed the words and the file showed a zero, for the same cell.
611
+ //
612
+ // Found by rendering the owner's own Buy signal formula through the shipped bundle
613
+ // (_qa_owner_20260803). The branch below is `makeCell`'s test, verbatim: a non-blank,
614
+ // non-numeric STRING is its own display.
615
+ // The three states, in the one order that makes them total β€” see `formulaIsBlank`.
616
+ if (formulaIsBlank(v)) return "";
617
+ if (formulaIsText(v)) return v;
618
+ return numberText(num(v), field.format);
619
+ }
620
+ case "int":
621
+ return v == null || v === "" ? "" : numberText(num(v), field.format);
622
+ case "pct":
623
+ return v == null || v === "" ? "" : num(v).toFixed(1) + "%";
624
+ case "date":
625
+ case "created_time":
626
+ return dateTimeText(field, v);
627
+ case "checkbox":
628
+ return checkboxOn(v) ? "Checked" : "";
629
+ case "rating": {
630
+ const n = num(v);
631
+ return n >= 1 ? `${Math.round(n)} of ${ratingMax(field)}` : "";
632
+ }
633
+ case "json":
634
+ // Wave-23 C7 β€” the SAME compact line the canvas cell paints. Explicit here rather than
635
+ // left to `default` for the reason the `formula` note above records: this function feeds
636
+ // ListView, KanbanView, the calendar, the record panel and all four EXPORT formats, and
637
+ // falling through would dump a whole 32 KB document into a CSV cell.
638
+ return jsonPreview(v);
639
+ case "code":
640
+ // ⭐ Wave-27 item 13 (R13) β€” the same compact line the canvas cell paints, and explicit
641
+ // for `json`'s exact reason: a snippet is multi-LINE, and falling through to `default`
642
+ // would put raw newlines into a CSV cell, a kanban card and a calendar chip.
643
+ return codePreview(v);
644
+ case "automation":
645
+ // The machine-written line, verbatim. Explicit rather than left to the `default` branch
646
+ // below: `formula` fell through a default once and printed every text result as `0` for
647
+ // months, and the lesson recorded there is that a type whose rendering is deliberate
648
+ // should SAY so where a reader looks for it.
649
+ return String(v ?? "");
650
+ case "metric":
651
+ // Wave-22 C7 β€” a server-computed number over the master snapshot series. BLANK IS A
652
+ // STATE, never zero: the engine sends "" when the window holds no snapshots, and
653
+ // rendering that as 0 would fabricate a measurement (the engine's own blank-never-zero
654
+ // law, kept at the display seam too).
655
+ return v == null || v === "" ? "" : numberText(num(v), field.format);
656
+ case "rollup": {
657
+ // ⭐ WAVE 29 (W29-T30) β€” THE MISSING CASE. `rollup` fell through to `default` and printed
658
+ // its raw fold string, so ONE cell rendered two ways: the canvas showed `1,491,552.43`
659
+ // (`cells.ts`'s rollup branch, comma-fixed 2026-08-10 on the owner's instruction) while
660
+ // every CSV, PDF, JSON-display and Excel export showed `1491552.43`. Same family as D-121
661
+ // (the record panel ignoring a field's format) β€” three surfaces, one concept.
662
+ //
663
+ // β›” THE BLANK RULE IS THE POINT, and it is why this is a guarded branch and not a call to
664
+ // `numberText(num(v), ...)`. `_rollup_fold` returns "" for "no rows to aggregate" and only
665
+ // the count family ever returns a real 0, so `num("")` β€” which is 0 β€” would paint the
666
+ // measurement the server just refused to invent. A fold that is not a number at all
667
+ // (`concatenate`, `arrayunique`, `latest` over text) keeps its own text.
668
+ // β‡’ Mirrors `cells.ts`'s branch line for line, deliberately: one concept, one rendering.
669
+ const raw = String(v ?? "");
670
+ const asNum = raw.trim() === "" ? NaN : Number(raw);
671
+ return Number.isFinite(asNum) ? numberText(asNum, field.format) : raw;
672
+ }
673
+ case "multiselect":
674
+ // The comma-joined SET, read back with breathing room ("A, B" not "A,B").
675
+ return String(v ?? "")
676
+ .split(",")
677
+ .map((s) => s.trim())
678
+ .filter((s) => s !== "")
679
+ .join(", ");
680
+ default:
681
+ return String(v ?? "");
682
+ }
683
+ }