import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, } from "react"; import type { CSSProperties, ReactNode } from "react"; import { DataEditor, GridCellKind } from "@glideapps/glide-data-grid"; import type { CellClickedEventArgs, DataEditorRef, EditableGridCell, GridKeyEventArgs, GridMouseEventArgs, GridSelection, DrawCellCallback, DrawHeaderCallback, GridCell, HeaderClickedEventArgs, Item, Rectangle, Theme, } from "@glideapps/glide-data-grid"; import "@glideapps/glide-data-grid/dist/index.css"; import { addressScope, embedStorageKey, hostedFirstView, useCustomerData, useHostedAddress, usePersonalGridLayout, withoutRetiredChoiceEdits } from "./useCustomerData"; import type { SurfaceAddress } from "./useCustomerData"; import { AMAZON_STILL_LOADING_MESSAGE } from "./mirrorLoading"; import type { RowWindowRequest, SurfaceScope, TableRowAcknowledgement } from "./apiBridge"; import { mutateQueryWorkspace, QUERY_BINDING_EVENT } from "../query/queryApi"; import type { QueryVirtualBinding } from "../query/queryApi"; import { acceptsQueryPreview, routeQueryViewMutation } from "./queryPreview"; import { diffViewOps, applyPendingOps, inverseOp, normalizeConfig as normalizeMemberConfig } from "./viewOps"; import type { ViewMemberOp } from "./viewOps"; // ⭐ WAVE 30 · W30-T42 (contract C2) — the WINDOWED grid's arithmetic, pure and node-run in // `verify_grid_ux.py`, because every one of these decisions is taken inside a callback where // only its own source text could otherwise be checked. import { PAGE_SIZES, fetchAggregates, fetchTableWindow, personalGridLayout, readPageSize, recordIdsKey, writePageSize, workspaceReadOrder } from "./apiBridge"; import { ACCESS_REFUSED_MESSAGE } from "./apiBridge"; import { GridPager, pageLabel } from "./GridPager"; import { GridActivity, useNativeActivity } from "./GridActivity"; import { withoutAppliedLeaves } from "./drillLimits"; // ⭐⭐ W50-T03 / CONTRACT C1 — the windowed aggregate's envelope. Lane F serves the route // (W50-T31); this side is written to C1's shape and degrades to the loaded window until it // lands, which is the done-when's own observable rather than a workaround. import type { AggregateRequest, AggregateResult } from "./apiBridge"; import { EMPTY_WINDOW_PREDICATE, importantCountNote, limitSummary, lockedRecordsNote, pagingSummary, serverViewCount, windowedCapabilityNote, windowedFoldNote, windowPredicateKey, } from "./counts"; // ⭐ W35-T29/T30 (C5) — the record star's client, and its own stylesheet imported HERE, by the // module that renders its classes. W35-T22 in this same wave was the cost of doing otherwise. import { useRecordStars } from "./recordStars"; // ⚠ ALIASED, and the collision is worth naming: `./Stars`'s `StarIcon` is the RATING atom (a // 5-point star for a 1..5 field) and this one is the record MARK. Two different meanings, one // noun, already both in this file — importing the second under its own name would have shadowed // the first and silently repainted every rating picker. import { StarIcon as RecordStarMark } from "../ui/icons"; /* ⭐ W51-T06 clause 5 — THE SHARED LOCK GLYPH, never a second drawing of one. DESIGN.md section 4 ("THE THREE LOCKS") gives the product ONE mark, which is exactly why whatever wears it must say in words WHICH lock applies: "the marks are indistinguishable otherwise". */ import { LockMark } from "./icons"; import "./rowStar.css"; import "./chatDock.css"; import ChatDockSeat from "./ChatDockSeat"; import AssistantPanel from "../assistant/AssistantPanel"; import { defaultViewConfig, headerMarksFor, insertColumnConfig, useGridColumns } from "./useGridColumns"; // ⭐⭐ W50-T01 (R1) — `sliceForDisplay` IS NO LONGER IMPORTED. It was the client render cap's // group-safe slicer; the cap is retired, so the grid takes the pipeline's whole result. The // function is still exported from `useVisibleRows.ts` and still covered by `gridUx.test.ts` — // neither file is this ticket's to edit, and an unused export costs nothing. See the handoff. import { activeMeasureRuleIds, matchFilterTree, pendingMeasures, runPipeline, unresolvedConditions, useVisibleRows } from "./useVisibleRows"; import { cleanPercent, computeAggNumbers, computeAggs, formatServerAgg, formatShare, resolveSummary, sharesTheTotal, summaryOptions } from "./aggregations"; // ⭐⭐ W50-T03 (owner instruction 1, R2) — THE SUMMARY BAR. A component rather than a canvas // row, because R2's choice is per COLUMN and per VIEW, and a glide cell can carry a value but // never a menu. See its header for how it borrows the canvas's own column layout. import { SUMMARY_BAR_PX, SummaryBar } from "./summary/SummaryBar"; import type { CohortSets } from "./useVisibleRows"; import type { MeasureSets } from "./useVisibleRows"; import { drawAppCell, useGetCellContent } from "./useGetCellContent"; import { effectiveGridRows, savedValuePredicateNote } from "./effectiveGridRows"; import type { GroupRowPlaceholder } from "./useGetCellContent"; import { useGridSelection } from "./useGridSelection"; import Toolbar from "./Toolbar"; import { useSaveState } from "./SaveState"; import { cellSaveRefusals } from "./cellSaveRefusals"; import { cellNoteText, editOutbox, gridEditScope, patchCellNote, pendingCellEdits, pendingCellNotes } from "./apiBridge"; import CellNoteMenu, { cellNoteRefusal, drawCellNoteMarker } from "./CellNoteMenu"; import type { OutboxEdit } from "./editOutbox"; import { LP_RED_DEEP, LP_YELLOW_DEEP } from "./theme"; import type { AppTableHost } from "./appHostTypes"; import { DatePicker } from "./DatePicker"; import { viewAsActive } from "../settings/viewAs"; /** * ⭐⭐ W51-T03 / OWNER RULING R6 + CONTRACT C8 — THE ONE CONFIRM DIALOG, for every destructive * act this grid can start: a field delete, a view delete and a record delete, plus the duplicate * dialog which is the same shell with a primary button. * * ⛔ IMPORTED FROM THE MODULE, NOT THE `ui` BARREL. `ui/index.ts` does not re-export either of * these (measured), so `from "../ui"` does not compile. * ⛔ AND THIS REPLACES `FieldDeleteImpactDialog`, which was this file's field-delete door and * still lives in `filter-kit/FieldsHidePanel.tsx` for the Fields manager's own row. Two confirm * shapes for one act is what R6 retires; the manager's copy is another lane's fence. */ import { ConfirmDialog, DialogToggle } from "../ui/ConfirmDialog"; // D-673 / W54-T21 - the one Escape arbiter, for the route navigator's own close. import { useEscapeClose } from "../ui/useEscapeClose"; // W49-T17: R32's pre-delete disclosure. A static import is safe here -- nothing else in the // tree imports this component, so it joins THIS chunk rather than pinning another one open // [[tsc-cannot-see-a-broken-code-split]]. import { ViewDeleteDisclosure } from "../connectors/ViewDeleteDisclosure"; import type { ViewDependent, ViewShareAudience } from "../connectors/ViewDeleteDisclosure"; /** What the R32 disclosure needs while it is open, including what it could NOT learn. */ type PendingViewDelete = { id: string; name: string; loading: boolean; dependents: ViewDependent[]; share?: ViewShareAudience; unanswered: string[]; error?: string; }; import JsonViewer from "./JsonViewer"; import RecordDetail from "./RecordDetail"; import ViewSidebar, { viewMoveRefusal } from "./ViewSidebar"; import ColumnMenu from "./ColumnMenu"; import type { ColumnMenuState } from "./ColumnMenu"; import { HEADER_ICONS } from "./iconShapes"; import { bindHostEvent, eventId } from "./hostBridge"; // ⭐ WAVE 27 item 21 (R14) — which of this table's views carry an alert. The SERVER's // list is the only answer; the rail's alert door is a one-way create. import { fetchAlerts } from "../alerts/alertsApi"; import { API_V1, CREDENTIALS, NAV_MINIMIZE_EVENT, ROWS_STALE_EVENT, TOAST_EVENT, VIEW_OPEN_EVENT, WORKSPACE_STALE_EVENT, UNAUTHORIZED_EVENT, checkTenant, signal } from "../apiContract"; import type { ViewOpenDetail } from "../apiContract"; import { addTableField, addTableRow, clearTopicRowsCache, deleteTableField, deleteTableFields, deleteTableRow, dropTableRowsCache, fetchLinkTargets, refusalMessage, fetchHopTopics, fetchRollupSources, patchTableField, enrichField, removeChoice } from "./apiBridge"; import type { FieldDeleteResult, HopTopicOffer, LinkTarget, RollupSourceOffer } from "./apiBridge"; import SelectFromFile from "./SelectFromFile"; import ImportDialog from "./ImportDialog"; import { FormInterface } from "./FormInterface"; import type { FormSpec } from "./FormInterface"; // Owner item 16 / R4 / C-UNDO — the stack and every inverse. Pure, so a node gate can run it. import { describe, directed, popRedo, popUndo, pushUndo, stackFor } from "./undoStack"; import type { CellChange, UndoBook, UndoEntry, UndoRow, UndoValue } from "./undoStack"; import { buildXlsxWorkbook, exportFilename, exportSelectionKey, groupingApplies, runExport, summaryExportSheet, toExportGroups, triggerDownload } from "./export"; import type { ExportFormat, ExportGrouping } from "./export"; import { dataPathHash, readDataPath } from "./dataPath"; import type { DataDatabase, DataDatabaseFolder, DataPath } from "./dataPath"; import "../styles/wave44/data-workspace.css"; import "../styles/wave45/data-applications.css"; import "../styles/sdlc76/selection-bar.css"; // Load the grid chrome after the workspace sheet so equal-specificity rules keep their order. import "../styles/wave46/chrome.css"; // ⭐⭐ W50-T01 / R1 — the mode scroller the windowed card views need. Side-effect import, in the // same run as the wave 44/45/46 sheets: a stylesheet nothing imports does nothing at all. import "../styles/wave50/grid.css"; import "../styles/wave61/route-app.css"; import "../styles/sdlc72/app-fullscreen.css"; import { resolveActiveView } from "./viewEcho"; import { pruneStamps, reconcileFields } from "./optimism"; import { ROUTING_FILTERS_WRITE_DELAY_MS, pruneFilters, readRoutingFilters, routeFilterSignatureOf, writeRoutingFilters } from "./routePrefs"; import { applyViewOrder, isSyntheticFolderId, newFolderId, pruneFolderStamps, reconcileFolders, resolveFolderId } from "./folders"; import type { FolderStamps } from "./folders"; // ⭐ WAVE 27 item 22 — the cells the active view's filter forces on a record added under it. import { filterSeedValues } from "./filterSeed"; import { adoptNewFields, pendingViewCreates, projectWorkspaceViews, pruneTombstones, reconcileHeldFields, stampTombstone } from "./liveWorkspace"; import type { Tombstones } from "./liveWorkspace"; import type { CustomersPayload, GridFolder, VisibleRow } from "./types"; import type { ShowAs, SummaryChoice, SummaryMap } from "./types"; import { fieldClassOf, mayDeleteField as mayDeleteFieldRight } from "../filter-kit/fieldClass"; import type { FieldStamps } from "./optimism"; import { orderFormulas, parseFormula } from "./formulaEngine"; import type { FormulaAst } from "./formulaEngine"; import { applicationTemplateSurface, CalendarSettings, CalendarView, KanbanView, ListView, MapSettings, ModeSwitch, TemplateApplicationView, TimelineSettings } from "./viewModes"; import { SwipeView } from "./SwipeView"; import type { SwipeSpec } from "./SwipeView"; // The chart engine lives in `viz/` since EXIT wave 2 (W2-5/Y3) — the grid is now // one of its two callers, the Y1 page envelope being the other. import { DashboardView } from "../viz/DashboardView"; import { cleanCharts } from "../viz/chartData"; import type { ChartSpec } from "../viz/chartData"; import { MapView } from "./MapView"; import type { RouteSourceView } from "./MapView"; /* ═══ W18-C CATALOG ═══ (owner item 4, contract C6) */ import { CatalogView } from "./CatalogView"; import { useApplicationHost } from "./applicationHost"; import type { SavedApplication } from "./applicationHost"; import { GalleryView, TimelineView } from "./GalleryTimelineViews"; import { foldGridCell } from "./navFold"; import { CATALOG_CODE_FIELD } from "./catalogData"; import type { CatalogSpec, LinkSeed } from "./types"; /* ═══ end W18-C CATALOG ═══ */ import { lightTheme, HOVER_NEUTRAL, ACTIVE_ROW_NEUTRAL, CUSTOM_FIELD_MARK } from "./theme"; import { avatarInitials, barCellRenderer, dotCellRenderer, formatDisplay, imageCellRenderer, matchChoices, pickerTypeSeed, ratingCellRenderer, setAvatarRepaint, userCellRenderer } from "./cells"; import { chartCellRenderer } from "./sparklineCell"; import { asButtonCell, buttonCellRenderer, makeProgressCell, progressCellRenderer } from "./cells"; // S82-T20 (R6, R33): the App-only product cell. import { isProductCell, productCellRenderer, resolveRowHeight, withProductRow } from "./cells"; // ⭐ W50-T05 — ONE numeric reading of a stored cell, the same one `aggregations.ts` folds with. // A second parse here is how a cell painted blank while the total under it counted 1,234.50. import { actionHref, numberWriteRefusal, numericOrUndefined } from "./display"; // ⭐ W50-T05 — the value/share COMPOSITION. The share arithmetic stays in `formatShare`. import { withShare } from "../ui/fmt"; import { optionTint, pickTint } from "./choiceColors"; import { EMPTY_GRID_COPY_PROVENANCE, markGridCopy, observeCopyEvent, planFieldPaste, pasteRowCount, } from "./clipboard"; import { cellTipText, expandButtonRect, starButtonRect, GROUP_HEADER_FONT, GROUP_LABEL_PAD, hasShareMark, headerMarkFit, tipLeft } from "./overlayPlacement"; import { AnchoredOverlay, BodyPortal, useOverlayLayer } from "./OverlaySurface"; import type { AnchorRect } from "./OverlaySurface"; import { StarIcon } from "./Stars"; import { ALL_VIEW_ID, MAX_CALENDAR_METRICS, allViewName, MAX_FROZEN, choiceOptions, choiceVocabulary, clampFrozenCount, cleanApplicationRef, cleanDisplay, canSaveViewDisplay, isRetiredDisplay, formulaOf, topicForScope, isDateFamilyType, isFilterGroup, isGroupableField, isDerivedLink, isUserSchemaField, isBlankValue, isNumericFieldType, machineFoundRows, reFindConsequences, isPickType, mayEditField, mayEditFieldDefinition, adoptDuplicatedField, fieldLabel, isModeFrozen, isPresetField, isUndeletableView, mayEditView, mayToggleViewLock, viewControlsLocked, measureColumnIndex, ratingMax, ruleColumnKeys, shouldAdoptEmbeddedSelection, tableMode, uniqueDisplayName, routeSortRefusal, /* ⭐ W41-T38 — the rail's OWN name resolver, so a collision test compares what the reader actually sees. The rail has always drawn `viewDisplayName(view)`; `renameView` was testing `view.name`, and for the default view those two are different strings. */ viewDisplayName, // S85-T33 (D-233): the scoped-out cohort sentence, shared with the rail's mark. viewScopedOutMark, /* ⭐ W37-T26 (C4) — the view-membership leaf's two pure helpers. `viewRefsOf` is the ONE walk the resolver, the cycle detector and the gate share; `viewFilterCycle` is the refusal. */ viewFilterCycle, viewRefsOf } from "./types"; /* ⭐⭐ W41-T42 (owner instruction 23) — the pivot's whole vocabulary is DECLARED in `types.ts` and only consumed here, because W41-T43 (this file) and W41-T44 (`RecordDetail.tsx`) open the same feature through other doors and neither of them may edit `types.ts`. */ import { AUDIT_FIELD_TYPES, buildPivotRequest, cleanSecondaryView, emptyViewConfig, PIVOT_PATH, PIVOT_WINDOW_LABELS, pivotRefusalFromBody, pivotResponse, relationalTargets } from "./types"; import type { DisplayMode, DisplaySpec, Field, HostEvent, FieldScope, FieldType, FilterNode, FilterRule, FilterTree, PivotResponse, PivotRefusal, PivotWindow, RelatedPin, RelatedVia, Row, SavedView, SortRule, ViewConfig, Viewer, } from "./types"; import type { WindowSpec } from "./windows"; import { windowLabel } from "./windows"; /** * ⭐⭐ WAVE 38 · T06 (owner instruction 1) — "OPEN THE CHAT ABOUT THIS DATA", raised by the SHELL. * * Owner: *"When the Navigation is minimized: the icon that opens the AI chatbot overlay with the * grid…"* The launcher lives in the frame's minimised rail; `chatOpen` and the `` mount * live here. So the shell asks and this surface answers, the shape every cross-fence click-through * in this app already has (`VIEW_OPEN_EVENT`, `AUTOMATION_OPEN_EVENT`, `QUERY_OPEN_EVENT`). * * ⛔ THE CANONICAL DECLARATION IS THIS ONE, and its twin in `shell/Shell.tsx` says why the pair * exists rather than one shared constant in `apiContract.ts`: that file was outside the ticket's * `files:` list, `customer-grid/**` may not import `shell/**`, and a static import out of this * module would pull the spreadsheet engine into the shell's entry chunk past the `lazy()` that * keeps it out. `verify_wiring.py`'s W38-T06 row matches the LITERAL on both sides so the two * spellings cannot drift apart in silence. * * ⛔ NO `retryEmit` LADDER, deliberately. `VIEW_OPEN_EVENT` rides one because it races a fresh hash * navigation against a grid that is still mounting. This launcher only exists in a rail that is * already beside a mounted grid, so a bare `signal()` is the honest emit — the same call the fold * signal two fences over makes. */ export const GRID_CHAT_OPEN_EVENT = "aios:grid-chat-open"; // One identity for the life of the module: a new array remounts glide's open cell editor, which // selects the text typed so far, and the next keystroke replaces it. const CUSTOM_RENDERERS = [ratingCellRenderer, userCellRenderer, imageCellRenderer, chartCellRenderer, barCellRenderer, dotCellRenderer, productCellRenderer, progressCellRenderer, buttonCellRenderer]; /** * W40-T30, 2026-08-24 — W39-T22's virtual "Go" directions column is GONE, removed on owner * instruction 27: "Remove the 'Go' field for Google Maps. Use the URL field we already have, * with the Google link derived from the address by Formula, or make it editable so you can put * it there. It is a pre-set field." * * It was a synthetic `GridColumn` appended after the real ones and resolved by POSITION * (`cell[0] === visibleCols.length`), which is why its removal touches the cell resolver, the * click door and the column-count handed to `useGridSelection` rather than one block. The * transit link is now an ordinary PRE-SET URL FIELD on the customer database, whose value is * computed server side (W40-T08), so it exports, permissions, reorders and hides like every * other field instead of living outside the field system. * * Nothing replaces it HERE by design: a normal field simply occupies that place. The * no-dead-link rule the old blank-cell branch enforced now belongs to the field's value, which * is absent when the address is. */ /** * Wave-14 R7 — **a button label is ONE LINE.** Every button row in this file is a flex row with * no width reservation, so on a narrow grid box the items shrink and their labels wrap: * "Remove from cohort" becomes two lines, the row grows, and the bar stops being a bar. It only * happens below a width no fixed-size screenshot is taken at, which is why it survived. * * ⚠ Applied INLINE rather than on `.cg-btn`, where it belongs: `index.css` is PANEL's fence this * wave. A mailbox line asks them to hoist it onto `.cg-btn` globally — after which this is * redundant, and harmless, because it says exactly the same thing. */ const ONE_LINE = { whiteSpace: "nowrap" } as const; const LINK_ADD_ROW = { display: "flex", alignItems: "center", gap: 8, marginLeft: "auto", minWidth: 0 } as const; const LINK_ADD_NOTICE = { color: LP_RED_DEEP, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", maxWidth: 360 } as const; function formatHistoryValue(value: unknown): string { if (value === null || value === "") return "Empty"; if (typeof value === "string") return value; try { return JSON.stringify(value) ?? "Unavailable"; } catch { return "Unavailable"; } } /** * How many VISIBLE columns glide freezes. Module-level and used twice on purpose (item 15): the * `freezeColumns` prop and the group bar's label fit must read ONE answer, because the label is * clipped to exactly this strip and a second copy of the clamp would let the two disagree by a * column — which shows up as a label cut early for no visible reason. */ function frozenCountOf(config: ViewConfig): number { return Math.min(MAX_FROZEN, Math.max(1, config.frozenCount ?? 1)); } /** * Route provenance is minted by the API from this saved config. The client only sends the * current config as a compare guard, so a forged browser fingerprint cannot become durable. */ /* WAVE 21 item 3 (R6): the id and the NAME both moved to `types.ts` — the id because a second copy of a pinned literal is the drift class this repo gates against, the name because it is now topic-derived and the host mints the same string. */ /** * owner item 2 (2026-08-03) — the measure-cell skeleton's pulse, and its ceiling. * * 140ms against the 4-step colour ramp is a ~0.6s cycle: a wait, not a strobe. The ceiling is * ~60s, after which the cells fall back to ordinary blanks — a measure that has not resolved in * a minute is not "still loading", and a shimmer that never ends promises a number that is not * coming. Shared constant so the two are read in one place rather than tuned apart. */ const PULSE_MS = 140; const PULSE_MAX_TICKS = Math.round(60_000 / PULSE_MS); /** Referentially stable, so the fallback does not change `getCellContent`'s identity per render * and repaint the canvas forever. */ const NO_PENDING_KEYS: ReadonlySet = new Set(); /** S67-T27 — likewise for the open groups' stand-in rows, when nothing is grouped on the server. */ const NO_GROUP_PLACEHOLDERS: ReadonlyMap = new Map(); type GroupPagePaint = { queryKey: string; paintKey: string; offset: number; size: number; rows: Row[]; header: Extract; }; type ServerGroupPage = Omit & { header?: GroupPagePaint["header"]; pending: boolean; failed?: string; painted?: GroupPagePaint; }; function groupPagePaint(page: ServerGroupPage | undefined, paintKey: string): GroupPagePaint | undefined { if (!page || page.paintKey !== paintKey) return undefined; if (!page.pending && !page.failed && page.header) return { queryKey: page.queryKey, paintKey, offset: page.offset, size: page.size, rows: page.rows, header: page.header, }; return page.painted; } /** S67-T27 (R38) — the sentence a group whose page failed shows in place of its records. */ const GROUP_PAGE_FAILED = "These records could not be loaded."; /** * I2 — measure a cell's text in GLIDE'S OWN font, so "is this cut off?" is a fact rather than * a character-count guess (a guess is wrong in both directions: "IIIII" is narrow, "WWWWW" is * wide, and being wrong means either a missing tip or a tip over text you can already read). * One lazily-built offscreen context for the whole module — `measureText` is cheap, but * creating a canvas per mouse-move would not be. */ let _tipCtx: CanvasRenderingContext2D | null | undefined; function measureCellText(text: string): number { if (_tipCtx === undefined) { _tipCtx = document.createElement("canvas").getContext("2d"); // glide's default `baseFontStyle` is 13px; the family comes from our own theme. if (_tipCtx) _tipCtx.font = `13px ${lightTheme.fontFamily ?? "Inter, sans-serif"}`; } return _tipCtx ? _tipCtx.measureText(text).width : 0; } /** * Item 15 — the GROUP BAR's measurer, and it is a SECOND context on purpose. * * `measureCellText` above is set to plain "13px", which is right for ordinary cells and WRONG for * a group bar: that row carries `baseFontStyle: GROUP_HEADER_FONT` (semibold), and glide paints a * cell with the merged theme's font. Measuring the fit with the lighter weight under-truncates * and the label overflows into the frozen strip's hard clip — the exact failure `fitGroupLabel` * exists to prevent. Font string built from the SAME constant the cell's themeOverride uses, so * the two cannot drift. */ let _groupCtx: CanvasRenderingContext2D | null | undefined; function measureGroupText(text: string): number { if (_groupCtx === undefined) { _groupCtx = document.createElement("canvas").getContext("2d"); if (_groupCtx) _groupCtx.font = `${GROUP_HEADER_FONT} ${lightTheme.fontFamily ?? "Inter, sans-serif"}`; } return _groupCtx ? _groupCtx.measureText(text).width : 0; } /** * ⭐⭐ W50-T01 / OWNER RULING R1 (2026-09-03) — `DISPLAY_PAGE` AND `DISPLAY_STEP` ARE GONE, AND * SO IS EVERYTHING THAT READ THEM. * * Owner, verbatim: *"The client RENDER cap is retired: Grid/List paint every loaded row (the grid * is canvas-virtualized); Gallery, Kanban, Calendar and Timeline get windowed rendering and a real * scroll container; no 'See more / Show all' bar anywhere."* Owner item 8's first-50 page, its * "Showing first N of M" bar and both of its buttons are deleted with it. Nothing throttles what * the client paints now: glide virtualises the canvas, and the DOM card views mount a window of * the full list inside their own scroller (`.cg-mode-scroll`, `styles/wave50/grid.css`). * * ⛔ THE SERVER WINDOW IS THE OTHER HALF OF R1 AND IT IS UNTOUCHED. `serverWindowed`, * `requestWindow`, `windowPredicate`, `WINDOW_ROWS` and `windowedFoldNote` all stay: a 1M-row * table still arrives one 200-row page at a time, and the fold still says what it covers. * Retiring that too would put an unbounded read on the wire, a different ruling nobody made. */ /* ═══════════════════════════════════════════════════════════════════════════════════════════ ═══ W18-B VOID ═══ (wave 18, owner item 1b) — the two constants the void geometry needs that belong to the BROWSER and to GLIDE rather than to us. Both are mirrors, and both say here what they are mirroring, because a mirror that does not name its original is how the two copies stop agreeing. ═══════════════════════════════════════════════════════════════════════════════════════════ */ /** The header band. `headerHeight={36}` at the DataEditor mount is the original. * Not `+ groupHeaderHeight`: glide adds that only when `enableGroups` is on, which it turns on * when a COLUMN carries a `group` — `useGridColumns` never sets one (scrolling-data-grid.js:13). */ const HEADER_PX = 36; /** * ⭐ W40-T20 — WHAT THE SHARE MARK MEANS, in words, because a canvas sprite cannot carry a * `title` or an `aria-label` of its own. * * DESIGN.md §4 "one mark, one meaning": whatever carries a mark must name what the mark applies * to, or two marks are indistinguishable. In the view rail that is an attribute on the element; * on this surface the header is painted pixels, so the header TIP is the only place the meaning * can live, and hovering the column is how a reader gets it. * * ⛔ NOT the rail's receiver wording. Contract C1: `shared` says the field HAS grants, and the * server stamps it on the owner's own copy too, so "shared with you by ..." would be a lie for * the person who shared it out. One sentence that is true on both legs is the answer. * * ⛔⛔ AND IT MUST NOT NAME AN AUDIENCE. The first draft of this line read "Everyone with access * to this table sees it", which is FALSE in exactly the case W40-T03 (owner instruction 21) exists * to fix: `routes_customers._merge_shared_fields` merges a shared definition for EVERY user and * `core.perm_scope.field_grant_hidden` then hides it again from anyone the grant does not name, so * a field shared with one person is not a field everyone sees. Nothing on this side of the wire can * tell a wildcard grant from a one-person grant — `Field.shared` says only THAT there are grants — * so a tooltip claiming the audience would ship the same mislabel one surface over. It names the * mark and points at the control that owns the answer, which is where the DECISION is made * (DESIGN.md §4, "explanation lives where the decision is"). */ const SHARE_MARK_MEANING = "Shared field. Access is set in Share field."; /** glide's own row-marker width ladder, `data-editor.js:103`, verbatim. * * ⚠ It is passed BACK to glide as `rowMarkerWidth` rather than merely predicted here. The * marker column is part of the content width the void's left edge is measured from, so a * four-pixel disagreement between what glide draws and what we compute is a four-pixel seam of * white against the tint — visible, and invisible to every gate. Pinning makes the two the same * number by construction; mirroring the ladder (rather than pinning one constant) is what keeps * the pin from changing the marker column's width on tables of more than 100 rows. */ function rowMarkerPx(rows: number): number { return rows > 10_000 ? 48 : rows > 1000 ? 44 : rows > 100 ? 36 : 32; } /** The scrollbar gutter this browser steals from a scrollable box, measured once. * * ⛔ WHY THE VOID HAS TO KNOW. The void rectangles sit ON TOP of glide's scroller, so a * rectangle drawn to the box's own edge paints over the scrollbar and hides it. The two cases * are CROSSED, which is the part that is easy to get backwards: the BOTTOM void has to stop * short when the columns overflow (a horizontal scrollbar), and the RIGHT void has to stop * short when the rows overflow (a vertical one). Both happen in ordinary use — twelve columns * filtered to five rows is exactly the owner's case. * * 0 on overlay-scrollbar platforms (macOS, touch), which is correct: nothing is stolen there. */ let scrollbarGutterPx: number | null = null; function scrollbarGutter(): number { if (scrollbarGutterPx !== null) return scrollbarGutterPx; if (typeof document === "undefined") return 0; const probe = document.createElement("div"); probe.style.cssText = "position:absolute;top:-9999px;width:100px;height:100px;overflow:scroll"; document.body.append(probe); scrollbarGutterPx = probe.offsetWidth - probe.clientWidth; probe.remove(); return scrollbarGutterPx; } /* ═══ end W18-B VOID (module scope) ═══ */ interface LocalFieldPresentation { fields: Field[]; activeViewId: string; /** Wave-6 item 3c — per-key freshness for this browser's own field-def * writes (edits + tombstones), consumed by reconcileFields at init. */ fieldStamps?: FieldStamps; /** 2026-08-04 — viewId → when THIS browser deleted it. The views half of the tombstone * rule fields and folders already had, needed the moment the rail adopts host views * after mount (liveWorkspace.ts). Persisted, not a ref, because a remount inside the * echo window would otherwise re-adopt a view the user deleted a second ago. */ viewTombstones?: Tombstones; /** Selection metadata has its own stamp, independent of field writes. */ activeViewAt?: number; } function sameConfig(a: ViewConfig, b: ViewConfig): boolean { return JSON.stringify(a) === JSON.stringify(b); } type LockedFilterRule = FilterRule & { locked?: boolean }; type LockedSortRule = SortRule & { locked?: boolean }; type ManagedRouteClause = { managedBy: "loopable"; kind: "route-membership"; operator: "or"; pids: number[]; }; function hasLockedFilter(nodes: FilterNode[]): boolean { return nodes.some((node) => isFilterGroup(node) ? hasLockedFilter(node.children) : (node as LockedFilterRule).locked === true ); } function hasLockedSort(sorts: SortRule[]): boolean { return sorts.some((sort) => (sort as LockedSortRule).locked === true); } /** A duplicate has a new View id, the one C3 alteration path. Preserve the actual rules but * remove the immutable-record mark, so the new View does not inherit a false in-place refusal. */ function unlockedFilterCopy(nodes: FilterNode[]): FilterNode[] { return nodes.map((node) => { if (isFilterGroup(node)) return { ...node, children: unlockedFilterCopy(node.children) }; const { locked: _locked, ...rule } = node as LockedFilterRule; return rule; }); } function unlockedViewConfigCopy(config: ViewConfig): ViewConfig { return { ...config, filters: unlockedFilterCopy(config.filters), sorts: config.sorts.map((sort) => { const { locked: _locked, ...rule } = sort as LockedSortRule; return rule; }), }; } /** C2's server-issued clause is an OR inclusion. This reader validates only its declared shape; * it never derives route membership from Map rows or ids. */ function managedRoutePids(value: unknown): number[] { if (!value || typeof value !== "object") return []; const clause = value as Partial; if (clause.managedBy !== "loopable" || clause.kind !== "route-membership" || clause.operator !== "or" || !Array.isArray(clause.pids)) return []; return [...new Set(clause.pids.filter((pid): pid is number => Number.isInteger(pid)))]; } /** * ⭐ W41-T42 — the pivot's four states, and the fourth one is the point. * * `absent` is NOT an empty result. It is "the endpoint that answers this question is not there, * or did not answer" (C10's server half is W41-T20, which had not been built when this shipped), * and it renders a sentence rather than a grid. Collapsing it into `ok` with zero rows would * put "no related records" on screen as the answer to a question nobody has asked yet. */ type PivotState = | { status: "idle" } | { status: "loading" } | { status: "absent" } | { status: "refused"; refusal: PivotRefusal } | { status: "ok"; answer: PivotResponse }; /** * One pivoted cell, as text. ⚠ A BLANK IS A BLANK: `null` and `undefined` print nothing rather * than the words "null" or "0", which is the same rule `isBlankValue` carries for the grid. No * formatting is applied beyond that, because the pivoted database's field formats belong to * that database and this surface has not been given them. */ function pivotCellText(value: string | number | null | undefined): string { return value === null || value === undefined ? "" : String(value); } /** * S67-T30 — a SERVER LOOKUP field (one carrying `opens.via`: an Amazon "Parent ASIN", "SKU" or * "ASIN") that a saved view has never seen joins that view beside its source column. Only such a * field, and only when it is ABSENT from the saved `order`: a lookup already in `order` stays * exactly as saved, so a person who hid it keeps it hidden. It lands right after the nearest * preceding field (declaration order) the saved `order` holds, and joins a saved non-empty * `visible` when the database shows it by default (`defaultVisible`, i.e. `defaultViewConfig`'s * own answer). Every other field, and every view without a saved `order`, is untouched: seeded * views carry curated partial orders that must not start showing other fields. */ export function placeUnseenLookups( order: string[], visible: string[] | null, fields: Field[], defaultVisible: ReadonlySet ): { order: string[]; visible: string[] | null } { const isLookup = (field: Field) => typeof (field as Field & { opens?: { via?: unknown } }).opens?.via === "string"; if (!fields.some((field) => isLookup(field) && !order.includes(field.key))) { return { order, visible }; } const nextOrder = [...order]; const nextVisible = visible ? [...visible] : null; let anchor: string | null = null; for (const field of fields) { if (nextOrder.includes(field.key)) { anchor = field.key; continue; } if (!isLookup(field)) continue; // No preceding field in the saved order: append, where `reconcileOrder` would put it today. const at = anchor === null ? nextOrder.length : nextOrder.indexOf(anchor) + 1; nextOrder.splice(at, 0, field.key); if (nextVisible && defaultVisible.has(field.key) && !nextVisible.includes(field.key)) { nextVisible.push(field.key); } anchor = field.key; } return { order: nextOrder, visible: nextVisible }; } function normalizeConfig(config: Partial | undefined, fields: Field[]): ViewConfig { const base = defaultViewConfig(fields); const savedOrder = Array.isArray(config?.order) && config.order.length ? config.order : null; const savedVisible = Array.isArray(config?.visible) && config.visible.length ? config.visible : null; const placed = savedOrder ? placeUnseenLookups(savedOrder, savedVisible, fields, new Set(base.visible)) : null; return { ...base, ...config, filters: Array.isArray(config?.filters) ? config.filters : [], // Legacy views persisted a flat rule array with an implicit AND — anything // other than an explicit "or" normalizes to "and", so old views are unchanged. filterConj: config?.filterConj === "or" ? "or" : "and", sorts: Array.isArray(config?.sorts) ? config.sorts : [], order: placed ? placed.order : base.order, visible: placed?.visible ?? savedVisible ?? base.visible, widths: config?.widths && typeof config.widths === "object" ? config.widths : {}, memberPids: Array.isArray(config?.memberPids) ? config.memberPids : [], // Wave-6 items 10/11. Both normalize junk to ABSENT (grid / 1 frozen), so // a legacy view is byte-identical to itself after a round trip. W13 (C4 as // amended): cleanDisplay keeps grid-carried field picks. // Keep the retirement marker until the server purge; render normalization is separate. display: isRetiredDisplay(config?.display) ? config?.display : cleanDisplay(config?.display), // W45 C3: a View carries only Application identity/revision. The selected asset's typed // config is resolved from the registry at render time and never normalized into this object. application: cleanApplicationRef(config?.application), frozenCount: clampFrozenCount(config?.frozenCount), /** * ⭐⭐ W41-T42 · CONTRACT C6 — the saved pivot, VALIDATED rather than merely carried. * * ⛔ THE SPREAD ABOVE IS WHY THIS ARM EXISTS, and it is not the reason the ticket predicted. * `normalizeConfig` does NOT allowlist: `...config` means `secondaryView` survives the read * for free, so nothing had to be added for the key to arrive. What the spread also means is * that JUNK FROM THE WIRE REACHES THE RENDERER UNVALIDATED — an unknown `window` string, a * missing `database`, a `config` that is not an object. Every other structured member on this * list (`display`, `frozenCount`, `widths`, `memberPids`) is validated on read; this one is * not special, and `cleanDisplay` one line up is the precedent this copies exactly. * * ⚠ There is no client `cleanConfig`. The ticket, contract C6 and a comment in `Toolbar.tsx` * all name one; a repo-wide grep returns only that comment. The function that actually drops * an unnamed key is SERVER-side, in `platform/core/grid_events.py::handle_one`, and no * wave-41 ticket owns that file. */ secondaryView: cleanSecondaryView(config?.secondaryView), }; } /** * The pinned system view, as this browser mints it when no host copy has arrived. * * WAVE 21 item 3 (R6) — the NAME is the scope's now (`allViewName`), not the literal "All * customers" this minted on every topic including `ut_*` databases of anything at all. The * ID is unchanged and deliberately so (see `ALL_VIEW_ID`). */ function allRecordsView(fields: Field[], scope: string): SavedView { return { id: ALL_VIEW_ID, name: allViewName(scope), kind: "system", locked: true, config: defaultViewConfig(fields), }; } /** Adapt E's already-validated Query view to the existing renderer without creating a native view. */ function queryPreviewView(binding: QueryVirtualBinding, fields: Field[]): SavedView { const raw = binding.view; const keys = new Set(fields.map((field) => field.key)); const config = defaultViewConfig(fields); const visible = Array.isArray(raw.visible) ? raw.visible.filter((key): key is string => typeof key === "string" && keys.has(key)) : []; if (visible.length) { config.visible = visible; config.order = [...visible, ...config.order.filter((key) => !visible.includes(key))]; } config.filters = Array.isArray(raw.filters) ? raw.filters as FilterNode[] : []; config.filterConj = raw.filterConj === "or" ? "or" : "and"; config.sorts = Array.isArray(raw.sorts) ? raw.sorts.filter((item): item is { colId: string; dir?: unknown } => !!item && typeof item === "object" && typeof (item as { colId?: unknown }).colId === "string" && keys.has((item as { colId: string }).colId) ).map((item) => ({ colId: item.colId, dir: item.dir === "desc" ? "desc" : "asc" })) : []; config.groupBy = typeof raw.groupBy === "string" && keys.has(raw.groupBy) ? raw.groupBy : null; if (raw.display && typeof raw.display === "object") config.display = raw.display as DisplaySpec; /** * ⭐⭐ W35-T25 — THE MEMBERS AN EDIT CAN MOVE, READ BACK FROM THE SERVER'S COPY. * * R2 made the spec editable and `routes_query.QUERY_EDITABLE_SPEC` is the allow-list it may * move. Every one of them has to be read HERE too, or the round trip is one-directional: the * edit posts, the server stores it, and the next mount rebuilds the view from the AI's members * alone — so a resize would survive a reload on THIS browser (the local bucket) and vanish on * any other, which is the worst of the three possible behaviours because it looks like it works. * * ⚠ Each is validated against the CURRENT field list, exactly like the members above: the * server cleans on write, this cleans on read, and neither trusts the other's vintage. */ if (Array.isArray(raw.order)) { const order = raw.order.filter((key): key is string => typeof key === "string" && keys.has(key)); if (order.length) config.order = [...order, ...config.order.filter((key) => !order.includes(key))]; } if (raw.widths && typeof raw.widths === "object") { const widths: Record = {}; for (const [key, width] of Object.entries(raw.widths as Record)) if (keys.has(key) && typeof width === "number" && width > 0) widths[key] = width; config.widths = widths; } if (typeof raw.colorBy === "string" && keys.has(raw.colorBy)) config.colorBy = raw.colorBy; if (typeof raw.rowHeightMode === "string") config.rowHeightMode = raw.rowHeightMode as ViewConfig["rowHeightMode"]; if (typeof raw.frozenCount === "number") config.frozenCount = clampFrozenCount(raw.frozenCount); return { id: binding.artifactId, name: typeof raw.name === "string" && raw.name ? raw.name : binding.source.label, kind: "custom", locked: true, config, }; } /** Preserve the legacy colour helper for callers outside the Data toolbar. */ export function withColorField(config: ViewConfig, key: string): ViewConfig { const spec = cleanDisplay(config.display) ?? { mode: "grid" as const }; const display: DisplaySpec = { ...spec }; if (key) display.colorField = key; else delete display.colorField; return { ...config, colorBy: key || null, display: cleanDisplay(display) }; } /** Atomically scrub every view reference to the fields the server actually removed. */ export function configWithoutFields( config: ViewConfig, removed: readonly string[], ): ViewConfig { const gone = new Set(removed.filter((key) => typeof key === "string" && key !== "")); if (gone.size === 0) return config; const widths = { ...(config.widths ?? {}) }; for (const key of gone) delete widths[key]; const next: ViewConfig = { ...config, order: (config.order ?? []).filter((key) => !gone.has(key)), visible: (config.visible ?? []).filter((key) => !gone.has(key)), widths, sorts: (config.sorts ?? []).filter((sort) => !gone.has(sort.colId)), groupBy: config.groupBy && gone.has(config.groupBy) ? null : config.groupBy, colorBy: config.colorBy && gone.has(config.colorBy) ? null : config.colorBy, }; const spec = next.display; if ((spec?.colorField && gone.has(spec.colorField)) || (spec?.coordField && gone.has(spec.coordField))) { const display: DisplaySpec = { ...spec }; if (display.colorField && gone.has(display.colorField)) delete display.colorField; if (display.coordField && gone.has(display.coordField)) delete display.coordField; next.display = cleanDisplay(display); } return next; } export type FieldDeleteDoor = "overlay" | "definition" | "route"; export function fieldDeleteDoor( field: Field | undefined, opts: { isUserTable: boolean; lockedKey: string; viewer?: Viewer }, ): FieldDeleteDoor | null { if (!field || field.key === opts.lockedKey || isPresetField(field) || (field as Field & { deletionLocked?: boolean }).deletionLocked) return null; const classification = fieldClassOf(field); if (classification && !mayDeleteFieldRight(classification, opts.viewer)) return null; if (field.custom && !field.shared) return "overlay"; if (opts.isUserTable && !field.custom && isUserSchemaField(field, true)) { return "definition"; } return null; } export interface FieldBulkDoorDeps { viewer?: Viewer; config: ViewConfig; updateConfig: (next: ViewConfig) => void; order: string[]; visible: Set; lockedKey: string; fieldByKey: Map; isUserTable: boolean; scope: SurfaceScope; rowsPath: string; setFields: (update: (current: Field[]) => Field[]) => void; stampFieldDelete: (key: string) => void; } export interface FieldBulkDoors { onSetFieldsHidden: (keys: string[], hidden: boolean) => void; onShareFields: null; onReassignFields: null; onDeleteFields: (keys: string[]) => void; onRemoveField: null; onRemoveFromMine: null; } function reportFieldDeleteRefusals( results: readonly FieldDeleteResult[], fieldByKey: Map, ): void { const refused = results.filter((item) => item.status === "refused"); if (refused.length === 0) return; const explained = refused.find((item) => typeof item.reason === "string" && item.reason.trim().length > 0); if (!explained) { signal(TOAST_EVENT, refused.length === 1 ? "That column was left alone, and the server gave no reason." : `${refused.length} of those columns were left alone, and the server gave no reason.`); return; } const label = fieldByKey.get(explained.key)?.label ?? explained.key; signal(TOAST_EVENT, refused.length === 1 ? `${label} was left alone. ${explained.reason}` : `${refused.length} of those columns were left alone. ${label}: ${explained.reason}`); } export function useFieldBulkDoors(deps: FieldBulkDoorDeps): FieldBulkDoors { const { config, updateConfig, order, visible, lockedKey, fieldByKey, isUserTable, scope, rowsPath, setFields, stampFieldDelete, viewer } = deps; const emitHostEvent = useMemo(() => bindHostEvent(scope), [scope]); const onSetFieldsHidden = useCallback((keys: string[], hidden: boolean) => { const next = new Set(visible); for (const key of keys) { if (hidden) { if (key !== lockedKey) next.delete(key); } else next.add(key); } updateConfig({ ...config, visible: [...new Set([lockedKey, ...next])] }); }, [config, lockedKey, updateConfig, visible]); const onDeleteFields = useCallback((keys: string[]) => { const overlay: string[] = []; const definition: string[] = []; const route: string[] = []; const noDoor: string[] = []; for (const key of keys) { const door = fieldDeleteDoor(fieldByKey.get(key), { isUserTable, lockedKey, viewer }); if (door === "overlay") overlay.push(key); else if (door === "definition") definition.push(key); else if (door === "route") route.push(key); else noDoor.push(key); } void (async () => { const gone = [...overlay]; let touchedServer = false; let unreadableAnswer = false; if (definition.length > 0) { const outcome = await deleteTableFields(scope, definition); gone.push(...outcome.deleted); touchedServer = outcome.deleted.length > 0; unreadableAnswer = outcome.unreadable; reportFieldDeleteRefusals(outcome.results, fieldByKey); } if (noDoor.length > 0) { signal(TOAST_EVENT, noDoor.length === 1 ? "One of those columns cannot be deleted here, so it was left alone." : `${noDoor.length} of those columns cannot be deleted here, so they were left alone.`); } if (gone.length > 0) { const goneSet = new Set(gone); setFields((current) => current.filter((item) => !goneSet.has(item.key))); updateConfig(configWithoutFields({ ...config, order, visible: [...visible] }, gone)); for (const key of overlay) { stampFieldDelete(key); emitHostEvent({ id: eventId("fielddel"), type: "field_delete", key }); } } if (touchedServer || unreadableAnswer) { clearTopicRowsCache(rowsPath); signal(WORKSPACE_STALE_EVENT); signal(ROWS_STALE_EVENT); } })(); }, [config, fieldByKey, isUserTable, lockedKey, order, rowsPath, scope, setFields, stampFieldDelete, updateConfig, visible, emitHostEvent, viewer]); return useMemo(() => ({ onSetFieldsHidden, onDeleteFields, onShareFields: null, onReassignFields: null, onRemoveField: null, onRemoveFromMine: null }), [onDeleteFields, onSetFieldsHidden]); } function readLocalFields(storageKey: string): LocalFieldPresentation | null { try { const raw = localStorage.getItem(`aios-grid-fields:${storageKey}`); if (!raw) return null; const value = JSON.parse(raw) as LocalFieldPresentation; return { fields: value.fields, fieldStamps: value.fieldStamps, activeViewId: value.activeViewId, activeViewAt: value.activeViewAt, viewTombstones: value.viewTombstones }; } catch { return null; } } /** * ⭐⭐ W37-T23 / D-334 — the LOCAL-ONLY stratum's prefix, named once. * * A key the server never issues (a real `storageKey` is `_table_workspace`-shaped), so it can * never collide with one. It was written out twice as a template literal and tested nowhere; the * persist effect now tests it, and a prefix spelled in two places is a prefix that eventually * disagrees with itself. */ const LOCAL_KEY_PREFIX = "local:"; /** * ⭐⭐ WAVE 41 · T36 (owner instruction 10) — HOW LONG TO WAIT BEFORE CALLING A FOLDER MOVE * REFUSED. * * ⛔ THIS IS NOT A SECOND ECHO WINDOW AND IT MUST NEVER BE ONE. `TOMBSTONE_WINDOW_MS` (120_000) is * the owner's two minutes and stays exactly where it is: widening it would only make the drop * quieter. This is the opposite lever, and much shorter, because an ACCEPTED move answers far * sooner than that. `core/grid_events.py`'s folder branch returns True, `routes_grid.py` puts * that in `rerender`, `apiBridge.ts::applyEventResult` raises `WORKSPACE_STALE_EVENT`, and * `useCustomerData.ts::reread` fetches `/workspace` uncached. So a placement the server kept is * back on `payload.workspace.views[].folderId` inside one round trip, and a placement still * missing well past one round trip was refused. * * ⚠ GENEROUS ON PURPOSE. A cold container's first `/workspace` is seconds, not milliseconds, so * the cost of being wrong here is one unnecessary sentence and a row that the pending re-read * then puts back. The cost of being too patient is the owner's actual complaint: two silent * minutes and then a view that moves on its own. */ const MOVE_CONFIRM_MS = 15_000; function writeLocalFields(storageKey: string, value: LocalFieldPresentation): void { try { localStorage.setItem(`aios-grid-fields:${storageKey}`, JSON.stringify({ fields: value.fields, fieldStamps: value.fieldStamps, activeViewId: value.activeViewId, activeViewAt: value.activeViewAt, viewTombstones: value.viewTombstones, })); } catch { // Storage can be blocked in hardened/opaque iframes. The host bridge remains durable. } } function nextViewId(): string { return `view_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`; } /** A multiselect cell's SET, out of its comma-joined string (the `multi` contract). */ function splitMulti(v: string): string[] { return v .split(",") .map((s) => s.trim()) .filter((s) => s !== ""); } /** Wave-5 item 3 — does any leaf of the filter tree name this column? * * ⚠ Wave-20 item 2 RETARGETED the note that stood here ("measure leaves carry measure keys, * which are never field keys, so they cannot false-positive"). True about false POSITIVES, * and precisely why it was a false NEGATIVE: a measure column's own condition names the * MEASURE, so this answered "not filtered" for a column the user had visibly filtered, and * the menu never offered "Don't filter by this field" on it. Both doors now go through * `ruleColumnKeys` — the same resolution the tint uses, so the menu and the colour can never * disagree about which columns a filter is about. */ function treeNamesField( nodes: FilterNode[], key: string, measureCols: Map ): boolean { for (const n of nodes) { if (isFilterGroup(n)) { if (treeNamesField(n.children, key, measureCols)) return true; } else if (ruleColumnKeys(n as FilterRule, measureCols).includes(key)) return true; } return false; } /** Wave-5 item 3 — "Don't filter by this field": drop every leaf naming the column, prune * groups that end up empty. Returns new arrays throughout (the config is state). */ function dropFieldFromTree( nodes: FilterNode[], key: string, measureCols: Map ): FilterNode[] { const out: FilterNode[] = []; for (const n of nodes) { if (isFilterGroup(n)) { const children = dropFieldFromTree(n.children, key, measureCols); if (children.length) out.push({ ...n, children }); } else if (!ruleColumnKeys(n as FilterRule, measureCols).includes(key)) { out.push(n); } } return out; } // The header sprite map moved to iconShapes.ts (wave-8 I20/I21) — it is data + // SVG-source builders with no React in it, which is what lets verify_icons.py // import it under node and assert the (i) actually contrasts. function slugify(label: string): string { return ( label .toLowerCase() .replace(/[^a-z0-9]+/g, "_") .replace(/^_|_$/g, "") .slice(0, 28) || "field" ); } function numberBatchRefusal(fields: readonly Field[], updates: readonly Partial[]): string | undefined { const definitions = new Map(fields.map((field) => [field.key, field])); for (const row of updates) for (const [key, value] of Object.entries(row)) { const field = definitions.get(key); const reason = field && numberWriteRefusal(field, value); if (reason) return reason; } return undefined; } interface FieldBuildExtra { if?: Field["if"]; formula?: string; max?: number; scope?: FieldScope; label?: string; colorCodeOptions?: boolean; optionColors?: Record; /** * ⭐⭐ 2026-08-09 — THE RELATIONAL BAGS, WHICH THIS INTERFACE USED TO DROP ON THE FLOOR. * * `ColumnMenu.FieldConfigExtra` has carried them since 2026-08-07 and `extraFor` builds a * complete bag; this type — the receiving end of the same `extra` argument — never declared * either key, so `buildOverlayField` could not copy what it could not see. The measured result * on nurilab: a column stored as * `{key:'custom_video_views_90j26', label:'Video Views', type:'rollup', source:'overlay'}` * with NO bag, in one user's workspace stratum, which `compute_relation_cells` never reads. * Named, configured, rendering, and permanently blank — the owner's *"the Rollup doesn't * work"*. ⛔ Both halves were needed: this type, and the `createField` route below. */ link?: Record; rollup?: Record; /** * ⭐⭐ W37-T22 (owner item 15 / R4, contract C7) — the geocode pseudo-kind's bag, declared HERE * as well as on `ColumnMenu.FieldConfigExtra` for the exact reason the two lines above it were * added: this type is the RECEIVING end of the same `extra` argument, and a key it does not * declare is a key `buildOverlayField` cannot copy. The relational pair's own note records what * that cost — a column stored with no bag, "named, configured, rendering, and permanently * blank". Two declarations of one bag is the price of the two-file split; one of them missing * is the defect. */ geocode?: Record; /** Item 15 (C-RENAME) — the option renames this save carries, by row identity. Consumed by * `retypeField` (which emits `choice_rename`) and ignored by every create path: a field * being CREATED has no values to migrate. */ renames?: { from: string; to: string }[]; /** S76-T28: the value a new record takes when its creator leaves this field empty. */ defaultValue?: Field["defaultValue"] | null; } /** * One constructor for a user-created field, shared by "insert field" and Change-field's * "New field" half (wave-2 item 5) so the two doors cannot drift. A `multiselect` carries its * declared options AND `multi: true` — the cell is a comma-joined SET, and the flag is what the * grouping contract keys on (belt to the type-derived brace in groupRows). * * Wave-5: `formula` and `created_time` are built in the HOST's OWN emission shape (source * 'odoo' + derived — aios_grid.READONLY_CUSTOM_TYPES), so the optimistic local def and the * next payload's echo are byte-identical and nothing restyles on the round trip. `rating` * carries top-level `max`, `formula` carries top-level `formula` (the ~20:20 contract * amendment: options stays the select-family list). Wave-6 item 6: both types are now * `filterable: true` — the host flipped its emission, and conditions on them evaluate in the * client engine over computedRows (this table's counts are client-mode; a windowed table's * columns come from the semantic model, so the SQL engine never sees these types). */ /** * ⭐⭐ 2026-08-09 (owner ruling) — DOES THE PRE-SET LOCK CLOSE THIS COLUMN'S SCHEMA? * * Owner: *"No rollup field should be uneditable, everything is custom and changeable always."* * A ROLLUP holds no data of its own — it is a question asked of other rows, re-askable at any * time, and re-asking it costs nothing because the answer is recomputed from the authoritative * store on the next pass. `preset` still closes every column that HOLDS something: retyping a * pre-set `followers` column would strand real measurements in a column that can no longer read * them. * * ⛔ THE CLIENT MIRROR OF `core.user_tables.preset_editable`, and `verify_rollup_editor.py` * holds the two in step. This check has THREE enforcement points (here, `may_edit_field`, and * `routes_tables._field_or_refuse`'s sentence); a client that kept hiding the editor while the * route allowed the PATCH would read as "you fixed nothing", which is the failure mode a fix in * one of three places always wears. */ function isSchemaLocked(field: Field): boolean { return field.automation?.preset === true && field.type !== "rollup"; } /** * ⭐⭐ W41-T40 (owner instruction 16, contract C8) — THE KINDS THAT TOTAL THE MOMENT THEY EXIST. * * Owner: *"Every number field and every formula returning a number shows its sum at the bottom * of the table AND per group when grouped."* * * ⛔ COVERAGE IS NOT NUMERIC-NESS, IT IS WHO STAMPS `field.agg`. `computeAggs` folds every type * `isNumericFieldType` admits — which has included `metric` and `rollup` since 2026-08-07 — and * folds NOTHING that carries no `agg`. This door stamped `currency` and `int` alone, so a `pct`, * a `metric` and a `rollup` were created foldable and never folded, under a picker that * cheerfully offered Sum on all three. The fold was never the missing half. * * ⛔ `sum` rather than a per-kind guess: the instruction says sum, and the column menu's summary * picker is one click away for a column that wants Average. A default nobody can predict is * worse than one they can. * * ⚠ A rollup or formula whose fold returns TEXT (`concatenate`, `arrayjoin`) is stamped too and * simply renders blank — `computeAggs` returns nothing when a set holds no numeric value at all. * That is the same imprecision `formula` has carried since wave 5; see `isNumericFieldType`. * * ⛔ THE MEASURE DOOR IS NOT THIS DOOR AND MUST NOT COPY THIS LIST. A `measure_` column's `agg` * is decided SERVER-side and hard-coded twice (`aios_grid.clean_measure_field` and the read arm * of `fields_from_workspace`: `"agg": "sum" if mtype in ("currency", "int") else None`). Widening * the optimistic client def alone would total a `pct` measure for the seconds before the * workspace echo lands and then silently stop — a green build over a dead feature. * * ⛔⛔ `metric` IS A MEMBERLESS ARM TODAY, AND SAYING SO IS THE POINT. It is deliberately absent * from `CREATABLE_TYPES` (see the `FieldType` union: the column menu has no measure/window face, * so offering it would mint permanently blank columns) — metric columns are SPAWNED by * automations as pre-set fields, and no spawn reaches this constructor. So this entry stamps * nothing that exists: it is forward cover for the day the kind becomes creatable, kept for the * same reason `aios_grid.py` keeps its memberless preset-measure branch. ⛔ **It must never be * read as evidence that metric columns total.** They do not; the def that spawns them carries no * `agg`, and `user_tables.clean_fields` (:971) preserves only what its writer supplied. That * stamp belongs to the spawn path, which is server-side. */ const DEFAULT_SUMMED_TYPES: readonly FieldType[] = ["currency", "int", "pct", "metric", "rollup"]; /** Transport acceptance is not a field-save acknowledgement. */ function waitForFieldWrite( event: Extract, scope: SurfaceScope, emit: (event: HostEvent) => boolean ): Promise { return new Promise((resolve) => { let settled = false; let unsubscribe = () => {}; let unsubscribePending = () => {}; let timer: ReturnType | undefined; const finish = (saved: boolean) => { if (settled) return; settled = true; unsubscribe(); unsubscribePending(); clearTimeout(timer); resolve(saved); }; const matches = (edit: OutboxEdit) => { const payload = edit.payload as HostEvent | null; return edit.id === event.id && edit.scope === scope && edit.kind === "event" && payload?.type === "field_upsert" && payload.id === event.id && payload.field?.key === event.field.key; }; const pending = () => editOutbox.snapshot().pending.some(matches); unsubscribe = editOutbox.subscribeReceipts((edit, receipt) => { if (matches(edit) && receipt.id === event.id && (receipt.ok || receipt.confirmedRefusal === true)) finish(receipt.ok); }); unsubscribePending = editOutbox.subscribe(() => { // Success removes the pending entry immediately before broadcasting its receipt. queueMicrotask(() => { if (!settled && !pending()) finish(false); }); }); // Queued intent follows the outbox's retries and session boundary, not this UI deadline. timer = setTimeout(() => { if (!pending()) finish(false); }, 60_000); try { if (!emit(event)) finish(false); } catch { finish(false); } }); } function buildOverlayField( label: string, type: FieldType, options?: string[], extra?: FieldBuildExtra ): Field { const key = `custom_${slugify(label)}_${Math.random().toString(36).slice(2, 7)}`; if (type === "formula" || type === "created_time") { return { key, label, type, source: "odoo", derived: true, filterable: true, default: true, custom: true, ...(type === "formula" ? { agg: "sum", ...(extra?.formula ? { formula: extra.formula } : {}) } : {}), }; } return { key, label, type, source: "overlay", default: true, custom: true, // W41-T40 — see `DEFAULT_SUMMED_TYPES`. The POST body below forwards whatever this stamps // (`...(field.agg ? { agg: field.agg } : {})`), and both read paths preserve `agg` for ANY // type in `FIELD_AGGS` (`aios_grid` :795, `user_tables` :971/:2157), so the stamp survives // the round trip rather than living until the first echo. agg: DEFAULT_SUMMED_TYPES.includes(type) ? "sum" : undefined, // The relational bags ride the local definition too, so the optimistic field and the // server's echo describe the same column. Without them the grid held a bagless twin of a // field the store had configured, and `mayEditField`/`isDerivedLink` read the twin. ...(extra?.link ? { link: extra.link as Field["link"] } : {}), ...(extra?.rollup ? { rollup: extra.rollup as Field["rollup"] } : {}), ...(extra?.if ? { if: extra.if } : {}), // ⭐⭐ W37-T22 (R4 / C7) — the geocode bag rides the local definition too, so the optimistic // field and the server's echo describe the same column. Without this line the grid would hold // a bagless twin of a column the store HAD configured, and every reader of `field.geocode` // (the enricher's target picker, the map's coordinate offer) would read the twin. ...(extra?.geocode ? { geocode: extra.geocode as Field["geocode"] } : {}), ...((type === "select" || type === "multiselect") && options?.length ? { options } : {}), ...((type === "select" || type === "multiselect") ? { colorCodeOptions: extra?.colorCodeOptions !== false, ...(extra?.optionColors && Object.keys(extra.optionColors).length ? { optionColors: extra.optionColors } : {}), } : {}), ...(type === "multiselect" ? { multi: true } : {}), ...(type === "rating" ? { max: extra?.max ?? 5 } : {}), ...(extra && "defaultValue" in extra ? { defaultValue: extra.defaultValue ?? undefined } : {}), }; } /** The surface this grid draws. `cohort` is the same table over hand-curated SETS — the server * confirms it by stamping `workspace.cohortMode`, which is the only thing the body below reads. * * MEMOIZED (owner item 1, 2026-07-31): the shell re-renders on every chrome state flip — nav * collapse, toast, settings — and an unmemoized grid re-rendered its whole 3,400-line tree * each time. Measured cost: 200ms-5s of main-thread block, which ate the 240ms rail-fold * transition whole (the fold froze, then SNAPPED — the exact "static" the owner named). The * props surface is one stable string, so memo makes chrome state changes free; the grid still * re-renders for its own state (edits, resize) and remounts on route change via `key`. */ /* ═══ ⭐⭐ W50-T02 — THE GROUP FOLD, INVERTED AND MOVED OUT OF THE PIPELINE ═══════════════════ * * Owner instruction 1: *"Group module closed by default, and the data to show all by default."* * Owner instruction 2: *"When a Grid view is grouped, the user can click Collapse all and the * opposite (Expand all)."* (R16 read both back verbatim.) * * ⭐ WHY THE SET IS INVERTED. The state used to be `collapsed` — the group keys a reader had * folded — and "everything folded on mount" cannot be written that way: the keys are minted by * the pipeline, so the default would have to know the answer before the question ran. An * `expanded` set says it with no keys at all: EMPTY MEANS EVERY GROUP IS FOLDED, and a key is * added only when somebody opens that group. * * ⛔⛔ AND WHY THE FOLD IS NO LONGER A PIPELINE INPUT — THIS IS THE HALF THAT IS EASY TO GET * WRONG AND EXPENSIVE TO GET WRONG. `groupRows` OMITS a folded group's data rows from * `visibleRows`, and `visibleRows` is what the whole surface derives its ANSWERS from: * `pidToIndex.size` is the toolbar's record count, `totalsAggs` is the grand total, * `filteredPids` is the bulk-selection domain, and `modeDataRows` is every card view's data. * Folding inside the pipeline and then folding by DEFAULT would open the grid reading "0 * records" over a full book, with a grand total to match — the second clause of instruction 1 * ("the data to show all by default") broken by the first. * * ⭐ SO THE PIPELINE RUNS UNFOLDED (`EMPTY_COLLAPSED`) AND THE FOLD IS A PRESENTATION PASS OVER * ITS OUTPUT. That is not a new principle here, it is the one this repo already wrote down * twice: `export.ts:76` ("export always runs with an EMPTY collapsed set, so no bucket is * folded") and the export bucketing pass below ("a group the reader happens to have folded on * screen must still export its rows"). A fold is what a reader is LOOKING at; it is never what * the view MATCHED. * ⚠ A consequence worth stating rather than leaving to be met: `recordCount` no longer drops to * 0 when a reader folds every group. That was true before this change and nothing reported it. */ const EMPTY_COLLAPSED: Set = new Set(); /** ⭐ W50-T03 — ONE frozen empty map for every view that has chosen no summary yet, for * `EMPTY_COLLAPSED`'s reason exactly: a fresh `{}` per render is a new identity, and every * memo keyed on it would recompute the whole fold on every frame. */ const EMPTY_SUMMARY: SummaryMap = {}; /** ⭐ W50-T05 — referentially stable, so a server-windowed table with no C1 answer yet does not * change `getCellContent`'s identity on every render and repaint the whole canvas. */ const EMPTY_SHARE_TOTALS: Record = {}; /** ⭐ W50-T05 — half the gap between the value line and the share under it, in canvas pixels. * ⚠ NOT a font size and not a stylesheet rule: this is a baseline offset either side of the * cell's centre, so the pair stays vertically centred at every row height the grid offers. */ const SHOW_AS_LINE_GAP = 7; /** ⭐ W50-T05 — the marker `ui/fmt.ts::withShare` composes `both` with, and the ONLY line break * any cell's `displayData` carries. Named rather than inlined so the writer and the reader of * this protocol cannot drift, and so a search for it finds both ends. */ const SHOW_AS_BREAK = "\n"; // S70-T12: mirror modes keep the predicate on the server. Group keys stay JSON scalars, // including null; the general aggregate parser turns them into strings for canvas headers. const WINDOWED_VIEW_MODES: readonly DisplayMode[] = [ "grid", "list", "gallery", "kanban", "calendar", "chart", "map", ]; type ModeGroup = { key: string | number | null; label: string; count: number; aggregates: Record }; type ModeGroups = { groups: ModeGroup[]; totalGroups: number; totalRows: number; aggregates: Record }; type ModeAgg = { colId: string; agg: string; p?: number }; async function mirrorModeGroups(table: string, req: RowWindowRequest, by: string, aggs: ModeAgg[], offset: number, size: number, abort: AbortSignal, rowSource?: EmbeddedRowSource): Promise { if (rowSource) return rowSource.readGroups(req, by, aggs, offset, size); const response = await fetch(`${API_V1}/odoo-tables/${encodeURIComponent(table)}/aggregates`, { method: "POST", credentials: CREDENTIALS, signal: abort, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ filters: req.filters ?? [], filterConj: req.filterConj ?? "and", search: req.search ?? "", related: req.related, ids: req.ids, groupBy: by, groupOffset: offset, groupLimit: size, aggs }), }); if (checkTenant(response)) throw new Error("Your workspace changed. Reloading."); if (response.status === 401) { signal(UNAUTHORIZED_EVENT); throw new Error("Sign in to read this window."); } const body = await response.json().catch(() => null); if (!response.ok) throw new Error(refusalMessage(body, response.status)); if (!body || !Array.isArray(body.groups) || typeof body.total_groups !== "number" || typeof body.total_rows !== "number") throw new Error("Groups could not be read for this window."); // A dropped group, range or subtotal would describe a different population. Refuse the // mode in words, instead of painting a plausible partial answer or a page-derived total. if (Array.isArray(body.limits) && body.limits.length) { const cause = body.limits.map((limit: { cause?: string }) => limit.cause).filter(Boolean).join(". "); throw new Error(`This window could not be grouped${cause ? `: ${cause}` : "."}`); } return { groups: body.groups, totalGroups: body.total_groups, totalRows: body.total_rows, aggregates: body.aggregates ?? {} }; } // Count-only reads use the existing permission-scoped aggregate door. Unlike the summary // bridge, an empty aggs list is intentional and a malformed total never defaults to zero. async function readImportantViewCount(table: string, view: SavedView, related: RelatedPin | null, abort: AbortSignal): Promise { try { const response = await fetch(`${API_V1}/odoo-tables/${encodeURIComponent(table)}/aggregates`, { method: "POST", credentials: CREDENTIALS, signal: abort, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ filters: view.config.filters ?? [], filterConj: view.config.filterConj ?? "and", search: "", related, aggs: [] }), }); if (checkTenant(response)) return null; if (response.status === 401) { signal(UNAUTHORIZED_EVENT); return null; } if (!response.ok) return null; return serverViewCount(await response.json().catch(() => null)); } catch { return null; } } function productsFrozenDetail(payload: (CustomersPayload & { paused?: boolean; frozenAt?: number }) | null) { if (payload?.paused !== true || typeof payload.frozenAt !== "number" || !Number.isFinite(payload.frozenAt) || payload.frozenAt <= 0) return null; // scope_cache stores Unix wall-clock seconds, not milliseconds or a monotonic clock. const frozenAt = new Date(payload.frozenAt * 1000); if (!Number.isFinite(frozenAt.getTime())) return null; const stamp = frozenAt.toLocaleString(undefined, { year: "numeric", month: "long", day: "numeric", hour: "numeric", minute: "2-digit", timeZoneName: "short", }); const note = limitSummary(payload.limits?.filter((entry) => entry.effect === "frozen") .map((entry) => ({ ...entry, cause: `Odoo is paused with data as of ${stamp}.` })), undefined, () => "Products"); return note?.full ?? null; } function MirrorModeSkeleton() { return
; } function MirrorModeFailure({ message, retry }: { message: string; retry: () => void }) { const plain = message.replace(/[\u2013\u2014]/g, ","); const sentence = plain.split(/\.\s/)[0]; return
{sentence}{" "}
; } // Small group/day windows have the same buttons as a grid footer. Previous/Next remain // disabled while loading; there is no Show all door or bound on the reachable population. function MirrorWindowPager({ offset, size, total, pending, label, onPage }: { offset: number; size: number; total: number; pending: boolean; label: string; onPage: (offset: number) => void; }) { return ; } function useMirrorGroups(table: string, request: RowWindowRequest, field: Field, aggs: ModeAgg[], offset: number, size: number, active = true, rowSource?: EmbeddedRowSource) { const key = JSON.stringify([table, request, field.key, aggs, offset, size, active, rowSource?.key]); const [answer, setAnswer] = useState<{ key: string; data?: ModeGroups; error?: string }>({ key: "" }); const [retry, setRetry] = useState(0); useEffect(() => { const abort = new AbortController(); let live = true; setAnswer({ key }); if (!active) return () => { live = false; abort.abort(); }; void mirrorModeGroups(table, request, field.key, aggs, offset, size, abort.signal, rowSource).then( (data) => { if (live) setAnswer({ key, data }); }, (error: unknown) => { if (live) setAnswer({ key, error: error instanceof Error ? error.message : "Groups could not be read for this window." }); }); return () => { live = false; abort.abort(); }; // The serialized key is the complete request; equal objects do not restart a fetch. // eslint-disable-next-line react-hooks/exhaustive-deps }, [key, retry]); return { data: answer.key === key ? answer.data : undefined, error: answer.key === key ? answer.error : undefined, retry: () => setRetry((n) => n + 1) }; } function MirrorRecordWindow({ table, request, field, group, titleKey, fieldByKey, cardKeys, size, calendar = false, onOpen, rowSource }: { table: string; request: RowWindowRequest; field: Field; group: ModeGroup; titleKey: string; fieldByKey: Map; cardKeys: string[]; size: number; calendar?: boolean; hosted?: boolean; onOpen: (record: Row) => void; rowSource?: EmbeddedRowSource; }) { const [offset, setOffset] = useState(0); const [retry, setRetry] = useState(0); const key = JSON.stringify([table, request, field.key, group.key, offset, size, rowSource?.key]); const [page, setPage] = useState<{ key: string; rows?: Row[]; total?: number; error?: string }>({ key: "" }); const seq = useRef(0); useEffect(() => { const current = ++seq.current; let live = true; setPage({ key }); const readWindow = rowSource ? (_table: string, query: RowWindowRequest, _onFailure: (reason: string) => void) => rowSource.readWindow(query) : fetchTableWindow; void readWindow(table, { ...request, offset, limit: size, group: { by: field.key, key: group.key } }, (reason) => { if (live && seq.current === current) console.debug("[CustomerGrid]", "record window failure", reason); }) .then((result) => { if (!live || seq.current !== current) return; if (!result) { console.debug("[CustomerGrid]", "record window failure", "Window request failed."); setPage({ key, error: "Records unavailable." }); return; } // A deep OFFSET may be slow but remains reachable. Only a changed predicate or // unsupported projection refuses; informational latency never becomes a row cap. const resultFieldByKey = new Map(result.fields.map((field) => [field.key, field])); const windowLimitNote = limitSummary(result.limits, result.counts, (key) => resultFieldByKey.get(key)?.label); if (windowLimitNote) console.debug("[CustomerGrid]", "record window limit", windowLimitNote.full); const limit = limitSummary(result.limits?.filter((entry) => entry.effect !== "slow" && entry.effect !== "none"), result.counts, (key) => resultFieldByKey.get(key)?.label); if (limit) { setPage({ key, error: "Records unavailable." }); return; } const total = result.counts?.matched ?? group.count; if (offset >= total && offset > 0) { setOffset(Math.max(0, Math.ceil(total / size) - 1) * size); return; } setPage({ key, rows: result.rows, total }); }, () => { if (live && seq.current === current) { console.debug("[CustomerGrid]", "record window failure", "Window request failed."); setPage({ key, error: "Records unavailable." }); } }); return () => { live = false; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [key, retry]); const settled = page.key === key; const rows = settled ? page.rows : undefined; const error = settled ? page.error : undefined; const pending = !rows && !error; const open = (row: Row) => { signal(NAV_MINIMIZE_EVENT); onOpen(row); }; return <>
{pending ? : error ? setRetry((n) => n + 1)} /> : rows?.length === 0 ?
No records
: rows?.map((row) => calendar ? :
open(row)} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); if (!event.repeat) open(row); } }}> {String(row[titleKey] ?? "")} {cardKeys.map((key) => { const f = fieldByKey.get(key); if (!f) return null; const text = formatDisplay(f, row[key]); if (!text) return null; const href = actionHref(f, row[key]); const tint = f.type === "select" || f.type === "status" ? optionTint(f, text) : undefined; return ; })}
)}
{(page.total ?? group.count) > size && } ; } function MirrorKanban({ table, request, field, fieldByKey, cardKeys, titleKey, size, clamped, aggs, summaryMap, hosted = false, onOpen, onAddOption, rowSource }: { table: string; request: RowWindowRequest; field: Field; fieldByKey: Map; cardKeys: string[]; titleKey: string; size: number; clamped: boolean; aggs: ModeAgg[]; summaryMap: SummaryMap; hosted?: boolean; rowSource?: EmbeddedRowSource; onOpen: (record: Row) => void; onAddOption: ((anchor: AnchorRect) => void) | null; }) { const [offset, setOffset] = useState(0); const columnsPerPage = 12; const { data, error, retry } = useMirrorGroups(table, request, field, aggs, offset, columnsPerPage, true, rowSource); useEffect(() => { if (data && offset >= data.totalGroups && offset > 0) setOffset(Math.max(0, Math.ceil(data.totalGroups / columnsPerPage) - 1) * columnsPerPage); }, [data, offset]); return
{error ? : !data ? : data.groups.length === 0 ?
No records match this view.
:
{data.groups.map((group) => { const tint = typeof group.key === "string" && group.key ? optionTint(field, group.key) : undefined; return
{group.label || "(empty)"} {group.count.toLocaleString()}
{aggs.map((agg) => { const f = fieldByKey.get(agg.colId); const value = group.aggregates[agg.colId]; return f && value != null ?
{f.label} {formatServerAgg(f, resolveSummary(f, summaryMap), value, data.aggregates[agg.colId])}
: null; })}
; })}{onAddOption &&
}
} {data && data.totalGroups > columnsPerPage && }
; } function MirrorCalendar({ table, request, field, fieldByKey, titleKey, today, size, summary, metrics, hosted = false, onOpen, rowSource }: { table: string; request: RowWindowRequest; field: Field; fieldByKey: Map; titleKey: string; today?: string; size: number; summary: boolean; hosted?: boolean; rowSource?: EmbeddedRowSource; metrics?: { id: string; field: string; agg: string }[]; onOpen: (record: Row) => void; }) { const [pickedMonth, setMonth] = useState(""); const month = pickedMonth || (today && /^\d{4}-\d{2}-\d{2}/.test(today) ? today.slice(0, 7) : ""); const year = Number(month.slice(0, 4)), m = Number(month.slice(5, 7)); const days = month ? new Date(Date.UTC(year, m, 0)).getUTCDate() : 0; const range: RowWindowRequest = { ...request, filterConj: "and", filters: [ ...(request.filters?.length ? [{ conj: request.filterConj === "or" ? "or" as const : "and" as const, children: request.filters }] : []), { colId: field.key, op: "between", value: `${month}-01`, value2: `${month}-${String(days).padStart(2, "0")}` }, ] }; const aggs = summary ? (metrics ?? []).map((metric) => ({ colId: metric.field, agg: metric.agg === "avg" ? "average" : metric.agg })) : []; const { data, error, retry } = useMirrorGroups(table, range, field, aggs, 0, 42, !!month, rowSource); const shift = (delta: number) => setMonth(new Date(Date.UTC(year, m - 1 + delta, 1)).toISOString().slice(0, 7)); const leading = month ? (new Date(Date.UTC(year, m - 1, 1)).getUTCDay() + 6) % 7 : 0; const cells = Array.from({ length: Math.ceil((leading + days) / 7) * 7 }, (_, i) => i >= leading && i < leading + days ? i - leading + 1 : null); const groups = new Map(data?.groups.map((group) => [String(group.key), group])); const calendarError = error || (data && (data.totalGroups !== data.groups.length || data.groups.some((group) => !new RegExp(`^${month}-\\d{2}$`).test(String(group.key)))) ? "This window could not be grouped by day." : undefined); if (!month) return
Calendar needs a date anchor.
; return
{new Date(Date.UTC(year, m - 1, 1)).toLocaleDateString(undefined, { month: "long", year: "numeric", timeZone: "UTC" })} {today && } {data && {data.totalRows.toLocaleString()} records}
{calendarError ? : !data ? : <>{data.totalRows === 0 &&
No records this month.
}
{["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].map((day) =>
{day}
)} {cells.map((day, index) => { const iso = day ? `${month}-${String(day).padStart(2, "0")}` : ""; const group = groups.get(iso); return
{day}
{group && <>{group.count.toLocaleString()} records {summary ? (metrics ?? []).map((metric) => { const f = fieldByKey.get(metric.field), value = group.aggregates[metric.field]; return f ?
{f.label}{" "} {value == null ? "Unavailable" : formatServerAgg(f, { agg: (metric.agg === "avg" ? "average" : metric.agg) as SummaryChoice["agg"] }, value)}
: null; }) : } }
; })}
}
; } /** The session key a view's own fold is remembered under. ⛔ EXACT SHAPE, named by the ticket: * `cg-fold::`. `tableKey` is the surface scope (`customer`, `product`, * `ut_*`), the same identity `useGridSelection` keys its own per-surface memory on. */ export function foldKeyFor(tableKey: string, viewId: string): string { return `cg-fold:${tableKey}:${viewId}`; } /** Read a view's remembered OPEN groups. Session-scoped and best effort: storage can be blocked * (private windows, embedded frames) and the fold must still work, so every failure is the * default — everything folded. */ function readFoldMemory(key: string): Set { if (typeof window === "undefined") return new Set(); try { const raw = window.sessionStorage.getItem(key); if (!raw) return new Set(); const parsed: unknown = JSON.parse(raw); if (!Array.isArray(parsed)) return new Set(); return new Set(parsed.filter((k): k is string => typeof k === "string")); } catch { return new Set(); } } /** ...and the write half. Same contract: a refusal is silent and costs the reader nothing. */ function writeFoldMemory(key: string, expanded: ReadonlySet): void { if (typeof window === "undefined") return; try { window.sessionStorage.setItem(key, JSON.stringify([...expanded])); } catch { /* storage blocked — the fold still works, it just does not survive a remount */ } } /** * The presentation pass: hide the body of every group the reader has not opened. * * ⚠ RETURNS THE INPUT ARRAY UNCHANGED when nothing is folded, and that identity is load-bearing * rather than tidy: `displayPidToIndex` uses it to know it may reuse the pipeline's own index * map, which is what keeps the ungrouped grid free of a per-render pass over every row. * ⚠ A folded group KEEPS ITS HEADER (with its count and its subtotals, both computed over the * whole bucket) and loses its footer — the same shape `groupRows` produces for a folded group, * so nothing downstream can tell which of the two folded it. */ /** * HOTFIX 2026-09-24 — PAGE A WHOLE-BOOK LIST. Ungrouped: the data rows `[offset, offset + size)`. * Grouped: every group keeps its header and footer, an open group shows `size` of its rows from * its own offset, and its footer carries `page` so the same footer pager the read-through grid * uses can move it. Totals were computed over the whole bucket before this, so they stay whole. */ export function pageClientRows( rows: VisibleRow[], offset: number, size: number, groupOffsets: ReadonlyMap ): VisibleRow[] { const grouped = rows.some((vr) => vr.kind === "group-header"); if (!grouped) { const data = rows.filter((vr) => vr.kind === "data"); if (data.length <= size && offset === 0) return rows; return data.slice(offset, offset + size); } const out: VisibleRow[] = []; let bucket: VisibleRow[] = []; let key = ""; const flush = (footer: VisibleRow | null) => { const start = groupOffsets.get(key) ?? 0; out.push(...bucket.slice(start, start + size)); if (footer && footer.kind === "group-footer") { out.push(bucket.length > size ? { ...footer, page: { offset: start, total: bucket.length, size } } : footer); } bucket = []; }; for (const vr of rows) { if (vr.kind === "group-header") { key = vr.groupKey; out.push(vr); } else if (vr.kind === "data") { bucket.push(vr); } else { flush(vr); } } if (bucket.length) flush(null); return out; } export function foldGroups(rows: VisibleRow[], expanded: ReadonlySet): VisibleRow[] { const out: VisibleRow[] = []; let hidden = false; let touched = false; for (const vr of rows) { if (vr.kind === "group-header") { const folded = !expanded.has(vr.groupKey); hidden = folded; if (folded !== vr.collapsed) touched = true; out.push(folded === vr.collapsed ? vr : { ...vr, collapsed: folded }); continue; } if (hidden) { touched = true; continue; } out.push(vr); } return touched ? out : rows; } /** * ⭐⭐ WAVE 50 · W50-T04 · OWNER RULINGS R3 + R4 — **GROUP ANALYTICS, AS ONE PURE PASS.** * * R3: *"every group header carries the same summary bar as the footer (every chosen aggregate, * count, % of total)."* R4: *"% of total base is ALWAYS the view's grand total."* * * ⛔⛔ **THE DENOMINATOR IS TAKEN FROM `rows` — THE MATCHED SET, UNFOLDED — AND FROM NOWHERE * ELSE, WHICH IS THE WHOLE OF R4.** The caller hands this the pipeline's own `visibleRows`, not * `foldedRows` and not `displayRows`, for exactly the reason W50-T03 spelled out one memo up: a * fold is a reader's choice about what to LOOK AT. A denominator that followed the fold would * make every share on the screen change as somebody tidied it, and the column would stop adding * to 100. ⛔ It is equally never the SUM OF THE GROUPS: over C1's 1,000-group cap that would * total only the largest buckets, and no median composes from per-group medians at any cap. * * ⛔ **AND IT RESOLVES THROUGH THE VIEW'S `summary` MAP, WHICH `groupRows` DOES NOT.** * `useVisibleRows.groupRows` calls `computeAggs(bucket, fields)` with NO map — the legacy path, * i.e. `field.agg` or nothing — so a header showed a blank where the summary bar showed a Sum, * and R3's "the SAME summary bar as the footer" was false by construction. Both the header's * aggregate and the footer's are recomputed here under the map, so all three rows agree. * ⭐⭐ W51-T02 / R3 — **AND THE HEADER AND THE FOOTER NOW CARRY THE SAME ONE VALUE.** W50-T04's * note here said the share rode the header only, because the header composed an aggregate AND an * automatic share while the footer showed the aggregate alone. R3 removed the composition, so * both rows paint the picker's single choice; a reader who wants a share picks "% of total" and * gets it in both places, which is the ruling's "the picker OWNS group headers and the bar". * ⚠ The group's ROW-COUNT share still rides the header's LABEL alone (`out.share` below) — that * is a property of the grouping, not of a column, and a footer has no label to carry it. * * ⚠ A MULTI-VALUE group column puts one record in several buckets (`groupRows`' own rule, owner * 2026-07-27), so those groups' counts sum to more than the view's row count and their shares * to more than 100%. That is the grouping's arithmetic, not this pass's: R4 fixes the BASE, and * changing the base per group is the thing it forbids. * * ⚠ RETURNS ITS INPUT BY IDENTITY when there is no group header to enrich — the same contract * `foldGroups` holds, and for the same reason: `displayPidToIndex` reads that identity to know * it may reuse the pipeline's map instead of walking every row on every render. */ export interface GroupAnalytics { /** * groupKey -> the HEADER's per-column string: ⭐ W51-T02 / R3 — ONE VALUE PER COLUMN, and it * is the bottom bar's picker's choice, "% of total" included. Under W50-T04 this map carried * the aggregate AND an automatic share; instruction 1 is that second number. */ head: Map>; /** * groupKey -> the FOOTER's per-column string. ⚠ THE SAME CONTENT AS `head` SINCE W51-T02, and * the two maps are kept apart anyway: R3 makes a header and a footer say the same thing today, * and folding them into one field would make the next divergence a refactor rather than an * assignment. `applyGroupAnalytics` stamps each onto its own row kind. */ foot: Map>; /** groupKey -> the group's ROW COUNT as a share of the view's grand row count. */ share: Map; /** groupKey -> that group's RAW aggregate per column. Summary mode sorts on these, because * sorting the DISPLAY strings would order "$9" after "$1,204" and call it descending. */ nums: Map>; } export function groupAnalytics( rows: VisibleRow[], fields: Field[], summary: SummaryMap ): GroupAnalytics { const out: GroupAnalytics = { head: new Map(), foot: new Map(), share: new Map(), nums: new Map(), }; let headers = 0; for (const vr of rows) if (vr.kind === "group-header") headers += 1; if (!headers) return out; const buckets = new Map(); const all: Row[] = []; let open: Row[] | null = null; for (const vr of rows) { if (vr.kind === "group-header") { open = buckets.get(vr.groupKey) ?? []; buckets.set(vr.groupKey, open); continue; } if (vr.kind === "group-footer") { open = null; continue; } if (vr.kind !== "data") continue; all.push(vr.record); if (open) open.push(vr.record); } const grandNums = computeAggNumbers(all, fields, summary); const grandRows = all.length; for (const [key, bucket] of buckets) { /* ⭐⭐ W51-T02 / R3 — THE VIEW'S TOTALS RIDE INTO THE SAME FOLD, AND THAT IS THE WHOLE MECHANISM. W50-T04 folded the bucket, folded it again raw, then composed an automatic second number on top. R3 retired the composition: "% of total" is now one of the picker's choices, so a share is produced BY the fold rather than beside it, and `grandNums` is the denominator it divides by. One value per column, and it is the reader's own choice. */ const groupText = computeAggs(bucket, fields, summary, grandNums); const groupNums = computeAggNumbers(bucket, fields, summary); out.nums.set(key, groupNums); out.foot.set(key, groupText); out.head.set(key, groupText); /* The ROW COUNT's own share, and it rides the LABEL because the count does. The painter draws `▼