runloopable / web /src /sheet /BindingEditor.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
8133df9 verified
Raw History Blame Contribute Delete
126 kB
// sheet/BindingEditor.tsx — what a bound cell points at (wave 49, W49-T06, R4/R8/R14; // wave 51, W51-T12, R9/R10/R11). // // ⭐⭐ R4 SAYS "THE FILTER USES THE EXACT SAME UI AS A VIEW'S FILTER", SO THIS MOUNTS // `filter-kit/FilterBuilderPanel` ITSELF. That component turned out to need NO change to run here: // its only required props are `fields`, `filters` and `onChange`, and its own docstrings already // anticipate "a panel over a module whose rows it has never loaded" - which is exactly a Sheet // cell. The ticket allowed adding an optional prop if one were needed; none was. // // ⛔ THE FILTER TREE SAVED HERE IS BYTE-COMPATIBLE WITH A VIEW'S. `FilterBuilderPanel` emits a // `FilterTree` (`{conj, nodes}`) and that value is stored verbatim on the binding. Inventing a // second shape here is the failure C2 names: the server compiles a view's filter and a cell's // filter through the same `compile_filter_tree`, so two shapes would mean two dialects and one of // them would eventually stop being tested. // // ⛔⛔ W51-T12 - THE ROOT NODE IS `.sheet-binding-panel` AND NOT `.sheet-binding`, AND THAT ONE // CLASS IS THE WHOLE TICKET. `styles/wave49/sheet.css` declares `.sheet-binding` as // `position: fixed; z-index: var(--cg-z-drawer)` - an OVERLAY, floating over the canvas it // describes. W50-QA-1 is what that costs: an absolutely positioned panel over the map made every // pin beneath it unclickable, and no z-index repairs document-order stacking. The design contract's // clause is that the right-side panel is a real COLUMN and the content beside it SHRINKS. // `.sheet-page` is already a flex row (`align-items: stretch`) and this component already renders // as one of its direct children, so a root of `flex: 0 0 380px` narrows `.sheet-body` - and that is // observable as a MEASUREMENT (the grid's own width with the panel open versus closed), which is // the one thing a screenshot cannot tell apart from an overlay. // // ⚠ THE NEW CLASS IS DELIBERATE, NOT COSMETIC. `wave49/sheet.css` loads from inside SheetPage's // LAZY chunk and therefore BEATS `styles/wave51/sheet-chrome.css` (imported eagerly by index.css) // at equal specificity, so an override of `.sheet-binding`'s `position` written in this lane's // sheet would lose the cascade and change nothing on screen // ([[a-lazy-chunk-stylesheet-beats-an-eager-one]]). A name nothing else declares has no fight to // lose. The INNER classes (`.sheet-field`, `.sheet-scope`, `.sheet-radio`, `.sheet-binding-title`, // `.sheet-binding-actions`) are all top-level selectors rather than descendants of `.sheet-binding`, // so every one of them keeps its shipped paint. // // ⚠ DESIGN CONTRACT: sentence case, quiet buttons, token-only colour and type, motion 150 ms // ease-out on opacity and transform, no emoji, and no em dash or en dash in any string on screen. import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react"; import { API_V1, CREDENTIALS } from "../apiContract"; import { fetchWorkspace, peekWorkspace } from "../customer-grid/apiBridge"; import type { SurfaceScope } from "../customer-grid/apiBridge"; import { dayText } from "../customer-grid/display"; import { FieldSelectButton } from "../customer-grid/FieldSelect"; import { FieldTypeIcon, MenuIcon } from "../customer-grid/icons"; import { BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/OverlaySurface"; import type { Field, FilterNode, FilterTree, GridWorkspace, Measure, SavedView } from "../customer-grid/types"; import { choiceVocabulary, isFilterGroup, MULTI_VALUE_OPS } from "../customer-grid/types"; import type { WindowSpec } from "../customer-grid/windows"; import { normalizeWindow, WINDOW_KINDS, ENDING_KINDS, ENDING_LABELS, ENDING_STEPS, TO_DATE_KINDS, endingBounds, endingStepDefault, MAX_N, windowLabel } from "../customer-grid/windows"; import type { EndingKind, EndingStep } from "../customer-grid/windows"; // ⭐⭐ W53-T15 (ruling R8) — THE FILTER BUILDER IS NO LONGER MOUNTED IN THIS COLUMN. The SHARED // `FilterBuilderPanel` the Data module also uses is untouched; `SheetFilterPopup` wraps it in the // base kit's centred dialog so its condition rows have room, and only the Sheet mounts that // wrapper. This file therefore stops importing the panel itself. import { countConditions, isNumericType } from "../filter-kit/ops"; import { SheetFilterPopup } from "../filter-kit/SheetFilterPopup"; import { FilterFieldStatusContext } from "../filter-kit/FilterBuilderPanel"; import type { FilterValuesState, RelatedFilterField, UnavailableRelatedFilterDatabase } from "../filter-kit/FilterBuilderPanel"; import { WindowPicker } from "../filter-kit/WindowPicker"; import { useEscapeClose } from "../ui/useEscapeClose"; import { fetchDistinctValues, previewCell, readWorkbook } from "./sheetApi"; import type { Workbook } from "./types"; import DrillModal from "./DrillModal"; import { formatRef, parseRef } from "./a1"; import { bindingAggregate, bindingDisplay, bindingFilterClauses, bindingOnDrag, bindingPeriod, bindingRelated, PERIOD_UNITS, BINDING_ENDING_STEP, BINDING_PERIOD_STEP, VIEW_BINDING_TYPES, VIEW_BINDING_LIMIT_DEFAULT, VIEW_BINDING_LIMIT_MAX } from "./types"; import type { BindingAggregate, BindingDragStep, BindingOnDrag, BindingPeriod, PeriodUnit, ViewBinding, DragAcross as SharedDragAcross } from "./types"; // D-687: the drag arithmetic has ONE owner, and it is the file the drag path itself calls. import { shiftPeriodStart } from "./sheetState"; import { useCellRefHighlight } from "./refHighlight"; import { bindingStepMode, bindingStepValues, resolveEndingCell, seedBindingStep, bindingRefSlots, filterValueLeaves, keepCellFilterValues, resolveFilterCell, showCellFilterValues, updateFilterValueLeaf, FILTER_REF_KEYS } from "./bindingRefs"; import type { ReadBindingCell } from "./bindingRefs"; import "../styles/wave57/binding-actions.css"; import "../styles/wave58/sheet.css"; import "../styles/wave59/binding.css"; import "../styles/wave66/binding.css"; const BINDING_SECTIONS = [ { key: "data", label: "Data", icon: <MenuIcon name="description" /> }, { key: "rows", label: "Filter", icon: <MenuIcon name="filter" /> }, { key: "copied", label: "When copied", icon: <MenuIcon name="duplicate" /> }, { key: "place", label: "Place", icon: <MenuIcon name="addEnd" /> }, ] as const; const clampViewLimit = (value: number): number => Number.isFinite(value) ? Math.min(VIEW_BINDING_LIMIT_MAX, Math.max(1, Math.trunc(value))) : VIEW_BINDING_LIMIT_DEFAULT; const AGGREGATES = [ { fn: "sum", label: "Sum" }, { fn: "count", label: "Count" }, { fn: "avg", label: "Average" }, { fn: "min", label: "Minimum" }, { fn: "max", label: "Maximum" }, ] as const; /** The fold's name inside a sentence. `AGGREGATES` carries the capitalised option text a select * needs; a heading reading "takes its Sum over" would be title case in the middle of a line, * which the design contract's sentence-case rule forbids. Same five folds, said the other way. */ const AGGREGATE_NOUN: Record<string, string> = { sum: "sum", count: "count", avg: "average", min: "minimum", max: "maximum", }; // ══ W53-T13: WHICH COLUMNS THE SERVER CAN ACTUALLY TOTAL (R7, standing rule 9) ═══════════════ // // ⭐⭐ THE PICKER MUST NOT OFFER A COLUMN THAT WILL REFUSE. `isNumericType` answers "does this // column behave like a number", which is the right question for the filter builder and the wrong // one here: a `formula` column is numeric to the filter kit and has NO SERVER VALUE AT ALL (it is // worked out in the browser for each row by `formulaEngine.ts`), so totalling it would ask the // database to add up a column it does not hold. `modules/sheet.py::aggregate_refusal` refuses it // by name at bind time; this predicate is what stops the person being sent there in the first // place, and the two have to agree or the picker offers a dead end. // // ⚠ IT IS A SECOND OPINION ABOUT THE SAME RULE, WHICH IS ACCEPTED HERE FOR ONE REASON: the server // is still the one that decides, and it refuses by name if this list is ever wrong. The client's // job is to keep a person out of a refusal, never to be the only thing checking. /** The rollup folds that produce a number. Mirrors `core/user_tables.py::ROLLUP_FNS`, minus the * folds that produce text or a boolean (`latest`, `and`/`or`/`xor`, `concatenate`, `arrayjoin`, * `arraycompact`, `arrayunique`). */ const NUMERIC_ROLLUP_FNS = [ "sum", "average", "stdev", "min", "max", "count", "counta", "countall", ]; /** A METRIC column: a business number measured over a window, rather than a value stored on the * record. The test is the `measure` bag, exactly as `aios_grid.measure_fields_of` tests it, never * the field's `type` (the two live ones on `customer_data` are typed `currency` and `int`). */ const isMetricField = (f: Field): boolean => Boolean(f.measure) || f.type === "metric"; /** Can this database add this column up? Mirrors `modules/sheet.py::aggregate_refusal`. */ const canTotal = (f: Field): boolean => { if (f.type === "formula") return false; if (f.type === "rollup") { const bag = f.rollup; if (!bag) return false; if (bag.source) return true; return NUMERIC_ROLLUP_FNS.includes(String(bag.fn ?? "")); } return true; }; /** A Sheet names a DATABASE KEY; the workspace door speaks `SurfaceScope`. Same pair as DrillModal. */ const scopeOf = (database: string): SurfaceScope | null => { if (database === "customer_data") return "customer"; if (database === "product_data") return "product"; return database.startsWith("ut_") ? (database as SurfaceScope) : null; }; // ══ THE PERIOD (R9) ═══════════════════════════════════════════════════════════════════════════ // // ⛔⛔ CONTRACT C2 SPELLS THIS ON THE WIRE AND THE UI DOES NOT GET A VOTE: // Unit values are lowercase on the wire. Day/Week starts use `YYYY-MM-DD`, with Week starting // on Monday; Month/Quarter/Year starts retain `YYYY-MM`. // A frozen period keeps that pair for returning to the calendar, and adds only // `frozen: true, from: "YYYY-MM-DD", to: "YYYY-MM-DD"` in place of a cell reference. // // ⭐ `start` IS THE PERIOD'S FIRST MONTH, and that is the decision the ticket leaves implicit. // `unit` and `start` have to jointly name exactly one period, so Q3 2026 is `2026-07` and the year // 2026 is `2026-01`. Stamping today's month under a quarter unit would agree with nothing: the // server compiler reads the pair, and two readings of `2026-08` under `quarter` (August, or Q3) // are a silent disagreement that no screen shows. export interface PeriodBinding extends BindingPeriod { frozen?: true; from?: string; to?: string; window?: WindowSpec; } // ⭐ D-687 - THE UNITS ARE `types.ts::PERIOD_UNITS` AND ARE NOT RE-TYPED HERE; ONLY THE WORDING IS // LOCAL. The table is keyed `Record<PeriodUnit, ...>` so a unit ADDED to the shared tuple is a // COMPILE ERROR here rather than a blank option, and the select is built by mapping the shared // tuple, so a unit REMOVED there leaves this control without a second edit. Each entry is written // out as an object literal because `verify_wiring.py:5641` reads three of them as literal text. const PERIOD_UNIT_LABELS: Record<PeriodUnit, { unit: PeriodUnit; label: string }> = { day: { unit: "day", label: "Day" }, week: { unit: "week", label: "Week" }, month: { unit: "month", label: "Month" }, quarter: { unit: "quarter", label: "Quarter" }, year: { unit: "year", label: "Year" }, }; const PERIOD_UNIT_OPTIONS = PERIOD_UNITS.map((unit) => PERIOD_UNIT_LABELS[unit]); const MONTH_NAMES = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; /** The noun a sentence uses for one step. Sentence case, and no dash anywhere near it. */ const UNIT_NOUN: Record<PeriodUnit, string> = { day: "day", week: "week", month: "month", quarter: "quarter", year: "year", }; const pad2 = (n: number) => String(n).padStart(2, "0"); /** `{year, month}` out of a `"YYYY-MM"`; today when the string is absent or malformed. */ function splitYm(ym: string): { y: number; m: number } { const hit = /^(\d{4})-(\d{2})$/.exec(ym ?? ""); if (!hit) { const now = new Date(); return { y: now.getFullYear(), m: now.getMonth() + 1 }; } const m = Number(hit[2]); return { y: Number(hit[1]), m: m >= 1 && m <= 12 ? m : 1 }; } const joinYm = (y: number, m: number) => `${y}-${pad2(m)}`; /** THE PERIOD'S FIRST MONTH, which is what `start` means. See the block above. */ export function normalizePeriodStart(unit: PeriodUnit, ym: string): string { if (unit === "day" || unit === "week") { const text = /^\d{4}-\d{2}$/.test(ym) ? `${ym}-01` : ym; const date = new Date(`${text}T00:00:00Z`); if (!Number.isFinite(date.getTime()) || date.toISOString().slice(0, 10) !== text) return text; if (unit === "week") date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 6) % 7); return date.toISOString().slice(0, 10); } const { y, m } = splitYm(ym.slice(0, 7)); if (unit === "year") return joinYm(y, 1); if (unit === "quarter") return joinYm(y, 1 + 3 * Math.floor((m - 1) / 3)); return joinYm(y, m); } /** The inclusive day range a calendar period covers. Mirrors * `platform/modules/sheet.py::period_window`, whose `to` is the LAST DAY of the period. */ export function periodRange(unit: PeriodUnit, ym: string): { from: string; to: string } { const start = normalizePeriodStart(unit, ym); if (unit === "day" || unit === "week") { const last = new Date(`${start}T00:00:00Z`); if (!Number.isFinite(last.getTime())) return { from: "", to: "" }; last.setUTCDate(last.getUTCDate() + (unit === "week" ? 6 : 0)); return { from: start, to: last.toISOString().slice(0, 10) }; } const last = new Date(`${shiftPeriodStart(start, unit, 1)}-01T00:00:00Z`); last.setUTCDate(last.getUTCDate() - 1); return { from: `${start}-01`, to: last.toISOString().slice(0, 10) }; } // ⚠ W53-T16 (instruction 13) - `periodLabel` LIVED HERE and is gone with the summary block that // was its only caller. The period a person reads is now the Year / Month / Quarter pickers // themselves, which is where they set it, so a second rendering of the same value had nothing left // to tell them. const todayYm = () => { const now = new Date(); return joinYm(now.getFullYear(), now.getMonth() + 1); }; /** * ⭐⭐ W51-T12 - THE READ-SIDE MIGRATION, AND IT IS A NAMED FUNCTION SO A GATE CAN PIN IT. * * Before this ticket a binding's period was `{ref}` and nothing else: a raw typed A1 string, with * no unit, no start and no lock. Under R9 an UNLOCKED period SHIFTS when the cell is copied across * columns, so reading an old binding as unlocked would change what a shipped cell answers the first * time somebody dragged it - a value moving on its own, with no edit and no warning. * * ⛔ SO A `ref`-ONLY PERIOD BECOMES LOCKED. `unit` and `start` are non-optional in C2 and have to * carry something, but on a ref-driven period they are INERT: the referenced cell decides the * period, and `locked: true` is what stops the drag rule from touching it either way. * * ⛔⛔ W53-T16 / D-660 - A STORED PERIOD THAT NAMES NO WINDOW READS BACK AS NO PERIOD, and this is * the READ half of the fix whose write half is `platform/modules/sheet.py::clean_period`. A period * carrying a unit but no usable `start` and no `ref` used to have TODAY'S MONTH filled in for it * here, so an all-time cell opened as "September 2026" and the next save narrowed it to one month * with nobody told. Filling a missing start is only legitimate when a `ref` decides the period * anyway, which is the inert case the paragraph above describes. */ export function migratePeriod(raw: unknown): PeriodBinding | null { if (!raw || typeof raw !== "object") return null; const p = raw as Record<string, unknown>; // D-687: types.ts belongs to another lane this wave, so wrap its reader rather than widen it. const shared = bindingPeriod({ period: p }); if (!shared) return null; const ref = shared.ref ?? ""; // ⛔ C5 - A DECLARED WINDOW MUST VALIDATE AS THE SHARED WINDOW VOCABULARY. Letting an invalid // window fall through would misread it as the legacy ref-only dialect or invent a calendar month. if ("window" in p) { const window = normalizeWindow(p.window); if (!window) return null; return { unit: "month", start: normalizePeriodStart("month", todayYm()), locked: true, window, ...(p.ending && typeof p.ending === "object" ? { ending: p.ending as PeriodBinding["ending"], endingStep: (p.endingStep ?? endingStepDefault(window.kind)) as EndingStep, endingOffset: Number(p.endingOffset ?? 0), locked: shared.locked, ...(ref ? { ref } : {}), } : {}), }; } const declared = PERIOD_UNITS.some((unit) => unit === p.unit); if (!declared) { // The legacy shape. Nothing shifts by surprise: it reads back LOCKED. if (!ref) return null; return { unit: "month", start: normalizePeriodStart("month", todayYm()), locked: true, ref }; } const { unit, start: stored, locked } = shared; // D-660: no window named, and no cell to take one from, so there is no period to read. const startPattern = unit === "day" || unit === "week" ? /^\d{4}-\d{2}-\d{2}$/ : /^\d{4}-\d{2}$/; if (!startPattern.test(stored) && !ref && p.frozen !== true) return null; const start = normalizePeriodStart(unit, stored || todayYm()); if (p.frozen === true) { return { unit, start, locked, frozen: true, from: typeof p.from === "string" ? p.from : "", to: typeof p.to === "string" ? p.to : "", }; } return ref ? { unit, start, locked, ref } : { unit, start, locked }; } // ══ THE DRAG RULES (R10) ══════════════════════════════════════════════════════════════════════ // // TWO DIRECTIONAL SETTINGS, and C2 spells them `onDrag: {across: "period"|"none", // down: {field: key}|"none"}`. Defaults: across = period, down = none. // ⛔⛔ THIS UNION IS STATED HERE ON PURPOSE AND D-687 DOES NOT REVOKE IT. `verify_wiring.py:5782` // reads this exact line as TEXT, because C2's wire vocabulary is what that leg was really for, and // this is the file that documents the wire. D-687 is about a SECOND OPINION that can drift in // silence, not about an absent declaration: the constant below makes any disagreement with // `types.ts::DragAcross` stop compiling, which is the outcome D-687 exists to get. export type DragAcross = "period" | "none"; export const DRAG_ACROSS_LOCK_STEP: [DragAcross, SharedDragAcross] extends [SharedDragAcross, DragAcross] ? true : never = true; export interface OnDragBinding { across: DragAcross; down: { field: string } | "none"; steps?: readonly BindingDragStep[]; } /** A copy step walks a column's stored values. Measure-backed and Metric columns are computed * numbers with no stored values to walk, so offering one promises a step `dragBoundCell` * cannot perform. * * S66-T16 / D-720 (R15, SDLC 66 board, 2026-09-25): a SET column (`multi`, or a multi-select) * is refused too. One cell of it holds several values, so "the next value down" has no single * answer, and the copy would bind a condition the person never picked. This supersedes the * 2026-09-16 re-anchor (W-145) that let a set column step by member; lane D's two * `verify_wiring.py` W58-T17 legs that pin that reading are a COMBINE-AMEND (context/S66-T16.md). */ export function isDragDownField(f: Field): boolean { if (f.multi || f.type === "multiselect") return false; return Boolean(f.key) && !f.key.startsWith("__") && !f.measure && f.type !== "metric"; } /** The saved `onDrag`, defaulted. `down` is carried as a field key, empty meaning nothing. */ export function readOnDrag(raw: unknown): { across: DragAcross; down: string } { const rules = bindingOnDrag({ onDrag: raw }); return { across: rules.across, down: rules.down === "none" ? "" : rules.down.field }; } /** `scope.adoptedFrom` (R11): the view was purged and its filter was copied into this cell. */ function adoptedFromOf(initial: Record<string, unknown> | null | undefined): string { const scope = initial?.scope as Record<string, unknown> | undefined; const adopted = scope?.adoptedFrom as Record<string, unknown> | undefined; const name = adopted?.name; return typeof name === "string" ? name : ""; } /** * ⭐⭐ W53-T12 — THE PANEL READS BACK WHAT WAS SAVED, WHICH IT DID NOT DO BEFORE. * * `database`, `period` and `onDrag` were hydrated from `initial`; `fn`, `field`, the scope kind, * the view id and the filter tree were NOT, so opening an already bound cell showed Sum, no * column and "Choose a view" no matter what the cell actually pointed at, and pressing Save wrote * those defaults over the real binding. Nothing could tell a person their saved view had gone * missing while the editor never showed which view they had saved. * * ⚠ AN AGGREGATE MAY CARRY `metric_key` INSTEAD OF `fn` (the server's normalizer accepts it and no * control here speaks it yet), so an unrecognised aggregate falls back to the panel's own defaults * rather than seeding a `<select>` with a value it has no option for. */ export function readAggregate(raw: unknown): { fn: string; field: string } { const a = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>; const named = typeof a.fn === "string" ? a.fn : ""; const known = AGGREGATES.some((x) => x.fn === named); return { fn: known ? named : "sum", field: known && typeof a.field === "string" ? a.field : "", }; } /** The saved scope: a view id, or a filter tree built in this panel. Neither means an empty view. */ export function readScope(raw: unknown): { kind: "view" | "filter"; viewId: string; tree: FilterTree; } { const empty: FilterTree = { conj: "and", nodes: [] }; const s = (raw && typeof raw === "object" ? raw : {}) as Record<string, unknown>; const viewId = typeof s.view_id === "string" ? s.view_id.trim() : ""; if (viewId) return { kind: "view", viewId, tree: empty }; const f = s.filter; if (f && typeof f === "object") { const t = f as Record<string, unknown>; return { kind: "filter", viewId: "", tree: { conj: t.conj === "or" ? "or" : "and", nodes: Array.isArray(t.nodes) ? (t.nodes as FilterTree["nodes"]) : [], }, }; } return { kind: "view", viewId: "", tree: empty }; } /** The view the binding NAMES, kept even after the id is cleared, so the notice can still say it. */ function savedViewOf(initial: Record<string, unknown> | null | undefined): { database: string; id: string; name: string; } { const scope = (initial?.scope ?? {}) as Record<string, unknown>; return { database: typeof initial?.database === "string" ? initial.database : "", id: typeof scope.view_id === "string" ? scope.view_id.trim() : "", name: typeof scope.view_name === "string" ? scope.view_name : "", }; } /** One-release compatibility: qualify leaves without discarding any operand or group. */ function rekeyFilter(tree: FilterTree, keyOf: (key: string) => string): FilterTree { const visit = (node: FilterNode): FilterNode => isFilterGroup(node) ? { ...node, children: node.children.map(visit) } : { ...node, colId: keyOf(node.colId), ...(node.rhs && "colId" in node.rhs ? { rhs: { ...node.rhs, colId: keyOf(node.rhs.colId) } } : {}) }; return { ...tree, nodes: tree.nodes.map(visit) }; } function initialFilterScope(initial: Record<string, unknown> | null | undefined) { const scope = readScope(initial?.mode === "view" ? { filter: initial.filter ?? { conj: "and", nodes: [] } } : initial?.scope); const rawScope = initial?.scope as Record<string, unknown> | undefined; const original = scope.kind === "view" && rawScope?.filter ? readScope({ filter: rawScope.filter }).tree : scope.tree; const legacy = bindingRelated(initial); if (!legacy) return { ...scope, tree: original }; const relatedTree = Array.isArray(legacy.filter) ? { conj: "and" as const, nodes: legacy.filter as FilterNode[] } : readScope({ filter: legacy.filter }).tree; const qualified = rekeyFilter(relatedTree, (key) => `related:${legacy.via}:${key}`); const nodes = original.conj === "or" && original.nodes.length ? [{ conj: original.conj, children: original.nodes }] : original.nodes; return { ...scope, tree: { conj: "and" as const, nodes: [...nodes, { conj: qualified.conj ?? "and", children: qualified.nodes }] } }; } function usesMetric(tree: FilterTree, fields: Field[], measures: Measure[]): boolean { const visit = (node: FilterNode): boolean => isFilterGroup(node) ? node.children.some(visit) : fields.some((field) => field.key === node.colId && isMetricField(field)) || measures.some((measure) => measure.key === node.colId); return tree.nodes.some(visit); } type BindingView = Pick<SavedView, "id" | "name"> & { config: Pick<SavedView["config"], "filterConj" | "filters">; }; /** Workspace view names and the filter clauses a copied cell can step. */ function viewList(raw: unknown): BindingView[] { if (!Array.isArray(raw)) return []; return (raw as GridWorkspace["views"]).map((v) => ({ id: v.id, name: v.name, config: { filterConj: v.config?.filterConj === "or" ? "or" : "and", filters: Array.isArray(v.config?.filters) ? v.config.filters : [], }, })); } // ══ ⭐⭐ W54-T31 (ruling R8; owner instructions 6 and 8) — THE AGGREGATE'S COLUMN LIST ═════════ // // ⭐⭐ R8, VERBATIM: "Aggregate is always visible. The Fields list appears in exactly two places: // choosing the Aggregate's column, and choosing a field inside 'A filter I build here'. It is // hidden everywhere else, including under 'A saved view', where the view already fixes the rows. // Each Fields list is labelled with what it is picking, so several `sales.. metrics` entries are // distinguishable." // // ⛔ WHAT CHANGED IS WHERE THE LIST LIVES, NOT WHETHER IT EXISTS. Before this ticket the list was // a permanently expanded box inside a 380px column: it painted under "A saved view" as well, and // it spent about 90px of the panel's height on a list nobody was currently choosing from // (`shots/T31-fields-before.png`). Instruction 6 asks for the Data module's Fields presentation // "but the popup in the middle, just like building a Filter under 'Rows to include'", so the list // becomes a centred dialog opened from a control that shows the CHOSEN column. The panel keeps a // single line for Column in every configuration, which is what instruction 8's "Fields should auto // hide for everything that is not part of the Aggregate value Column or the Filter fields" buys. // // ⛔⛔ THE PROVIDER AROUND THE DIALOG IS THE SAME LOAD-BEARING ONE `SheetFilterPopup` DOCUMENTS, // and it is why `SheetColumnPicker` is split from the dialog below it. The Sheet route mounts NO // `OverlayProvider` of its own (`App.tsx` gives one to the hosted-grid branch only), so a // body-level overlay opened here has a null `OverlayStackContext` and `useOverlayLayer` cannot // tell whether a higher layer owns a pointerdown. Wrapping puts every layer opened underneath // this dialog on one stack, so a click inside a nested picker is never read as an outside click // that dismisses the surface below it. That failure is exactly the "clicking Fields just closes // the window" report instruction 8 names. // // ⛔ AND IT IS MOUNTED LATE, CONDITIONALLY, for the reason the filter popup already records: // `useOverlayLayer` claims Escape the moment it runs and `ui/useEscapeClose` hands the key to the // LAST entry pushed. The editor's own claim was pushed at mount; this one is pushed when the // dialog opens, so one Escape closes the column list and the next closes the panel. interface ColumnPickerProps { /** The cell being bound, so the title says which cell this list is about. */ addr: string; /** The fold, said inside a sentence: "sum", "average", "minimum". */ aggregateNoun: string; /** The database's own label. Two databases can both offer a column called "Total". */ databaseLabel: string; /** The offer after the search box, which is what the list renders. */ shown: Field[]; /** The offer before the search box. The empty state must tell a search miss from an empty * database, and those two ask different things of the reader. */ offered: Field[]; /** Every field the database has, for the third empty-state sentence. */ all: Field[]; chosen: string; query: string; onQuery: (next: string) => void; onPick: (key: string) => void; onClose: () => void; } /** The dialog itself. Split from the export ONLY so `useOverlayLayer` runs BELOW the provider. */ function ColumnPickerDialog({ addr, aggregateNoun, databaseLabel, shown, offered, all, chosen, query, onQuery, onPick, onClose, }: ColumnPickerProps) { const panelRef = useRef<HTMLDivElement>(null); const titleId = useId(); const listId = useId(); useOverlayLayer({ panelRef, onDismiss: onClose, dismissOnOutside: false, initialFocus: "first", restoreFocus: true, trapFocus: true, }); return ( <BodyPortal> <div className="lp-dialog-scrim"> <div ref={panelRef} className="lp-dialog sheet-column-popup" role="dialog" aria-modal="true" aria-labelledby={titleId} data-overlay-kind="sheet-column" > <div className="lp-dialog-head"> <h2 className="lp-dialog-title" id={titleId}> {`The column ${addr} takes its ${aggregateNoun} over`} </h2> <button type="button" className="lp-dialog-x" aria-label={`Close the column list for ${addr}`} onClick={onClose} > <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false"> <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" /> </svg> </button> </div> {/* ⭐ THE SHAPE IS `filter-kit/FieldsHidePanel.tsx`'s, which is what instruction 6 asks for by name: a quiet heading, then a find box, then the rows. Nothing here is a new control; `cg-fields-section-title`, `cg-type-search`, `cg-type-list`, `cg-type-row` and `cg-fsel-hint` are all shipped, top-level classes in `index.css`. */} <div className="sheet-col-pick"> {/* ⭐⭐ THE HEADING R8 ASKS FOR, AND IT NAMES BOTH HALVES OF WHAT IS BEING PICKED: which database the columns come from, and what they are going to be used for. The owner's report was several entries reading "sales.. metrics" with nothing saying which list they belonged to; a list that says what it is picking answers that before a single row is read. */} <div className="cg-fields-section-title" id={listId}> {`Fields on ${databaseLabel} to take the ${aggregateNoun} over`} </div> {/* ⭐ THE SEARCH BOX HAS NO CONDITION AROUND IT (wave-50 R16). A control that appears at eleven fields and not at ten is a control nobody learns is there. */} <div className="cg-type-search sheet-pick-search"> <svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden> <circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" /> <path d="m10.4 10.4 3.1 3.1" stroke="currentColor" strokeWidth="1.35" strokeLinecap="round" /> </svg> <input type="text" value={query} placeholder="Find a column…" aria-label="Find a column" onChange={(e) => onQuery(e.currentTarget.value)} /> </div> {/* ⛔ THE LIST IS NOT RENDERED WHEN IT HAS NO ROWS. `.sheet-pick-list` carries a border and 3px of padding, so an empty one painted a thin bordered strip under the search box with the explanation sitting outside it, which reads as a picker that failed rather than a database with nothing to offer. */} {shown.length > 0 && ( <div className="cg-type-list sheet-pick-list" role="listbox" aria-labelledby={listId}> {shown.map((f) => ( <button key={f.key} type="button" role="option" aria-selected={f.key === chosen} className={"cg-type-row" + (f.key === chosen ? " is-on" : "")} onClick={() => onPick(f.key)} > {/* ⭐ THE ICON COMES BEFORE THE NAME (owner instruction 24), and a Metric wears the measure glyph rather than its storage type's. One glyph vocabulary, one source: `iconShapes.ts::TYPE_SHAPES`. */} <FieldTypeIcon type={isMetricField(f) ? "measure" : f.type} title={isMetricField(f) ? "Metric" : f.type} /> <span className="cg-type-label"> {f.label} {/* ⭐⭐ WHAT MAKES TWO ROWS TELLABLE APART. Labels collide - the owner saw several reading "sales.. metrics" - and the field's own key never does, because it is what the database stores the column under. `cg-fsel-hint` is the shipped quiet second line `FieldSelect` already paints under a label, so this is that pattern's second caller and not a new one. */} <span className="cg-fsel-hint">{f.key}</span> </span> {/* ⚠ THE WORD IS THERE TOO, because a glyph alone is only legible to somebody who already knows the vocabulary. */} {isMetricField(f) && ( <span className="sheet-period-note">Metric</span> )} </button> ))} </div> )} {/* AN EMPTY LIST SAYS WHY (R16). The causes need different acts from the reader. */} {shown.length === 0 && ( <p className="sheet-pick-empty"> {offered.length > 0 ? "No column matches that search." : (all.some((f) => isNumericType(f.type)) ? "The number columns on this database are worked out in the browser for " + "each row, so there is nothing stored here to total." : "This database has no number column to total.")} </p> )} </div> </div> </div> </BodyPortal> ); } /** The centred column list, on its own overlay stack. See the block above for why the provider * is not decoration. */ export function SheetColumnPicker(props: ColumnPickerProps) { return ( <OverlayProvider> <ColumnPickerDialog {...props} /> </OverlayProvider> ); } /** The field control's own footprint, using the existing static skeleton tone. */ function BindingSkeleton({ addr }: { addr: string }) { // Keep the picker footprint while its field list arrives, without hiding the editor body. return <span className="cg-select cg-fsel" role="status" aria-label={`Loading fields for ${addr}`}> <span className="sheet-binding-skeleton-control" style={{ width: "100%" }} aria-hidden="true" /> </span>; } export interface BindingEditorProps { workbookId: string; addr: string; /** Every database this reader may open (R8). The page supplies it; this panel invents nothing. */ databases: { key: string; label: string }[]; initial?: Record<string, unknown> | null; onSave: (binding: Record<string, unknown>) => void; onCancel: () => void; /** What a referenced cell reads now, so a filter value taken from a cell is shown, not blank. */ readCell?: ReadBindingCell; /** * HOTFIX 2026-09-29 (owner: "clicking edit for cell database ... is still very slow"). The * workbook the page is already painting. Preview and Save read their cell values from it * instead of downloading the whole workbook again (twice per Preview, before this). */ workbook?: Workbook; /** The tab the edited cell is on, so a bare reference like `F8` is read on THAT tab. */ homeTab?: { id: string; name: string }; } export default function BindingEditor({ workbookId, addr, databases, initial, onSave, onCancel, readCell, workbook, homeTab, }: BindingEditorProps) { const [activeSection, setActiveSection] = useState<typeof BINDING_SECTIONS[number]["key"]>("data"); const [shape, setShape] = useState<"value" | "view">(initial?.mode === "view" ? "view" : "value"); const [viewType, setViewType] = useState<ViewBinding["viewType"]>(() => VIEW_BINDING_TYPES.includes(initial?.viewType as ViewBinding["viewType"]) ? initial!.viewType as ViewBinding["viewType"] : "grid"); const [viewFields, setViewFields] = useState<string[]>(() => initial?.mode === "view" && Array.isArray(initial.fields) ? initial.fields.filter((key): key is string => typeof key === "string") : []); const [viewLimit, setViewLimit] = useState(() => clampViewLimit( typeof initial?.limit === "number" ? initial.limit : VIEW_BINDING_LIMIT_DEFAULT)); const [viewSort, setViewSort] = useState<ViewBinding["sort"]>(() => initial?.mode === "view" && Array.isArray(initial.sort) ? initial.sort.flatMap((item) => { if (!item || typeof item !== "object" || typeof item.field !== "string" || (item.dir !== "asc" && item.dir !== "desc")) return []; return [{ field: item.field, dir: item.dir }]; }) : []); const [database, setDatabase] = useState<string>( String((initial?.database as string) ?? databases[0]?.key ?? ""), ); // ⚠ SEEDED ONCE, AT MOUNT, the same way `migratePeriod` and `readOnDrag` below already are. A // `useEffect` that re-read `initial` would clobber a live edit the next time the parent // re-rendered for an unrelated reason, which is the failure the period note already describes. const savedAgg = useState(() => readAggregate(initial?.aggregate))[0]; const savedSource = useState(() => bindingAggregate(initial?.aggregate))[0]; // Seed new builders here; changing the shared fallback would alter other readers of saved bindings. const [sourceKind, setSourceKind] = useState<BindingAggregate["kind"]>( initial?.aggregate == null ? "number" : savedSource.kind, ); const [metricKey, setMetricKey] = useState(savedSource.kind === "number" ? savedSource.metric_key : ""); const savedScope = useState(() => initialFilterScope(initial))[0]; const savedView = useState(() => savedViewOf(initial))[0]; const [fn, setFn] = useState<string>(savedAgg.fn); const [field, setField] = useState<string>(savedAgg.field); const [scopeKind, setScopeKind] = useState<"view" | "filter">(savedScope.kind); const [viewId, setViewId] = useState<string>(savedScope.viewId); const [tree, setTree] = useState<FilterTree>(savedScope.tree); // W53-T15 — what the door below reports. `countConditions` walks nested groups too, so a filter // built out of groups is not undercounted into reading as empty. const conditionCount = useMemo(() => countConditions(tree.nodes ?? []), [tree]); const [fields, setFields] = useState<Field[]>([]); const [relatedOffer, setRelatedOffer] = useState<{ database: string; fields: RelatedFilterField[]; databases: { via: string; database: string; databaseLabel: string; relationLabel: string }[]; unavailable: UnavailableRelatedFilterDatabase[]; loaded: boolean; }>({ database: "", fields: [], databases: [], unavailable: [], loaded: false }); const [relatedNotice, setRelatedNotice] = useState(""); const filterFields = useMemo(() => [...fields, ...(relatedOffer.database === database ? relatedOffer.fields : [])], [fields, relatedOffer, database]); const [measures, setMeasures] = useState<Measure[]>([]); const [views, setViews] = useState<BindingView[]>([]); // ⛔ THE NOTICE BELOW IS GATED ON THIS FLAG AND NOT ON `views.length`. Before the first answer // arrives the list is legitimately empty, and a notice keyed on emptiness would flash "that view // is gone" at every perfectly valid binding for as long as the fetch took. const [viewsLoaded, setViewsLoaded] = useState(false); // Field-dependent controls wait for C2's workspace door. The editor body paints immediately. // `viewsLoaded` separately protects saved-view deletion notices from a failed read. const [optionsResolved, setOptionsResolved] = useState(false); // ⭐⭐ W53-T15 (ruling R8) — WHETHER THE CENTRED FILTER DIALOG IS ON SCREEN, and the ONLY state // this ticket adds. The tree itself stays in `tree`/`setTree` below and the dialog writes // straight into that setter, so there is no draft to reconcile when it closes. const [filterPopupOpen, setFilterPopupOpen] = useState(false); // ⭐⭐ W54-T31 (ruling R8) — WHETHER THE CENTRED COLUMN LIST IS ON SCREEN. It starts CLOSED on // every configuration including an unbound cell: the panel's job on open is to show what the // cell points at, and a list that opens itself would be back to spending the panel's height on // a choice nobody has asked to make. const [colPickerOpen, setColPickerOpen] = useState(false); // S68-T24: small related-field offers keep their own trigger; values start at a picker. const [relatedWanted, setRelatedWanted] = useState(savedScope.kind === "filter" || savedScope.tree.nodes.length > 0); const [valuesState, setValuesState] = useState<Record<string, FilterValuesState>>({}); const valuesRef = useRef<Record<string, FilterValuesState>>({}); const valuesRequests = useRef(new Map<string, Promise<FilterValuesState | undefined>>()); const valuesGeneration = useRef(0); const stepRequest = useRef(0); const [stepNotice, setStepNotice] = useState(""); const [userOptions, setUserOptions] = useState<string[]>([]); const [preview, setPreview] = useState<string>(""); const [notice, setNotice] = useState<string>(""); // ⚠ THE MIGRATION RUNS ONCE, AT MOUNT, and its result seeds the controls. Running it on every // render would re-read `initial` after the person had already changed a control, which is how an // editor forgets an edit the moment its parent re-renders for an unrelated reason. const migrated = useState(() => migratePeriod(initial?.period))[0]; const savedDrag = useState(() => bindingOnDrag(initial))[0]; const [unit, setUnit] = useState<PeriodUnit>(migrated?.unit ?? "month"); const [start, setStart] = useState<string>( migrated?.start ?? normalizePeriodStart("month", todayYm()), ); const [locked, setLocked] = useState<boolean>(migrated?.locked ?? false); // An absent flag is rolling, including every binding saved before frozen dates existed. const [frozen, setFrozen] = useState<boolean>(Boolean(migrated?.frozen)); const [frozenFrom, setFrozenFrom] = useState<string>( () => migrated?.from ?? periodRange(unit, start).from, ); const [frozenTo, setFrozenTo] = useState<string>( () => migrated?.to ?? periodRange(unit, start).to, ); const range = frozen ? { from: frozenFrom, to: frozenTo } : periodRange(unit, start); const resumeRollingPeriod = () => { setFrozen(false); setFrozenFrom(""); setFrozenTo(""); }; const editPeriodDate = (key: "from" | "to", value: string) => { // Capture the other displayed endpoint too: the dropdowns may have moved since mount. setFrozenFrom(key === "from" ? value : range.from); setFrozenTo(key === "to" ? value : range.to); setFrozen(true); }; // ⛔⛔ W57-T17 - THE DATABASE IS SEEDED AT MOUNT OUT OF A LIST THAT ARRIVES LATER, AND AN EMPTY // SEED NEVER HEALED. `databases` is fetched by `SheetPage` from `/api/v1/nav`; a panel opened // before that answer lands seeds `database` to `""`, and nothing re-seeds it. A `<select>` whose // value matches no option paints its FIRST option, so the panel then SHOWED "Odoo customers" // while `database` was empty: `scopeOf("")` is null, the workspace effect takes its no-door // branch, and every list in the panel is legitimately empty for a database the reader can see // named above them. Observed on a lane screenshot, where the column list read "Fields on to take // the sum over" with `databaseLabel` blank and "This database has no number column to total." // // ⭐ IT ONLY EVER FILLS AN EMPTY VALUE, which is what makes it safe beside the seed-once rule // the block above states: a database the person chose is never overwritten, and neither is one // read off `initial`. The condition can only be true before any choice has been made. useEffect(() => { if (!database && databases.length > 0) setDatabase(databases[0].key); }, [database, databases]); const [periodRef, setPeriodRef] = useState<string>(migrated?.ref ?? ""); // ⭐ C5 - THE TWO PERIOD SPELLINGS ARE SIBLINGS. The mode is seeded from the saved dialect so // opening and saving a rolling window cannot silently turn it into this month's calendar period. const [periodMode, setPeriodMode] = useState<"calendar" | "window">( migrated?.window ? "window" : "calendar", ); const [windowSpec, setWindowSpec] = useState<WindowSpec>(migrated?.window ?? { kind: "ytd" }); const [ending, setEnding] = useState<EndingKind>(migrated?.ending?.kind ?? "today"); const [endingFixed, setEndingFixed] = useState(migrated?.ending?.date ?? ""); const [endingN, setEndingN] = useState(String(migrated?.ending?.n ?? 1)); const [endingUnit, setEndingUnit] = useState<EndingStep>(migrated?.ending?.unit ?? "month"); const [endingStep, setEndingStep] = useState<EndingStep>( migrated?.endingStep ?? endingStepDefault(windowSpec.kind)); const [endingOffset, setEndingOffset] = useState(migrated?.endingOffset ?? 0); const [endingSheets, setEndingSheets] = useState<{ id: string; name: string }[]>([]); const [endingSheet, setEndingSheet] = useState(() => parseRef(migrated?.ref ?? "")?.sheet ?? ""); const parsedEndingRef = parseRef(periodRef); const endingRef = parsedEndingRef && !parsedEndingRef.sheet && endingSheet ? formatRef({ ...parsedEndingRef, sheet: endingSheet }) : periodRef.trim(); const hasEnding = (TO_DATE_KINDS as readonly string[]).includes(windowSpec.kind); const endingToday = new Date(); const relativeEndingBounds = ending === "n_before_today" && hasEnding ? endingBounds(windowSpec.kind, ending, "", `${endingToday.getFullYear()}-${pad2(endingToday.getMonth() + 1)}-${pad2(endingToday.getDate())}`, endingStep, endingOffset, Number(endingN), endingUnit) : null; // "Use a cell" is a LINK that REVEALS the A1 input (R9). The input was the whole period control // before this ticket and it is not deleted, only demoted to the thing behind that link. const [refOpen, setRefOpen] = useState<boolean>(Boolean(migrated?.ref)); // ⛔⛔ D-660 - `period` MUST NOT BE EMITTED UNLESS SOMEBODY ACTUALLY CHOSE ONE. A binding opened // with no saved period (`migrated === null`, an all-time sum) seeds `unit`/`start`/`locked` with // DEFAULTS purely so the controls have something to display; those defaults are not a decision // anybody made. Saving them unconditionally is exactly the bug: Save stamps `{unit:"month", // start:<this month>}` over an all-time binding the person never touched. So this flag starts // TRUE only when a period was already on the binding, and re-saving that binding unchanged keeps // saving it. // // ⭐⭐ W53-T16 - AND IT IS NOW A CONTROL SOMEBODY CAN SEE AND TURN OFF, not a hidden flag. Before // this ticket the flag was raised by any touch of any period control and could never be lowered: // an all-time cell LOOKED like it was set to this month (the pickers show a default they are not // applying) and a cell narrowed to a period could not be widened back to all time from this panel // at all, which is standing rule 1's second sentence - a limit nobody was told about. The switch // below states which of the two a cell is, and either answer is one click from the other. // New Metrics require a period. A saved Metric with no period keeps its all-time scope; // a malformed saved period is not an absent one. Field and view filters opt in. const savedAllTimeMetric = useState(() => initial != null && initial.mode !== "view" && initial.period == null && savedSource.kind === "number" && Boolean(savedSource.metric_key))[0]; const [valuePeriodOn, setValuePeriodOn] = useState<boolean>(Boolean(migrated) || (sourceKind === "number" && !savedAllTimeMetric)); const [viewPeriodOn, setViewPeriodOn] = useState<boolean>(Boolean(migrated)); const periodOn = shape === "view" ? viewPeriodOn : valuePeriodOn; const setPeriodOn = shape === "view" ? setViewPeriodOn : setValuePeriodOn; const [copySteps, setCopySteps] = useState<readonly BindingDragStep[]>(() => (savedDrag.steps ?? []).filter((step) => (step.field !== BINDING_PERIOD_STEP && step.field !== BINDING_ENDING_STEP) || !migrated?.locked)); const [copyStepsEdited, setCopyStepsEdited] = useState(false); const updateCopySteps = (steps: readonly BindingDragStep[]) => { stepRequest.current += 1; setStepNotice(""); setCopySteps(steps); setCopyStepsEdited(true); }; const across: DragAcross = copySteps.some((step) => step.field === BINDING_PERIOD_STEP || step.field === BINDING_ENDING_STEP) ? "period" : "none"; const setAcross = (value: DragAcross) => { const field = hasEnding ? BINDING_ENDING_STEP : BINDING_PERIOD_STEP; const kept = copySteps.filter((step) => step.field !== field); updateCopySteps(value === "none" ? kept : [...kept, { field, axis: "across", ...(hasEnding ? { size: endingStep } : {}), }]); }; const adoptedFrom = adoptedFromOf(initial); // ⭐ ESCAPE CLOSES THE PANEL, through the base kit's ONE arbiter (C8) rather than a listener of // this component's own. `cancelEditFirst` stays FALSE: the done-when says the panel closes on // Escape, and opting in would make the FIRST Escape do nothing whenever focus sat in one of the // text inputs this panel is full of. const panelRef = useRef<HTMLElement | null>(null); const onEscape = useCallback(() => onCancel(), [onCancel]); const escapeContainer = useCallback(() => panelRef.current, []); useEscapeClose(true, onEscape, { container: escapeContainer }); // C2 owns workspace memoisation in the existing client door; Sheet keeps no workspace cache. // Its field list fills the skeleton controls and revalidates saved fields/views as before. useEffect(() => { let live = true; const scope = scopeOf(database); setViewsLoaded(false); setOptionsResolved(false); setFields([]); setViews([]); setMeasures([]); // Picker pages belong to one mounted editor and one database, never to another caller. valuesGeneration.current += 1; valuesRef.current = {}; valuesRequests.current.clear(); setValuesState({}); setStepNotice(""); stepRequest.current += 1; if (!scope) { setFields([]); setViews([]); setUserOptions([]); // ⛔ W54-T33 — RESOLVED, NOT LOADING. This database has no workspace door, so its empty // lists are the true and final answer; leaving the flag down would leave a skeleton running // forever over a panel that is never going to be given anything else. setOptionsResolved(true); return () => { live = false; }; } // HOTFIX 2026-09-29: a scope this page read moments ago paints NOW from the memo, so a second // Edit does not sit on a skeleton for a multi-second assembly. The server read below still // runs and replaces these lists (and drops a view that no longer exists) when it answers. const memo = peekWorkspace(scope, { fieldsOnly: true }); if (memo) { setFields((memo.fields ?? []) as Field[]); setMeasures(memo.measures ?? []); setViews(viewList(memo.views)); setUserOptions(memo.userOptions ?? []); setViewsLoaded(true); setOptionsResolved(true); } (async () => { // ONE door, and it is the one that knows what exists now. const fresh = await fetchWorkspace(scope, { fieldsOnly: true }); if (!live) return; if (!fresh) { // A failed fresh permission question cannot leave an earlier offer writable. setFields([]); setMeasures([]); setViews([]); setUserOptions([]); setViewsLoaded(false); setNotice("These fields could not be loaded. Close and reopen this panel to try again."); // ⛔ W54-T33 — BUT THE PANEL REVEALS EITHER WAY. Nothing better is coming for this // database, and a skeleton that outlives the request it was waiting on tells the reader // the panel is broken rather than that the server would not answer. setOptionsResolved(true); return; } const list = viewList(fresh.views); setFields((fresh.fields ?? []) as Field[]); setMeasures(fresh.measures ?? []); setViews(list); // Keep declared people choices from the workspace without a records download. setUserOptions(fresh.userOptions ?? []); setViewsLoaded(true); // ⛔ A SELECTED VIEW THAT NO LONGER EXISTS IS CLEARED, so Save cannot store a dead id — that // stored id is exactly the state this ticket was reported for. The notice in `Rows to // include` is what explains the empty control; clearing without saying so would read as the // panel losing the choice on its own. setViewId((cur) => (cur && !list.some((v) => v.id === cur) ? "" : cur)); // ⛔ W54-T33 — LAST, AFTER THE DEAD ID IS CLEARED. React batches these into one paint, so // the first frame the reader sees is the settled one: a view that no longer exists has // already been dropped and its notice is already computed, rather than showing for a frame. setOptionsResolved(true); })(); return () => { live = false; valuesGeneration.current += 1; stepRequest.current += 1; }; }, [database]); // Reaching the filter still asks for its related-field list, independently of value pickers. useEffect(() => { if (scopeKind === "filter" || filterPopupOpen || colPickerOpen || activeSection === "copied") setRelatedWanted(true); }, [scopeKind, filterPopupOpen, colPickerOpen, activeSection]); // The related grid's field wall is checked on the server. Keep its labelled fields in the // existing Filter picker only; a customer's amount is not an order aggregate column. useEffect(() => { if (!relatedWanted || !database) return undefined; const controller = new AbortController(); setRelatedOffer({ database, fields: [], databases: [], unavailable: [], loaded: false }); setRelatedNotice(""); (async () => { try { const response = await fetch(`${API_V1}/sheets/filter-fields/${encodeURIComponent(database)}`, { credentials: CREDENTIALS, signal: controller.signal, }); const body = await response.json().catch(() => null); if (!response.ok || !Array.isArray(body?.fields) || !Array.isArray(body?.databases)) throw new Error(body?.error?.message || "Related fields could not be loaded. Close and reopen this panel to retry."); if (!controller.signal.aborted) { setRelatedOffer({ database, fields: body.fields as RelatedFilterField[], databases: body.databases, unavailable: Array.isArray(body.unavailable) ? body.unavailable : [], loaded: true }); const aliases = new Map<string, string>(); for (const field of body.fields as RelatedFilterField[]) for (const legacy of field.related?.legacyKeys ?? []) aliases.set(legacy, field.key); setTree((current) => rekeyFilter(current, (key) => aliases.get(key) ?? key)); } } catch (error) { if (!controller.signal.aborted) setRelatedNotice(error instanceof Error ? error.message : "Related fields could not be loaded. Close and reopen this panel to retry."); } })(); return () => controller.abort(); }, [database, relatedWanted]); const loadValues = useCallback((key: string, search = "", more = false): Promise<FilterValuesState | undefined> => { const held = valuesRef.current[key]; const pending = valuesRequests.current.get(key); if (held?.search === search && pending) return pending; if (!more && held?.search === search && held.loaded && !held.error) return Promise.resolve(held); if (more && (!held?.hasMore || held.pending)) return Promise.resolve(held); const definition = filterFields.find((candidate) => candidate.key === key) as RelatedFilterField | undefined; if (!definition) return Promise.resolve(undefined); const generation = valuesGeneration.current; const offset = more && held ? held.offset : 0; const state: FilterValuesState = { values: more && held ? held.values : [], pending: true, loaded: false, hasMore: more && held ? held.hasMore : false, offset, search }; valuesRef.current = { ...valuesRef.current, [key]: state }; setValuesState(valuesRef.current); const request = fetchDistinctValues(definition.related?.database ?? database, definition.related?.field ?? key, { offset, limit: 200, search }).then((got) => { if (generation !== valuesGeneration.current || valuesRef.current[key] !== state) return undefined; const next: FilterValuesState = got.ok ? { values: [...new Set([...state.values, ...got.value.values])], pending: false, loaded: true, hasMore: got.value.hasMore, offset: got.value.offset + got.value.limit, search, } : { ...state, pending: false, error: got.message }; valuesRef.current = { ...valuesRef.current, [key]: next }; setValuesState(valuesRef.current); valuesRequests.current.delete(key); return next; }); valuesRequests.current.set(key, request); return request; }, [database, filterFields]); const wantValues = useCallback((key: string, search = "") => { void loadValues(key, search); }, [loadValues]); const moreValues = useCallback((key: string) => { void loadValues(key, valuesRef.current[key]?.search ?? "", true); }, [loadValues]); /** The binding names a view the fresh list does not have. Said in the panel, not after a save. * * ⛔ IT STOPS BEING SAID THE MOMENT THE PERSON ANSWERS IT. The sentence asks for one of two acts, * so it must clear when either is taken: choosing a live view fills `viewId`, and switching to * "A filter I build here" moves `scopeKind`. Keying it on the SAVED id alone left the panel still * demanding a fix after the fix had been made, which reads as a control that ignores you. */ const savedViewMissing = viewsLoaded && Boolean(savedView.id) && savedView.database === database && scopeKind === "view" && !viewId && !views.some((v) => v.id === savedView.id); /** The same rule `Toolbar.tsx` computes for the grid (owner item 24): the declared list when a * field has one, the values seen in the rows when it does not. `choiceVocabulary` is pure and * already gated, so this is not a second definition of the rule, only a second caller of it. */ const statusValues = useMemo(() => { const map: Record<string, string[]> = {}; for (const f of filterFields) { if (f.type === "user") { map[f.key] = [...new Set([...userOptions, ...(valuesState[f.key]?.values ?? [])])]; continue; } if (f.type === "select" || f.type === "multiselect" || f.type === "status") { const declared = choiceVocabulary(f, []); map[f.key] = declared.length ? declared : valuesState[f.key]?.values ?? []; } else map[f.key] = valuesState[f.key]?.values ?? []; } return map; }, [filterFields, valuesState, userOptions]); // Offer every numeric column this database can total, including Metrics created in the app. // `isNumericType` checks numeric behaviour and `canTotal` checks whether the database can // aggregate the column. Date Metrics stay excluded; the server still refuses by name if // these client checks ever disagree with it. const numericFields = useMemo( () => fields.filter((f) => { // ⛔ DATE METRICS ARE EXCLUDED BY TYPE, never by a mutable label or key naming convention. if (isMetricField(f) && (f.type === "date" || f.type === "created_time")) return false; return !isMetricField(f) && isNumericType(f.type) && canTotal(f); }), [fields], ); // ⚠ W54-T31 - `offersMetric` MOVED, it was not dropped. The hint it gated belongs beside the // rows it describes, and those rows now live in `ColumnPickerDialog`, which derives the same // answer from the same list. A second copy here would have had no reader. /** The saved binding names a column this database will not total. Said in the panel, where the * choice is made, rather than as a refusal after a save. * * ⛔ IT IS GATED ON THE FIELD LIST HAVING ARRIVED, not on emptiness. Before the workspace door * answers, every column is "missing" and a notice keyed on that would flash a sentence about a * column that is perfectly fine, which is the failure `savedViewMissing` already records. */ const savedFieldUnavailable = fields.length > 0 && fn !== "count" && Boolean(field) && !numericFields.some((f) => f.key === field); const stepFields = useMemo(() => fields.filter(isDragDownField), [fields]); const selectedView = scopeKind === "view" ? views.find((v) => v.id === viewId) : undefined; const driverTree: FilterTree = scopeKind === "filter" ? tree : { conj: selectedView?.config.filterConj ?? "and", nodes: selectedView?.config.filters ?? [], }; const filterClauseOffers = stepFields.map((candidate) => ({ field: candidate, values: valuesState[candidate.key]?.values ?? bindingStepValues(candidate, [], userOptions), })); const savedDragDriverMissing = optionsResolved && copySteps.some((step) => step.field && step.field !== BINDING_ENDING_STEP && step.field !== BINDING_PERIOD_STEP && !stepFields.some((candidate) => candidate.key === step.field)); const chooseStepField = async (index: number, key: string) => { const serial = ++stepRequest.current; const replace = (step: BindingDragStep) => updateCopySteps(copySteps.map((held, i) => i === index ? step : held)); if (key === BINDING_ENDING_STEP || key === BINDING_PERIOD_STEP) { replace({ field: key, axis: copySteps[index].axis, ...(key === BINDING_ENDING_STEP ? { size: endingStepDefault(windowSpec.kind) } : {}), }); setLocked(false); return; } if (!key) { replace({ field: "", axis: copySteps[index].axis }); return; } const offer = filterClauseOffers.find((candidate) => candidate.field.key === key); if (!offer) return; setStepNotice("Loading values…"); const loaded = await loadValues(key); if (serial !== stepRequest.current) return; // Reuse copy's declared choices, presence/member parsing and ordering on this one field page. const seedValues = loaded ? bindingStepValues(offer.field, loaded.values.map((value, pid) => ({ pid, [key]: value })), userOptions) : offer.values; const first = seedValues[0]; setStepNotice(loaded?.error ?? (first === undefined ? "No values for this field." : "")); if (first === undefined || loaded?.error) return; setTree((current) => { const driver = scopeKind === "filter" ? current : driverTree; return bindingFilterClauses(driver).some((clause) => clause.colId === key) ? driver : seedBindingStep(driver, offer.field, first); }); setScopeKind("filter"); setViewId(""); setCopySteps((current) => current.map((held, i) => i === index ? { field: key, axis: held.axis, mode: bindingStepMode(offer.field) } : held)); setCopyStepsEdited(true); }; /** * ⭐⭐ W50-T21 (owner instruction 24: *"Sheet column picker (sum/count) shows the Field icons."*) * * ⛔ A `<select>` CANNOT CARRY AN ICON PER OPTION, which is why this is a real listbox and not a * styled dropdown. An `<option>` renders as plain text in every browser; there is no markup that * puts an SVG inside one. So the picker adopts the DATA layer's own field list vocabulary * (`cg-type-search`, `cg-type-list`, `cg-type-row`, `cg-type-label`), every class of which is * declared at TOP LEVEL and UNSCOPED in `index.css` and therefore already applies here. Copying * those measures into `styles/wave50/sheet.css` would be a second definition of a shipped rule. * * ⛔ THE SEARCH BOX IS ALWAYS SHOWN (wave-50 R16), never gated on a field count. A control that * appears at eleven fields and not at ten is a control nobody learns is there, and the reader * who needs it most is the one whose database has just grown past the threshold. * * ⚠ THE LIST IS STILL NUMERIC ONLY. `FieldTypeIcon` takes every `FieldType`, which invites * listing all of them; the picker's contract is the column an aggregate can be taken OVER, and * widening it would let someone sum a text column and get a refusal instead of a number. */ const [fieldQuery, setFieldQuery] = useState(""); const shownFields = useMemo(() => { const q = fieldQuery.trim().toLowerCase(); if (!q) return numericFields; return numericFields.filter((f) => (f.label ?? "").toLowerCase().includes(q) || String(f.key).toLowerCase().includes(q)); }, [fieldQuery, numericFields]); /** The chosen column, resolved over the FULL field list rather than over the offer, so a saved * column this database cannot total still shows its own name beside the notice that says so. * That is the same three-state rule `customer-grid/FieldSelect.tsx` documents at its head. */ const chosenField = useMemo(() => fields.find((f) => f.key === field), [fields, field]); const chosenIsMetric = shape === "value" && sourceKind === "number"; const keepingAllTimeMetric = savedAllTimeMetric && chosenIsMetric && initial?.database === database && savedSource.kind === "number" && savedSource.metric_key === metricKey; const filterUsesMetric = usesMetric(driverTree, fields, measures); const showMetricPeriod = chosenIsMetric || filterUsesMetric; useEffect(() => { if (!showMetricPeriod || !periodOn || periodMode !== "window" || ending !== "cell") return; if (workbook) { // HOTFIX 2026-09-29: the tab names are already painted; no whole-workbook download for them. setEndingSheets(workbook.sheets.map(({ id, name }) => ({ id, name }))); setEndingSheet((held) => held || homeTab?.name || workbook.sheets[0]?.name || ""); return; } let cancelled = false; void readWorkbook(workbookId).then((got) => { if (cancelled) return; if (!got.ok) { setNotice(got.message); return; } setEndingSheets(got.value.sheets.map(({ id, name }) => ({ id, name }))); setEndingSheet((held) => held || got.value.sheets[0]?.name || ""); }); return () => { cancelled = true; }; }, [workbookId, showMetricPeriod, periodOn, periodMode, ending, workbook, homeTab?.name]); const canStepPeriod = chosenIsMetric || shape === "view"; const periodClauseLabel = shape === "view" ? "Metric period" : `Metric period of ${measures.find((m) => m.key === metricKey)?.label || metricKey || "Metric"}`; const changeSource = (kind: BindingAggregate["kind"]) => { setSourceKind(kind); setMetricKey(""); setField(""); setFn("sum"); setPeriodOn(kind === "number"); setPreview(""); setColPickerOpen(false); }; const changeDatabase = (key: string) => { setDatabase(key); setMetricKey(""); setField(""); setViewId(""); setTree({ conj: "and", nodes: [] }); updateCopySteps([]); setPeriodOn(chosenIsMetric); setPreview(""); setViewFields([]); setViewSort([]); }; /** The database's own label, which the column list's heading names. Two databases can both * carry a column called "Total", and the heading is where that ambiguity is answered. */ const databaseLabel = databases.find((d) => d.key === database)?.label || database; const binding = useMemo(() => { const agg: BindingAggregate = sourceKind === "number" ? { kind: "number", metric_key: metricKey } : { kind: "column", fn: fn as "sum" | "count" | "avg" | "min" | "max", ...(fn !== "count" ? { field } : {}) }; const scope: Record<string, unknown> = scopeKind === "view" ? { view_id: viewId, view_name: views.find((v) => v.id === viewId)?.name ?? "", ...(savedScope.kind === "view" && savedScope.viewId === viewId && tree.nodes.length ? { filter: tree } : {}) } : { filter: tree }; // R11: a filter ADOPTED from a purged view keeps saying so. The sentence in the panel is the // only trace of where that filter came from, and re-saving the cell must not erase it. const adopted = (initial?.scope as Record<string, unknown> | undefined)?.adoptedFrom; if (scopeKind === "filter" && adopted) scope.adoptedFrom = adopted; const out: Record<string, unknown> = { database, aggregate: agg, scope }; if (agg.kind === "column" && agg.field && chosenField) out.fieldType = chosenField.type; // W55-T07 / R6: re-saving what this cell points at must not reset how its View drawer opens. // The display bag belongs to this binding, not to the saved View and not to localStorage. const display = bindingDisplay(initial); if (display) out.display = display; // C2's period, spelled the contract's way. R14: a period SOURCE is a `$`-anchored cell // reference; the A1 resolver reads it BEFORE the query is built, so it is an INPUT to the // filter and never a post-filter. It rides ALONGSIDE the unit and the start rather than // replacing them, because the pair still names what the cell falls back to. // ⛔⛔ D-660 - ONLY WRITE `period` WHEN THE PERIOD SWITCH IS ON. See the state declaration // above: an all-time binding re-saved with the switch off must stay all-time, not get silently // stamped to this month's default, and turning the switch off drops the key rather than writing // an empty period the server would have to guess about. if (showMetricPeriod) { if (periodOn) { // ⛔ C5 - EMIT EXACTLY ONE DIALECT. `clean_period` prefers unit/start when both are present, // so combining these branches would silently discard the rolling window. if (periodMode === "window") { out.period = { window: windowSpec, ...(hasEnding ? { ending: { kind: ending, ...(ending === "fixed" ? { date: endingFixed } : {}), ...(ending === "n_before_today" ? { n: Number(endingN), unit: endingUnit } : {}) }, endingStep, ...(endingOffset ? { endingOffset } : {}), locked: across === "none", ...(ending === "cell" ? { ref: endingRef } : {}), } : {}) }; } else { const period: Record<string, unknown> = { unit, start, locked: canStepPeriod ? locked : true, }; if (frozen) { period.frozen = true; period.from = frozenFrom; period.to = frozenTo; } else if (refOpen && periodRef.trim()) period.ref = periodRef.trim(); out.period = period; } } } // ⛔⛔ R8 REVOKED W51-T12'S ONE-AXIS-AT-A-TIME RULE. The wire keys keep C2's spelling // because `clean_on_drag` rebuilds anything else; emitting both slots independently lets one // Metric cell step its period and one filter clause without either choice erasing the other. const steps = copySteps.filter((step) => step.field && (step.field === BINDING_ENDING_STEP ? showMetricPeriod && periodOn && hasEnding && periodMode === "window" : step.field === BINDING_PERIOD_STEP ? showMetricPeriod && periodOn && canStepPeriod && !locked && periodMode === "calendar" : true)); // An unchanged legacy editor keeps the old copy semantics on save as well as on read. out.onDrag = !copyStepsEdited && !Array.isArray((initial?.onDrag as BindingOnDrag | undefined)?.steps) ? { across: savedDrag.across, down: savedDrag.down } : bindingOnDrag({ onDrag: { steps } }); if (shape === "view") { const viewBinding: ViewBinding = { database, mode: "view", viewType, fields: viewFields, // C2 stores the selected predicate itself, including a saved view's chosen filter. filter: scopeKind === "filter" ? tree : { conj: selectedView?.config.filterConj ?? "and", nodes: selectedView?.config.filters ?? [], }, sort: viewSort, limit: viewLimit, ...(out.period ? { period: out.period as Record<string, unknown> } : {}), onDrag: out.onDrag as BindingOnDrag, ...(initial?.mode === "view" && initial.database === database && initial.block ? { block: initial.block as ViewBinding["block"] } : {}), }; return viewBinding; } return out; }, [database, sourceKind, metricKey, fn, field, chosenField, scopeKind, viewId, views, tree, initial, savedScope, unit, start, locked, frozen, frozenFrom, frozenTo, refOpen, periodRef, periodOn, periodMode, windowSpec, across, copySteps, copyStepsEdited, savedDrag, chosenIsMetric, hasEnding, ending, endingFixed, endingN, endingUnit, endingStep, endingOffset, endingRef, shape, viewType, viewFields, viewSort, viewLimit, selectedView, canStepPeriod, showMetricPeriod]); // Read before either send; the server reads the stored source again independently. const prepareBinding = async (): Promise<Record<string, unknown> | null> => { let value = endingFixed; let prepared = binding; try { const filterRefs = bindingRefSlots(binding).filter((slot) => slot.kind === "filter"); if (filterRefs.length) { const scope = binding.scope as { filter: FilterTree }; let previewTree = scope.filter; const source = workbook ?? await (async () => { const got = await readWorkbook(workbookId); if (!got.ok) throw new Error(got.message); return got.value; })(); for (const slot of filterRefs) { const read = readCell && (workbook || slot.text.startsWith("=")) ? readCell(slot.text) : null; if (read?.problem) throw new Error(read.problem); const operand = read ? read.value : resolveFilterCell(source, slot.text, homeTab?.name); previewTree = updateFilterValueLeaf(previewTree, slot.indices!, (node) => ({ ...node, value: operand, ...((MULTI_VALUE_OPS as ReadonlySet<string>).has(node.op) ? { values: [operand] } : {}), })); } prepared = { ...binding, scope: { ...scope, filter: previewTree } }; } if (!showMetricPeriod || !periodOn || periodMode !== "window" || !hasEnding) return prepared; if (ending === "n_before_today") { if (!endingN.trim() || !Number.isInteger(Number(endingN)) || Number(endingN) < 1) throw new Error("Ending needs a number of 1 or more before today."); if (Number(endingN) > MAX_N) throw new Error(`Ending cannot be more than ${MAX_N} before today.`); } if (ending === "cell") { const source = workbook ?? await (async () => { const got = await readWorkbook(workbookId); if (!got.ok) throw new Error(got.message); return got.value; })(); value = resolveEndingCell(source, endingRef, homeTab?.name); } const today = new Date(); const day = `${today.getFullYear()}-${pad2(today.getMonth() + 1)}-${pad2(today.getDate())}`; if (!endingBounds(windowSpec.kind, ending, value, day, endingStep, endingOffset, Number(endingN), endingUnit)) throw new Error("Ending cannot be used because its date is invalid or falls before the lookback starts. Choose a later ending date."); return ending === "cell" ? { ...prepared, period: { ...(binding.period as Record<string, unknown>), ending: { kind: "cell", date: value }, } } : prepared; } catch (error) { setNotice(error instanceof Error ? error.message : "The Ending date could not be read. Choose a valid date."); return null; } }; // ⭐ THE NUMBER APPEARS BEFORE SAVING. `preview` evaluates the binding without persisting it, // which is what lets someone see whether they picked the right thing while they can still change // their mind - and it is the same door the cell will use, so the number cannot differ. const runPreview = async () => { setNotice(""); setPreview(""); const prepared = await prepareBinding(); if (!prepared) return; const got = await previewCell(workbookId, addr, prepared, homeTab?.id); if (!got.ok) { setNotice(got.message); return; } setPreview(got.value.display || String(got.value.value ?? "")); }; // Preview and Save wait for the field list even while the editor body is already visible. // A cell bound to a live view satisfies every other clause the moment the panel mounts, and a // Save taken then would write back a binding assembled from a list nobody had seen yet. // The rail and Save share these terms; new Metrics require a period, while an unchanged // saved all-time Metric keeps its absent period. Source and reference checks still apply. const sourceComplete = databases.some((d) => d.key === database) && (shape === "view" ? viewFields.length > 0 && viewFields.every((key) => fields.some((candidate) => candidate.key === key)) && Number.isInteger(viewLimit) && viewLimit >= 1 && viewLimit <= VIEW_BINDING_LIMIT_MAX : chosenIsMetric ? Boolean(metricKey) && measures.some((m) => m.key === metricKey) : fn === "count" || numericFields.some((candidate) => candidate.key === field)); const filterComplete = scopeKind === "filter" || Boolean(viewId); const frozenRangeComplete = !frozen || Boolean(range.from && range.to && range.from <= range.to); const periodComplete = (!chosenIsMetric || periodOn || keepingAllTimeMetric) && (!showMetricPeriod || !periodOn || periodMode !== "calendar" || frozenRangeComplete); const dataComplete = sourceComplete && (!chosenIsMetric || periodComplete); const copiedComplete = !savedDragDriverMissing; const relatedPending = relatedOffer.database !== database || !relatedOffer.loaded; const relatedKeys = bindingFilterClauses(tree).flatMap((leaf) => [leaf.colId, ...(leaf.rhs && "colId" in leaf.rhs ? [leaf.rhs.colId] : [])]).filter((key) => key.startsWith("linked:") || key.startsWith("related:")); // The server validates this saved predicate again on Save. Pending discovery does not // require an unchanged predicate to be reconstructed from an offer it already names. const savedRelatedUnchanged = initial?.database === database && scopeKind === savedScope.kind && JSON.stringify(tree) === JSON.stringify(savedScope.tree) && !relatedNotice; const aliasesPending = relatedKeys.length > 0 && relatedPending && !savedRelatedUnchanged; const relatedUnavailable = !relatedPending && relatedKeys.some((key) => !relatedOffer.fields.some((offer) => offer.key === key)); const ready = optionsResolved && viewsLoaded && !aliasesPending && !relatedUnavailable && dataComplete && filterComplete && periodComplete && copiedComplete && (shape === "value" || activeSection === "place"); const sectionComplete = { data: dataComplete, rows: filterComplete && periodComplete, copied: copiedComplete, place: ready, }; const sectionGates = BINDING_SECTIONS.filter(({ key }) => shape === "view" || key !== "place") .map((section, index, sections) => { const blocker = sections.slice(0, index).find(({ key }) => !sectionComplete[key]); return { ...section, reachable: !blocker, // The body paints before the field list (S68-T24), so until it answers a saved source reads // as incomplete: say Loading rather than tell the reader to pick what they already picked. blockedHint: !optionsResolved ? "Loading" : blocker?.key === "data" ? (sourceComplete ? "Set a Metric period" : "Pick a source") : blocker?.key === "rows" ? (filterComplete ? "Set a Metric period" : "Pick rows") : blocker?.key === "copied" ? "Choose a step field" : undefined, }; }); const lastReachableIndex = sectionGates.reduce( (last, section, index) => section.reachable ? index : last, 0, ); // Hotfix 2026-09-24 (owner): the per-step Next buttons are gone, and R44's "one shared Next" // with them. The step rail on the left is the one way between steps; it already refuses a step // that is not reachable yet and names what blocks it. useEffect(() => { setActiveSection((current) => { const currentIndex = BINDING_SECTIONS.findIndex(({ key }) => key === current); // Re-check the current selection so a backward click cannot be advanced by this effect. return currentIndex > lastReachableIndex ? BINDING_SECTIONS[lastReachableIndex].key : current; }); }, [activeSection, lastReachableIndex]); const { y: startYear, m: startMonth } = splitYm(start); const thisYear = new Date().getFullYear(); const years: number[] = []; for (let y = thisYear - 6; y <= thisYear + 1; y += 1) years.push(y); if (!years.includes(startYear)) years.push(startYear); years.sort((a, b) => a - b); // The filter conditions that read a cell. The cell is chosen inside the filter itself ("a cell"); // When copied lists them because whether that reference moves is how this cell copies. const cellLeaves = filterValueLeaves(tree).flatMap(({ node, indices }, index) => FILTER_REF_KEYS.flatMap((refKey) => node[refKey]?.ref ? [{ node, indices, index, refKey, ref: node[refKey]!.ref, locked: node[refKey]!.locked === true, title: filterFields.find((candidate) => candidate.key === node.colId)?.label || node.colId }] : [])); // Every cell this panel names is outlined on the grid while the panel is open (refHighlight.ts). useCellRefHighlight([ ...cellLeaves.map(({ ref }) => ref), showMetricPeriod && periodOn && (refOpen || ending === "cell") && periodRef ? (!parsedEndingRef?.sheet && ending === "cell" && endingSheet ? `'${endingSheet.replace(/'/g, "")}'!${periodRef.trim()}` : periodRef) : "", ]); // ⚠ W53-T16 - THESE NO LONGER RAISE A TOUCH FLAG, and that is the point of the switch: every // period control below is rendered only while `periodOn`, so reaching one of them is already the // decision the flag used to have to infer. const setYear = (y: number) => { resumeRollingPeriod(); setStart(normalizePeriodStart(unit, joinYm(y, startMonth))); }; const setMonthOfYear = (m: number) => { resumeRollingPeriod(); setStart(normalizePeriodStart(unit, joinYm(startYear, m))); }; const metricPeriodControls = ( <fieldset className="sheet-scope sheet-period"> <legend>Metric period</legend> {(!chosenIsMetric || (keepingAllTimeMetric && !periodOn)) && <div className="sheet-period-lock"> <button type="button" role="switch" aria-checked={periodOn} className={"sheet-lock-toggle" + (periodOn ? " is-on" : "")} onClick={() => setPeriodOn((v) => !v)}> <span className="sheet-lock-dot" aria-hidden /> <span>Use a Metric period</span> </button> </div>} {periodOn && ( <> {/* ⭐ C5 - THE MODE LABELS SAY WHAT EACH CHOICE DOES. Internal dialect names would make the reader guess which one can step and which one follows today. */} <label className="sheet-field"> <span>How to choose the period</span> <select value={periodMode} aria-label="How this period is chosen" onChange={(e) => setPeriodMode(e.target.value as "calendar" | "window")} > <option value="calendar">Calendar period</option> <option value="window">Lookback</option> </select> </label> {periodMode === "window" ? ( <> <label className="sheet-field"> <span>Lookback</span> <WindowPicker window={windowSpec} kinds={WINDOW_KINDS} onWindow={(next) => { setWindowSpec(next); setEndingStep(endingStepDefault(next.kind)); setEndingOffset(0); }} /> </label> {hasEnding && <> <label className="sheet-field"> <span>Ending</span> <select aria-label="Ending" value={ending} onChange={(e) => { setEnding(e.target.value as EndingKind); setEndingOffset(0); }}> {ENDING_KINDS.map((kind) => <option key={kind} value={kind}>{ENDING_LABELS[kind]}</option>)} </select> </label> {ending === "n_before_today" && <> <label className="sheet-field"> <span>Number</span> <input type="number" min={1} max={MAX_N} aria-label="Ending number" value={endingN} onChange={(e) => { setEndingN(e.target.value); setEndingOffset(0); }} /> </label> <label className="sheet-field"> <span>Unit</span> <select aria-label="Ending unit" value={endingUnit} onChange={(e) => { setEndingUnit(e.target.value as EndingStep); setEndingOffset(0); }}> {ENDING_STEPS.map((size) => <option key={size} value={size}> {size[0].toUpperCase() + size.slice(1) + "s"} </option>)} </select> </label> {relativeEndingBounds && <p className="sheet-period-note"> {dayText(relativeEndingBounds[0])} through {dayText(relativeEndingBounds[1])} </p>} </>} {ending === "fixed" && <label className="sheet-field"> <span>Ending date</span> <input type="date" aria-label="Ending date" value={endingFixed} onChange={(e) => { setEndingFixed(e.target.value); setEndingOffset(0); }} /> </label>} {ending === "cell" && <> {!parsedEndingRef?.sheet && <label className="sheet-field"> <span>Source sheet</span> <select aria-label="Ending source sheet" value={endingSheet} disabled={!endingSheets.length} onChange={(e) => setEndingSheet(e.target.value)}> {!endingSheets.length && <option value="">Loading sheets…</option>} {endingSheets.map((sheet) => <option key={sheet.id} value={sheet.name}>{sheet.name}</option>)} </select> </label>} <label className="sheet-field"> <span>Date cell</span> <input type="text" aria-label="Ending date cell" value={periodRef} placeholder="A1" onChange={(e) => { setPeriodRef(e.target.value); setEndingOffset(0); }} /> </label> </>} {endingOffset > 0 && <p className="sheet-period-note"> {`Ending moved later by ${endingOffset} ${endingStep}${endingOffset === 1 ? "" : "s"} when copied.`} </p>} </>} </> ) : ( <> <label className="sheet-field"> <span>Unit</span> <select value={unit} aria-label="Period unit" onChange={(e) => { const next = e.target.value as PeriodUnit; resumeRollingPeriod(); setUnit(next); // Re-seat the start on the new unit's first month, or the pair stops naming one // period: `2026-08` under `quarter` is not a quarter anybody can compile. setStart(normalizePeriodStart(next, start)); }} > {PERIOD_UNIT_OPTIONS.map((u) => <option key={u.unit} value={u.unit}>{u.label}</option>)} </select> </label> {unit === "day" || unit === "week" ? ( <label className="sheet-field"> <span>{unit === "week" ? "Week starting" : "Day"}</span> <input type="date" aria-label="Calendar period date" value={start} onChange={(e) => { resumeRollingPeriod(); setStart(normalizePeriodStart(unit, e.target.value)); }} /> </label> ) : <div className="sheet-field-row"> <label className="sheet-field"> <span>Year</span> <select value={String(startYear)} aria-label="Period year" onChange={(e) => setYear(Number(e.target.value))} > {years.map((y) => <option key={y} value={String(y)}>{y}</option>)} </select> </label> {unit === "month" && ( <label className="sheet-field"> <span>Month</span> <select value={String(startMonth)} aria-label="Period month" onChange={(e) => setMonthOfYear(Number(e.target.value))} > {MONTH_NAMES.map((name, i) => ( <option key={name} value={String(i + 1)}>{name}</option> ))} </select> </label> )} {unit === "quarter" && ( <label className="sheet-field"> <span>Quarter</span> <select value={String(Math.floor((startMonth - 1) / 3) + 1)} aria-label="Period quarter" onChange={(e) => setMonthOfYear(1 + 3 * (Number(e.target.value) - 1))} > {[1, 2, 3, 4].map((q) => <option key={q} value={String(q)}>{`Q${q}`}</option>)} </select> </label> )} </div>} <div className="sheet-field-row sheet-period-dates"> <label className="sheet-field"> <span>Starts</span> <input className="cg-input cg-cond-win-date" type="date" aria-label="Period start" value={range.from} onChange={(e) => editPeriodDate("from", e.target.value)} /> </label> <label className="sheet-field"> <span>Ends</span> <input className="cg-input cg-cond-win-date" type="date" aria-label="Period end" value={range.to} onChange={(e) => editPeriodDate("to", e.target.value)} /> </label> </div> <p className="sheet-period-note" aria-live="polite"> {dayText(range.from)} to {dayText(range.to)} </p> {frozen && ( <> <p className="sheet-period-note">Frozen to these dates until you choose a period.</p> <button type="button" className="sheet-period-link" onClick={resumeRollingPeriod} > Return to rolling period </button> </> )} {/* W56-T21 (owner instruction 13) - THE QUICK PICKS ARE GONE. Unit, year and month-or-quarter already reach every period the This and Last buttons could, so a second control for the same value was a second way to say one thing. `normalizePeriodStart` still normalises all three selects, and `shiftPeriodStart` comes from the shared drag arithmetic. */} {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the sentence under it says what each one costs when the cell is copied. */} {canStepPeriod ? ( <div className="sheet-period-lock"> <button type="button" role="switch" aria-checked={locked} className={"sheet-lock-toggle" + (locked ? " is-on" : "")} onClick={() => { const next = !locked; setLocked(next); setAcross(next ? "none" : "period"); }} > <span className="sheet-lock-dot" aria-hidden /> <span>Lock this period</span> </button> <p className="sheet-period-note"> {locked ? "Locked, so any copy of this cell keeps this period." : `Not locked, so a stepped copy moves by one ${UNIT_NOUN[unit]} per cell. ` + "Right and down move forward. Left and up move backward."} </p> </div> ) : ( <p className="sheet-period-note"> This Metric period stays fixed when copied. </p> )} {/* ⭐ "Use a cell" STAYS A LINK (R9). It reveals the A1 input rather than replacing the picker, so the ordinary reader never meets a cell reference and the person who wants one is one click away from it. */} {!refOpen && ( <button type="button" className="sheet-period-link" onClick={() => { // A cell SUPPLIES the period, so it cannot also be frozen to two // literal dates. Returning to rolling here is the same rule the // unit, year and month pickers follow, and it keeps the payload's // `frozen`-wins branch from silently dropping a typed reference. resumeRollingPeriod(); setRefOpen(true); }} > Use a cell </button> )} {refOpen && ( <label className="sheet-field"> <span>Period from a cell</span> <input type="text" value={periodRef} onChange={(e) => setPeriodRef(e.target.value)} placeholder="$B$1" /> </label> )} </> )} </> )} </fieldset> ); return ( <section className="sheet-binding-panel" ref={panelRef} aria-label={`Insert database in ${addr}`} > <header className="sheet-binding-head"> <h2 className="sheet-binding-title">{`Insert database in ${addr}`}</h2> <button type="button" className="sheet-binding-close" onClick={onCancel} aria-label={`Close database navigation for ${addr}`} title="Close" > <svg viewBox="0 0 16 16" aria-hidden="true" width="13" height="13" fill="none"> <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" /> </svg> </button> </header> {/* ⛔ THE SCROLLER IS THIS WRAPPER, NOT THE PANEL. A 380px column holding the whole filter builder is taller than the page, and a panel that scrolls as a whole pushes Save below the fold with nothing on screen saying it is there. */} <div className="sheet-binding-scroll"> {/* S68-T24: keep saved settings and navigation mounted while field controls fill in. */} <> <div className="sheet-binding-body"> <nav className="sheet-binding-rail" aria-label="Cell database sections"> {sectionGates.map(({ key, label, icon, reachable, blockedHint }) => ( <button key={key} type="button" className={"sheet-binding-rail-item" + (activeSection === key ? " is-active" : "")} aria-current={activeSection === key ? "page" : undefined} disabled={!reachable} title={blockedHint} onClick={() => setActiveSection(key)} > <span className="sheet-binding-rail-icon">{icon}</span> <span className="sheet-binding-rail-label">{label}</span> <span className="sheet-binding-rail-hint" style={{ minHeight: "2lh" }} aria-hidden={reachable}>{reachable ? "" : blockedHint}</span> </button> ))} </nav> <div className="sheet-binding-section" data-section={activeSection}> {activeSection === "data" && ( <> <fieldset className="sheet-source-path"> <legend>Result</legend> <label className="sheet-radio"> <input type="radio" name="sheet-binding-shape" checked={shape === "value"} onChange={() => { setShape("value"); setPreview(""); setNotice(""); }} /> <span>One value</span> </label> <label className="sheet-radio"> <input type="radio" name="sheet-binding-shape" checked={shape === "view"} onChange={() => { setShape("view"); setPreview(""); setNotice(""); }} /> <span>A view</span> </label> </fieldset> <label className="sheet-field"> <span>Database</span> <select value={database} onChange={(e) => changeDatabase(e.target.value)}> {databases.map((d) => <option key={d.key} value={d.key}>{d.label}</option>)} </select> </label> {shape === "value" ? <> <fieldset className="sheet-source-path"> <legend>Source</legend> <label className="sheet-radio"> <input type="radio" name="sheet-binding-source" checked={sourceKind === "number"} onChange={() => changeSource("number")} /> <span>Metric</span> </label> <label className="sheet-radio"> <input type="radio" name="sheet-binding-source" checked={sourceKind === "column"} onChange={() => changeSource("column")} /> <span>Field</span> </label> </fieldset> <div className="sheet-field-row"> {sourceKind === "number" ? ( <div className="sheet-field sheet-field--pick"> <span>Metric</span> {!optionsResolved ? <BindingSkeleton addr={addr} /> : <FieldSelectButton ariaLabel="Metric to summarise" placeholder="Choose a Metric…" value={metricKey} onChange={(key) => { setMetricKey(key); setField(""); if (key !== metricKey) setValuePeriodOn(true); }} fields={measures.filter((m) => isNumericType(m.type)).map((m) => ({ key: m.key, label: m.label, type: "measure" as const, }))} />} {chosenIsMetric && metricPeriodControls} <p className="sheet-notice" style={{ minHeight: "2lh" }}>{!optionsResolved ? "" : measures.length === 0 ? "No Metrics are available here. Choose another database." : "Binding adds a Metric column to this database if one is not already there."}</p> </div> ) : ( <label className="sheet-field"> <span>Aggregate</span> <select value={fn} onChange={(e) => { setFn(e.target.value); if (e.target.value === "count") setField(""); }}> {AGGREGATES.map((a) => <option key={a.fn} value={a.fn}>{a.label}</option>)} </select> </label> )} {/* Count takes no column, and offering one would suggest count(column), which skips blanks and answers a smaller number than the person meant. */} {sourceKind === "column" && fn !== "count" && ( <div className="sheet-field sheet-field--pick"> <span id="sheet-col-pick-label">Column</span> {/* ⭐⭐ W54-T31 (R8) — THE CONTROL SHOWS WHAT IS CHOSEN AND OPENS THE LIST; IT IS NOT THE LIST. `cg-select cg-fsel` is the shipped footprint every replaced `<select>` in this product already wears, so the Column line shares its height and its baseline with the Aggregate select above it rather than introducing a new control shape. The three states are `FieldSelect`'s own: unset reads as a prompt, a resolved column shows its mark and its name, and a column this database cannot offer shows its raw key in the amber `is-missing` slot instead of a plausible substitute. */} {!optionsResolved ? <BindingSkeleton addr={addr} /> : <button type="button" className={"cg-select cg-fsel sheet-col-open" + (chosenField ? "" : field ? " is-missing" : " is-empty")} aria-haspopup="dialog" aria-expanded={colPickerOpen} aria-labelledby="sheet-col-pick-label" title={chosenField ? chosenField.key : undefined} onClick={() => setColPickerOpen(true)} > {chosenField ? ( <FieldTypeIcon type={isMetricField(chosenField) ? "measure" : chosenField.type} title={isMetricField(chosenField) ? "Metric" : chosenField.type} /> ) : ( // No mark, but the SLOT stays, so the name sits in the same column whether or // not anything is chosen yet. <span className="cg-fsel-nomark" aria-hidden /> )} <span className="cg-fsel-label"> {chosenField?.label ?? (field || "Choose a column")} </span> <svg className="cg-fsel-caret" width="10" height="10" viewBox="0 0 16 16" fill="none" aria-hidden> <path d="M4 6l4 4 4-4" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" /> </svg> </button>} {/* ⛔⛔ MOUNTED ONLY WHILE OPEN, which is what orders Escape. See the block above `ColumnPickerDialog`: the editor's own Escape claim was pushed at mount, this one is pushed on open, and unmounting hands the key straight back. */} {colPickerOpen && ( <SheetColumnPicker addr={addr} aggregateNoun={AGGREGATE_NOUN[fn] ?? "total"} databaseLabel={databaseLabel} shown={shownFields} offered={numericFields} all={fields} chosen={field} query={fieldQuery} onQuery={setFieldQuery} onPick={(key) => { setField(key); setMetricKey(""); setColPickerOpen(false); }} onClose={() => setColPickerOpen(false)} /> )} {/* ⭐⭐ THE BIND TIME REFUSAL, SURFACED WHERE THE PERSON CAN ACT ON IT. The server refuses this column by name (`field_not_aggregable`), but only once a number is asked for; saying it here means the choice is corrected before a save. */} {savedFieldUnavailable && ( <p className="sheet-notice" role="alert"> {chosenField && isMetricField(chosenField) && !isNumericType(chosenField.type) ? `The saved Metric column ${chosenField.label || field} has no numeric type. Choose Metric as the source.` : `The saved column ${chosenField?.label || field} cannot be totalled on this database. ` + "Pick a column from the list, or count the records instead."} </p> )} </div> )} </div> </> : <> <label className="sheet-field"> <span>View type</span> <select aria-label="View type" value={viewType} onChange={(e) => setViewType(e.target.value as ViewBinding["viewType"])}> {VIEW_BINDING_TYPES.map((type) => <option key={type} value={type}> {type[0].toUpperCase() + type.slice(1)} </option>)} </select> </label> <label className="sheet-field"> <span>Fields to show</span> <select multiple required disabled={!optionsResolved} aria-label="Fields to show" value={viewFields} onChange={(e) => setViewFields(Array.from(e.target.selectedOptions, (option) => option.value))}> {fields.map((candidate) => <option key={candidate.key} value={candidate.key}> {candidate.label} </option>)} </select> </label> {!viewFields.length && <p className="sheet-period-note">Choose at least one field.</p>} <label className="sheet-field"> <span>Row limit</span> <input type="number" aria-label="Row limit" min={1} max={VIEW_BINDING_LIMIT_MAX} step={1} value={viewLimit} onChange={(e) => setViewLimit(clampViewLimit(e.target.valueAsNumber))} /> </label> </>} </> )} {activeSection === "rows" && ( <> <fieldset className="sheet-scope"> <legend>Rows to include</legend> <label className="sheet-radio"> <input type="radio" checked={scopeKind === "view"} onChange={() => setScopeKind("view")} /> <span>A saved view</span> </label> {scopeKind === "view" && ( <select disabled={!optionsResolved} value={viewId} onChange={(e) => setViewId(e.target.value)}> <option value="">Choose a view</option> {views.map((v) => <option key={v.id} value={v.id}>{v.name}</option>)} </select> )} {/* ⭐ W53-T12 — SAID HERE, THE MOMENT THE LIST RESOLVES, rather than as a refusal after a save or a refresh. `sheet-notice` with `role="alert"` is this panel's established inline shape, so the sentence lands where the choice is made. */} {savedViewMissing && ( <p className="sheet-notice" role="alert"> {`The saved view ${savedView.name || savedView.id} is not available any more. ` + "Pick a view that still exists, or build a filter here."} </p> )} <label className="sheet-radio"> <input type="radio" checked={scopeKind === "filter"} onChange={() => setScopeKind("filter")} /> <span>A filter I build here</span> </label> {/* ⭐⭐ W53-T15 (ruling R8) — A DOOR, NOT THE BUILDER. The same shared panel now opens in a centred dialog: this column is `flex: 0 0 380px` and a condition row cannot fit in it, so four conditions could only be reached by scrolling sideways. The button says how many conditions the cell already carries, because the builder that used to say so is now behind it. */} {scopeKind === "filter" && ( <> <button type="button" className="sheet-action" style={{ alignSelf: "flex-start" }} aria-haspopup="dialog" aria-expanded={filterPopupOpen} disabled={!optionsResolved} onClick={() => setFilterPopupOpen(true)} > {conditionCount === 0 ? "Build a filter" : `Edit filter (${conditionCount === 1 ? "1 condition" : `${conditionCount} conditions`})`} </button> {/* ⛔⛔ MOUNTED ONLY WHILE OPEN, and that is what orders Escape correctly rather than a flag inside the dialog. `useOverlayLayer` claims Escape as soon as it runs and `ui/useEscapeClose` gives the key to the LAST entry pushed, so a dialog mounted with the panel would have claimed Escape from the moment this editor opened. Mounting it here, later in time, puts it ABOVE this panel's own claim (pushed at mount, a few hundred lines up) and unmounting it hands Escape straight back, so one press closes the filter and the next closes the panel. */} {filterPopupOpen && ( <FilterFieldStatusContext.Provider value={{ relatedPending, unavailable: relatedOffer.database === database ? relatedOffer.unavailable : [], wantValues, moreValues, valuesState }}> <SheetFilterPopup addr={addr} database={database} fields={filterFields} filters={showCellFilterValues(tree, readCell)} onChange={(next) => setTree(keepCellFilterValues(next, readCell))} statusValues={statusValues} readCell={readCell} onClose={() => setFilterPopupOpen(false)} /> </FilterFieldStatusContext.Provider> )} </> )} {relatedOffer.database === database && relatedOffer.loaded && relatedOffer.databases.length === 0 && relatedOffer.unavailable.length === 0 && <p className="sheet-period-note" role="status">{databaseLabel} has no related database to filter by.</p>} {relatedNotice && <p className="sheet-notice" role="alert">{relatedNotice}</p>} {aliasesPending && !relatedNotice && <p className="sheet-period-note" role="status">Loading related fields…</p>} </fieldset> {!chosenIsMetric && showMetricPeriod && metricPeriodControls} </> )} {activeSection === "copied" && ( <> {/* ══ R10: THE DRAG RULES ═════════════════════════════════════════════════════════════ */} <fieldset className="sheet-scope sheet-drag"> <legend>When copied</legend> {/* Hotfix 2026-09-24 (owner: "the whole Filter section is so confusing, if we need it for copy, it should always just fall under the When copied section"). A condition that reads a cell is how this cell moves when copied, so the cell lives here, as ONE input: filled means "read this cell", blank means the value typed in the filter. There is no separate source switch. */} {cellLeaves.map(({ node, indices, title, refKey, ref, locked }) => ( <div key={`${indices.join(".")}.${refKey}`} className="sheet-step-driver"> <span>{node.op === "within" ? `${title}: ${windowLabel(node.dateWindow).toLowerCase()} up to the date in cell ${ref}` : node.op === "between" ? `${title} ${refKey === "valueRef" ? "from" : "to"} cell ${ref}` : `${title} reads cell ${ref}`}</span> <label className="sheet-radio"> <input type="checkbox" checked={locked} onChange={(e) => setTree(updateFilterValueLeaf(tree, indices, (leaf) => ({ ...leaf, [refKey]: { ...leaf[refKey]!, locked: e.target.checked } })))} /> <span>Keep this cell when copied</span> </label> </div> ))} {copySteps.map((step, index) => { const isEnding = step.field === BINDING_ENDING_STEP; const isPeriod = step.field === BINDING_PERIOD_STEP; const driverField = fields.find((candidate) => candidate.key === step.field); const localDriver = bindingFilterClauses(tree).find((clause) => clause.colId === step.field); const driverValue = localDriver?.op === "isEmpty" ? "Empty" : localDriver?.op === "isNotEmpty" ? "Filled" : localDriver?.value || localDriver?.values?.[0] || ""; const missing = step.field && !isEnding && !isPeriod && optionsResolved && !driverField; return <div key={index} className="sheet-step-driver"> <div className="sheet-field sheet-field--pick"> <span>Step field</span> <FieldSelectButton ariaLabel={index ? `Step field ${index + 1} when copied` : "Step field when copied"} placeholder="Choose a step field" value={step.field} onChange={(key) => { void chooseStepField(index, key); }} searchable searchPlaceholder="Find a step field…" emptyMessage="No step fields available." fields={[ ...(showMetricPeriod && periodOn && hasEnding && periodMode === "window" ? [{ key: BINDING_ENDING_STEP, label: "Ending", disabled: copySteps.some((held, i) => i !== index && held.field === BINDING_ENDING_STEP), }] : []), ...(showMetricPeriod && canStepPeriod && periodOn && periodMode === "calendar" ? [{ key: BINDING_PERIOD_STEP, label: periodClauseLabel, disabled: copySteps.some((held, i) => i !== index && held.field === BINDING_PERIOD_STEP), }] : []), ...filterClauseOffers.map(({ field: candidate }) => ({ key: candidate.key, label: `Step ${candidate.label}`, type: candidate.type, disabled: !optionsResolved || copySteps.some((held, i) => i !== index && held.field === candidate.key), })), ...(missing ? [{ key: step.field, label: `${step.field} (unavailable)`, disabled: true }] : []), ]} /> </div> <label className="sheet-field"> <span>Direction</span> <select aria-label={`Step ${index + 1} direction`} value={step.axis} onChange={(e) => updateCopySteps(copySteps.map((held, i) => i === index ? { ...held, axis: e.target.value as BindingDragStep["axis"] } : held))}> <option value="across">Across</option> <option value="down">Down</option> </select> </label> {isEnding && <label className="sheet-field"> <span>Ending step size</span> <select aria-label="Ending step size" value={step.size ?? endingStepDefault(windowSpec.kind)} onChange={(e) => updateCopySteps(copySteps.map((held, i) => i === index ? { ...held, size: e.target.value as EndingStep } : held))}> {ENDING_STEPS.map((size) => <option key={size} value={size}> {size[0].toUpperCase() + size.slice(1)} </option>)} </select> </label>} {localDriver && driverField && <span>{`${driverField.label}: ${driverValue}`}</span>} <button type="button" className="lp-btn lp-btn-quiet" aria-label={`Remove step field ${index + 1}`} onClick={() => updateCopySteps(copySteps.filter((_, i) => i !== index))}> <MenuIcon name="trash" /> Remove step field </button> </div>; })} <button type="button" className="lp-btn lp-btn-quiet" disabled={copySteps.some((step) => !step.field)} onClick={() => updateCopySteps([...copySteps, { field: "", axis: "across" }])}> <MenuIcon name="addEnd" /> Add step field </button> <p className="sheet-period-note" role="status" style={{ minHeight: "1lh" }}>{stepNotice}</p> {savedDragDriverMissing && <p className="sheet-notice" role="alert">The saved Step field is unavailable. Choose another field.</p>} </fieldset> </> )} {shape === "view" && activeSection === "place" && ( <> {ready && <DrillModal workbookId={workbookId} addr={addr} label="Place" previewBinding={binding as ViewBinding} onClose={() => setActiveSection("copied")} onPlace={() => { if (ready) onSave(binding); }} />} </> )} </div> </div> {/* ⛔⛔ W53-T16 (owner instruction 13) - THE FOUR SENTENCE SUMMARY IS DELETED, NOT HIDDEN. It restated the period, the lock and the two drag rules that the controls immediately above already say, in a panel 380px wide where every line it took pushed Save further off screen. The one line kept is R11's, because it is the only sentence here that names something NO control shows: the filter in this cell was copied out of a view that has since been deleted, and nothing else remembers that. */} {adoptedFrom && ( <p className="sheet-binding-line sheet-binding-adopted"> {`Filter adopted from the deleted view ${adoptedFrom}`} </p> )} {preview && <p className="sheet-preview">{`This cell would show ${preview}`}</p>} {relatedUnavailable && <p className="sheet-notice" role="status"> Some related fields in this filter are unavailable. Review the filter before saving. </p>} {notice && <p className="sheet-notice" role="alert">{notice}</p>} </> </div> {/* C7 and the owner's Apple principle: Save is this surface's ONE primary; Preview and Cancel are deliberately quiet. */} <div className="sheet-binding-actions"> {shape === "value" && <> <button type="button" className="lp-btn lp-btn-quiet" onClick={runPreview} disabled={!ready}> Preview </button> <button type="button" className="lp-btn lp-btn-primary" onClick={async () => { setNotice(""); const prepared = await prepareBinding(); if (prepared) onSave(binding); }} disabled={!ready}> Save </button> </>} <button type="button" className="lp-btn lp-btn-quiet" onClick={onCancel}> Cancel </button> </div> </section> ); }
// sheet/BindingEditor.tsx — what a bound cell points at (wave 49, W49-T06, R4/R8/R14;
// wave 51, W51-T12, R9/R10/R11).
//
// ⭐⭐ R4 SAYS "THE FILTER USES THE EXACT SAME UI AS A VIEW'S FILTER", SO THIS MOUNTS
// `filter-kit/FilterBuilderPanel` ITSELF. That component turned out to need NO change to run here:
// its only required props are `fields`, `filters` and `onChange`, and its own docstrings already
// anticipate "a panel over a module whose rows it has never loaded" - which is exactly a Sheet
// cell. The ticket allowed adding an optional prop if one were needed; none was.
//
// ⛔ THE FILTER TREE SAVED HERE IS BYTE-COMPATIBLE WITH A VIEW'S. `FilterBuilderPanel` emits a
// `FilterTree` (`{conj, nodes}`) and that value is stored verbatim on the binding. Inventing a
// second shape here is the failure C2 names: the server compiles a view's filter and a cell's
// filter through the same `compile_filter_tree`, so two shapes would mean two dialects and one of
// them would eventually stop being tested.
//
// ⛔⛔ W51-T12 - THE ROOT NODE IS `.sheet-binding-panel` AND NOT `.sheet-binding`, AND THAT ONE
// CLASS IS THE WHOLE TICKET. `styles/wave49/sheet.css` declares `.sheet-binding` as
// `position: fixed; z-index: var(--cg-z-drawer)` - an OVERLAY, floating over the canvas it
// describes. W50-QA-1 is what that costs: an absolutely positioned panel over the map made every
// pin beneath it unclickable, and no z-index repairs document-order stacking. The design contract's
// clause is that the right-side panel is a real COLUMN and the content beside it SHRINKS.
// `.sheet-page` is already a flex row (`align-items: stretch`) and this component already renders
// as one of its direct children, so a root of `flex: 0 0 380px` narrows `.sheet-body` - and that is
// observable as a MEASUREMENT (the grid's own width with the panel open versus closed), which is
// the one thing a screenshot cannot tell apart from an overlay.
//
// ⚠ THE NEW CLASS IS DELIBERATE, NOT COSMETIC. `wave49/sheet.css` loads from inside SheetPage's
// LAZY chunk and therefore BEATS `styles/wave51/sheet-chrome.css` (imported eagerly by index.css)
// at equal specificity, so an override of `.sheet-binding`'s `position` written in this lane's
// sheet would lose the cascade and change nothing on screen
// ([[a-lazy-chunk-stylesheet-beats-an-eager-one]]). A name nothing else declares has no fight to
// lose. The INNER classes (`.sheet-field`, `.sheet-scope`, `.sheet-radio`, `.sheet-binding-title`,
// `.sheet-binding-actions`) are all top-level selectors rather than descendants of `.sheet-binding`,
// so every one of them keeps its shipped paint.
//
// ⚠ DESIGN CONTRACT: sentence case, quiet buttons, token-only colour and type, motion 150 ms
// ease-out on opacity and transform, no emoji, and no em dash or en dash in any string on screen.
import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
import { API_V1, CREDENTIALS } from "../apiContract";
import { fetchWorkspace, peekWorkspace } from "../customer-grid/apiBridge";
import type { SurfaceScope } from "../customer-grid/apiBridge";
import { dayText } from "../customer-grid/display";
import { FieldSelectButton } from "../customer-grid/FieldSelect";
import { FieldTypeIcon, MenuIcon } from "../customer-grid/icons";
import { BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/OverlaySurface";
import type { Field, FilterNode, FilterTree, GridWorkspace, Measure, SavedView } from "../customer-grid/types";
import { choiceVocabulary, isFilterGroup, MULTI_VALUE_OPS } from "../customer-grid/types";
import type { WindowSpec } from "../customer-grid/windows";
import { normalizeWindow, WINDOW_KINDS, ENDING_KINDS, ENDING_LABELS, ENDING_STEPS, TO_DATE_KINDS,
endingBounds, endingStepDefault, MAX_N, windowLabel } from "../customer-grid/windows";
import type { EndingKind, EndingStep } from "../customer-grid/windows";
// ⭐⭐ W53-T15 (ruling R8) — THE FILTER BUILDER IS NO LONGER MOUNTED IN THIS COLUMN. The SHARED
// `FilterBuilderPanel` the Data module also uses is untouched; `SheetFilterPopup` wraps it in the
// base kit's centred dialog so its condition rows have room, and only the Sheet mounts that
// wrapper. This file therefore stops importing the panel itself.
import { countConditions, isNumericType } from "../filter-kit/ops";
import { SheetFilterPopup } from "../filter-kit/SheetFilterPopup";
import { FilterFieldStatusContext } from "../filter-kit/FilterBuilderPanel";
import type { FilterValuesState, RelatedFilterField, UnavailableRelatedFilterDatabase } from "../filter-kit/FilterBuilderPanel";
import { WindowPicker } from "../filter-kit/WindowPicker";
import { useEscapeClose } from "../ui/useEscapeClose";
import { fetchDistinctValues, previewCell, readWorkbook } from "./sheetApi";
import type { Workbook } from "./types";
import DrillModal from "./DrillModal";
import { formatRef, parseRef } from "./a1";
import { bindingAggregate, bindingDisplay, bindingFilterClauses, bindingOnDrag, bindingPeriod, bindingRelated,
PERIOD_UNITS, BINDING_ENDING_STEP, BINDING_PERIOD_STEP,
VIEW_BINDING_TYPES, VIEW_BINDING_LIMIT_DEFAULT, VIEW_BINDING_LIMIT_MAX } from "./types";
import type { BindingAggregate, BindingDragStep, BindingOnDrag, BindingPeriod, PeriodUnit,
ViewBinding, DragAcross as SharedDragAcross } from "./types";
// D-687: the drag arithmetic has ONE owner, and it is the file the drag path itself calls.
import { shiftPeriodStart } from "./sheetState";
import { useCellRefHighlight } from "./refHighlight";
import { bindingStepMode, bindingStepValues, resolveEndingCell, seedBindingStep,
bindingRefSlots, filterValueLeaves, keepCellFilterValues, resolveFilterCell, showCellFilterValues,
updateFilterValueLeaf, FILTER_REF_KEYS } from "./bindingRefs";
import type { ReadBindingCell } from "./bindingRefs";
import "../styles/wave57/binding-actions.css";
import "../styles/wave58/sheet.css";
import "../styles/wave59/binding.css";
import "../styles/wave66/binding.css";
const BINDING_SECTIONS = [
{ key: "data", label: "Data", icon: <MenuIcon name="description" /> },
{ key: "rows", label: "Filter", icon: <MenuIcon name="filter" /> },
{ key: "copied", label: "When copied", icon: <MenuIcon name="duplicate" /> },
{ key: "place", label: "Place", icon: <MenuIcon name="addEnd" /> },
] as const;
const clampViewLimit = (value: number): number => Number.isFinite(value)
? Math.min(VIEW_BINDING_LIMIT_MAX, Math.max(1, Math.trunc(value))) : VIEW_BINDING_LIMIT_DEFAULT;
const AGGREGATES = [
{ fn: "sum", label: "Sum" },
{ fn: "count", label: "Count" },
{ fn: "avg", label: "Average" },
{ fn: "min", label: "Minimum" },
{ fn: "max", label: "Maximum" },
] as const;