// 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: }, { key: "rows", label: "Filter", icon: }, { key: "copied", label: "When copied", icon: }, { key: "place", label: "Place", icon: }, ] 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 = { 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` 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 = { 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 = { 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; // 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 | null | undefined): string { const scope = initial?.scope as Record | undefined; const adopted = scope?.adoptedFrom as Record | 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 ` onQuery(e.currentTarget.value)} /> {/* ⛔ 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 && (
{shown.map((f) => ( ))}
)} {/* AN EMPTY LIST SAYS WHY (R16). The causes need different acts from the reader. */} {shown.length === 0 && (

{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.")}

)} ); } /** 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 ( ); } /** 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 ; } 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 | null; onSave: (binding: Record) => 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("data"); const [shape, setShape] = useState<"value" | "view">(initial?.mode === "view" ? "view" : "value"); const [viewType, setViewType] = useState(() => VIEW_BINDING_TYPES.includes(initial?.viewType as ViewBinding["viewType"]) ? initial!.viewType as ViewBinding["viewType"] : "grid"); const [viewFields, setViewFields] = useState(() => 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(() => 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((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( 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(savedAgg.fn); const [field, setField] = useState(savedAgg.field); const [scopeKind, setScopeKind] = useState<"view" | "filter">(savedScope.kind); const [viewId, setViewId] = useState(savedScope.viewId); const [tree, setTree] = useState(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([]); 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([]); const [views, setViews] = useState([]); // ⛔ 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>({}); const valuesRef = useRef>({}); const valuesRequests = useRef(new Map>()); const valuesGeneration = useRef(0); const stepRequest = useRef(0); const [stepNotice, setStepNotice] = useState(""); const [userOptions, setUserOptions] = useState([]); const [preview, setPreview] = useState(""); const [notice, setNotice] = useState(""); // ⚠ 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(migrated?.unit ?? "month"); const [start, setStart] = useState( migrated?.start ?? normalizePeriodStart("month", todayYm()), ); const [locked, setLocked] = useState(migrated?.locked ?? false); // An absent flag is rolling, including every binding saved before frozen dates existed. const [frozen, setFrozen] = useState(Boolean(migrated?.frozen)); const [frozenFrom, setFrozenFrom] = useState( () => migrated?.from ?? periodRange(unit, start).from, ); const [frozenTo, setFrozenTo] = useState( () => 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 `` CANNOT CARRY AN ICON PER OPTION, which is why this is a real listbox and not a * styled dropdown. An `