// 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 `