Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download web/src/customer-grid/ColumnMenu.tsx from fsanyoto/runloopable: direct link, hf CLI and curl.
- Browser
- Download file 280 kB
-
https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/customer-grid/ColumnMenu.tsx
- Command line
-
hf download hf://spaces/fsanyoto/runloopable/web/src/customer-grid/ColumnMenu.tsx
-
curl -L -o ColumnMenu.tsx https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/customer-grid/ColumnMenu.tsx
280 kB
import { Fragment, useMemo, useRef, useState } from "react";
// ββ W46-T31 (contract C6) β the lane's sheet, imported from the COMPONENT rather than added to
// `index.css`. An @imported sheet is inlined at the top of the cascade and loses every
// equal-specificity fight below it. [[a-lane-stylesheet-cannot-override-index-css]]
import "../styles/wave46/field-panels.css";
// β W36-T07 (owner item 10) β the field agent. Its own module for `ColumnMenu`'s own reason:
// this file pulls the whole grid and cannot load under a node gate, so the chat had to sit
// where a test can render it.
import { FieldAgentChat } from "./FieldAgentChat";
import type { FieldProposal } from "./fieldAgent";
// ββ W50-T06 (owner instruction 5 / R5) β the formula editor. Its own module for the same
// reason `FieldAgentChat` is: this file cannot load under a node gate, and `verify_ui.py`
// compiles `FormulaEditor.tsx` ALONE to run its catalogue reader against a frozen C2 fixture.
import { FormulaEditor, stripLeadingEquals } from "./FormulaEditor";
import { emptyIfDefinition, IfStatementEditor } from "./IfStatementEditor";
import { AnchoredOverlay } from "./OverlaySurface";
import type { AnchorRect } from "./OverlaySurface";
import { FieldTypeIcon, MenuLabel } from "./icons";
import { FieldSelectButton } from "./FieldSelect";
// ββ W40-T24 β the pre-set definition lock. It lives in `display.ts` rather than here because a
// rule stated inside JSX cannot be LOADED by a node gate; `display.ts`'s header carries the full
// argument, and `_test/gridUx.test.ts` is what runs it.
import { columnDefinitionOffer } from "./display";
// ββ W40-T29 β the ADVANCED grouping is a pure function in `types.ts` for the reason
// `columnDefinitionOffer` sits in `display.ts`: this file imports React, so nothing stated inside
// it can be LOADED by a node gate, and "which types are advanced" is exactly the kind of decision
// that must be runnable rather than read back to itself as source text.
import { AUDIT_FIELD_TYPES, CODE_LANGUAGE_LABELS, CODE_LANGUAGES, CREATABLE_TYPES, choiceOptions, choiceRemovalMessage, choiceRenames,
codeLanguageOf, directionLabel, groupTypePickerRows, isDerivedLink, isMachineOwned,
isNumericFieldType, isOfferableField, isProfileField, offerableCreateKind, parseOptions, ratingMax,
ROLLUP_FN_LABELS, ROLLUP_FNS, ROLLUP_PRESET_FNS, ROLLUP_PRESETS, rollupPresetOf,
serverOptionLimit,
filterTreeConj, filterTreeNodes, linkSelectionFilterIssue, offerableFields, TYPE_DESCRIPTIONS,
ROLLUP_REF_OPS, mayEditFieldDefinition, ifDefinitionIssue } from "./types";
import type { Conjunction, Field, FieldFormat, FieldScope, FieldType, FilterNode, FilterTree, Measure,
IfDefinition, RollupCondition, RollupFn, RollupPreset, RollupRefOp, RollupSource, ShowAs, SummaryChoice,
SummaryMap, Viewer } from "./types";
import type { HopTopic, HopTopicOffer, LinkTarget, RollupSourceOffer } from "./apiBridge";
import type { WindowSpec } from "./windows";
import { normalizeWindow, windowLabel } from "./windows";
import { FilterBuilderPanel, WindowPicker } from "../filter-kit";
// ββ W41-T29 (R6, contract C2) β the ONE pair of rights predicates plus the copy that says what
// they refused, read from the same module the Fields manager reads. C2: no surface re-implements
// either test, so this menu asks rather than deriving a second answer of its own.
// β `mayDeleteField` IS IMPORTED UNDER AN ALIAS. This file already binds that identifier as a
// local `const` (the wave-39 `createdBy` courtesy sentence, ~40 lines below), and shadowing an
// import with a same-named local is a `tsc` error rather than a silent win.
// β W41-T31 (instruction 1, R19) β the description-only arm's THREE strings and its two
// predicates come from the same module, for the same C2 reason: this pane is not a second
// producer of a sentence, and `descriptionEditedOf` is C8's strict reader (absent is not false).
import {
DESCRIPTION_RESET_LABEL,
deleteRefusalReason,
descriptionResetOffered,
fieldClassOf,
mayRemoveField,
mayDeleteField as mayDeleteFieldRight,
PRESET_DESCRIPTION_ONLY_HINT,
REMOVE_FIELD_HINT,
REMOVE_FIELD_LABEL,
} from "../filter-kit/fieldClass";
import { SHARE_SHAPE, TYPE_LABELS } from "./iconShapes";
// ββ W50-T05 / R2 β **`aggOptions` AND `AGG_LABELS` ARE GONE FROM THIS FILE, DELIBERATELY.**
// R2 moved the column summary off `field.agg` and onto `ViewConfig.summary`, and this menu was
// named in W50-T03's own note as the last writer of the retired store. It now offers the SAME
// vocabulary the bottom bar offers (`summaryOptions`) and reads the SAME resolution
// (`resolveSummary`), so one column cannot say "Summary: Sum" in its header menu while the bar
// under it folds something else β which is exactly what two doors onto one stored value costs
// when they are two vocabularies as well.
import { resolveSummary, summaryLabel, summaryOptions } from "./aggregations";
// β W50-T05 β the "Show as" vocabulary and its words, from the module that owns the
// composition (`withShare`). Written here would be a fourth spelling of three modes.
import { SHOW_AS_LABELS, SHOW_AS_MODES } from "../ui/fmt";
import { validateFormula } from "./formulaEngine";
import { BRAND_SWATCHES, defaultOptionColor, nearestSwatch, normalizeOptionColor,
OPTION_PALETTE } from "./choiceColors";
import { fieldDeletionLocked } from "./FieldProperties";
import type { ChoiceRemoval } from "./apiBridge";
export interface ColumnMenuState {
fieldKey: string;
anchor: AnchorRect;
/**
* Item 12 (R8) β which pane this opening lands on. Absent = the action list, i.e. every
* pre-wave-26 opening. `"edit"` is the kanban's "Add option" door.
*
* β Narrowed to the ONE pane that has a door rather than the whole `MenuPane` union: widening
* it would let any future caller deep-link into `permissions`, whose entry is gated on the
* viewer inside the menu's own action list β a state you can only reach through a check would
* become a state you can reach around it.
*/
pane?: "edit";
}
interface FieldConfigExtra {
defaultValue?: Field["defaultValue"] | null;
if?: IfDefinition;
formula?: string;
max?: number;
scope?: FieldScope;
label?: string;
colorCodeOptions?: boolean;
optionColors?: Record<string, string>;
/**
* β Wave-20 owner item 15 (contract C-RENAME) β **AN EXPLICIT MAPPING, NEVER A DIFF.**
*
* Renaming a choice used to change the DECLARED list and nothing else, so every cell still
* held the old label and the column went blank-looking: "Blue" was no longer a choice, and
* the rows that said "Blue" said something the field did not offer. The migration needs to
* know that Blue BECAME Navy β and neither end can infer that from two lists, because
* "renamed Blue to Navy" and "deleted Blue, added Navy" produce the identical pair
* (`routes_tables.py` says the same thing from the server's side).
*
* It is knowable HERE, and only here: every option row carries a stable `OptionDraft.id`
* from the moment the editor opens, so a row whose label changed is a RENAME by identity, a
* new row is an addition, and a removed row is a removal. No guessing, at either end.
*/
renames?: { from: string; to: string }[];
/** Wave-18 C5-AUTOFIELD β an automation column's configuration, the same way `formula`
* carries an expression. Validated host-side (`aios_grid._clean_automation`). */
automation?: { kind: string; source: "record_url_field" | "self"; urlField?: string };
/** ββ W37-T22 (R4 / C7) β the geocode pseudo-kind's bag: which column holds the address.
* Carried on `extra` exactly as `automation`/`link`/`rollup` are, and validated host-side by
* `aios_grid._clean_geocode`. The created field's `type` is `text` (see `Field.geocode`). */
geocode?: { addressField: string; country?: string };
/** β 2026-08-07 β a `link` column's target. REQUIRED for the type: `_clean_field` returns
* None for a link with no bag, so a create without this is a column that never appears. */
link?: {
table: string;
on?: string;
from?: string;
single?: boolean;
selectionMode?: "manual" | "automatic";
selectionFilter?: FilterTree;
via?: HopViaBag;
};
/** β 2026-08-07 β a `rollup` column's aggregate. Same requirement, same reason.
* β 2026-08-09 β or, INSTEAD, a `source` binding: the read-through kind, which summarises
* rows that were never copied into the workspace. The host's `_clean_rollup` reads `source`
* first and returns before it ever looks at `link`, so the two are exclusive by construction
* rather than by a rule someone has to remember. */
rollup?: {
link?: string; field?: string; fn?: string;
limit?: number; sortBy?: string; sortDir?: "asc" | "desc";
distinctBy?: string;
/** ββ 2026-08-09 β the PRE-filter: applied before the most-recent window, so "the last 10"
* counts only records that already match. `_clean_rollup` refuses a `ref` leaf here (there
* is no fixed set yet for a statistic to describe). */
where?: RollupCondition[];
whereConj?: "and" | "or";
conditions?: RollupCondition[];
conditionConj?: "and" | "or";
source?: RollupSource;
};
/** β Wave-27 item 13 (R13) β a `code` column's language. OPTIONAL, unlike the two bags above
* it: `_clean_field` accepts a code column without one and it renders as plain text, so this
* is an ordinary edit rather than a create requirement. */
code?: { language: string };
/** ββ Wave-34 (owner ruling R13) β an AI ENRICHMENT column's config. REQUIRED, like `link`
* and `rollup` and unlike `code`: `_clean_field` returns None for an `ai_enrich` column with
* no bag, because a prompt is the only thing that can ever produce a value here. Shaped
* exactly as `core.user_tables._clean_ai_enrich` stores it, so the panel and the store cannot
* disagree about a key name. */
aiEnrich?: {
prompt: string;
model?: string;
maxTokens: number;
trigger: { mode: string; cron?: string };
overwrite: string;
};
}
interface ColumnMenuProps {
viewControlsReadOnly?: boolean;
state: ColumnMenuState;
field: Field;
/** Every field of the table, for "Change field" (owner item 9): the clicked column can be
* swapped for any other field β including hidden ones like Notes β in place. */
fields: Field[];
/**
* β 2026-08-07 β the OTHER databases a `link` column may point at, with their fields (so the
* rollup editor can offer real column names rather than a free-text key). Supplied by the host
* from `GET /tables`, which already filters by `may_open`.
*
* β ABSENT on the Odoo-backed Customer/Product grids, and that is what withdraws the two
* relational types from their create menu β there is no second user table to point at there,
* so offering "Link to another record" would be offering a column that can never resolve.
*/
linkTargets?: LinkTarget[];
/**
* ββ 2026-08-09 β the READ-THROUGH rollup's offer (topic β measure β dim β window), fetched
* by the host from `GET /tables/rollup-sources`.
*
* β EMPTY IS MEANINGFUL AND IS THE COMMON CASE. A tenant with no connected source gets `[]`,
* and the editor then never renders the mode switch at all β a rollup is simply a link fold,
* as it was before this existed. So this prop is what turns the second kind ON, not a flag.
*/
rollupSourceOffer?: RollupSourceOffer;
/** Dedicated typed offer from GET /grid/hop-topics; never derived from rollup sources. */
hopTopicOffer?: HopTopicOffer;
locked: boolean;
/** Product-owned preset fields may still drive view actions, but their schema is immutable. */
schemaLocked?: boolean;
/** Linked grids expose personal layout actions only, even when edit callbacks exist. */
embedded?: boolean;
canAddField?: boolean;
columnWidth?: number;
onColumnWidth?: (width: number) => void;
/**
* ββ W40-T24 β the grid is a `ut_*` runtime database rather than an Odoo-backed topic. It
* feeds `columnDefinitionOffer` (display.ts), which is this menu's ONE statement of the pre-set
* definition lock, and EVERY verdict reads it: a shared-definition column on a user database is
* the user's to reshape, and the identical shape on an Odoo-backed topic is not.
* β OPTIONAL and false by default only for the "+" create instance, which has no real subject
* column β it passes `locked`, so its verdicts are the closed ones either way. A real column
* menu must pass it; defaulting is a convenience for the create door, not a shrug.
*/
isUserTable?: boolean;
/** Wave-5 item 1 β who is looking. Gates the permissions entry (creator-or-admin). */
viewer?: Viewer;
/** Wave-5 item 3 β what the CURRENT VIEW does with this field, so the conditional
* "Don't sort/filter/group by this field" entries render exactly when they apply. */
sortedDir: "asc" | "desc" | null;
isFiltered: boolean;
isGrouped: boolean;
/** types.isGroupableField, computed by the caller (it owns lockedKey). */
groupable: boolean;
onClose: () => void;
onNote: (note: string) => void;
onHide: () => void;
/** Header drag has a keyboard-equivalent path in this same action surface. */
onMoveLeft?: () => void;
onMoveRight?: () => void;
onCreate: (
label: string,
type: FieldType,
anchorKey: string | null,
side: "left" | "right" | "end",
options?: string[],
measureSpec?: { key: string; window: WindowSpec },
extra?: FieldConfigExtra
) => void;
/** Swap THIS column for another field, in place (owner item 9). */
onChangeField: (newKey: string) => void;
/**
* Wave-2 item 5: the Change-field window's "New field" half β create a fresh overlay field
* of the chosen type and swap this column for it in one motion. The old field hides exactly
* as an ordinary change does. Wave-6 item 2 REPLACES this flow on created (`custom_`)
* fields with `onRetype` below.
*/
onCreateAndSwap: (
label: string,
type: FieldType,
options?: string[],
extra?: FieldConfigExtra
) => void;
/**
* Wave-6 item 2, re-homed by owner item 8 (2026-07-31): supplied for CREATED (`custom_`)
* fields only β the EDIT FIELD pane's type picker RETYPES THIS FIELD IN PLACE (same key,
* new type/options; values never converted β unreadable cells show blank, disclosed in the
* pane). `extra.label` rides along when the name changed in the same save, so rename+retype
* is ONE upsert β two sequential emits would each read the stale def and revert the other.
*/
/** β 2026-08-07 (D-79) β flip the C3 profile flag on a `text` column of a `ut_*` table.
* Absent on every surface that is not a user table, which is what hides the control. */
onProfileFlag?: (key: string, on: boolean) => void;
onRetype?: (
type: FieldType,
options?: string[],
extra?: FieldConfigExtra
) => void;
/**
* Owner, 2026-09-02 - retire a SAVED option of this choice field, with the cells that hold it.
* `confirm: false` answers how many cells use it (the warning); `confirm: true` removes the
* option and clears those values, immediately. Supplied beside `onRetype`, for the same fields,
* by the same predicate, so a field whose type cannot be edited cannot lose options either.
*/
onChoiceRemove?: (option: string, confirm: boolean) => Promise<ChoiceRemoval | null>;
/**
* ββ 2026-08-09 (owner) β RECONFIGURE an existing `link`/`rollup` column's bag.
*
* A DIFFERENT DOOR FROM `onRetype`, not a variant of it. `onRetype` writes the per-user overlay
* stratum and refuses anything that is not a `custom_` overlay field; these bags live in the
* table's SHARED definition and reach it through `PATCH /tables/{key}/fields/{fkey}`. Wiring
* this through `onRetype` would have meant a Save button that runs and does nothing on exactly
* the columns the owner was trying to edit.
*
* β Supplied for USER DATABASES only β its absence is what withdraws the editor from the
* Odoo-backed grids, where there is no such endpoint.
*/
onFieldConfig?: (patch: {
label?: string;
type?: FieldType;
options?: string[];
colorCodeOptions?: boolean;
optionColors?: Record<string, string>;
renames?: { from: string; to: string }[];
defaultValue?: Field["defaultValue"] | null;
format?: FieldFormat;
if?: IfDefinition;
link?: Record<string, unknown>;
rollup?: Record<string, unknown>;
}) => void;
/** Wave-6 item 5 β rename this created field (ordinary field_upsert with a new label).
* Supplied for creatable strata only. */
onRename?: (label: string) => void;
/**
* Owner item 8 (2026-07-31) β edit a FORMULA field's source in place (the Edit-field pane's
* per-type editor for the formula type, validated with the field itself as selfKey so a
* cycle is refused at authoring). `label` rides along exactly like onRetype's β one upsert.
* Supplied for created formula fields only.
*/
onFormula?: (formula: string, label?: string) => void;
/** Wave-6 item 4 β open straight into the create form at this position (the header "+"
* passes "end"). Cancel then CLOSES rather than falling back to the action list. */
initialPosition?: CreatePosition;
/**
* β WAVE-26 ITEM 12 (owner ruling R8) β open straight into a PANE, the way `initialPosition`
* opens straight into the create form.
*
* The kanban's "Add option" door passes `"edit"`. The owner's words were *"its literally the
* same thing as adding a new option when you click edit field on multi-select"*, and this prop
* is what makes that literal rather than approximate: the lane editor IS this component's Edit
* pane, so it writes the SHARED field definition through the same `onRetype` upsert, obeys the
* same permission wall, carries the same rename-by-row-identity migration and the same colour
* swatches. A second options editor would have had to re-earn every one of those.
*
* Back then CLOSES β same rule as `initialPosition`: there is no action list behind a pane
* that was opened directly.
*/
initialPane?: MenuPane;
/** Wave-6 item 9c β true on the cohort page: the create forms offer the Scope control
* ("This cohort table only" = DEFAULT vs "All customer tables"). */
scopeChoice?: boolean;
/** Wave-6 item 11c β pin state + actions. `onPinTo` absent when pinning would be a no-op
* (identity column, or already the boundary); `onUnpin` absent when nothing is pinned. */
pinnedTo?: boolean;
onPinTo?: () => void;
onUnpin?: () => void;
/**
* Wave-2 item 8c: change the PERIOD of a measure-carrying column. Supplied for any field with
* `.measure` β user-created `measure_*` columns and the pre-set measure fields alike. The
* caller emits the ordinary `field_upsert` (and auto-renames the header when the user never
* renamed it).
*/
/**
* W48C-T12 (go-live QA 2026-09-02): the Edit pane exposes the SAME Metric controls as Create -
* the Number (which measure) and the Period. `measureKey` rides beside the window when the
* person picked a different number; absent, the number is unchanged. One upsert either way.
*/
onPeriod?: (window: WindowSpec, measureKey?: string) => void;
/**
* Delete this USER-CREATED column outright (owner gap closed 2026-07-27). Supplied ONLY for
* the deletable strata (`custom_` overlay fields, `measure_` formula columns) β absent means
* the control is not rendered at all, so a base field cannot even be offered the action.
*/
onDelete?: () => void;
/** Owner-only change to C3's server-owned deletion lock. */
onSetDeletionLock?: (locked: boolean) => void;
/** Copies a canonical Data path that opens this field's properties. */
onCopyFieldLink?: () => void;
/**
* ββ W41-T29 (R6(b)) β DROP A COLUMN SOMEBODY ELSE SHARED WITH ME, off my own list. A
* DIFFERENT ACT from `onDelete`, and therefore a different door: it destroys no definition and
* no values, and pointing "Remove from my fields" at the delete handler would be a benign word
* on a destructive action.
* A host supplies null when no real remove door exists. Shared-with-me fields still lose Delete.
*/
onRemoveFromMine: (() => void) | null;
/** ββ Wave-34 (R13) β run this AI enrichment column over many rows.
* `scope` is `"blank"` (only cells still empty) or `"always"` (every row the AI
* wrote). OPTIONAL for `onDelete`'s reason: a host that has not wired the door shows
* no row, rather than a row that does nothing. */
onEnrich?: (scope: "blank" | "always") => void;
/**
* ββ W51-T03 / OWNER RULING R6 β duplicate this field as a tenant-owned custom field, through
* ONE door.
*
* β IT TAKES NO ARGUMENT ANY MORE, AND THE MISSING ARGUMENT IS THE FEATURE. The prop used to
* be `(copyValues: boolean) => void`, which forced this menu to state the copy choice as two
* separate verbs before the reader had even seen the column. Owner, instruction 5: *"'Duplicate
* definition' and 'Duplicate permitted value' are confusing: one button."* The choice survives
* where it can be answered β the host counts what the column actually holds and either opens the
* shared confirm dialog with a "Duplicate cells" toggle or, when the column holds nothing,
* duplicates at once. A menu cannot make that decision because it cannot see the rows.
*/
onDuplicate?: () => void;
/** Wave-5 item 10 β save a display format. Supplied for number/currency/formula and
* date/created_time fields. */
onFormat?: (format: FieldFormat) => void;
/**
* ββ WAVE 50 Β· W50-T05 / OWNER RULING R2 β set this column's SUMMARY, **AS A VIEW SETTING**.
*
* β THIS PROP REPLACES `onAggregate`, AND THE RENAME IS THE FEATURE. R2: *"the summary choice
* is PER VIEW, not per field"*. The old prop took an `AggName | undefined` and its host wrote
* `field.agg` β the store W50-T03 retired β so a menu pick and a bar pick disagreed about
* where the answer lived, and `verify_grid_ux.py`'s own R2 clause said in prose that this
* control "still does" write the field. It does not any more: the host writes
* `view.config.summary[colId]`, the same key and the same `SummaryChoice` shape the bar's
* `onSummaryPick` writes. `resolveSummary` still READS `field.agg` as a legacy fallback, which
* is what keeps every already-saved view rendering what it was saved with, with no migration.
*
* β "None" is `{ agg: "none" }`, a STORED value rather than an absent key β that is how a
* reader turns a numeric column's Sum default OFF, and why the choice is never `undefined`.
*/
onSummary?: (choice: SummaryChoice) => void;
/** β W50-T05 β the view's summary map, so this pane resolves the SAME choice the bar shows
* (R2's order: the view's key, then the legacy `field.agg`, then Sum on a numeric family).
* Absent = an empty map, which is what a host with no view config in scope has. */
summary?: SummaryMap;
/**
* ββ W50-T05 β **HOW THIS COLUMN READS: Value, % of total, or Both.**
*
* Offered wherever a field write is possible, and the pane itself refuses any column outside
* `isNumericFieldType` β the eligibility test, never a hand-written kind list (ERROR 20).
*
* β THE HOST MUST ROUTE THIS THROUGH THE DEFINITION DOOR ON A SHARED COLUMN (D-468 / D-275).
* `CustomerGrid.tsx`'s `saveField` writes the per-user OVERLAY stratum, which forks a `ut_*`
* shared definition into a private copy of itself; `setFieldConfig` PATCHes the one shared
* record in place. This prop states the choice and says nothing about the door, which is why
* the branch is asserted at the host and not here.
*/
onShowAs?: (showAs: ShowAs) => void;
/** Wave-5 item 1 β Sort by this field (replaces the view's sort), and the conditional
* clears (item 3). All of these mutate the EXISTING view config β no new host surface. */
onSort?: (dir: "asc" | "desc") => void;
onClearSort?: () => void;
onFilterBy?: () => void;
onClearFilter?: () => void;
onGroupByField: () => void;
onClearGroup: () => void;
/** Assignable people, from the host's real user list. Empty = the host did not supply one,
* and "Assignee" is offered without choices rather than with invented ones. */
userOptions?: string[];
/**
* CG-8's measures, reused as the vocabulary of a FORMULA-MEASURE column (owner item 7):
* `Sales Β· the last 90 days` as a column the user creates. Empty = the semantic store is
* unavailable here, and the option is simply not offered (same rule as measure conditions).
*/
measures?: Measure[];
/**
* ββ W37-T22 (owner item 15 / R4, contract C7) β MAY A GEOCODE COLUMN BE CREATED ON THIS
* SURFACE? REQUIRED rather than optional-with-a-default, deliberately: a defaulted boolean is
* how a capability ships silently off at whichever call site somebody forgets, and both call
* sites for this menu live in one file.
* β It answers "will the bag SURVIVE the create here", NOT "does this table have an address
* column" β the menu ANDs it with the address vocabulary itself. See `TypePicker`'s
* `offerGeocode` doc for why the two questions currently differ.
*/
geocodable: boolean;
/**
* ββ W39-T17 β THE SERVER-ISSUED TABLE KEY, and the ONLY reason "Share field" needs a prop at
* all: a column is not addressable on its own. A field share's oid is
* `"<table_key>:<field_key>"` (`core.shares.field_oid`), and nothing else in this file knows
* which database the column lives on β the only `topic` here belongs to the rollup source
* offer, which is a rollup's TARGET topic, not this column's table.
*
* ββ IT MUST BE `payload.workspace.storageKey` AND NOTHING ELSE, and a near-miss fails
* SILENTLY. `core.shares.split_field_oid` fails closed to `(None, None)` on any id it cannot
* split; `routes_shares._object_ref` then answers `route=None` and `_notify_new_grantees`
* returns EARLY, so the grant is written and NOBODY IS TOLD. The host's local fallback
* (`${LOCAL_KEY_PREFIX}${scope}`) is, in `CustomerGrid`'s own words, "a key the server never
* issues" β a share built on one is junk that looks like it worked.
*
* β ABSENT IS A REAL STATE AND IT WITHDRAWS THE ROW. A workspace read that 403s leaves no
* storageKey, and a query PREVIEW's columns are a projection rather than the database's own;
* both pass nothing, and the menu then offers no Share entry rather than one that cannot
* resolve. `shared_overlay` is keyed by exactly this spelling on both sides
* (`product_table_workspace` for a registry topic, the bare key for a `ut_*` database) and
* `_object_ref` strips the `_table_workspace` suffix itself, so it travels UNMODIFIED.
*/
tableKey?: string;
}
type CreatePosition = "left" | "right" | "end";
// β wave-7 item W4's menu-action icon set + `MenuLabel` MOVED to `icons.tsx` (wave-14
// item 19): the view menu needs the same vocabulary, and two hand-drawn padlocks in two
// files is how one of them ends up a different padlock. `icon=` takes a NAME now.
/**
* The menu's panes (wave-5 item 2). The NOTE editor and the editors used to render inline in
* the menu body; each opens its OWN dedicated window. One overlay, one pane at a time;
* "menu" is the action list.
*
* Owner item 8 (2026-07-31): "edit" ABSORBS the former "rename" and "swap" panes β one
* Airtable-grade Edit-field window owning the field's name, its type (with the per-type
* choices/stars/formula config), and the Change-field control that swaps the column to show
* another field.
*/
type MenuPane = "menu" | "edit" | "format" | "summary" | "showAs" | "width";
/**
* How each creatable type reads in the menu. DERIVED from CREATABLE_TYPES rather than listed
* again: a hand-maintained copy is a third place the vocabulary lives, and the failure mode is
* silent β add a type to the contract, forget this list, and the type is accepted by the host,
* asserted by the drift gate, and simply never offered to anyone.
*
* `Record<FieldType, string>` is what forces it: adding a member to the union without a label
* here fails `tsc`, so the compiler is the gate and no test has to click a canvas header menu.
*
* Wave-8 I20: the map itself MOVED to icons.tsx, beside the per-type glyphs β a type's label
* and its icon are one vocabulary, and splitting them across two files is how they drift.
* Imported here; the totality guarantee above is unchanged (icons.tsx types it identically).
*/
const FIELD_TYPES = CREATABLE_TYPES.map((value) => ({ value,
label: value === "if" ? "If statement" : TYPE_LABELS[value] }));
/** Types whose choices are declared in an options editor at creation time.
* β Takes `CreateKind`, not `FieldType`: both PSEUDO-kinds answer false (a Metric's choices
* are the measure catalog, a geocode column's are a column pick), and typing it narrower is what
* made `tsc` name every one of these call sites when `geocode` landed. That is the check
* working. */
function needsOptions(t: CreateKind): boolean {
return t === "select" || t === "multiselect";
}
function supportsDefaultValue(type: CreateKind): type is FieldType {
return ["text", "int", "currency", "pct", "select", "date"].includes(type);
}
function defaultValueFromDraft(type: FieldType, value: string): Field["defaultValue"] {
return ["int", "currency", "pct"].includes(type) && value !== "" ? Number(value) : value;
}
function defaultValueDraftValid(type: CreateKind, value: string): boolean {
if (value === "") return true;
if (["int", "currency", "pct"].includes(type)) return Number.isFinite(Number(value));
return type !== "date" || /^\d{4}-\d{2}-\d{2}$/.test(value);
}
function DefaultValueEditor({ type, enabled, value, options, onEnabled, onValue }: {
type: FieldType;
enabled: boolean;
value: string;
options: string[];
onEnabled: (enabled: boolean) => void;
onValue: (value: string) => void;
}) {
return <>
<label className="cg-check-row" style={{ flexDirection: "row" }} title="Used only when a new record omits this field">
<input type="checkbox" checked={enabled}
onChange={(event) => onEnabled(event.target.checked)} />
<span>Default value</span>
</label>
{enabled && <label>
<span>Value</span>
{type === "select" ? <select className="cg-select" value={value}
aria-label="Default value" onChange={(event) => onValue(event.target.value)}>
<option value="">Empty</option>
{value && !options.includes(value) && <option value={value}>{value}</option>}
{options.filter((option) => option !== "").map((option) =>
<option key={option} value={option}>{option}</option>)}
</select> : <input className="cg-input" value={value} aria-label="Default value"
aria-invalid={!defaultValueDraftValid(type, value)}
type={type === "date" ? "date" : ["int", "currency", "pct"].includes(type) ? "number" : "text"}
step="any" onChange={(event) => onValue(event.target.value)} />}
</label>}
</>;
}
interface OptionDraft {
id: string;
label: string;
color: string;
}
const DEFAULT_OPTION_LABELS = ["Not started", "In progress", "Blocked", "Done"];
/**
* β WAVE 28 Β· R4 / C1 β how a SET-STATISTIC comparison reads in the operator list.
*
* β KEYED BY `RollupRefOp`, so the day `core.user_tables.ROLLUP_REF_OPS` gains or loses an
* operator this map fails to compile rather than rendering a bare identifier β the same
* discipline `ROLLUP_FN_LABELS` uses, and the reason the Ο picker maps `ROLLUP_REF_OPS` instead
* of hand-filtering the full operator list.
* β The wording names the STATISTIC, not the arithmetic: "2 Ο above the mean" is the sentence a
* person is trying to write, and "is greater than mean + kΒ·stdev" is the implementation of it.
*/
/**
* β MIRRORS `core.user_tables.ROLLUP_MAX_SIGMAS`, and `verify_rollup_editor.py` HOLDS THE TWO IN
* STEP by importing the server's constant and comparing (a real enforcer this time β `types.ts`
* spent a wave claiming one that contained zero occurrences of the word it guarded,
* [[limit-with-no-enforcer]]).
*
* β WHY THE CONTROL MUST KNOW THE BOUND AT ALL. `_clean_rollup` REFUSES the whole field outside
* this range β not the leaf, the FIELD β so an unbounded box invites a value and then answers a
* 400 naming a cap the control never mentioned. That is `maxPosts` exactly: it offered 200 while
* the save door refused anything over 12 ([[default-must-pass-its-own-guard]]). A control must
* display what it will SEND.
*/
const MAX_SIGMAS = 10;
/** The default when a Ο row is born or its box is left empty β C1's worked example uses 2. */
const DEFAULT_SIGMAS = 2;
const REF_OP_LABELS: Record<RollupRefOp, string> = {
gt: "is more than β¦ Ο above the mean",
gte: "is at least β¦ Ο above the mean",
lt: "is less than β¦ Ο above the mean",
lte: "is at most β¦ Ο above the mean",
};
/**
* ββ 2026-08-09 (owner) β ONE CONDITION LIST, RENDERED TWICE, because a rollup now filters at
* two different moments and they mean different things.
*
* Owner: *"instead of last 12 posts, we also want to make it so its last N record, where the
* record's Status is video."* That is a filter the WINDOW must respect β pick the reels first,
* then take the last 10 of them. The existing list is the opposite by design (wave 28 / C1 moved
* it below the window so a `ref: {sigmas}` threshold is a statistic OF the rows being folded), so
* the two cannot be one control.
*
* β EXTRACTED RATHER THAN COPIED. Two near-identical 130-line JSX blocks is how one of them
* keeps offering an operator the other dropped β and the operator list here is already the
* server's (`ROLLUP_REF_OPS`), so a hand-edited second copy would drift from `_clean_rollup`
* silently ([[one-evaluator-per-question]]).
* β `allowRef` IS A REFUSAL MIRRORED, NOT A UI PREFERENCE. `_clean_rollup` refuses a `ref` leaf
* in `where` β before the window there is no fixed set for a mean to be about β so offering the
* Ο operators there would be a control whose only outcome is a 400 on the whole field.
*/
function RollupConditionList({
title,
hint,
conditions,
onConditions,
conj,
onConj,
targetFields,
allowRef,
idPrefix,
}: {
title: string;
hint: string;
conditions: RollupCondition[];
onConditions: (v: RollupCondition[]) => void;
conj: "and" | "or";
onConj: (v: "and" | "or") => void;
targetFields: { key: string; label: string }[];
allowRef: boolean;
idPrefix: string;
}) {
const patch = (index: number, next: RollupCondition) =>
onConditions(conditions.map((item, i) => (i === index ? next : item)));
return (
<div className="cg-rollup-conditions">
<div className="cg-rollup-conditions__head">
<span>{title}</span>
<button
type="button"
className="cg-btn"
disabled={targetFields.length === 0 || conditions.length >= 20}
onClick={() => onConditions([
...conditions,
{ field: targetFields[0]?.key ?? "", op: "eq", value: "" },
])}
>
Add condition
</button>
</div>
{conditions.length > 1 ? (
<select
className="cg-input"
aria-label={`Match all or any ${title.toLowerCase()} conditions`}
value={conj}
onChange={(event) => onConj(event.target.value as "and" | "or")}
>
<option value="and">All conditions must match</option>
<option value="or">Any condition may match</option>
</select>
) : null}
{conditions.map((condition, index) => (
<div className="cg-rollup-condition" key={`${idPrefix}-${index}-${condition.field}`}>
<select
className="cg-input"
aria-label={`${title} condition ${index + 1} column`}
value={condition.field}
onChange={(event) => patch(index, { ...condition, field: event.target.value })}
>
{targetFields.map((targetField) => (
<option key={targetField.key} value={targetField.key}>{targetField.label}</option>
))}
</select>
{/*
ββ WAVE 28 Β· R4 / C1 β THE THRESHOLD MAY BE THE SET'S OWN STATISTICS.
Owner's request (Nurilab): an average of the last 10 posts with outliers trimmed β
"anything beyond 2 sigma". That is not a new aggregator, it is a CONDITION whose
threshold is computed from the scoped rows themselves: mean + k*stdev of the same
column, over the window `sortBy`+`limit` kept, BEFORE these conditions filter.
β ONE CONTROL, NOT TWO, AND THAT IS WHAT MAKES THE XOR SAFE. `value` and `ref` may
never both be present β the server refuses the whole FIELD, not just the leaf β so
a separate "compare againstβ¦" switch beside the operator would leave the editor
free to write a `ref` while a stale `value` still rode along, producing a 400 on
Save that names a key the user never typed. Folding the choice into the operator
makes the illegal state unrepresentable: picking a plain op WRITES `value` and
drops `ref`, picking a statistic op does the reverse, and there is no third path.
β THE OPS ARE `ROLLUP_REF_OPS`, IMPORTED, never a hand-filtered copy of the full
list. `eq`/`neq` against a computed float is a coin flip on binary representation
and `contains` against a number never matches β the server draws that line and a
second copy here would be free to drift from it.
β THE `value` IS COMPOUND (`ref:gt`) so the select always resolves to exactly one
option. A `<select>` whose value matches nothing renders the FIRST option while
the stored key says otherwise, and the next patch writes the lie back
([[cg-condition-builder-items]]).
*/}
<select
className="cg-input"
aria-label={`${title} condition ${index + 1} operator`}
value={condition.ref ? `ref:${condition.op}` : condition.op}
onChange={(event) => {
const raw = event.target.value;
const isRef = raw.startsWith("ref:");
const op = (isRef ? raw.slice(4) : raw) as RollupCondition["op"];
// β THE LEAF IS REBUILT, NEVER SPREAD-AND-PATCHED. `{ ...item, ref: undefined }`
// leaves the key present-and-undefined; `JSON.stringify` drops it today, but the
// contract is "the key is absent", and relying on a serialiser's treatment of
// `undefined` to enforce a server-side XOR is a guarantee held by accident.
patch(index, isRef
? { field: condition.field, op,
ref: { sigmas: condition.ref?.sigmas ?? DEFAULT_SIGMAS } }
: { field: condition.field, op, value: condition.value ?? "" });
}}
>
<optgroup label="Compared with a value">
<option value="eq">is</option>
<option value="neq">is not</option>
<option value="contains">contains</option>
<option value="not_contains">does not contain</option>
<option value="is_empty">is empty</option>
<option value="is_not_empty">is not empty</option>
<option value="gt">is greater than</option>
<option value="gte">is at least</option>
<option value="lt">is less than</option>
<option value="lte">is at most</option>
</optgroup>
{allowRef ? (
<optgroup label="Compared with the set's own spread">
{ROLLUP_REF_OPS.map((op) => (
<option key={op} value={`ref:${op}`}>{REF_OP_LABELS[op]}</option>
))}
</optgroup>
) : null}
</select>
{condition.ref ? (
<label className="cg-cond-ref">
{/* β A BARE NUMBER BOX WOULD BE A CONTROL THAT WILL NOT SAY WHAT IT SETS. The
unit is sigmas and the sign is meaningful (negative selects the LOW tail), so
both are printed beside the input rather than left to be inferred from a
placeholder. */}
<input
className="cg-input"
type="number"
step="0.5"
/* β THE SERVER'S OWN BOUND, BOTH WAYS. Outside it `_clean_rollup` refuses the
whole FIELD, so an unbounded box would invite a 400 naming a cap it never
showed β `maxPosts`'s scar, in a control built the same day it was quoted. */
min={-MAX_SIGMAS}
max={MAX_SIGMAS}
aria-label={`${title} condition ${index + 1} standard deviations from the mean`}
/* β UNCONTROLLED + COMMIT ON BLUR, the idiom `maxPosts` uses and for its
reason: a controlled box patching per keystroke stores "-" as 0 and "1" on
the way to "1.5" as a legal value, and `Number("")` is 0 β so simply
CLEARING the box would silently store "0 sigma", a real but different
query, and the field could never be retyped because it snaps back. */
defaultValue={String(condition.ref.sigmas)}
onBlur={(event) => {
const raw = Number(event.target.value);
// Empty/garbage falls back to the default rather than to 0 β 0 means "at
// the mean" and is a value somebody must choose, never one they land on by
// deleting a character.
const parsed = event.target.value.trim() === "" || !Number.isFinite(raw)
? DEFAULT_SIGMAS
: raw;
// CLAMPED, not refused: the box is a dial, and a dial that rejects is a
// dead control. The clamp is what makes "displays what it will send" true.
const sigmas = Math.max(-MAX_SIGMAS, Math.min(MAX_SIGMAS, parsed));
if (String(sigmas) !== event.target.value) event.target.value = String(sigmas);
patch(index, { field: condition.field, op: condition.op, ref: { sigmas } });
}}
/>
<span>Ο from the mean of this column (negative reads below it)</span>
</label>
) : !(["is_empty", "is_not_empty"] as string[]).includes(condition.op) ? (
<input
className="cg-input"
aria-label={`${title} condition ${index + 1} value`}
value={condition.value ?? ""}
onChange={(event) => patch(index, {
field: condition.field, op: condition.op, value: event.target.value,
})}
/>
) : null}
<button
type="button"
className="cg-icon-btn"
aria-label={`Remove ${title.toLowerCase()} condition ${index + 1}`}
onClick={() => onConditions(conditions.filter((_item, i) => i !== index))}
>
Γ
</button>
</div>
))}
<div className="cg-field-hint">{hint}</div>
</div>
);
}
let optionDraftSequence = 0;
function nextOptionDraftId(): string {
optionDraftSequence += 1;
return `choice-${optionDraftSequence}`;
}
function optionDrafts(
labels: string[],
saved: Record<string, string> | undefined = undefined
): OptionDraft[] {
return labels.map((label) => ({
id: nextOptionDraftId(),
label,
color:
normalizeOptionColor(saved?.[label]) ??
normalizeOptionColor(defaultOptionColor(label))!,
}));
}
function optionSettings(
drafts: OptionDraft[],
type: CreateKind,
maxOptions: number | null
): { options: string[]; colors: Record<string, string>; capMessage: string | null } {
const clean = drafts.map((draft) =>
type === "multiselect" ? draft.label.replace(/,/g, " ") : draft.label
);
const parsed = parseOptions(clean.join("\n"), maxOptions);
const options = parsed.options;
const firstByLabel = new Map<string, OptionDraft>();
drafts.forEach((draft, index) => {
const label = clean[index].trim();
if (label && !firstByLabel.has(label.toLowerCase()))
firstByLabel.set(label.toLowerCase(), draft);
});
const colors: Record<string, string> = {};
for (const option of options) {
const draft = firstByLabel.get(option.toLowerCase());
const color = normalizeOptionColor(draft?.color);
// The deterministic fallback is not durable data. Persist only a genuine user override;
// this keeps an untouched legacy field byte-stable while a renamed row retains its colour.
if (color && color !== normalizeOptionColor(defaultOptionColor(option)))
colors[option] = color;
}
return { options, colors, capMessage: parsed.message };
}
function optionAppearanceSignature(
options: string[],
colors: Record<string, string> | undefined
): string {
return options
.map((option) => {
const custom = colors
? Object.entries(colors).find(
([label]) => label.trim().toLowerCase() === option.toLowerCase()
)?.[1]
: undefined;
return `${option}\u0000${
normalizeOptionColor(custom) ?? normalizeOptionColor(defaultOptionColor(option))
}`;
})
.join("\u0001");
}
/**
* Item 22 (R5) β the option COLOUR control: ten brand swatches, no free RGB.
*
* It was an `<input type="color">`, which offered sixteen million colours in a product whose
* whole visual argument is five. The trigger keeps the old 24px circle's footprint (it is the
* same affordance in the same place) and opens a 5Γ2 grid: each hue's light `-tint` on the top
* row, its `-pastel` beneath. A stored colour that is not on the palette marks its NEAREST
* swatch β so the picker says what the value reads as β and re-picking is what rewrites it.
*/
function SwatchPicker({
value,
disabled,
label,
onPick,
}: {
value: string | undefined;
disabled?: boolean;
/** The option this colours, for the accessible name. */
label: string;
onPick: (hex: string) => void;
}) {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLButtonElement>(null);
const current = nearestSwatch(value);
return (
<>
<button
ref={ref}
type="button"
className="cg-option-color"
disabled={disabled}
style={{ background: current?.bg ?? normalizeOptionColor(value) ?? "#FFFFFF" }}
aria-label={`Colour for ${label}${current ? ` β ${current.label}` : ""}`}
aria-haspopup="dialog"
aria-expanded={open}
title="Change option colour"
onClick={() => setOpen((o) => !o)}
/>
{open && ref.current && (
<AnchoredOverlay
anchor={ref.current}
className="cg-pop cg-swatch-pop"
onDismiss={() => setOpen(false)}
role="dialog"
ariaLabel={`Colour for ${label}`}
dataKind="option-colour"
>
<div className="cg-swatch-grid">
{BRAND_SWATCHES.map((swatch) => (
<button
key={swatch.id}
type="button"
className={"cg-swatch" + (current?.id === swatch.id ? " is-on" : "")}
style={{ background: swatch.bg, color: swatch.fg }}
aria-label={swatch.label}
aria-pressed={current?.id === swatch.id}
title={swatch.label}
onClick={() => {
onPick(swatch.bg);
setOpen(false);
}}
>
{/* The check is drawn in the swatch's OWN ink, which is also the ink its
chips will use β so the mark doubles as a preview of readability. */}
{current?.id === swatch.id && (
<svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden>
<path
d="m3.5 8.5 3 3 6-6.5"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
/>
</svg>
)}
</button>
))}
</div>
</AnchoredOverlay>
)}
</>
);
}
function OptionsEditor({
idPrefix,
drafts,
onDrafts,
colorCode,
onColorCode,
type,
maxOptions,
onRemove,
}: {
idPrefix: string;
drafts: OptionDraft[];
onDrafts: (next: OptionDraft[]) => void;
colorCode: boolean;
onColorCode: (next: boolean) => void;
type: CreateKind;
maxOptions: number | null;
/** When supplied, the X on a row asks the parent (which may need to warn) instead of
* dropping the draft itself. The create pane never supplies it: nothing there is saved. */
onRemove?: (draft: OptionDraft) => void;
}) {
const update = (id: string, patch: Partial<OptionDraft>) =>
onDrafts(drafts.map((draft) => (draft.id === id ? { ...draft, ...patch } : draft)));
const settings = optionSettings(drafts, type, maxOptions);
return (
<div className="cg-options-editor">
<div className="cg-options-head">
<strong>Options</strong>
<label className="cg-option-toggle">
<input
type="checkbox"
checked={colorCode}
onChange={(event) => onColorCode(event.target.checked)}
/>
<span>Color-code options</span>
</label>
</div>
<div className="cg-option-list">
{drafts.map((draft, index) => (
<div className="cg-option-row" key={draft.id}>
<SwatchPicker
value={
normalizeOptionColor(draft.color) ??
OPTION_PALETTE[index % OPTION_PALETTE.length].bg
}
disabled={!colorCode}
label={draft.label || `option ${index + 1}`}
onPick={(hex) => update(draft.id, { color: hex })}
/>
<input
id={`${idPrefix}-${draft.id}`}
className="cg-input cg-option-name"
type="text"
maxLength={120}
value={draft.label}
placeholder="Option name"
aria-label={`Option ${index + 1}`}
onChange={(event) => {
const label =
type === "multiselect"
? event.target.value.replace(/,/g, " ")
: event.target.value;
update(draft.id, { label });
}}
onKeyDown={(event) => {
if (event.key !== "Enter") return;
event.preventDefault();
onDrafts([
...drafts,
{
id: nextOptionDraftId(),
label: "",
color: OPTION_PALETTE[drafts.length % OPTION_PALETTE.length].bg,
},
]);
}}
/>
<button
type="button"
className="cg-option-remove"
aria-label={`Remove ${draft.label || `option ${index + 1}`}`}
title="Remove option"
onClick={() =>
onRemove
? onRemove(draft)
: onDrafts(drafts.filter((item) => item.id !== draft.id))
}
>
<svg viewBox="0 0 16 16" aria-hidden="true">
<path d="M4 4l8 8M12 4l-8 8" />
</svg>
</button>
</div>
))}
</div>
<button
type="button"
className="cg-option-add"
onClick={() =>
onDrafts([
...drafts,
{
id: nextOptionDraftId(),
label: "",
color: OPTION_PALETTE[drafts.length % OPTION_PALETTE.length].bg,
},
])
}
>
Add option
</button>
<span className="cg-field-hint">
{settings.options.length} option{settings.options.length === 1 ? "" : "s"}.
{type === "multiselect" && " Commas inside an option are not supported."}
</span>
{settings.capMessage && (
<span className="cg-field-hint is-refusal" role="alert">
{settings.capMessage}
</span>
)}
</div>
);
}
/**
* A source-backed choice field may be editable at the record level while its schema stays owned
* by the database contract. The normal options editor must not promise a definition write for
* that field, but hiding its hydrated vocabulary makes an imported value look unconfigured.
*/
function ChoicePreview({ field }: { field: Field }) {
const options = choiceOptions(field);
if (options.length === 0) return null;
return (
<div className="cg-options-editor cg-options-preview">
<div className="cg-options-head"><strong>Choices</strong></div>
<div className="cg-options-preview-list">
{options.map((option) => (
<span className="cg-option-preview" key={option}>{option}</span>
))}
</div>
</div>
);
}
/**
* The create-picker's kind: a creatable overlay type, or the FORMULA-MEASURE pseudo-kind.
* "measure" is deliberately NOT a FieldType β a measure column's real type comes from the
* measure itself (currency/int/pct), and widening the union would let it leak into every
* switch that renders cells.
*/
type CreateKind = FieldType | "measure" | "geocode";
type PickerKind = CreateKind | RollupPreset;
const PRESET_LABELS: Record<RollupPreset, string> = { count: "Count", lookup: "Lookup" };
/**
* ββ W37-T22 (R4 / C7) β the geocode pseudo-kind's picker label, and the address-column families
* it may read. Declared here beside `CreateKind` because three places consume them (the picker
* row, the config pane's field list and `canCreate`) and a second spelling of either is how two
* of them end up disagreeing about what is offered.
* β NO DASH of any kind in the label β it reaches the screen, and `web_prose` cannot see a
* wrapped JSX sentence, so this one is on the author.
*
* ββ W40-T29 (owner instruction 31) β SHORTENED TO ONE NOUN. The label used to carry a trailing
* clause naming where the numbers come from, which is the IMPLEMENTATION read out at someone
* scanning a list of nouns; every other row in that list is the thing you get, not how it is got,
* and the source column is picked one control later anyway. The old wording is not repeated here:
* a rename that leaves its own before-picture in a doc block is how the next reader reinstates it,
* and `_test/gridUx.test.ts` asserts the whole file is free of it.
* β THE IDENTIFIER STAYS. One producer, one consumer, and `verify_grid_ux.py`'s geocode-door scan
* matches `label: GEOCODE_LABEL` BY NAME, so inlining the string here would blind the gate rather
* than satisfy it.
*/
const GEOCODE_LABEL = "Coordinates";
const GEOCODE_ADDRESS_TYPES: readonly FieldType[] = ["text", "url", "email", "phone"];
/**
* Owner item 8 (2026-07-31) β the create pane's field-type picker: a find box over an icon
* listbox, replacing the icon-less native select. Each row wears the SAME mark its column
* header will wear (`FieldTypeIcon` β TYPE_SHAPES), so the vocabulary teaches itself. The
* "measure" pseudo-kind borrows the currency mark: a measure column's real type is
* currency/int/pct, and inventing a 17th glyph for a pseudo-kind would put a mark on screen
* that no column ever wears.
*/
function TypePicker({
value,
onPick,
offerMeasure,
offerGeocode,
offerPresets,
isUserTable,
only,
}: {
value: PickerKind;
onPick: (k: PickerKind) => void;
offerMeasure: boolean;
/**
* ββ W37-T22 (R4 / C7) β offer the geocode pseudo-kind. REQUIRED, not optional: an optional
* boolean prop defaults to "off" at every call site somebody forgets, which is
* mounted-but-never-offered wearing a default.
* β IT IS NOT "does this table have a text column". It is "will the bag SURVIVE a create on
* this surface", and today those differ: on the Odoo customer/product grids a created column
* takes the overlay path into `aios_grid._field_extras`, which carries the bag; on a `ut_*`
* database every grid-created column goes to the DEFINITION (W29-T22) through
* `user_tables._clean_field`, which is a strict allowlist with no `geocode` arm yet and would
* store the column WITHOUT its configuration. Offering it there would create a field that is
* named, configured and permanently unable to run, which is the `image`-in-wave-19 failure.
* β The caller therefore ANDs the capability with the vocabulary; when `_clean_field` learns
* the arm (raised as `ASK C-6`), the capability half becomes constant and this reads as
* "has an address column", which is what W37-T22's `done-when` asks for.
*/
offerGeocode: boolean;
/** Presets author a rollup bag and are create-only, never retype options. */
offerPresets: boolean;
/** Runtime database surfaces withhold create kinds their server refuses. */
isUserTable: boolean;
/** Restrict the list (the Edit-field pane passes RETYPE_TYPES β the overlay-editable
* strata a created field may become). Absent = every creatable type. */
only?: readonly FieldType[];
}) {
const [q, setQ] = useState("");
const [describedKind, setDescribedKind] = useState<PickerKind | null>(null);
const needle = q.trim().toLowerCase();
const offerable = only
? FIELD_TYPES.filter((r) => (only as readonly string[]).includes(r.value))
: FIELD_TYPES;
const base = offerable.filter((row) => offerableCreateKind(row.value, isUserTable));
const rows: { value: PickerKind; label: string }[] = [
...base,
...(offerPresets
? ROLLUP_PRESETS.map((preset) => ({ value: preset, label: PRESET_LABELS[preset] }))
: []),
// C-NAME (item 9, 2026-08-02): "Formula measure (over a period)" -> "Metric". Two words
// of jargon and a parenthetical, replaced by the word people already use for the thing.
// The internal key stays `measure` β see the C-NAME amendment in the wave doc.
...(offerMeasure
? [{ value: "measure" as CreateKind, label: "Metric" }]
: []),
// ββ W37-T22 (R4 / C7) β the geocode pseudo-kind, offered on the same terms the Metric row
// above it is: exactly when the surface can actually deliver it. The two rows are the whole
// membership of `CreateKind` beyond `FieldType`, which is why they sit together.
...(offerGeocode
? [{ value: "geocode" as CreateKind, label: GEOCODE_LABEL }]
: []),
].filter((r) => !needle || r.label.toLowerCase().includes(needle));
// ββ W40-T29 (owner instruction 31) β the list stopped being a wall of 22 nouns here, and the
// grouping is applied to the ALREADY-FILTERED rows on purpose: one find box still reaches both
// groups, and a group the needle empties is dropped by `groupTypePickerRows` heading and all
// rather than leaving a label with nothing behind it (R8).
const groups = groupTypePickerRows(rows);
return (
<div className="cg-type-picker">
<div className="cg-type-search">
<svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden="true">
<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={q}
placeholder="Find a field type"
aria-label="Find a field type"
onChange={(event) => setQ(event.target.value)}
/>
</div>
<div className="cg-type-list" role="listbox" aria-label="Field type">
{groups.map((group) => (
// β A FRAGMENT, NOT A WRAPPER, and the reason is an accessibility one rather than a
// layout one. `.cg-type-list` is the flex column that lays the rows out, so a wrapping
// div would need `display: contents` to stay out of the way β which DROPS the element
// from the accessibility tree, inside the one container that is claiming to be a
// listbox. `FieldSelect.tsx` reached this conclusion first for its own grouped list
// ("Pre-set fields" / "Your fields" / "New field"); this follows it rather than
// inventing a second answer to a question the codebase already settled.
// β The heading is `role="presentation"` for the same reason: a listbox's children are
// options, and a bare div claiming nothing is what keeps the heading out of the option
// set while leaving it visible. Arrow-key navigation elsewhere collects
// `button.cg-type-row`, so a non-button child is invisible to it by construction.
<Fragment key={group.heading ?? "ordinary"}>
{group.heading && (
<div className="cg-type-group" role="presentation">
{group.heading}
</div>
)}
{group.rows.map((r) => (
<div
key={r.value}
role="option"
aria-selected={value === r.value}
className="cg-type-option"
>
<button
type="button"
className={"cg-type-row" + (value === r.value ? " is-on" : "")}
onClick={() => onPick(r.value)}
>
<FieldTypeIcon
type={
r.value === "measure" ? "currency" : r.value === "geocode" ? "text"
: r.value === "count" || r.value === "lookup" ? "rollup"
: r.value === "if" ? "formula" : r.value
}
size={16}
/>
<span className="cg-type-label">{r.label}</span>
</button>
<button
type="button"
className="cg-type-info"
aria-label={`About ${r.label}`}
aria-expanded={describedKind === r.value}
title={TYPE_DESCRIPTIONS[r.value]}
onClick={() => setDescribedKind((current) => current === r.value ? null : r.value)}
>
{/* ββ W46-T31 (owner instruction 27) β THE ADD-FIELD INFO MARK JOINS THE HOUSE
ICON VOCABULARY. It was the literal characters `(i)`, the one glyph in this
menu drawn in text while every mark beside it is a 16-viewBox stroked SVG:
it inherited the row's font rather than the icon size, could not take the
hairline weight, and rendered differently on every platform's font stack.
β THE BUTTON IS UNCHANGED β `type`, `className`, `aria-label`,
`aria-expanded`, `title` and `onClick` all stay exactly as they were. Only
the visible glyph moved from text to a mark, and `aria-hidden` on the svg
is what keeps the `aria-label` the single spoken name. */}
<svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden focusable="false" stroke="currentColor" strokeWidth={1.25} strokeLinecap="round" strokeLinejoin="round">
<circle cx="8" cy="8" r="5.7" />
<path d="M8 7.4v3.4" />
<path d="M8 5.2v.1" />
</svg>
</button>
{describedKind === r.value && (
<div className="cg-type-description" role="status">
{TYPE_DESCRIPTIONS[r.value]}
</div>
)}
</div>
))}
</Fragment>
))}
{rows.length === 0 && <div className="cg-pop-note">No matching type.</div>}
</div>
</div>
);
}
/** The Change-field dropdown's "New field" entries. A colon cannot occur in a real field key
* (keys are slugs), so the prefix cannot collide with one. */
const NEW_PREFIX = "new:";
/**
* The types a created field may be retyped TO (the Edit-field pane's type picker): the
* overlay-editable strata only. `formula` and `created_time` are a DIFFERENT stratum
* (source 'odoo', host-computed shape) β turning an overlay column into one is not a retype,
* and the host accepts in-place rebuilds on `custom_` overlay defs only.
*/
// Wave-18 C5-AUTOFIELD: `automation` joins the exclusion, and for a reason the two above do not
// share. It IS an overlay type, so the host would accept the retype β which is exactly the
// hazard. Retyping a Notes column to Automation hands every row's typed value to the next run to
// overwrite; retyping the other way strands machine-written statuses in a column a person can
// now edit. Neither is a change of TYPE, both are data loss with a tidy name.
const RETYPE_TYPES = CREATABLE_TYPES.filter(
(t) => !AUDIT_FIELD_TYPES.includes(t) && t !== "formula" && t !== "created_time" && t !== "automation" && t !== "if" && t !== "autonumber"
);
/** The automation kinds a column can carry. v1 is one; the shape is a list so the second is a
* line rather than a refactor. Mirrors `aios_grid.AUTOMATION_KINDS` (host-whitelisted). */
const AUTOMATION_KINDS: { key: string; label: string; hint: string }[] = [
{
key: "instagram_profile",
label: "Instagram profile",
hint: "Reads what is anonymously public about the profile in the chosen URL column, and "
+ "writes the result here. Runs from the Automation surface, on demand or on a schedule.",
},
];
const DEFAULT_MEASURE_WINDOW: WindowSpec = { kind: "ltm" };
/** The head every pane shares: title line, context line, close X. */
function PaneHead({
title,
sub,
onClose,
}: {
title: string;
sub?: string;
onClose: () => void;
}) {
return (
<div className="cg-column-head">
<div>
<div className="cg-column-title">{title}</div>
{sub && <div className="cg-column-type">{sub}</div>}
</div>
<button
type="button"
className="cg-icon-btn"
onClick={onClose}
aria-label="Close column menu"
>
Γ
</button>
</div>
);
}
/**
* Wave-6 item 9c β the Scope control, rendered by BOTH create surfaces on the cohort page
* (one component so the two doors cannot drift). "This cohort table only" is the DEFAULT β
* the owner's ask: a field made while working a cohort belongs to that work unless the user
* says otherwise.
*/
function ScopeControl({
value,
onValue,
}: {
value: FieldScope;
onValue: (v: FieldScope) => void;
}) {
return (
<label>
<span>Scope</span>
{/* β wave17 R1 β "cohort" scope means *served ONLY on the cohort TABLE*, and that table
(the retired `#/cohort` surface) no longer exists. A field created with it today would
be reachable from nowhere. So it is DISABLED for new selection.
β It is still RENDERED, and only disabled when it is not the current value. A `<select>`
whose `value` matches no option renders the FIRST option instead
([[cg-condition-builder-items]]) β dropping the row outright would silently re-scope
every existing cohort-scoped field to global on the next save, which is a data change
nobody asked for wearing a cosmetic edit's clothes. */}
<select
className="cg-select cg-scope-select"
value={value}
aria-label="Field scope"
onChange={(event) => onValue(event.target.value as FieldScope)}
>
<option value="cohort" disabled={value !== "cohort"}>
The cohort table only (retired)
</option>
<option value="global">All customer tables</option>
</select>
</label>
);
}
/**
* Wave-5 items 9/11 β the extra editors a new field's type may need, shared VERBATIM by the
* two create surfaces (insert-field and Change-field's "New field" half) so the two doors
* cannot drift: a FORMULA gets its source editor with live validation and a reference picker;
* a RATING gets its star count (the contract's 2..10).
*/
/**
* ββ Wave-34 (R13) β the AI enrichment draft, as the panel holds it.
*
* FLAT, while the wire bag nests `trigger`. That is deliberate: a form is edited one control at a
* time and a nested draft makes every setter a two-level spread, which is where a patcher drops a
* sibling key. `extraFor` does the one nesting at the moment of sending.
*/
// W42-T08: the governed semantic hop optionally carried by a Link field.
export interface HopViaBag {
topic: string;
source_dim: string;
target_dim: string;
target_key: string;
scope_key: string;
measure: string;
filter: FilterNode[];
filterConj: Conjunction;
window: string;
}
export interface HopDraft {
topic: string;
sourceDim: string;
targetDim: string;
targetKey: string;
measure: string;
filter: FilterNode[];
filterConj: Conjunction;
window: string;
scopeKey: string;
}
export const HOP_WINDOW_ALL = "all_time";
export const emptyHopDraft = (): HopDraft => ({
topic: "", sourceDim: "", targetDim: "", targetKey: "", measure: "",
filter: [], filterConj: "and", window: HOP_WINDOW_ALL, scopeKey: "",
});
interface HopOffer {
topics: HopTopic[];
windows: { key: string; label: string }[];
scopeKey: string;
draft: HopDraft;
onDraft: (patch: Partial<HopDraft>) => void;
}
export function hopVia(
draft: HopDraft | null | undefined,
scopeKey: string
): HopViaBag | null {
if (!draft) return null;
const topic = draft.topic.trim();
const sourceDim = draft.sourceDim.trim();
const targetDim = draft.targetDim.trim();
const targetKey = draft.targetKey.trim();
const measure = draft.measure.trim();
const scope = (draft.scopeKey || scopeKey || "").trim();
if (!topic || !sourceDim || !targetDim || !targetKey || !measure || !scope) return null;
return {
topic,
source_dim: sourceDim,
target_dim: targetDim,
target_key: targetKey,
scope_key: scope,
measure,
filter: draft.filter,
filterConj: draft.filterConj,
window: draft.window || HOP_WINDOW_ALL,
};
}
export const hopIncomplete = (draft: HopDraft | null | undefined, scopeKey: string): boolean =>
!!draft && draft.topic.trim() !== "" && hopVia(draft, scopeKey) === null;
export function hopDraftFrom(link: unknown): HopDraft {
const via = (link as { via?: Record<string, unknown> } | null | undefined)?.via;
const draft = emptyHopDraft();
if (!via || typeof via !== "object") return draft;
const text = (value: unknown) => (typeof value === "string" ? value : "");
return {
topic: text(via.topic),
sourceDim: text(via.source_dim),
targetDim: text(via.target_dim),
targetKey: text(via.target_key),
measure: text(via.measure),
filter: Array.isArray(via.filter) ? (via.filter as FilterNode[]) : [],
filterConj: via.filterConj === "or" ? "or" : "and",
window: text(via.window) || HOP_WINDOW_ALL,
scopeKey: text(via.scope_key),
};
}
interface AiEnrichDraft {
prompt: string;
model: string;
maxTokens: number;
mode: string;
cron: string;
overwrite: string;
}
/** The three moments an enrichment column can run. Mirrors `AI_ENRICH_TRIGGER_MODES`. */
const AI_ENRICH_MODES: ReadonlyArray<{ value: string; label: string }> = [
{ value: "manual", label: "Only when I ask" },
{ value: "on_change", label: "When a referenced column changes" },
{ value: "schedule", label: "On a schedule" },
];
/**
* What an AUTOMATIC run may replace. β There is no "overwrite anything" option and there must
* not be: a cell somebody typed into is never overwritten by an agent, whatever is chosen here,
* so "Every row" means every row THE AI WROTE. The labels say that rather than leaving a user to
* discover it, because a control that quietly means less than it says is worse than a narrower
* control (`core.user_tables.ai_enrich_human_authored` is the law it is describing).
*/
const AI_ENRICH_OVERWRITE: ReadonlyArray<{ value: string; label: string }> = [
{ value: "blank", label: "Only rows that are still empty" },
{ value: "stale", label: "Empty rows, and AI answers whose inputs have changed" },
{ value: "always", label: "Every row the AI wrote, every run" },
];
function ExtraTypeEditor({
kind,
fields,
formulaText,
onFormulaText,
formulaError,
maxValue,
onMaxValue,
codeLanguage,
onCodeLanguage,
aiEnrich,
onAiEnrich,
idPrefix,
automationKind = "instagram_profile",
onAutomationKind,
automationUrlField = "",
onAutomationUrlField,
linkTargets = [],
linkTable = "",
onLinkTable,
linkSingle = false,
onLinkSingle,
linkSelectionMode = "manual",
onLinkSelectionMode,
linkSelectionFilter = null,
onLinkSelectionFilter,
hop = null,
rollupPreset = null,
rollupMode = "link",
onRollupMode,
rollupSourceOffer = { topics: [], windows: [] },
rollupSource = { topic: "", measure: "", groupBy: "", on: "", window: "ytd" },
onRollupSource,
rollupLink = "",
onRollupLink,
rollupField = "",
onRollupField,
rollupFn = "sum",
onRollupFn,
rollupLimit = 0,
onRollupLimit,
rollupSortBy = "",
onRollupSortBy,
rollupDistinctBy = "",
onRollupDistinctBy,
rollupWhere = [],
onRollupWhere,
rollupWhereConj = "and",
onRollupWhereConj,
rollupConditions = [],
onRollupConditions,
rollupConditionConj = "and",
onRollupConditionConj,
}: {
/** β `CreateKind`, and this pane renders NOTHING for either pseudo-kind. A Metric's editor is
* the Number+Period pair and a geocode column's is the Address column pick, both of which sit
* in the create pane beside this mount: this editor dispatches on `FieldType`, and widening it
* to hold a kind no stored column ever has would put two vocabularies in one switch. */
kind: CreateKind;
fields: Field[];
formulaText: string;
onFormulaText: (v: string) => void;
formulaError: string | null;
maxValue: number;
onMaxValue: (n: number) => void;
/** β Wave-27 item 13 (R13) β the code column's language draft. REQUIRED at every call site,
* unlike the `automation` drafts below it: this pane RENDERS a <select> for a `code` kind, and
* an unwired one would be a control that configures nothing, which is worse than no control
* ([[wrong-parent-not-broken-control]]). Every mount can reach the kind, so every mount says
* which draft it is editing. */
codeLanguage: string;
onCodeLanguage: (v: string) => void;
/** ββ Wave-34 (R13) β the AI enrichment draft. REQUIRED for `codeLanguage`'s exact reason and
* one step stronger: this pane renders the ONLY control that can make an `ai_enrich` column
* creatable at all, so an unwired mount would render a prompt box that saves nothing and a
* Create button that `canCreate` then blocks forever with no visible cause. */
aiEnrich: AiEnrichDraft;
onAiEnrich: (patch: Partial<AiEnrichDraft>) => void;
idPrefix: string;
/** C5-AUTOFIELD β the automation column's config drafts. Optional so the call sites that
* cannot reach an automation type (the Change-field "new field" form) need no change. */
automationKind?: string;
onAutomationKind?: (v: string) => void;
automationUrlField?: string;
onAutomationUrlField?: (v: string) => void;
/** β 2026-08-07 β the relational drafts. Optional for the same reason the automation ones
* are: the Change-field "new field" form reaches these kinds too, and a call site that does
* not offer them should need no change. */
linkTargets?: LinkTarget[];
linkTable?: string;
onLinkTable?: (v: string) => void;
linkSingle?: boolean;
onLinkSingle?: (v: boolean) => void;
linkSelectionMode?: "manual" | "automatic";
onLinkSelectionMode?: (v: "manual" | "automatic") => void;
linkSelectionFilter?: FilterTree | null;
onLinkSelectionFilter?: (v: FilterTree | null) => void;
hop?: HopOffer | null;
/** Count/Lookup presets reopen in their reduced editor only when the stored bag is exact. */
rollupPreset?: RollupPreset | null;
/** β 2026-08-09 β which KIND of rollup is being built. `"link"` folds workspace rows;
* `"source"` reads through to a governed Odoo topic without copying a row into the store. */
rollupMode?: "link" | "source";
onRollupMode?: (v: "link" | "source") => void;
rollupSourceOffer?: RollupSourceOffer;
rollupSource?: RollupSource;
onRollupSource?: (v: RollupSource) => void;
rollupLink?: string;
onRollupLink?: (v: string) => void;
rollupField?: string;
onRollupField?: (v: string) => void;
rollupFn?: RollupFn;
onRollupFn?: (v: RollupFn) => void;
rollupLimit?: number;
onRollupLimit?: (v: number) => void;
rollupSortBy?: string;
onRollupSortBy?: (v: string) => void;
rollupDistinctBy?: string;
onRollupDistinctBy?: (v: string) => void;
/** ββ 2026-08-09 β the PRE-filter (`rollup.where`): which linked records the window may
* spend its slots on. Separate from `rollupConditions`, which runs after it. */
rollupWhere?: RollupCondition[];
onRollupWhere?: (v: RollupCondition[]) => void;
rollupWhereConj?: "and" | "or";
onRollupWhereConj?: (v: "and" | "or") => void;
rollupConditions?: RollupCondition[];
onRollupConditions?: (v: RollupCondition[]) => void;
rollupConditionConj?: "and" | "or";
onRollupConditionConj?: (v: "and" | "or") => void;
}) {
if (kind === "formula") {
// 2026-07-31 (owner item 2): other FORMULA fields are referencable now β evaluation is
// topological and a cycle is refused at validation, so the old exclusion is gone.
const referencable = offerableFields(fields).filter((f) => f.key !== "__proto__");
return (
<>
{/* ββ W50-T06 (owner instruction 5) β *"wider when configuring (it expands) and taller
by default; it behaves like Excel"*. The three-row box with no guidance is gone: the
editor opens at six rows, grows with what is typed, autocompletes from the C2
catalogue and shows each function's form while its arguments are being filled in.
β The MENU's own 560px width is a `:has(.cg-formula-editor)` rule in
`styles/wave50/grid.css`, not a class threaded through six `AnchoredOverlay` call
sites β the pane is the thing that knows it needs the room. */}
<label>
<span>Formula</span>
<FormulaEditor
value={formulaText}
onChange={onFormulaText}
fields={referencable.map((f) => ({
key: f.key, label: f.label, type: f.type,
}))}
placeholder={"MAX(0, {revenue_ly} - {revenue_ytd})"}
ariaLabel="Formula"
/>
</label>
<div className="cg-cond-line cg-formula-insert">
<FieldSelectButton
ariaLabel="Insert a field reference"
placeholder="Insert a field referenceβ¦"
// An ACTION picker, not a value one: it never holds a selection, so it stays in
// the placeholder state and `keepOpen` lets a formula take three references
// without three trips through the button.
value={undefined}
keepOpen
onChange={(key) =>
onFormulaText((formulaText + " {" + key + "}").trimStart())
}
fields={referencable.map((f) => ({
key: f.key, label: f.label, type: f.type,
}))}
/>
</div>
{/*
β 2026-08-10 β THE BLANK TRAP, said before it is hit rather than after.
`{a} - {b}` is BLANK when `b` is blank, because arithmetic propagates a missing
operand β so the trimmed-average chain the owner built ("views minus the outliers")
blanks its whole column on exactly the profiles that have NO outlier to subtract,
which is the majority of them. That reads as "the formula is broken" and the column
it blanks is the one it was built for.
The idiom is Excel's own: the AGGREGATE functions skip blanks, so `SUM({b}, 0)` is
"b, or nothing at all". Shown ALWAYS, never folded into the catalogue's per-function
documentation β a signature is reference, and this is the one sentence that changes
what somebody types. Kept to one line (DESIGN.md Β§4).
β W50-T06 retired the hard-coded list this used to name (and the `showFormulaHelp`
prop that suppressed it); the rule above outlived both and is unchanged by either.
*/}
<div className="cg-field-hint cg-formula-blank-hint">
A blank in any part blanks the whole result. Wrap an optional column as{" "}
{"SUM({field}, 0)"} to read it as zero.
</div>
{/* ββ THE HARD-CODED FUNCTION LIST THAT USED TO SIT HERE IS DELETED, AND ITS DELETION
IS THE POINT OF THE TICKET, NOT A TIDY-UP. It named thirty functions in prose; the
runtime carries a hundred and one, so the sentence was already wrong, and every
function added after it was written made it wronger with nothing able to notice.
R5 replaced it with a CATALOGUE, and the editor above reads that catalogue: the
names arrive as a live list and each one documents itself with its own signature and
description. DESIGN.md Β§4 "never over-explain" then decides the rest β a paragraph
repeating what the signature popover already says is duplication with a second,
staler authority. `showFormulaHelp` went with it: the prop existed only to suppress
this block in the edit pane. */}
{formulaText.trim() !== "" && formulaError ? (
<div className="cg-field-hint cg-formula-error">{formulaError}</div>
) : null}
</>
);
}
if (kind === "rating") {
return (
<label>
<span>Number of stars</span>
<input
id={`${idPrefix}-rating-max`}
className="cg-input cg-rating-max"
type="number"
min={2}
max={10}
value={maxValue}
aria-label="Number of stars"
onChange={(event) => {
const n = Math.round(Number(event.target.value));
onMaxValue(Number.isFinite(n) ? Math.max(2, Math.min(10, n)) : 5);
}}
/>
</label>
);
}
if (kind === "code") {
// β Wave-27 item 13 (R13) β the create form's only code-specific question. The hint is not
// decoration: "code" in a product that also runs automations invites the assumption that
// picking a language makes the snippet executable, and R13 is explicit that there is no
// execution engine. Saying so at the moment of choosing is cheaper than a support answer.
return (
<label>
<span>Language</span>
<select
id={`${idPrefix}-code-language`}
className="cg-select"
value={codeLanguage}
aria-label="Code language"
onChange={(event) => onCodeLanguage(event.target.value)}
>
{CODE_LANGUAGES.map((lang) => (
<option key={lang} value={lang}>
{CODE_LANGUAGE_LABELS[lang]}
</option>
))}
</select>
<span className="cg-field-hint">
Chooses how the snippet is coloured. It is never run.
</span>
</label>
);
}
if (kind === "ai_enrich") {
// ββ WAVE-34 (owner ruling R13) β *"a prompt per row that populates text. Detailed
// configuration in the field's own config, including a token-usage limit."*
//
// β THE PROMPT IS FIRST AND IT IS THE ONLY REQUIRED CONTROL, because it is the only one
// without which the column can never hold anything (`_clean_field` refuses the field). The
// other four all have a working default, so a user who types one sentence and presses Create
// gets a column that runs.
// β Every control below is an EXISTING one (`cg-input`, `cg-select`, `cg-field-hint`,
// `<label><span>β¦`): `index.css` belongs to another lane this wave, so this panel is built
// from the vocabulary already in the file rather than from a rule I cannot add.
const refs = Array.from(
new Set((aiEnrich.prompt.match(/\{([a-zA-Z0-9_]{1,60})\}/g) ?? []).map((m) => m.slice(1, -1)))
);
const known = new Set(fields.map((f) => f.key));
const unknown = refs.filter((r) => !known.has(r));
return (
<>
<label>
<span>Prompt</span>
<textarea
id={`${idPrefix}-ai-prompt`}
className="cg-input"
rows={3}
value={aiEnrich.prompt}
placeholder="Summarise what {name} sells, in one line."
aria-label="Enrichment prompt"
onChange={(event) => onAiEnrich({ prompt: event.target.value })}
/>
{/* β THE UNRESOLVED-TOKEN WARNING IS NOT DECORATION. A `{token}` naming no column is
sent verbatim to the model, which then answers a different question on every row and
returns text that looks exactly like a correct answer. The server reports it per row
at run time; saying it here costs one run nobody has paid for yet. */}
{unknown.length > 0 ? (
<span className="cg-field-hint">
{unknown.map((u) => `{${u}}`).join(", ")} is not a column on this database. Wrap a
column key in braces to put its value into the prompt.
</span>
) : (
<span className="cg-field-hint">
Put a column key in braces to use its value, the way a formula does. Each row gets
its own answer.
</span>
)}
</label>
<label>
<span>When it runs</span>
<select
id={`${idPrefix}-ai-mode`}
className="cg-select"
value={aiEnrich.mode}
aria-label="When the enrichment runs"
onChange={(event) => onAiEnrich({ mode: event.target.value })}
>
{AI_ENRICH_MODES.map((m) => (
<option key={m.value} value={m.value}>
{m.label}
</option>
))}
</select>
</label>
{/* A cadence box only where a cadence is read. A schedule stored under "Only when I ask"
is a setting the user can see and nothing will ever act on, which is the shape D-246
wears on the Odoo sync, so the server drops it and this never offers it. */}
{aiEnrich.mode === "schedule" ? (
<label>
<span>Schedule</span>
<input
id={`${idPrefix}-ai-cron`}
className="cg-input"
value={aiEnrich.cron}
placeholder="0 6 * * *"
aria-label="Enrichment schedule"
onChange={(event) => onAiEnrich({ cron: event.target.value })}
/>
<span className="cg-field-hint">Minute, hour, day, month, weekday.</span>
</label>
) : null}
<label>
<span>Which rows</span>
<select
id={`${idPrefix}-ai-overwrite`}
className="cg-select"
value={aiEnrich.overwrite}
aria-label="Which rows a run may fill"
onChange={(event) => onAiEnrich({ overwrite: event.target.value })}
>
{AI_ENRICH_OVERWRITE.map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
<span className="cg-field-hint">
A cell you have typed into is never overwritten by a run, whichever of these is chosen.
</span>
</label>
<label>
<span>Token limit per row</span>
<input
id={`${idPrefix}-ai-tokens`}
type="number"
className="cg-input"
min={16}
max={4000}
value={aiEnrich.maxTokens}
aria-label="Token limit per row"
onChange={(event) => onAiEnrich({ maxTokens: Number(event.target.value) || 300 })}
/>
{/* R6's standing rule, at the control rather than in a support answer: a run that hits
its ceiling STOPS and says how far it got, so this number is the whole budget's
basis and not a soft target. */}
<span className="cg-field-hint">
Also sets the whole run's budget. A run that reaches it stops and reports how many
rows it filled.
</span>
</label>
<label>
<span>Model</span>
<input
id={`${idPrefix}-ai-model`}
className="cg-input"
value={aiEnrich.model}
placeholder="Leave empty for the default"
aria-label="Enrichment model"
onChange={(event) => onAiEnrich({ model: event.target.value })}
/>
<span className="cg-field-hint">
Empty uses the cheapest provider configured on this deployment.
</span>
</label>
</>
);
}
if (kind === "created_time") {
return (
<div className="cg-field-hint">
Read-only. When the record was created in the source system.
</div>
);
}
if (kind === "created_by" || kind === "last_modified_time" || kind === "last_modified_by") {
return <div className="cg-field-hint">Read-only. {TYPE_DESCRIPTIONS[kind]}</div>;
}
if (kind === "automation") {
// C5-AUTOFIELD β the field's GEAR. An automation column has no value the user types, so
// this pane configures what a RUN does instead: which job, and which column carries the
// thing it reads. The schedule and the Run-now button are NOT here β they belong to the
// automation itself, on the Automation surface, because one job can fill a column across
// many records and its cadence is a property of the job, not of the column.
const urlish = offerableFields(fields).filter(
(f) => f.type === "url" || f.type === "text"
);
const chosen = AUTOMATION_KINDS.find((k) => k.key === automationKind)
?? AUTOMATION_KINDS[0];
return (
<>
<label>
<span>What it reads</span>
<select
id={`${idPrefix}-automation-kind`}
className="cg-input"
value={automationKind}
aria-label="Automation kind"
onChange={(event) => onAutomationKind?.(event.target.value)}
>
{AUTOMATION_KINDS.map((k) => (
<option key={k.key} value={k.key}>
{k.label}
</option>
))}
</select>
</label>
<label>
<span>URL column</span>
<select
id={`${idPrefix}-automation-url`}
className="cg-input"
value={automationUrlField}
aria-label="URL column"
onChange={(event) => onAutomationUrlField?.(event.target.value)}
>
<option value="">Choose a columnβ¦</option>
{urlish.map((f) => (
<option key={f.key} value={f.key}>
{f.label}
</option>
))}
</select>
</label>
<div className="cg-field-hint">{chosen.hint}</div>
<div className="cg-field-hint">
Cells here are written by the run and cannot be typed into. A value you entered
would be replaced by the next run without saying so.
</div>
{/* A v1 LIMIT, said out loud rather than discovered. The column can be created on any
table, but an Instagram automation only accepts a blank database as its target
(`clean_config('field_instagram')`), because the run writes rows and an Odoo-sourced
table is read-only at the source. Without this line a user creates the column on
Customer, goes to Automation, and finds no way to point anything at it. */}
<div className="cg-field-hint">
Runs target a blank database. On a connector-backed table this column can be created
but no automation can write to it yet.
</div>
</>
);
}
if (kind === "link") {
// β 2026-08-07 β Airtable's "Link to another record", and the whole editor is ONE question:
// which database. The relation itself is then the cell (a set of linked rows).
const hopTopic = hop?.topics.find((topic) => topic.key === hop.draft.topic);
const hopTargetFields = linkTargets.find((target) => target.key === linkTable)?.fields
.filter((candidate) => candidate.type !== "link" && candidate.type !== "rollup") ?? [];
const hopWindow = hop?.draft.window || HOP_WINDOW_ALL;
const hopWindowOffered = !!hop?.windows.some((candidate) => candidate.key === hopWindow);
const selectionFields = linkTargets.find((target) => target.key === linkTable)?.fields ?? [];
const selectionIssue = linkSelectionFilterIssue(linkSelectionFilter, selectionFields);
return (
<>
<label>
<span>Database</span>
<select
id={`${idPrefix}-link-table`}
className="cg-input"
value={linkTable}
aria-label="Database to link to"
onChange={(event) => {
onLinkTable?.(event.target.value);
if (linkSelectionFilter) onLinkSelectionFilter?.({ conj: "and", nodes: [] });
hop?.onDraft({ targetKey: "" });
}}
>
<option value="">Choose a databaseβ¦</option>
{linkTargets.map((t) => (
<option key={t.key} value={t.key}>{t.label}</option>
))}
</select>
</label>
{linkTargets.length === 0 ? (
<div className="cg-field-hint">
There is no other database to link to yet. Create one first, then come back.
</div>
) : null}
<label>
<span>How links are chosen</span>
<select
id={`${idPrefix}-link-selection-mode`}
className="cg-input"
value={linkSelectionMode}
aria-label="How linked records are selected"
disabled={!!hop?.draft.topic}
onPointerDown={(event) => event.stopPropagation()}
onChange={(event) => onLinkSelectionMode?.(
event.target.value === "automatic" ? "automatic" : "manual"
)}
>
<option value="manual">Nothing, I will pick the records myself</option>
<option value="automatic">Set links automatically</option>
</select>
</label>
{hop ? (
<div className="cg-hop">
<label className="cg-hop-question">
<span>Through</span>
<select
id={`${idPrefix}-hop-topic`}
className="cg-input"
value={hop.draft.topic}
aria-label="Data to travel through"
onChange={(event) => {
const topic = event.target.value;
onLinkSelectionMode?.(topic ? "automatic" : "manual");
hop.onDraft({
topic,
sourceDim: "",
targetDim: "",
measure: "",
filter: [],
filterConj: "and",
});
}}
>
<option value="">Nothing, link the records directly</option>
{hop.topics.map((topic) => (
<option key={topic.key} value={topic.key}>{topic.label}</option>
))}
</select>
</label>
{hop.topics.length === 0 ? (
<div className="cg-field-hint">No governed data is available to travel through.</div>
) : null}
{hopTopic ? (
<div className="cg-hop-body">
<label>
<span>Matched from</span>
<select
id={`${idPrefix}-hop-source-dim`}
className="cg-input"
value={hop.draft.sourceDim}
aria-label="What names a row of this database"
onChange={(event) => hop.onDraft({ sourceDim: event.target.value })}
>
<option value="">Choose the starting match</option>
{hopTopic.dims.map((dim) => (
<option key={dim.key} value={dim.key}>{dim.label}</option>
))}
</select>
</label>
<label>
<span>Matched to</span>
<select
id={`${idPrefix}-hop-target-dim`}
className="cg-input"
value={hop.draft.targetDim}
aria-label="What names a row of the other database"
onChange={(event) => hop.onDraft({ targetDim: event.target.value })}
>
<option value="">Choose the destination match</option>
{hopTopic.dims.map((dim) => (
<option key={dim.key} value={dim.key}>{dim.label}</option>
))}
</select>
</label>
<label>
<span>Column over there</span>
<select
id={`${idPrefix}-hop-target-key`}
className="cg-input"
value={hop.draft.targetKey}
aria-label="Column in the other database holding that value"
onChange={(event) => hop.onDraft({ targetKey: event.target.value })}
>
<option value="">Choose the destination column</option>
{hopTargetFields.map((candidate) => (
<option key={candidate.key} value={candidate.key}>{candidate.label}</option>
))}
</select>
</label>
<label>
<span>Measure</span>
<select
id={`${idPrefix}-hop-measure`}
className="cg-input"
value={hop.draft.measure}
aria-label="Measure"
onChange={(event) => hop.onDraft({ measure: event.target.value })}
>
<option value="">Choose a measure</option>
{hopTopic.measures.map((measure) => (
<option key={measure.key} value={measure.key}>{measure.label}</option>
))}
</select>
</label>
{hop.windows.length > 0 ? (
<label>
<span>Over</span>
<select
id={`${idPrefix}-hop-window`}
className="cg-input"
value={hopWindow}
aria-label="Date window"
onChange={(event) => hop.onDraft({ window: event.target.value })}
>
{hopWindowOffered ? null : <option value={hopWindow}>{hopWindow}</option>}
{hop.windows.map((candidate) => (
<option key={candidate.key} value={candidate.key}>{candidate.label}</option>
))}
</select>
</label>
) : null}
<div className="cg-hop-filter">
<span className="cg-type-title">Keep only</span>
<FilterBuilderPanel
fields={hopTopic.dims}
database={hopTopic.key}
filters={{ conj: hop.draft.filterConj, nodes: hop.draft.filter }}
onChange={(next) => hop.onDraft({
filter: filterTreeNodes(next),
filterConj: filterTreeConj(next),
})}
/>
</div>
{(hop.draft.scopeKey || hop.scopeKey).trim() === "" ? (
<div className="cg-field-hint">
This database has no usable starting scope, so the hop cannot be saved.
</div>
) : null}
</div>
) : null}
</div>
) : null}
<label className="cg-check-row" style={{ flexDirection: "row", alignItems: "center" }}>
<input
id={`${idPrefix}-link-selection-filter`}
type="checkbox"
checked={linkSelectionFilter !== null}
disabled={!linkTable}
onPointerDown={(event) => event.stopPropagation()}
onChange={(event) => onLinkSelectionFilter?.(
event.target.checked ? { conj: "and", nodes: [] } : null
)}
/>
<span>Limit record selection to records matching a condition</span>
</label>
{linkSelectionFilter ? (
<div className="cg-hop-filter" data-link-selection-filter>
{/* Keep the shared builder readable in either pane without adding a scroll container. */}
<style>{`
.cg-column-menu:has([data-link-selection-filter]) {
width: min(780px, calc(100vw - 16px));
}
.cg-column-menu [data-link-selection-filter] .cg-cond-line {
flex-wrap: wrap;
}
.cg-column-menu [data-link-selection-filter] :is(.cg-cond-row, .cg-cond-group) {
flex: 1 1 480px;
max-width: 100%;
}
.cg-column-menu [data-link-selection-filter] :is(
.cg-cond-row, .cg-cond-rhs, .cg-cond-between, .cg-cond-window,
.cg-cond-anchor, .cg-builder-add, .cg-builder-footer
) {
flex-wrap: wrap;
}
.cg-column-menu [data-link-selection-filter] :is(.cg-input, .cg-select) {
width: auto;
max-width: 100%;
}
.cg-column-menu [data-link-selection-filter] .cg-cond-row > :is(
.cg-cond-val, .cg-cond-cohorts, .cg-cond-rhs
) {
flex: 1 1 160px;
}
.cg-column-menu [data-link-selection-filter] :is(.cg-cond-between, .cg-cond-anchor) {
flex: 1 1 320px;
min-width: 0;
display: flex;
align-items: center;
gap: 6px;
}
.cg-column-menu [data-link-selection-filter] :is(
.cg-cond-between, .cg-cond-anchor
) > .cg-cond-val {
flex: 1 1 144px;
}
.cg-column-menu [data-link-selection-filter] .cg-cond-anchor-mode {
flex: 0 0 176px;
}
.cg-column-menu [data-link-selection-filter] :is(
.cg-cond-rhs, .cg-cond-between, .cg-cond-window, .cg-cond-anchor
) {
max-width: 100%;
}
`}</style>
<FilterBuilderPanel
fields={selectionFields}
database={linkTable}
filters={linkSelectionFilter}
onChange={(next) => onLinkSelectionFilter?.(next)}
/>
{selectionIssue ? <div className="cg-field-hint" role="status">{selectionIssue}</div> : null}
</div>
) : null}
<label className="cg-cond-line" style={{ flexDirection: "row", alignItems: "center" }}>
<input
type="checkbox"
checked={linkSingle}
aria-label="Allow only one linked record"
onPointerDown={(event) => event.stopPropagation()}
onChange={(event) => onLinkSingle?.(event.target.checked)}
/>
<span>Allow only one linked record</span>
</label>
{hop?.draft.topic ? null : (
<div className="cg-field-hint">
A cell here holds the records you pick. Add a Rollup column afterwards to summarise a
column of those records: an average, a total, a count.
</div>
)}
</>
);
}
if (kind === "rollup") {
// β 2026-08-07 β Airtable's rollup, plus the LAST-N window Airtable does not have.
//
// The editor reads as the sentence the column answers, in order: through WHICH relation, over
// WHICH column, folded HOW, and across WHICH records. That last control is the owner's
// headline ("average Views over last N posts") and Airtable cannot express it β its rollup
// conditions filter by predicate, never by rank.
const linkFields = offerableFields(fields).filter((f) => f.type === "link");
const chosenLink = linkFields.find((f) => f.key === rollupLink);
const target = linkTargets.find((t) => t.key === chosenLink?.link?.table);
const targetFields = offerableFields(target?.fields ?? []);
// β COUNTALL IS THE ONE FUNCTION WITH NO SOURCE COLUMN β it counts linked RECORDS, so the
// field picker would be a control that configures nothing. Airtable's rule, and ours.
const needsField = rollupFn !== "countall";
// ββ 2026-08-09 β THE SECOND KIND OF ROLLUP. Everything above summarises rows that live in
// this workspace; a SOURCE rollup summarises rows that were never copied here β one grouped
// SQL query over the governed Odoo model answers every parent row at once. That is the only
// way a column can total 256,810 order lines, which is 4x what a database here may hold.
const sourceTopics = rollupSourceOffer.topics;
const topic = sourceTopics.find((t) => t.key === rollupSource.topic);
const dim = topic?.dims.find((d) => d.key === rollupSource.groupBy);
const setSource = (patch: Partial<RollupSource>) =>
onRollupSource?.({ ...rollupSource, ...patch });
// β A join column must hold a SCALAR the group key can equal. Link and rollup columns hold a
// comma-joined id list and a computed value respectively, so neither can ever match.
const joinable = offerableFields(fields).filter(
(f) => f.type !== "link" && f.type !== "rollup" && f.key !== "__proto__"
);
const sourceEditor = (
<>
<label>
<span>Odoo data</span>
<select
id={`${idPrefix}-rollup-topic`}
className="cg-input"
value={rollupSource.topic}
aria-label="Odoo topic"
onChange={(event) =>
// β CLEAR THE MEASURE AND THE DIM WITH THE TOPIC. Both are keys OF the topic, so
// carrying them across a topic change leaves a bag naming a measure the new topic
// does not have β which the save door refuses, on a form that looks complete.
setSource({ topic: event.target.value, measure: "", groupBy: "" })
}
>
<option value="">Choose what to summariseβ¦</option>
{sourceTopics.map((t) => (
<option key={t.key} value={t.key}>{t.label}</option>
))}
</select>
</label>
{sourceTopics.length === 0 ? (
<div className="cg-field-hint">
No live data sources are available for this workspace. A source rollup reads a
connected system; this one has none connected yet.
</div>
) : null}
{topic ? (
<>
<label>
<span>Measure</span>
<select
id={`${idPrefix}-rollup-measure`}
className="cg-input"
value={rollupSource.measure}
aria-label="Measure"
onChange={(event) => setSource({ measure: event.target.value })}
>
<option value="">Choose a measureβ¦</option>
{topic.measures.map((m) => (
<option key={m.key} value={m.key}>{m.label}</option>
))}
</select>
</label>
<label>
<span>One row per</span>
<select
id={`${idPrefix}-rollup-dim`}
className="cg-input"
value={rollupSource.groupBy}
aria-label="Group by"
onChange={(event) => setSource({ groupBy: event.target.value })}
>
<option value="">Choose a groupingβ¦</option>
{topic.dims.map((d) => (
<option key={d.key} value={d.key}>{d.label}</option>
))}
</select>
</label>
<label>
<span>Matched on</span>
<select
id={`${idPrefix}-rollup-on`}
className="cg-input"
value={rollupSource.on}
aria-label="Column to match on"
onChange={(event) => setSource({ on: event.target.value })}
>
<option value="">Choose this database's columnβ¦</option>
{joinable.map((f) => (
<option key={f.key} value={f.key}>{f.label}</option>
))}
</select>
</label>
{/* β THE JOIN IS THE ONE THING THE SERVER CANNOT CHECK. It knows the measure exists
and the dim is groupable; it cannot know that THIS column holds the same kind of
value the grouping keys by. A wrong match is not an error β it is a column of
blanks. So the control says which kind of value it needs. */}
{dim ? (
<div className="cg-field-hint">
{dim.keyedBy === "id"
? `Pick the column holding the Odoo ID for ${dim.label.toLowerCase()}. Matching on a name instead leaves every cell blank.`
: `Pick the column holding the ${dim.label.toLowerCase()} value itself. This grouping keys by its own value, not by an ID.`}
</div>
) : null}
<label>
<span>Over</span>
<select
id={`${idPrefix}-rollup-window`}
className="cg-input"
value={rollupSource.window || "all_time"}
aria-label="Date window"
onChange={(event) => setSource({ window: event.target.value })}
>
{rollupSourceOffer.windows.map((w) => (
<option key={w.key} value={w.key}>{w.label}</option>
))}
</select>
</label>
<div className="cg-field-hint">
Recomputed against live data: the window moves with today's date rather than
freezing the dates it was created on.
</div>
</>
) : null}
</>
);
const linkEditor = (
<>
{rollupPreset ? (
<div className="cg-field-hint">{TYPE_DESCRIPTIONS[rollupPreset]}</div>
) : null}
<label>
<span>Through</span>
<select
id={`${idPrefix}-rollup-link`}
className="cg-input"
value={rollupLink}
aria-label="Link column"
onChange={(event) => onRollupLink?.(event.target.value)}
>
<option value="">Choose a link columnβ¦</option>
{linkFields.map((f) => (
<option key={f.key} value={f.key}>{f.label}</option>
))}
</select>
</label>
{linkFields.length === 0 ? (
<div className="cg-field-hint">
This database has no link column yet. A rollup summarises records reached through a
link, so add one of those first.
</div>
) : null}
{rollupPreset ? null : (
<label>
<span>Fold</span>
<select
id={`${idPrefix}-rollup-fn`}
className="cg-input"
value={rollupFn}
aria-label="Rollup function"
onChange={(event) => onRollupFn?.(event.target.value as RollupFn)}
>
{ROLLUP_FNS.map((fn) => (
<option key={fn} value={fn}>{ROLLUP_FN_LABELS[fn]}</option>
))}
</select>
</label>
)}
{needsField ? (
<label>
<span>Column</span>
<select
id={`${idPrefix}-rollup-field`}
className="cg-input"
value={rollupField}
aria-label="Column to roll up"
onChange={(event) => onRollupField?.(event.target.value)}
>
<option value="">Choose a columnβ¦</option>
{targetFields.map((f) => (
<option key={f.key} value={f.key}>{f.label}</option>
))}
</select>
</label>
) : null}
{/*
ββ 2026-08-09 Β· D-99 β THE STATE THE OWNER'S REPORT DESCRIBES, SAID OUT LOUD.
Owner: *"if we want to use Rollup field to apply to the related database, it doesn't
work. Because the linked Field can't be selected yet."*
β WHAT IS ACTUALLY REACHABLE HERE, measured rather than guessed. The `Through` picker
offers EVERY link column β `linkFields` filters on `f.type === "link"` and excludes
nothing preset, derived or `automation:`-tagged, so the scouted hypothesis ("the picker
omits preset links") is refuted at source. What CAN happen is one step later: the
target is resolved out of `linkTargets`, which is `GET /tables` filtered by
`user_tables.may_open` (creator, admin, or an explicit share). An automation-OWNED child
dataset is stamped with a machine owner, so for a user who is neither its creator nor an
admin it is simply ABSENT from that list β and then `targetFields` is `[]`, this Column
picker holds nothing but its placeholder, and `Add condition` below is disabled.
β AND UNTIL NOW IT SAID NOTHING. An empty picker beside a dead button reads as "this
feature is broken"; it is in fact a permission fact about ONE database, and the fix for
it is a share, not a bug report. This is the absent-vs-empty third state the automation
panel already distinguishes ("No view list was offered for that database") β the same
discipline, applied to the surface that actually got reported.
β IT NAMES THE TABLE RATHER THAN APOLOGISING. `chosenLink.link.table` is the key the
bag points at, and printing it is what turns "it doesn't work" into a thing to go and
grant.
*/}
{chosenLink && !target ? (
<div className="cg-field-hint">
This link points at <b>{chosenLink.link?.table}</b>, which is not among the databases
you can open, so its columns cannot be listed here and the conditions below stay
unavailable. Ask an admin to share that database with you, then reopen this editor.
</div>
) : null}
{/*
ββ 2026-08-09 (owner) β THE PRE-FILTER, ABOVE THE WINDOW, AND THE SCREEN ORDER IS THE
ORDER OF OPERATIONS. Owner: *"instead of last 12 posts, we also want to make it so its
last N record, where the record's Status is video."*
Everything below this block narrows a set that this block has already chosen:
include β order β how many β deduplicate β then keep only. Reading top to bottom is
reading what the server does, in sequence. The post-filter list used to sit HERE, above
the window it runs after, which is the one arrangement that teaches the wrong model.
*/}
{rollupPreset ? null : (
<>
<RollupConditionList
idPrefix={`${idPrefix}-rollup-where`}
title="Include records"
hint={"Applied BEFORE the window below, so βlast 10β counts only records that "
+ "match. View filters never change a Rollupβs result."}
conditions={rollupWhere}
onConditions={(v) => onRollupWhere?.(v)}
conj={rollupWhereConj}
onConj={(v) => onRollupWhereConj?.(v)}
targetFields={targetFields}
allowRef={false}
/>
<label>
<span>Across</span>
<select
id={`${idPrefix}-rollup-sort`}
className="cg-input"
value={rollupSortBy}
aria-label="Which records to include"
onChange={(event) => onRollupSortBy?.(event.target.value)}
>
<option value="">Every linked record</option>
{targetFields.map((f) => (
<option key={f.key} value={f.key}>Most recent by {f.label}</option>
))}
</select>
</label>
{rollupSortBy ? (
<label>
<span>How many</span>
<input
type="number"
className="cg-input"
min={1}
value={rollupLimit || 1}
aria-label="How many records"
onChange={(event) =>
onRollupLimit?.(Math.max(1, Number(event.target.value) || 1))
}
/>
</label>
) : null}
<label>
<span>Deduplicate by</span>
<select
id={`${idPrefix}-rollup-distinct`}
className="cg-input"
value={rollupDistinctBy}
aria-label="Deduplicate linked records by"
onChange={(event) => onRollupDistinctBy?.(event.target.value)}
>
<option value="">Keep every linked row</option>
{targetFields.map((f) => (
<option key={f.key} value={f.key}>One row per {f.label}</option>
))}
</select>
</label>
{/* β THE RULE STATED AT THE CONTROL, because the server refuses the pair and a refusal
the user meets after pressing Create is a refusal they had no way to avoid. "The
last N" with no declared order is not a measurement β it is whichever N rows happen
to sit first in the store. */}
<div className="cg-field-hint">
{rollupSortBy
? `The ${rollupLimit || 1} most recent linked records, newest first.`
: "Every linked record. Choose an order above to summarise just the most recent few."}
</div>
{rollupDistinctBy ? (
<div className="cg-field-hint">
Duplicate linked rows with the same identity count once; the newest row wins when an
order is selected.
</div>
) : null}
{/*
ββ WAVE 28 Β· C1 β THE POST-FILTER, BELOW THE WINDOW, WHICH IS WHERE IT ALWAYS RAN.
Only its POSITION on screen moved (2026-08-09), and the move is the point: this list
selects among the records the window above already kept, so a threshold measured "over
this set" is measured over exactly those. That is why the Ο operators live here and are
refused in the pre-filter β before the window there is no set for a mean to be about.
β THE HINT HOLDS LITERAL CHARACTERS, never `\u`-escapes. It shipped to the live Space
printing `it kept β which is what a βΟ from the meanβ` ON SCREEN,
because the escapes were written with a DOUBLED backslash and the JS string then had
nothing left to interpret. `tsc` is happy β a wrong string is valid TypeScript β and no
gate reads prose. It was caught by opening the deployed pane and LOOKING at it
([[ui-invisible-to-assertions]]).
*/}
<RollupConditionList
idPrefix={`${idPrefix}-rollup-cond`}
title="Then keep only"
hint={"Applied AFTER the window above, over exactly the records it kept, which is "
+ "what a βΟ from the meanβ threshold is measured against."}
conditions={rollupConditions}
onConditions={(v) => onRollupConditions?.(v)}
conj={rollupConditionConj}
onConj={(v) => onRollupConditionConj?.(v)}
targetFields={targetFields}
allowRef
/>
</>
)}
<div className="cg-field-hint">
Computed for you and refreshed as the linked records change. The cell cannot be typed
into.
</div>
</>
);
// β THE MODE SWITCH RENDERS ONLY WHEN THERE IS A CHOICE TO MAKE. On a workspace with no
// connected source the offer is empty, and a two-way toggle whose second option can never
// work is a control that configures nothing ([[wrong-parent-not-broken-control]]). The link
// editor is then simply what a rollup is, exactly as it was before this existed.
if (rollupPreset || !sourceTopics.length) return linkEditor;
return (
<>
<label>
<span>Summarise</span>
<select
id={`${idPrefix}-rollup-mode`}
className="cg-input"
value={rollupMode}
aria-label="What this rollup summarises"
onChange={(event) => onRollupMode?.(event.target.value as "link" | "source")}
>
<option value="link">Records in this workspace</option>
<option value="source">Live Odoo data</option>
</select>
</label>
<div className="cg-field-hint">
{rollupMode === "source"
? "Answered straight from the source. It can total hundreds of thousands of rows because none of them are copied into this database."
: "Folds the records a link column reaches, which must already exist in this workspace."}
</div>
{rollupMode === "source" ? sourceEditor : linkEditor}
</>
);
}
return null;
}
export default function ColumnMenu({
viewControlsReadOnly = false,
state,
field,
fields,
linkTargets = [],
rollupSourceOffer = { topics: [], windows: [] },
hopTopicOffer = { topics: [], windows: [], omissions: [] },
geocodable,
locked,
schemaLocked = false,
canAddField = true,
embedded = false,
columnWidth = 160,
onColumnWidth,
isUserTable = false,
viewer,
sortedDir,
isFiltered,
isGrouped,
groupable,
onClose,
onNote,
onHide,
onMoveLeft,
onMoveRight,
onCreate,
onChangeField,
onCreateAndSwap,
onProfileFlag,
onRetype,
onChoiceRemove,
onFieldConfig,
onRename,
onFormula,
initialPosition,
initialPane,
scopeChoice = false,
pinnedTo = false,
onPinTo,
onUnpin,
onPeriod,
onDelete,
onSetDeletionLock,
onCopyFieldLink,
onRemoveFromMine,
onEnrich,
onDuplicate,
onFormat,
onSummary,
summary,
onShowAs,
onSort,
onClearSort,
onFilterBy,
onClearFilter,
onGroupByField,
onClearGroup,
userOptions = [],
measures = [],
tableKey,
}: ColumnMenuProps) {
const optionLimit = serverOptionLimit(fields);
const fieldOfferable = isOfferableField(field);
const hopScopeKey = tableKey === "customer_data"
? "customer"
: tableKey === "product_data"
? "product"
: tableKey ?? "";
const hopTopics: HopTopic[] = hopTopicOffer.topics;
/**
* ββ W40-T24 (owner instruction 18, contract C2) β the pre-set DEFINITION lock, read from the
* one place that states it. `display.ts` carries the whole argument, including the measured
* reason the lock is spelt `isUserSchemaField` and NOT `isPresetField` (nine product_data
* contract columns, Supplier among them, are declared `source: "overlay"` so that their cells
* stay typeable, and `isPresetField` answers false for every one).
*
* β ONLY `swap` AND `remove` ARE READ HERE, and that is the design, not an omission: `rename`
* and `retype` are already enforced at the host by withholding their handlers, and a second
* refusal in this file could only subtract from a door the host deliberately opened.
*/
const offer = columnDefinitionOffer(field, { isUserTable, isPrimary: locked });
const canEditDefinition = !embedded && !schemaLocked && mayEditFieldDefinition(field, viewer);
/**
* ββ W41-T31 (owner instruction 1, ruling R19) β THE DESCRIPTION-ONLY DOOR.
*
* Owner: *"A pre-set field's 'Edit field' should not exist except to change the description;
* the pre-set description is the one place a user adds a description."*
*
* β A SECOND PREDICATE, NOT A WIDER `canEditDefinition`, and the distinction is the ticket's
* own instruction. Widening the one above would re-open the Name box, the type picker, the
* retype, Change field, the period row and the delete β every door the pre-set lock closed on
* purpose β to buy one textarea. This one says only "there is a description here to write",
* and every surface that asks "may this definition change?" keeps getting the same `false`
* it got before.
*
* β IT IS THE PRE-SET LOCK IT READS, and only that. `schemaLocked` is
* `CustomerGrid.isSchemaLocked`, i.e. `automation.preset === true && type !== "rollup"` β the
* client mirror of `core.user_tables.preset_editable`. That is the lock DESIGN section 4 calls
* the pre-set field: it closes the DEFINITION and leaves the cells as typeable as they were.
* A locked database and a locked view are different locks and neither is asked about here.
*
* β `onNote` IS A REQUIRED PROP, so the second clause is a runtime seatbelt rather than a real
* gate β but it is the handler the whole pane exists to reach, and `typeof` is how you write
* that without TS2774 ("this condition will always return true").
*/
const canEditDescription = !embedded && schemaLocked && typeof onNote === "function";
/**
* Either door opens the Edit-field pane; WHICH pane is decided at the render, below. Read by
* the menu row and by the seed, so the two can never disagree about whether it is on offer.
*
* β THE SEED IS A SECOND GATE and it refused `"edit"` independently of the menu row: on a
* `schemaLocked` field it forced `"menu"` for EVERY `initialPane`, so a host opening straight
* onto the edit pane (`viewModes` does) landed a pre-set on the action list instead. Rewritten
* so the `"edit"` case asks `editPaneOffered` and every OTHER initial pane keeps the blanket
* `schemaLocked` refusal it had β creating a column, not describing one, is what that refused.
*/
const editPaneOffered = canEditDefinition || canEditDescription;
const [pane, setPane] = useState<MenuPane>(
embedded ? "menu" : initialPane === "edit"
? (editPaneOffered ? "edit" : "menu")
: (schemaLocked ? "menu" : initialPane ?? "menu")
);
const [note, setNote] = useState(field.note ?? "");
const [position, setPosition] = useState<CreatePosition | null>(embedded ? null : initialPosition ?? null);
const [widthDraft, setWidthDraft] = useState(String(Math.round(columnWidth)));
/** Delete is DESTRUCTIVE (a custom field's stored values go with it) β first click arms,
* second click fires. Reopening the menu disarms (state is per-mount, keyed by field). */
const [label, setLabel] = useState("");
/** Whether the user has typed their own name β an auto-suggested measure label must never
* overwrite one, but should keep tracking the measure/window until they do. */
const [labelTouched, setLabelTouched] = useState(false);
const [kind, setKind] = useState<CreateKind>("text");
const [createDefaultEnabled, setCreateDefaultEnabled] = useState(false);
const [createDefaultValue, setCreateDefaultValue] = useState("");
const [ifDraft, setIfDraft] = useState<IfDefinition>(emptyIfDefinition);
const [editIf, setEditIf] = useState<IfDefinition>(() => field.if ?? emptyIfDefinition());
const ifSourceFields = fields.filter((source) => isOfferableField(source));
const editIfSourceFields = ifSourceFields.filter((source) => source.key !== field.key);
/** β W36-T07 β the field agent's pane, inside the create pane rather than beside it: it
* produces the same definition the form does, so it belongs in the same doorway. */
const [askAgent, setAskAgent] = useState(false);
const [createOptionDrafts, setCreateOptionDrafts] = useState<OptionDraft[]>(() =>
optionDrafts(DEFAULT_OPTION_LABELS)
);
const [createColorCode, setCreateColorCode] = useState(true);
const [measureKey, setMeasureKey] = useState(measures[0]?.key ?? "");
/** ββ W37-T22 (R4 / C7) β which column the geocode kind reads. Empty = not chosen yet, which
* is what `canCreate` refuses on: a geocode column with no address column is a column no run
* can ever fill, the same argument the `automation` URL-column rule makes below. */
const [geocodeAddressField, setGeocodeAddressField] = useState("");
/** D-3 β the optional country hint. Absent means "anywhere", so an empty box changes nothing and
* `canCreate` deliberately does NOT gate on it. */
const [geocodeCountry, setGeocodeCountry] = useState("");
const [measureWindow, setMeasureWindow] = useState<WindowSpec>(DEFAULT_MEASURE_WINDOW);
/** Wave-5 item 9/11 β the create form's formula source and rating star count. */
const [formulaText, setFormulaText] = useState("");
const [maxValue, setMaxValue] = useState(5);
/** β Wave-27 item 13 (R13) β the create form's code LANGUAGE. Seeded to `plain`, which is
* also what an absent bag means, so creating without touching this stores nothing extra. */
const [codeLanguage, setCodeLanguage] = useState<string>("plain");
/**
* ββ Wave-34 (owner ruling R13) β the create form's AI ENRICHMENT config.
*
* β ONE BAG AND ONE PATCHER, not six flat props. `link`/`rollup`/`automation` above are each a
* scatter of `xState`/`onXState` pairs, and the scouted consequence is concrete: the swap form
* mounts `ExtraTypeEditor` WITHOUT those setters, so choosing one of those kinds there renders
* a panel whose controls are wired to `undefined`. A single bag cannot be half-passed, so this
* kind cannot arrive at that door inert.
* β The defaults ARE the server's defaults (`AI_ENRICH_DEFAULT_TOKENS = 300`, `mode: manual`,
* `overwrite: blank`), so creating without touching anything but the prompt stores exactly what
* the panel showed.
*/
const [aiEnrich, setAiEnrich] = useState<AiEnrichDraft>(() => ({
prompt: "",
model: "",
maxTokens: 300,
mode: "manual",
cron: "",
overwrite: "blank",
}));
/** β FUNCTIONAL UPDATE, not `setAiEnrich({...aiEnrich, ...patch})`. Two controls in this panel
* can change in one tick (picking `schedule` reveals the cron box, which the user then types
* into), and a spread over a captured `aiEnrich` would drop whichever landed first. */
const patchAiEnrich = (patch: Partial<AiEnrichDraft>) =>
setAiEnrich((prev) => ({ ...prev, ...patch }));
/** C5-AUTOFIELD β the create form's automation config. */
const [automationKind, setAutomationKind] = useState(AUTOMATION_KINDS[0].key);
const [automationUrlField, setAutomationUrlField] = useState(
() => offerableFields(fields).find((f) => f.type === "url")?.key ?? ""
);
/**
* β 2026-08-07 β the create form's LINK and ROLLUP configuration.
*
* β BOTH KINDS ARE UNCREATABLE WITHOUT THEIR BAG β `core.user_tables._clean_field` returns
* None for a `link` with no `link` bag and for a `rollup` with no `rollup` bag β so `canCreate`
* gates on these below rather than letting the server refuse a column the user just named.
* That refusal would be silent in the worst way: created, named, configured, gone on reload.
*/
const [linkTable, setLinkTable] = useState("");
const [linkSingle, setLinkSingle] = useState(false);
const [linkSelectionMode, setLinkSelectionMode] = useState<"manual" | "automatic">("manual");
const [linkSelectionFilter, setLinkSelectionFilter] = useState<FilterTree | null>(null);
const [hopDraft, setHopDraft] = useState<HopDraft>(emptyHopDraft);
const patchHopDraft = (patch: Partial<HopDraft>) =>
setHopDraft((current) => ({ ...current, ...patch }));
/** β 2026-08-09 β the read-through half. `rollupMode` decides which bag `extraFor` builds;
* the two are mutually exclusive because the host's `_clean_rollup` returns the `source`
* shape before it ever reads `link`. */
const [rollupMode, setRollupMode] = useState<"link" | "source">("link");
const [rollupSource, setRollupSource] = useState<RollupSource>({
topic: "", measure: "", groupBy: "", on: "", window: "ytd",
});
const [rollupLink, setRollupLink] = useState("");
const [rollupField, setRollupField] = useState("");
const [rollupFn, setRollupFn] = useState<RollupFn>("sum");
/** 0 = every linked record (Airtable's only behaviour). Non-zero needs a sort β see below. */
const [rollupLimit, setRollupLimit] = useState(0);
const [rollupSortBy, setRollupSortBy] = useState("");
const [rollupDistinctBy, setRollupDistinctBy] = useState("");
const [rollupWhere, setRollupWhere] = useState<RollupCondition[]>([]);
const [rollupWhereConj, setRollupWhereConj] = useState<"and" | "or">("and");
const [rollupConditions, setRollupConditions] = useState<RollupCondition[]>([]);
const [rollupConditionConj, setRollupConditionConj] = useState<"and" | "or">("and");
const [rollupPreset, setRollupPreset] = useState<RollupPreset | null>(null);
const pickKind = (picked: PickerKind) => {
const preset = picked === "count" || picked === "lookup" ? picked : null;
setRollupPreset(preset);
if (!preset) {
setKind(picked as CreateKind);
return;
}
setKind("rollup");
setRollupMode("link");
setRollupFn(ROLLUP_PRESET_FNS[preset]);
if (preset === "count") setRollupField("");
setRollupLimit(0);
setRollupSortBy("");
setRollupDistinctBy("");
setRollupWhere([]);
setRollupConditions([]);
};
const [swapTo, setSwapTo] = useState("");
/** The "New field" half of Change-field keeps its own name/options β a half-typed insert
* form must not leak into a swap and vice versa. */
const [swapLabel, setSwapLabel] = useState("");
const [swapOptionDrafts, setSwapOptionDrafts] = useState<OptionDraft[]>(() =>
optionDrafts(DEFAULT_OPTION_LABELS)
);
const [swapColorCode, setSwapColorCode] = useState(true);
const [swapFormulaText, setSwapFormulaText] = useState("");
const [swapMaxValue, setSwapMaxValue] = useState(5);
/** β Wave-27 item 13 (R13) β the swap form's OWN language draft. It gets one rather than
* reading the create form's, because `extraFor` used to close over the create drafts and the
* swap path passes its own `src`/`starCount` in for exactly that reason: two forms sharing a
* draft means changing a language in one silently changes what the other will save. */
const [swapCodeLanguage, setSwapCodeLanguage] = useState<string>("plain");
/** Item 8c β the period DRAFT. null = untouched (the field's own window shows). Buffered
* behind an Apply rather than emitted per keystroke: a custom range is typed one date at a
* time, and each emit is a full host round trip that would repaint the column half-ready. */
const [periodDraft, setPeriodDraft] = useState<WindowSpec | null>(null);
/** Format pane draft β seeded from the field, saved whole. */
const [fmtDraft, setFmtDraft] = useState<FieldFormat>(() => ({ ...(field.format ?? {}) }));
/** Item 9c β the create forms' Scope draft. 'cohort' is the DEFAULT per the contract. */
const [scopeDraft, setScopeDraft] = useState<FieldScope>("cohort");
/** The Edit pane's NAME draft, seeded from the current label (wave-6 item 5's rename,
* re-homed into the Edit-field pane by owner item 8). */
const [renameDraft, setRenameDraft] = useState(field.label);
/** Owner item 8 β the Edit pane's TYPE draft plus the per-type config drafts: options
* prefilled from the field (a select retyped to multi select keeps its choices), star
* count from the field's own max, formula source from the field's own source. */
const [editType, setEditType] = useState<FieldType>(field.type);
const [editDefaultEnabled, setEditDefaultEnabled] = useState(field.defaultValue !== undefined);
const [editDefaultValue, setEditDefaultValue] = useState(String(field.defaultValue ?? ""));
const [editOptionDrafts, setEditOptionDrafts] = useState<OptionDraft[]>(() =>
optionDrafts(
choiceOptions(field).length ? choiceOptions(field) : DEFAULT_OPTION_LABELS,
field.optionColors
)
);
/** Item 15 (C-RENAME) β what each option ROW said when the editor opened, by draft id. A ref,
* not state: it is the fixed point the renames are measured against and it must not move
* while the user types. Seeded from the same call that seeds the drafts, so the two cannot
* disagree about which row is which. */
const editOptionOrigin = useRef<Map<string, string>>(new Map());
if (editOptionOrigin.current.size === 0 && editOptionDrafts.length)
editOptionOrigin.current = new Map(
editOptionDrafts.map((draft) => [draft.id, draft.label.trim()])
);
/** W48C-T12 - the Edit pane's NUMBER draft for a Metric column, seeded from the field itself.
* The create pane has always offered "Number" beside "Period"; the edit pane offered only the
* period, so a saved Metric could never be pointed at a different measure (the go-live QA of
* 2026-09-02 reproduced exactly that). */
const [editMeasureKey, setEditMeasureKey] = useState<string>(() => field.measure?.key ?? "");
/**
* Owner, 2026-09-02 - REMOVING A SAVED OPTION WARNS, THEN CLEARS ITS CELLS. The X on an option
* row used to drop the draft and let Save write a shorter list, which orphaned every cell that
* held the label (they rendered as a value that was no longer an option). Now a row whose
* ORIGIN label is a saved option asks the server how many cells use it: none, and it is removed
* at once; some, and a confirmation names the count and the consequence before anything moves.
* A draft that was never saved simply leaves the list, as before.
*/
const [pendingRemoval, setPendingRemoval] =
useState<{ draftId: string; label: string; cells: number } | null>(null);
const [removalBusy, setRemovalBusy] = useState(false);
const [removalError, setRemovalError] = useState<string | null>(null);
const dropEditDraft = (draftId: string) => {
setEditOptionDrafts((current) => current.filter((item) => item.id !== draftId));
editOptionOrigin.current.delete(draftId);
};
const requestOptionRemoval = async (draft: OptionDraft) => {
const savedLabel = editOptionOrigin.current.get(draft.id) ?? "";
const isSaved =
!!savedLabel &&
choiceOptions(field).some((o) => o.toLowerCase() === savedLabel.toLowerCase());
if (!onChoiceRemove || !isSaved) {
dropEditDraft(draft.id);
return;
}
setRemovalError(null);
setRemovalBusy(true);
const probe = await onChoiceRemove(savedLabel, false);
if (!probe) {
setRemovalBusy(false);
setRemovalError("Could not check where this option is used. Reload the database, then try again.");
return;
}
if (probe.cells === 0) {
const done = await onChoiceRemove(savedLabel, true);
setRemovalBusy(false);
if (done?.applied) dropEditDraft(draft.id);
else setRemovalError("The option was not removed. Reload the database, then try again.");
return;
}
setRemovalBusy(false);
setPendingRemoval({ draftId: draft.id, label: savedLabel, cells: probe.cells });
};
const confirmOptionRemoval = async () => {
if (!pendingRemoval || !onChoiceRemove) return;
setRemovalError(null);
setRemovalBusy(true);
const done = await onChoiceRemove(pendingRemoval.label, true);
setRemovalBusy(false);
if (!done?.applied) {
setRemovalError("The option was not removed. Reload the database, then try again.");
return;
}
dropEditDraft(pendingRemoval.draftId);
setPendingRemoval(null);
};
const [editColorCode, setEditColorCode] = useState(field.colorCodeOptions !== false);
const [retypeMaxValue, setRetypeMaxValue] = useState(() => ratingMax(field));
const [editFormulaText, setEditFormulaText] = useState(() =>
typeof field.formula === "string" ? field.formula : ""
);
/** C5-AUTOFIELD β the Edit pane's automation drafts, seeded from the field's own config. */
const [editAutomationKind, setEditAutomationKind] = useState(
() => field.automation?.kind ?? AUTOMATION_KINDS[0].key
);
const [editAutomationUrlField, setEditAutomationUrlField] = useState(
() => field.automation?.urlField ?? ""
);
/** β Wave-27 item 13 (R13) β the Edit pane's language draft, seeded from the field's own bag
* through the shared resolver (never `field.code!.language`: an unconfigured code column is
* the common case, and `codeLanguageOf` is the one place that answers what absent means). */
const [editCodeLanguage, setEditCodeLanguage] = useState<string>(() => codeLanguageOf(field));
/**
* ββ 2026-08-09 (owner) β THE EDIT PANE'S OWN RELATIONAL DRAFT, seeded from the field's bag.
*
* Owner: *"even when i click edit field for rollup, it doesn't actually show me the
* configuration that I use to generate it, it only shows change to a different field."*
* Exactly right, and it was worse than missing: `RETYPE_TYPES` includes `rollup`, so the pane
* offered a type picker whose "Rollup" option would re-save the column with NO bag.
*
* β ONE OBJECT, NOT TWELVE `useState`s, and the reason is seeding. Every draft here must start
* as what the STORE holds β a pane that opens on defaults and then saves them is a pane that
* silently rewrites a working column the moment somebody opens it to look. One object seeded
* once from `field.rollup` makes "opened but unchanged" literally equal to the stored bag, so
* the dirty check below is an object comparison rather than twelve remembered pairs.
*/
type RollupBag = NonNullable<Field["rollup"]>;
const [editRollup, setEditRollup] = useState<RollupBag>(() => ({ ...(field.rollup ?? {}) }));
const patchEditRollup = (patch: Partial<RollupBag>) =>
setEditRollup((current) => {
const next = { ...current, ...patch } as RollupBag;
// β AN EMPTY LIST IS AN ABSENT KEY, matching what `extraFor` sends on the create path and
// what `_clean_rollup` stores. Otherwise "remove the last condition" would save
// `conditions: []` while the stored bag has no such key, and the column would read as
// dirty forever.
for (const key of ["where", "conditions"] as const) {
if (Array.isArray(next[key]) && next[key]!.length === 0) {
delete next[key];
delete next[key === "where" ? "whereConj" : "conditionConj"];
}
}
if (!next.sortBy) {
// The server refuses a limit with no declared order; dropping both together keeps the
// draft in a shape that can always be saved.
delete next.limit;
delete next.sortDir;
}
return next;
});
const [editLinkTable, setEditLinkTable] = useState(() => field.link?.table ?? "");
const [editLinkSingle, setEditLinkSingle] = useState(() => field.link?.single === true);
const [editLinkSelectionMode, setEditLinkSelectionMode] = useState<"manual" | "automatic">(
() => field.link?.selectionMode === "automatic" ? "automatic" : "manual"
);
const [editLinkSelectionFilter, setEditLinkSelectionFilter] = useState<FilterTree | null>(
() => field.link?.selectionFilter ?? null
);
const [editHopDraft, setEditHopDraft] = useState<HopDraft>(() => hopDraftFrom(field.link));
const patchEditHopDraft = (patch: Partial<HopDraft>) =>
setEditHopDraft((current) => ({ ...current, ...patch }));
const swapToNewType = swapTo.startsWith(NEW_PREFIX)
? (swapTo.slice(NEW_PREFIX.length) as FieldType)
: null;
const createChoice = optionSettings(createOptionDrafts, kind, optionLimit);
const options = createChoice.options;
const swapChoice = swapToNewType
? optionSettings(swapOptionDrafts, swapToNewType, optionLimit)
: { options: [] as string[], colors: {} as Record<string, string>,
capMessage: null as string | null };
const swapNewOptions = swapChoice.options;
/** Owner item 8 β the Edit pane's parsed choices for the drafted type. */
const editChoice = optionSettings(editOptionDrafts, editType, optionLimit);
const editOptions = editChoice.options;
// Wave-5 item 9, amended 2026-07-31 (owner item 2) β live formula validation for BOTH
// create surfaces. Refs may now name OTHER formula fields (evaluation is topological);
// what is refused is a CYCLE, checked against every formula's SOURCE. Both surfaces here
// CREATE a field, so no cycle is possible yet and no selfKey is passed β the retype path
// (in-place formula edit) would pass the edited field's key.
const knownKeys = useMemo(
() => new Set(fields.filter((f) => f.type !== "formula").map((f) => f.key)),
[fields]
);
const formulaSources = useMemo(() => {
const out = new Map<string, string>();
for (const f of fields) {
if (f.type !== "formula") continue;
const src = typeof f.formula === "string" ? f.formula : "";
if (src) out.set(f.key, src);
}
return out;
}, [fields]);
// ββ W50-T06 (owner instruction 5) β A LEADING `=` IS ACCEPTED AND STRIPPED, and the
// stripping happens HERE, on the way into the validator, not only on the way into the store.
// A spreadsheet user's first keystroke in this box is `=`; the runtime does not accept one,
// so validating the raw text would answer that keystroke with a parse error and the editor
// would read as broken before a single function had been typed. Stripping at BOTH ends means
// what is judged is exactly what is saved.
// β `formulaEngine.ts` is another lane's file and is deliberately untouched: the runtime's
// grammar is unchanged, and `=` is an EDITOR affordance rather than a language feature.
const formulaCheck = useMemo(() => {
const src = stripLeadingEquals(formulaText);
return src.trim() === ""
? { ok: false, error: "Type a formula", refs: [] as string[] }
: validateFormula(src, knownKeys, formulaSources);
}, [formulaText, knownKeys, formulaSources]);
const swapFormulaCheck = useMemo(() => {
const src = stripLeadingEquals(swapFormulaText);
return src.trim() === ""
? { ok: false, error: "Type a formula", refs: [] as string[] }
: validateFormula(src, knownKeys, formulaSources);
}, [swapFormulaText, knownKeys, formulaSources]);
const chosenMeasure = measures.find((m) => m.key === measureKey);
/**
* ββ W37-T22 (R4 / C7) β the columns a geocode field may read, and the offer predicate.
*
* β TWO CONDITIONS, ANDed, and the second is the one a reader will want to delete. `geocodable`
* says the surface can PERSIST the bag (see `TypePicker`'s `offerGeocode` doc for why the Odoo
* grids can and a `ut_*` database cannot yet); the address list says the table has something to
* read. Offering on the vocabulary alone would create a field that is named, configured and
* permanently unable to run.
*/
const addressFields = useMemo(
() => offerableFields(fields).filter(
(f) => (GEOCODE_ADDRESS_TYPES as readonly string[]).includes(f.type)
),
[fields]
);
const offerGeocode = geocodable && addressFields.length > 0;
/** The suggested name reads as the sentence the column answers: "Sales Β· the last 90 days". */
const suggestedLabel = chosenMeasure
? `${chosenMeasure.label} Β· ${windowLabel(measureWindow)}`
: "";
const effectiveLabel =
kind === "measure" && !labelTouched && !label.trim() ? suggestedLabel : label;
const createDefaultOffered = isUserTable && supportsDefaultValue(kind);
const createDefaultValid = !createDefaultOffered || !createDefaultEnabled ||
defaultValueDraftValid(kind, createDefaultValue);
// A select/multiselect starts with an empty vocabulary and learns values from the shared write
// path, so creation and retyping never block on predeclared options. A measure column needs a
// measure; a formula column needs a formula that PARSES β an
// unparseable formula would be a permanently blank column, refused here rather than shipped.
const canCreate =
canAddField &&
effectiveLabel.trim() !== "" &&
createDefaultValid &&
(kind !== "if" || ifDefinitionIssue(ifDraft, ifSourceFields) === null) &&
(!needsOptions(kind) || createChoice.capMessage === null) &&
(kind !== "measure" || !!chosenMeasure) &&
// ββ W37-T22 (R4 / C7) β a geocode column with no address column to read is a column no run
// can ever fill: the identical argument the `automation` URL-column rule below makes, and the
// one the `link`/`rollup`/`ai_enrich` rules make one step harder. Refused here rather than
// created and then discovered to be inert.
(kind !== "geocode" || geocodeAddressField !== "") &&
(kind !== "formula" || formulaCheck.ok) &&
// C5-AUTOFIELD: an automation column with no URL column to read is a column no run can
// ever fill β the same "permanently blank column" the formula rule above refuses, so it
// is refused here rather than created and then discovered.
(kind !== "automation" || automationUrlField !== "") &&
// β 2026-08-07 β both relational kinds are UNCREATABLE without their bag: `_clean_field`
// returns None for a `link` with no target and a `rollup` with no link/function, so
// creating one without this gate produces a column that is named, configured and simply
// absent on the next read. The same "permanently blank column" argument as the two rules
// above, one step worse β the column does not exist at all.
// ββ Wave-34 (R13) β the same argument one kind over: `_clean_field` returns None for an
// `ai_enrich` column with no prompt, so creating one without this gate produces a column that
// is named, configured and simply absent on the next read.
(kind !== "ai_enrich" || aiEnrich.prompt.trim() !== "") &&
(kind !== "link" || (linkTable !== "" && !hopIncomplete(hopDraft, hopScopeKey) &&
linkSelectionFilterIssue(linkSelectionFilter,
linkTargets.find((target) => target.key === linkTable)?.fields ?? []) === null)) &&
(kind !== "rollup" || (rollupMode === "source"
// β 2026-08-09 β the read-through bag. ALL FOUR keys are required by `_clean_rollup`
// (`if not (topic and measure and group_by and on): return None`), and `on` is the one a
// user forgets: without it the bag names a real measure grouped a real way with nothing
// to match it to any row, and the field would be refused after Create.
? (rollupSource.topic !== "" && rollupSource.measure !== "" &&
rollupSource.groupBy !== "" && rollupSource.on !== "")
: (
rollupLink !== "" &&
(rollupFn === "countall" || rollupField !== "") &&
// `latest` without an order is store order wearing a deterministic name.
(rollupFn !== "latest" || rollupSortBy !== "")
)));
const extraFor = (
t: CreateKind,
src: string,
starCount: number,
lang: string,
hopSource: HopDraft | null
): FieldConfigExtra | undefined => {
if (t === "if") return { if: ifDraft };
// W50-T06 β the save side of the leading-`=` rule. See `formulaCheck` above.
if (t === "formula") return { formula: stripLeadingEquals(src).trim() };
if (t === "rating") return { max: starCount };
// β Wave-27 item 13 (R13). The bag is ALWAYS sent, including `plain` β the host's
// `_clean_code` evaluates plain to None and therefore CLEARS the key, which is what makes
// "switch this column back to Plain text" a change that saves. Omitting it instead would
// inherit the previous language (the patch path's omit-means-keep rule).
if (t === "code") return { code: { language: lang } };
// ββ Wave-34 (R13) β the enrichment bag, shaped exactly as `_clean_ai_enrich` stores it.
// β `cron` TRAVELS ONLY WITH `schedule`, and `model` only when set: the server drops both in
// those cases anyway, so sending them would put keys in the payload that come back absent,
// which is how a panel starts looking like it does not save. Same rule the rollup bags above
// follow for `limit`/`sortBy`.
if (t === "ai_enrich")
return {
aiEnrich: {
prompt: aiEnrich.prompt.trim(),
...(aiEnrich.model.trim() ? { model: aiEnrich.model.trim() } : {}),
maxTokens: aiEnrich.maxTokens,
trigger: {
mode: aiEnrich.mode,
...(aiEnrich.mode === "schedule" && aiEnrich.cron.trim()
? { cron: aiEnrich.cron.trim() }
: {}),
},
overwrite: aiEnrich.overwrite,
},
};
if (t === "automation")
return {
automation: {
kind: automationKind,
source: "record_url_field",
urlField: automationUrlField,
},
};
// β 2026-08-07 β the relational bags, shaped exactly as `_clean_link` / `_clean_rollup`
// store them. β NO `on` KEY: a link created from this menu is an ORDINARY one (the user
// picks records). The DERIVED mode is the automation's, spawned with its join declared β
// offering "join on a column of the other table" here would be a second, harder mental
// model for the same button.
if (t === "link") {
const via = hopVia(hopSource, hopScopeKey);
return { link: { table: linkTable, selectionMode: linkSelectionMode,
...(linkSelectionFilter ? { selectionFilter: linkSelectionFilter } : {}),
...(linkSingle ? { single: true } : {}),
...(via ? { from: "pid", on: via.target_key, via } : {}) } };
}
if (t === "rollup" && rollupMode === "source")
// β THE SOURCE BAG TRAVELS ALONE. `_clean_rollup` reads `source` first and returns
// immediately, so sending `link`/`fn` alongside it would ship keys the store drops β
// harmless today and exactly the kind of dead payload that later reads as configuration.
return {
rollup: {
source: {
topic: rollupSource.topic,
measure: rollupSource.measure,
groupBy: rollupSource.groupBy,
on: rollupSource.on,
// β `all_time` is sent as an ABSENT window, which is what it means: the validator
// accepts the literal too, but the bag is smaller and reads as "no window".
...(rollupSource.window && rollupSource.window !== "all_time"
? { window: rollupSource.window }
: {}),
},
},
};
if (t === "rollup")
return {
rollup: {
link: rollupLink,
...(rollupFn === "countall" ? {} : { field: rollupField }),
fn: rollupFn,
// β `limit` AND `sortBy` TRAVEL TOGETHER OR NEITHER TRAVELS. The host refuses a limit
// with no declared order, so sending one would turn a valid-looking form into a 400.
...(rollupSortBy
? { sortBy: rollupSortBy, sortDir: "desc" as const,
limit: rollupLimit || 1 }
: {}),
...(rollupDistinctBy ? { distinctBy: rollupDistinctBy } : {}),
// β EACH LIST TRAVELS WITH ITS OWN CONJUNCTION OR NEITHER TRAVELS β `_clean_rollup`
// stores the pair together, so sending a conj with no list would be a stored key
// nothing reads, and a list with no conj would take the server's default rather than
// the one this editor showed.
...(rollupWhere.length
? { where: rollupWhere, whereConj: rollupWhereConj }
: {}),
...(rollupConditions.length
? { conditions: rollupConditions, conditionConj: rollupConditionConj }
: {}),
},
};
return undefined;
};
const optionExtraFor = (
t: CreateKind,
colors: Record<string, string>,
colorCode: boolean
): FieldConfigExtra =>
needsOptions(t)
? {
colorCodeOptions: colorCode,
...(Object.keys(colors).length ? { optionColors: colors } : {}),
}
: {};
/** Item 9c β the Scope choice rides the create extras only where the page offers it. */
const withScope = (e?: FieldConfigExtra): FieldConfigExtra | undefined =>
scopeChoice ? { ...(e ?? {}), scope: scopeDraft } : e;
const create = () => {
const clean = effectiveLabel.trim();
if (!clean || !position || !canCreate) return;
if (kind === "measure") {
if (!chosenMeasure) return;
onCreate(clean, chosenMeasure.type, position === "end" ? null : field.key, position,
undefined, { key: chosenMeasure.key, window: measureWindow },
withScope(undefined));
onClose();
return;
}
// ββ W37-T22 (R4 / C7) β the geocode PSEUDO-KIND creates a real `text` column carrying its
// bag, the `measure` branch above's construction. `kind` is not a `FieldType` here, so it
// cannot be passed through as one; widening `FieldType` instead would drag the name into
// five vocabularies and a cell renderer for a column that renders as text anyway.
if (kind === "geocode") {
if (!geocodeAddressField) return;
const country = geocodeCountry.trim().toUpperCase();
onCreate(clean, "text", position === "end" ? null : field.key, position, undefined,
undefined, withScope({
geocode: {
addressField: geocodeAddressField,
// Absent, never `""`: an empty country is the default's second spelling, and
// two spellings of one state is how a round trip starts churning.
...(country ? { country } : {}),
},
}));
onClose();
return;
}
onCreate(clean, kind, position === "end" ? null : field.key, position,
needsOptions(kind) ? options : undefined, undefined,
withScope({
...extraFor(kind, formulaText, maxValue, codeLanguage, hopDraft),
...optionExtraFor(kind, createChoice.colors, createColorCode),
...(createDefaultOffered && createDefaultEnabled
? { defaultValue: defaultValueFromDraft(kind, createDefaultValue) } : {}),
}));
onClose();
};
const canCreateSwap =
swapToNewType != null &&
swapLabel.trim() !== "" &&
(!needsOptions(swapToNewType) || swapChoice.capMessage === null) &&
(swapToNewType !== "if" || ifDefinitionIssue(ifDraft, ifSourceFields) === null) &&
(swapToNewType !== "formula" || swapFormulaCheck.ok) &&
// ββ Wave-34 (R13) β the SAME completeness gate `canCreate` carries, on this door too.
//
// β AND THIS DOOR HAD NO SUCH GATE FOR ANY KIND, WHICH IS A PRE-EXISTING DEFECT I AM NOT
// FIXING HERE, ONLY REPORTING. `canCreate` refuses a `link` with no target, a `rollup` with
// no function and an `automation` with no URL column; this predicate refuses none of them,
// and the swap form's own `<ExtraTypeEditor>` mount passes none of their setters either, so
// picking one of those three from "Change field" renders a panel wired to nothing and Save
// ships whatever stale draft the CREATE pane happens to hold. Booked for the register rather
// than repaired mid-ticket ([[defects-that-mask-each-other]] is why: the missing gate and the
// missing props hide each other, and fixing one alone arms the other).
// β `ai_enrich` cannot arrive here inert, because it is ONE bag and one patcher rather than a
// scatter of optional setters, so this conjunct is the whole of its half.
(swapToNewType !== "ai_enrich" || aiEnrich.prompt.trim() !== "");
const createAndSwap = () => {
if (!swapToNewType || !canCreateSwap) return;
onCreateAndSwap(
swapLabel.trim(),
swapToNewType,
needsOptions(swapToNewType) ? swapNewOptions : undefined,
withScope({
...extraFor(swapToNewType, swapFormulaText, swapMaxValue, swapCodeLanguage, null),
...optionExtraFor(swapToNewType, swapChoice.colors, swapColorCode),
})
);
onClose();
};
// ------------------------------------------------------- owner item 8: Edit-field dirties
// ONE Save applies whatever changed β name, type, choices, stars, formula source β and it
// must leave as ONE upsert when several changed together: sequential emits each read the
// stale def and the second reverts the first (label rides extra.label / onFormula's label).
const cleanRename = renameDraft.trim();
// β 2026-08-09 β `onFieldConfig` is a SECOND door that can rename. `onRename` writes the
// per-user overlay and is supplied for `custom_` fields only, so a pre-set Rollup β now
// reconfigurable by owner ruling β had a configuration it could change and a name it could
// not. Both ride the same PATCH; the label is part of the definition either way.
const editNameDirty =
(!!onRename || !!onFieldConfig) && cleanRename !== "" && cleanRename !== field.label;
const editNoteDirty = note !== (field.note ?? "");
const editDefaultOffered = isUserTable && canEditDefinition && !!onFieldConfig &&
supportsDefaultValue(editType);
const editDefaultDirty = editDefaultOffered && (
editDefaultEnabled !== (field.defaultValue !== undefined) ||
(editDefaultEnabled && editDefaultValue !== String(field.defaultValue ?? ""))
);
const editDefaultValid = !editDefaultOffered || !editDefaultEnabled ||
defaultValueDraftValid(editType, editDefaultValue);
const editOptionsChanged =
needsOptions(editType) &&
editOptions.join("\n") !== choiceOptions(field).join("\n");
const editAppearanceChanged =
needsOptions(editType) &&
(editColorCode !== (field.colorCodeOptions !== false) ||
optionAppearanceSignature(editOptions, editChoice.colors) !==
optionAppearanceSignature(choiceOptions(field), field.optionColors));
const editStarsChanged = editType === "rating" && retypeMaxValue !== ratingMax(field);
/** The type half was touched: a different type, or the SAME type with edited choices/stars
* (the owner's named case β "change the list of the single selections"). */
/** C5-AUTOFIELD β the automation config is a property of the column exactly as the choice
* list is, so a change to it makes the type half DIRTY and rides the same one upsert. */
const editAutomationChanged =
editType === "automation" &&
field.type === "automation" &&
(editAutomationKind !== (field.automation?.kind ?? AUTOMATION_KINDS[0].key) ||
editAutomationUrlField !== (field.automation?.urlField ?? ""));
const editRetypeTouched =
onRetype != null &&
(editType !== field.type || editOptionsChanged || editAppearanceChanged ||
editStarsChanged || editAutomationChanged);
const editRetypeValid =
editType !== "automation" || editAutomationUrlField !== "";
const editFormulaCheck = useMemo(
() =>
stripLeadingEquals(editFormulaText).trim() === ""
? { ok: false, error: "Type a formula", refs: [] as string[] }
: validateFormula(
stripLeadingEquals(editFormulaText), knownKeys, formulaSources, field.key
),
[editFormulaText, knownKeys, formulaSources, field.key]
);
const editFormulaTouched =
!!onFormula &&
field.type === "formula" &&
stripLeadingEquals(editFormulaText).trim() !==
(typeof field.formula === "string" ? field.formula.trim() : "");
// A touched-but-invalid half BLOCKS the whole save β otherwise Save would apply the name
// and silently drop the half-finished type change beside it.
const editBlocked =
!editDefaultValid ||
(editRetypeTouched && !editRetypeValid) ||
(editFormulaTouched && !editFormulaCheck.ok) ||
(needsOptions(editType) && editChoice.capMessage !== null);
// Item 21 (2026-08-02) β the PERIOD moved into this pane, so its dirty-check has to be
// computed before the pane's save gate rather than beside the menu's own button. Same three
// lines, hoisted: `canSaveEdit` reads `periodChanged`, and a `const` read before its
// initialiser is a TDZ crash at render, not a compile error.
const currentWindow = field.measure ? normalizeWindow(field.measure.window) : null;
const draftWindow = periodDraft ? normalizeWindow(periodDraft) : null;
const periodChanged =
draftWindow != null &&
JSON.stringify(draftWindow) !== JSON.stringify(currentWindow);
const canPeriod = !!field.measure && !!onPeriod;
const measureChanged =
canPeriod && !!editMeasureKey && editMeasureKey !== (field.measure?.key ?? "");
/**
* ββ 2026-08-09 β THE RELATIONAL EDIT: is this pane driving a `link`/`rollup` bag?
*
* β GATED ON `onFieldConfig`, which the host supplies for USER DATABASES ONLY. These bags live
* in the table's shared definition (`PATCH /tables/{key}/fields/{key}`); there is no such door
* on the Odoo-backed Customer/Product grids, so offering the editor there would be a form whose
* Save has nowhere to go.
*/
const editingRelational =
!!onFieldConfig && (field.type === "rollup" || field.type === "link");
/**
* ββ W40-T24 β WHERE THE EDIT PANE'S OPENING FOCUS LANDS, decided ONCE.
*
* `AnchoredOverlay`'s `initialFocus` is the selector `[data-overlay-autofocus]` and it does
* `querySelector(...)?.focus()` β a MISS is silent, and focus then stays on the grid header
* button behind the overlay. That is what removing the swap picker from a pre-set column would
* have caused: the picker carried `overlayAutofocus={!onRename}`, so on Supplier it WAS the
* pane's focus target, and taking it away leaves a dialog nobody's keyboard is inside. The
* defect would not show in a screenshot of the fix.
*
* Precedence, first match wins, exactly as `querySelector` reads the DOM: the editable Name box
* Β· the swap picker Β· the Description box, which is the one control a pre-set column still owns.
* β It also settles a latent double-marking: an `editingRelational` column with no `onRename`
* put the attribute on the Name box AND the picker, and which one won was document order rather
* than a decision.
*/
const nameIsFocusTarget = !!onRename || editingRelational;
const editRollupValid =
field.type !== "rollup" ||
(editRollup.source
? !!(editRollup.source.topic && editRollup.source.measure &&
editRollup.source.groupBy && editRollup.source.on)
: !!editRollup.link &&
(editRollup.fn === "countall" || !!editRollup.field) &&
(editRollup.fn !== "latest" || !!editRollup.sortBy));
const editRelationalTouched =
editingRelational &&
(field.type === "rollup"
? JSON.stringify(editRollup) !== JSON.stringify(field.rollup ?? {})
: editLinkTable !== (field.link?.table ?? "") ||
editLinkSingle !== (field.link?.single === true) ||
editLinkSelectionMode !== (field.link?.selectionMode === "automatic" ? "automatic" : "manual") ||
JSON.stringify(editLinkSelectionFilter) !== JSON.stringify(field.link?.selectionFilter ?? null) ||
JSON.stringify(hopVia(editHopDraft, hopScopeKey)) !==
JSON.stringify(hopVia(hopDraftFrom(field.link), hopScopeKey)));
const editingIf = !!onFieldConfig && field.type === "if" && !!field.if;
const editIfTouched = editingIf && JSON.stringify(editIf) !== JSON.stringify(field.if);
const canSaveEdit =
/**
* β W41-T31 β THE DESCRIPTION-ONLY PANE'S WHOLE SAVE CONDITION, and it is one dirty flag
* because the pane renders one control. The arm below asks four other questions whose
* answers are all seeded-clean here, and one of them can go WRONG rather than merely
* useless: a pre-set `link` column is `editingRelational` (the type exclusion in
* `isSchemaLocked` covers `rollup` only), and that branch also demands `editRollupValid`
* and a non-empty link table β so a pre-set link with a half-filled stored bag would have
* had Save greyed out with nothing but a description typed into it.
*
* β THE `else` ARM IS BYTE-IDENTICAL TO WHAT IT WAS. `canEditDescription` requires
* `schemaLocked`, which forces `canEditDefinition` false, which is what gates the full pane
* β so no field that reaches the arm below can take this branch, and the non-pre-set Save
* gate is unchanged by construction rather than by inspection.
*/
canEditDescription
? editNoteDirty
: (!editBlocked &&
(!editingIf || ifDefinitionIssue(editIf, editIfSourceFields) === null) &&
// ββ Wave-34 (R13) β the third door onto the same completeness rule (`canCreate` and
// `canCreateSwap` are the other two). Retyping a column to AI enrichment without a prompt
// is refused by the server, so Save is refused here instead: a 400 arriving after the click
// is the same "named, configured, gone" surprise one layer later.
(editType !== "ai_enrich" || aiEnrich.prompt.trim() !== "") &&
(editingRelational
? (editRollupValid && (editRelationalTouched || editNameDirty || editNoteDirty) &&
(field.type !== "link" ||
(editLinkTable !== "" && !hopIncomplete(editHopDraft, hopScopeKey) &&
linkSelectionFilterIssue(editLinkSelectionFilter,
linkTargets.find((target) => target.key === editLinkTable)?.fields ?? []) === null)))
: (editNameDirty || editRetypeTouched || editDefaultDirty || editFormulaTouched || editIfTouched ||
(canPeriod && (periodChanged || measureChanged)) || editNoteDirty)));
/**
* Item 15 β the renames, by ROW IDENTITY. A row that kept its id and changed its label was
* renamed; a row with an id nobody has seen is new; an id that is gone was deleted. Empty
* labels are skipped (a row being cleared before it is retyped is not a rename to ""), and a
* rename to a label that already existed is skipped too β that is a MERGE, and merging two
* choices into one is a different operation from renaming, with a different answer for the
* cells that held either.
*/
const optionRenames = (): { from: string; to: string }[] =>
// A field that was not a choice field before has no values to migrate, and one being
// retyped AWAY from choices is a different question (its cells stop being options at all).
needsOptions(editType) && needsOptions(field.type)
? choiceRenames(editOptionDrafts, editOptionOrigin.current, choiceOptions(field))
: [];
const applyEdit = () => {
if (!canSaveEdit) return;
if (editDefaultOffered && onFieldConfig &&
(editDefaultDirty || editRetypeTouched || editNameDirty)) {
const renames = optionRenames();
const value = editDefaultDirty || editType !== field.type
? defaultValueFromDraft(editType, editDefaultValue)
: field.defaultValue;
onFieldConfig({
defaultValue: editDefaultEnabled ? value : null,
...(editNameDirty ? { label: cleanRename } : {}),
...(editRetypeTouched ? {
type: editType,
...(editType === "select" ? {
options: editOptions,
colorCodeOptions: editColorCode,
optionColors: editChoice.colors,
} : {}),
...(renames.length ? { renames } : {}),
} : {}),
});
if (editNoteDirty) onNote(note);
onClose();
return;
}
if (!canEditDescription && editingIf && onFieldConfig && (editIfTouched || editNameDirty)) {
onFieldConfig({ if: editIf, ...(editNameDirty ? { label: cleanRename } : {}) });
if (editNoteDirty) onNote(note);
onClose();
return;
}
/**
* ββ W41-T31 β THE DESCRIPTION-ONLY SAVE MUST NOT COME THROUGH HERE, and `canEditDescription`
* is the clause that guarantees it rather than hoping the drafts are clean.
*
* This branch is a REBUILD (see the comment inside it): `_clean_rollup` does not merge with
* the stored bag, so any key this pane did not send comes back as a VALUE, not as
* "unchanged". The description-only pane renders no relational editor at all, so its
* `editRollup` / `editLinkTable` drafts are whatever the seeding produced β and
* `editRelationalTouched` compares them by `JSON.stringify`, which a seed that normalises,
* reorders or defaults a single key would fail. That is not hypothetical: a pre-set `link`
* column IS `editingRelational` (`isSchemaLocked` excludes `rollup`, not `link`), so the one
* click meant to save a sentence could have re-emitted the column's link bag.
*
* With this guard the save falls through every leg below β `editRetypeTouched`,
* `editFormulaTouched`, `editNameDirty` and `periodChanged` are all seeded-clean and none of
* their controls is on the pane β and lands on the ordinary path's `if (editNoteDirty)
* onNote(note); onClose();`, which is the one persist site this ticket wants.
*/
if (!canEditDescription &&
editingRelational && onFieldConfig && (editRelationalTouched || editNameDirty)) {
const editVia = hopVia(editHopDraft, hopScopeKey);
// β THE WHOLE BAG, EVERY SAVE. `_clean_rollup` is a pure cleaner over what it receives β
// it does not merge with the stored bag β so a partial patch is a REBUILD, and an omitted
// `limit` would silently become "no limit" rather than "unchanged".
onFieldConfig({
...(editNameDirty ? { label: cleanRename } : {}),
...(field.type === "rollup"
? { rollup: editRollup as Record<string, unknown> }
: { link: { ...field.link, table: editLinkTable,
selectionMode: editLinkSelectionMode,
selectionFilter: editLinkSelectionFilter ?? undefined,
...(field.link?.on
? { on: field.link.on }
: editVia ? { on: editVia.target_key } : {}),
...(field.link?.from
? { from: field.link.from }
: editVia ? { from: "pid" } : {}),
single: editLinkSingle,
via: editVia ?? undefined } }),
});
if (editNoteDirty) onNote(note);
onClose();
return;
}
if (editRetypeTouched && onRetype) {
const renames = optionRenames();
onRetype(
editType,
needsOptions(editType) ? editOptions : undefined,
{
...(renames.length ? { renames } : {}),
...(editType === "rating" ? { max: retypeMaxValue } : {}),
// β Wave-27 item 13 (R13) β always sent for a code column, `plain` included: the
// host clears the key on plain, so this is what makes the picker reversible.
...(editType === "code" ? { code: { language: editCodeLanguage } } : {}),
...(needsOptions(editType)
? {
colorCodeOptions: editColorCode,
...(Object.keys(editChoice.colors).length
? { optionColors: editChoice.colors }
: {}),
}
: {}),
...(editType === "automation"
? {
automation: {
kind: editAutomationKind,
source: "record_url_field" as const,
urlField: editAutomationUrlField,
},
}
: {}),
// ββ Wave-34 (R13) β RETYPING A COLUMN TO AI ENRICHMENT CARRIES ITS BAG, or the
// server refuses the whole write: `_clean_field` returns None for an `ai_enrich`
// column with no prompt. The edit pane renders the same panel the create pane does
// (`ExtraTypeEditor` is mounted with `kind={editType}`), so the draft the user just
// filled in is the one sent here.
...(editType === "ai_enrich"
? {
aiEnrich: {
prompt: aiEnrich.prompt.trim(),
...(aiEnrich.model.trim() ? { model: aiEnrich.model.trim() } : {}),
maxTokens: aiEnrich.maxTokens,
trigger: {
mode: aiEnrich.mode,
...(aiEnrich.mode === "schedule" && aiEnrich.cron.trim()
? { cron: aiEnrich.cron.trim() }
: {}),
},
overwrite: aiEnrich.overwrite,
},
}
: {}),
...(editNameDirty ? { label: cleanRename } : {}),
}
);
} else if (editFormulaTouched && onFormula) {
onFormula(stripLeadingEquals(editFormulaText).trim(), editNameDirty ? cleanRename : undefined);
} else if (editNameDirty && onRename) {
onRename(cleanRename);
}
// Item 21 β the period is an INDEPENDENT property of a measure column, not a branch of
// the identity edit, so it applies ALONGSIDE whatever the chain above did rather than
// instead of it: renaming "Sales YTD" to "Sales" and re-pointing it at the last 90 days
// is one edit to the user and must not silently drop half of itself.
if (canPeriod && (periodChanged || measureChanged))
onPeriod!(draftWindow ?? field.measure!.window,
measureChanged ? editMeasureKey : undefined);
if (editNoteDirty) onNote(note);
onClose();
};
/**
* Fields this column can be CHANGED to, split per wave-2 item 5: the "Pre-set fields" group
* (the shared contract's predicate, `source === 'odoo' && !custom`) versus "Your fields" β
* the overlay stratum and user-created columns. Hidden fields included in both: "change this
* to Notes" is the whole point, and swapping BACK to a hidden custom field is the documented
* restore path. The locked primary column cannot be swapped.
*
* ββ W40-T24 β NOR CAN A PRE-SET ONE, which is `offer.swap`. This list is what the picker
* would contain; `swapOffered` is whether the picker exists at all, and it is read twice (the
* control itself, and the focus fallback that has to know whether the control is there).
*/
const swapOptions = offerableFields(fields).filter((f) => f.key !== field.key);
const presetSwap = swapOptions.filter((f) => f.source === "odoo" && !f.custom);
const yourSwap = swapOptions.filter((f) => !(f.source === "odoo" && !f.custom));
const swapOffered = offer.swap && swapOptions.length > 0;
// Item 8c β the period draft is valid when it normalizes and differs from what the field
// already has. Compared through normalizeWindow so `{kind:'ltm'}` and `{kind:'ltm', n:undefined}`
// read as the same window.
// β Wave-23 C8 (owner item 4 / R9) β FIRST in the chain, because it is the most specific true
// thing about the column and the branches below it were saying something false. An
// `automation` or `metric` column, and every column an automation SPAWNED (the `automation`
// tag), is overlay-sourced and non-derived, so it fell through to "Editable overlay field" β
// which is what the wash now visibly contradicts. ONE line, no second sentence about what an
// automation is (R13 / DESIGN.md Β§4): the person reading a column menu is deciding whether to
// type in it, and "filled by automation" is the whole answer.
// β Wave-25 C3/R7 β AHEAD of the machine line, because a profile column is the one cell on
// the row a person is SUPPOSED to fill, and "filled by automation" would say the opposite. It
// states the consequence rather than the mechanism: clearing this cell also clears the
// columns the enrichment wrote, and a person who does not know that reads the wipe as a bug.
// That is the one fact worth a menu line here (DESIGN.md Β§4 β never over-explain).
/**
* ββ 2026-08-10 β WHICH SIDE OF THE RELATION IS THIS? (owner: "a linked field should spawn in
* both databases")
*
* The spawn itself was already there β `user_tables.sync_reciprocal_link` creates the backlink
* on the target for every ordinary link, and the two engines declare BOTH directions of their
* derived links themselves. What was missing is the half a user can actually see: three
* genuinely different columns all rendered as chips of linked rows and all described as
* "Editable overlay field", including the computed reciprocal, which is not editable at all.
*
* The three, and the one fact that separates them:
* ordinary β no `on`, no `inverse`. YOU pick the records. This is the stored truth.
* reciprocal β `inverse` names the source field. Computed from the other side's picks;
* typing here is refused (`is_computed_cell`), so saying "editable" was a lie.
* derived β `on` names a column in the target that already holds this row's key. The
* engine owns it; there is no picking on either side.
*
* β Read through `isDerivedLink`, never a fourth hand-rolled "does the bag have an `on`" β
* `user_tables`' own note warns that a fourth reader is how one of them keeps answering yes
* after the others stop.
* β AHEAD of `isMachineOwned` for links only. "Filled by automation" is TRUE of a preset
* derived link and it is the less specific true thing: the reader is deciding whether they can
* click into this cell and pick something, and which side they are on is that answer.
*/
const linkTargetLabel =
field.type === "link"
? linkTargets.find((t) => t.key === field.link?.table)?.label ?? ""
: "";
const linkSideLine =
field.type !== "link"
? null
: field.link?.inverse
? `Linked from ${linkTargetLabel || "another database"} Β· rows that point here`
: isDerivedLink(field)
? `Links to ${linkTargetLabel || "another database"} Β· matched automatically`
: `Links to ${linkTargetLabel || "another database"} Β· you pick the records`;
const typeLineBase = isProfileField(field)
? "Instagram profile Β· clearing it clears the enriched columns"
: linkSideLine
? linkSideLine
: isMachineOwned(field)
? "Filled by automation"
: field.measure
? (field.custom && canEditDefinition ? "Metric, definition editable" : "Metric, read-only")
: field.type === "formula"
? "Formula field, computed"
: field.type === "autonumber"
? "Autonumber, read-only"
: AUDIT_FIELD_TYPES.includes(field.type)
? `${TYPE_LABELS[field.type]}, read-only`
: field.type === "created_time"
? "Created time, read-only"
: field.derived
? "Read-only, derived"
: field.source === "odoo"
? "Read-only source field"
: "Editable overlay field";
// Item 9c β a cohort-scoped def says so wherever its identity is stated (contract:
// "defs may come back carrying scope: 'cohort' (label it)").
const typeLine =
field.scope === "cohort" ? `${typeLineBase} Β· this cohort only` : typeLineBase;
/** Wave-5 item 10 β which format editor this field gets, if any. */
// An Odoo float column arrives as type "number", outside FieldType, and is a number field.
const formatKind: "number" | "date" | null =
field.type === "int" || field.type === "currency" || field.type === "formula" ||
field.type === "pct" || field.type === "rollup" || (field.type as string) === "number"
? "number"
: field.type === "date" || field.type === "created_time" || field.type === "last_modified_time"
? "date"
: null;
const canEditNumberPolicy = isUserTable && canEditDefinition && !!onFieldConfig &&
(field.type === "int" || field.type === "currency" || field.type === "pct");
/**
* Item 6 β Insert left/right (and Add at end) jump STRAIGHT to the create form: name + type
* autofocused, and none of the note/change-field/other-column chrome rendered around it.
*/
// R8: a retained pane or a caller-supplied initial pane cannot expose schema controls.
if (!embedded) {
if (position && canAddField) {
return (
<AnchoredOverlay
anchor={state.anchor}
className="cg-column-menu"
onDismiss={onClose}
role="dialog"
ariaLabel={
position === "end" ? "Add field" : `Insert field ${position} of ${field.label}`
}
// The SAME selector as the full-menu branch, so React reconciling the two states does
// not re-run the overlay's focus effect (its deps see one constant) β which would steal
// focus to the first button a frame after the name input autofocused.
initialFocus="[data-overlay-autofocus]"
dataKind="column-menu"
>
<PaneHead
title={
position === "end"
? "Add field"
: position === "left"
? "Insert field left"
: "Insert field right"
}
sub={position === "end" ? "Added as the last column" : `Next to ${field.label}`}
onClose={onClose}
/>
<div className="cg-column-create">
{/* ββ W36-T07 (owner item 10) β *"the Field agent needs to have an ability to chat
with, so the user can further align request"*. The agent fills THIS form rather
than owning a second creation path: accepting a proposal seeds the name, the kind
and any options, and the ordinary Add-field button is still what commits them. One
create door, two ways to reach it.
β R11 β the Metric kind is a target the agent can propose, not a thing being
retired. Every prior instruction to retire it is REVOKED (owner, 2026-08-18). */}
{askAgent ? (
<FieldAgentChat
existing={fields}
linkTargets={linkTargets}
database={tableKey}
onCancel={() => setAskAgent(false)}
onAccept={(proposal: FieldProposal) => {
if (proposal.existingField) {
if (offerableFields(fields).some((f) => f.key === proposal.existingField)) {
onChangeField(proposal.existingField);
onClose();
}
return;
}
setLabel(proposal.label);
setLabelTouched(true);
pickKind(proposal.kind);
if (proposal.linkTarget && linkTargets.some((t) => t.key === proposal.linkTarget?.key))
setLinkTable(proposal.linkTarget.key);
if (proposal.options && proposal.options.length)
setCreateOptionDrafts(optionDrafts(proposal.options));
setAskAgent(false);
}}
/>
) : (
<button
type="button"
className="cg-fagent-open"
onClick={() => setAskAgent(true)}
>
Describe it instead, and the field agent will propose one
</button>
)}
<label>
<span>Name</span>
<input
className="cg-input"
autoFocus
data-overlay-autofocus
value={effectiveLabel}
onChange={(event) => {
setLabel(event.target.value);
setLabelTouched(true);
}}
onKeyDown={(event) => event.key === "Enter" && create()}
/>
</label>
<div className="cg-type-block">
<span className="cg-type-title">Field type</span>
{/* Owner item 8 (2026-07-31): every type wears its own mark β the same TYPE_SHAPES
glyph its column header wears. A native <option> cannot hold an SVG (the ruling
iconShapes.ts records), so the control is a find box over a listbox of real
rows, Airtable-style. The measure row appears exactly when the host offers
measures β the same availability rule as the filter's measure conditions. */}
<TypePicker
value={rollupPreset ?? kind}
onPick={pickKind}
offerMeasure={measures.length > 0}
offerGeocode={offerGeocode}
offerPresets
isUserTable={isUserTable}
/>
</div>
{kind === "measure" && (
<>
{/* C-NAME β the row asked "Measure"/"Choose a measureβ¦", which named the
INTERNAL concept at the user. What the person is picking is the business
number ("Sales", "Gross margin"), so the label says that. */}
<label>
<span>Number</span>
{/* Item 20 (C-FLDSEL) β "Choose a numberβ¦" was an `<option value="">` that
only rendered while nothing was chosen; it is the picker's PLACEHOLDER
now, so the prompt is a state of the control rather than a row of the
vocabulary that could be picked. */}
<FieldSelectButton
ariaLabel="Number to summarise"
placeholder="Choose a numberβ¦"
value={chosenMeasure ? measureKey : undefined}
onChange={setMeasureKey}
fields={measures.map((m) => ({
key: m.key, label: m.label, type: "measure" as const,
}))}
/>
</label>
<label>
<span>Period</span>
<span className="cg-measure-window">
<WindowPicker window={measureWindow} onWindow={setMeasureWindow} />
</span>
</label>
{/* The helper line now carries what the old label's parenthetical was doing β
"(over a period)" β plus an example, because "Metric" alone does not say
that the answer moves with the window above it. */}
<div className="cg-field-hint">
A total, average or count over the period you choose, such as Sales, last 90
days. Computed for every customer, and read-only.
</div>
</>
)}
{/* ββ W37-T22 (owner item 15 / R4, contract C7) β THE GEOCODE PANE. It sits beside the
Metric pane above rather than inside `ExtraTypeEditor`, because that editor
dispatches on `FieldType` and this is a pseudo-kind: putting it there would mean
widening the editor's own union for a kind no stored column ever has. */}
{kind === "geocode" && (
<>
<label>
<span>Address column</span>
<FieldSelectButton
ariaLabel="Column holding the address"
placeholder="Choose a columnβ¦"
value={geocodeAddressField || undefined}
onChange={setGeocodeAddressField}
fields={addressFields.map((f) => ({
key: f.key, label: f.label, type: f.type,
}))}
/>
</label>
<label>
<span>Country (optional)</span>
<input
type="text"
value={geocodeCountry}
maxLength={2}
placeholder="US"
aria-label="Two letter country code the lookup is limited to"
onChange={(event) => setGeocodeCountry(event.target.value)}
/>
</label>
{/* β NO DASH OF ANY KIND in this sentence, and `web_prose` cannot see a wrapped JSX
sentence, so it is on the author. β It says the two things a person cannot
discover by clicking: nothing runs by itself (R3, and under R14 the reason is
the free geocoder's rate limit rather than a bill), and what the cell will hold
(C7, a coordinate pair a map or a formula can read). */}
<div className="cg-field-hint">
Fills each row with a latitude and longitude read from the column you choose, so
the map and any formula can use them. A country code keeps the lookup in one
place, which matters when a street name exists in several. Nothing is looked up
until you run it on the records you pick.
</div>
</>
)}
{kind === "if" && <IfStatementEditor definition={ifDraft} fields={ifSourceFields}
onChange={setIfDraft} />}
<ExtraTypeEditor
aiEnrich={aiEnrich}
onAiEnrich={patchAiEnrich}
kind={kind}
fields={fields}
formulaText={formulaText}
onFormulaText={setFormulaText}
formulaError={formulaCheck.ok ? null : formulaCheck.error ?? null}
maxValue={maxValue}
onMaxValue={setMaxValue}
codeLanguage={codeLanguage}
onCodeLanguage={setCodeLanguage}
idPrefix="cg-create"
automationKind={automationKind}
onAutomationKind={setAutomationKind}
automationUrlField={automationUrlField}
onAutomationUrlField={setAutomationUrlField}
linkTargets={linkTargets}
linkTable={linkTable}
onLinkTable={setLinkTable}
linkSingle={linkSingle}
onLinkSingle={setLinkSingle}
linkSelectionMode={linkSelectionMode}
onLinkSelectionMode={setLinkSelectionMode}
linkSelectionFilter={linkSelectionFilter}
onLinkSelectionFilter={setLinkSelectionFilter}
hop={{
topics: hopTopics,
windows: hopTopicOffer.windows,
scopeKey: hopScopeKey,
draft: hopDraft,
onDraft: patchHopDraft,
}}
rollupPreset={rollupPreset}
rollupMode={rollupMode}
onRollupMode={setRollupMode}
rollupSourceOffer={rollupSourceOffer}
rollupSource={rollupSource}
onRollupSource={setRollupSource}
rollupLink={rollupLink}
onRollupLink={(value) => {
setRollupLink(value);
setRollupField("");
setRollupSortBy("");
setRollupDistinctBy("");
// Every condition names a column of the OLD target, so both lists are cleared for
// the same reason: a leaf pointing at a field the new table does not have is a
// filter that can only ever match nothing.
setRollupWhere([]);
setRollupConditions([]);
}}
rollupField={rollupField}
onRollupField={setRollupField}
rollupFn={rollupFn}
onRollupFn={setRollupFn}
rollupLimit={rollupLimit}
onRollupLimit={setRollupLimit}
rollupSortBy={rollupSortBy}
onRollupSortBy={setRollupSortBy}
rollupDistinctBy={rollupDistinctBy}
onRollupDistinctBy={setRollupDistinctBy}
rollupWhere={rollupWhere}
onRollupWhere={setRollupWhere}
rollupWhereConj={rollupWhereConj}
onRollupWhereConj={setRollupWhereConj}
rollupConditions={rollupConditions}
onRollupConditions={setRollupConditions}
rollupConditionConj={rollupConditionConj}
onRollupConditionConj={setRollupConditionConj}
/>
{needsOptions(kind) && (
<OptionsEditor
idPrefix="cg-create-option"
drafts={createOptionDrafts}
onDrafts={setCreateOptionDrafts}
colorCode={createColorCode}
onColorCode={setCreateColorCode}
type={kind}
maxOptions={optionLimit}
/>
)}
{createDefaultOffered && supportsDefaultValue(kind) && <DefaultValueEditor type={kind}
enabled={createDefaultEnabled} value={createDefaultValue} options={options}
onEnabled={setCreateDefaultEnabled} onValue={setCreateDefaultValue} />}
{kind === "user" && (
<div className="cg-field-hint">
{userOptions.length
? `${userOptions.length} people can be assigned, from your user list.`
: "No user list yet, so there is no one to assign."}
</div>
)}
{scopeChoice && <ScopeControl value={scopeDraft} onValue={setScopeDraft} />}
<div className="cg-form-actions">
<button
type="button"
className="cg-btn cg-btn--primary"
disabled={!canCreate}
onClick={create}
>
Create field
</button>
<button
type="button"
className="cg-btn"
// Opened straight into the form (the header "+")? Cancel means close β
// there is no action list behind it to fall back to.
onClick={() => (initialPosition ? onClose() : setPosition(null))}
>
Cancel
</button>
</div>
</div>
</AnchoredOverlay>
);
}
// ------------------------------- EDIT FIELD, DESCRIPTION ONLY (W41-T31, instruction 1, R19)
/**
* ββ A PRE-SET FIELD'S "Edit field", AND IT IS A PANE OF ITS OWN rather than the full one
* with six things switched off.
*
* Owner: *"A pre-set field's 'Edit field' should not exist except to change the description;
* the pre-set description is the one place a user adds a description. Standardize."* A
* separate return is what makes the first half literally true: there is no Name box, no type
* picker, no retype, no Change field, no period row and no delete IN THE TREE, so none of
* them can be reached by a condition that drifts three waves from now. It is also how the
* ticket's last clause is proved: the pane below is not touched, so a non-pre-set field's
* Edit field cannot have changed.
*
* β MUTUALLY EXCLUSIVE BY CONSTRUCTION, NOT BY ORDERING. `canEditDescription` is true only
* when `schemaLocked` is, and `canEditDefinition` is false whenever `schemaLocked` is true β
* so no field can satisfy both, and moving this block would change nothing.
*/
if (pane === "edit" && canEditDescription) {
return (
<AnchoredOverlay
anchor={state.anchor}
className="cg-column-menu"
onDismiss={onClose}
role="dialog"
ariaLabel={`Edit field ${field.label}`}
initialFocus="[data-overlay-autofocus]"
dataKind="column-menu"
>
<PaneHead title="Edit field" sub={typeLine} onClose={onClose} />
<div className="cg-column-create cg-field-edit cg-desc-only">
{/* DESIGN section 4, the three locks: the mark NAMES WHICH LOCK. This one says
"definition", so it cannot be read as "you cannot type here" (a locked database)
nor as a curated row set (a locked view). One line, and it leads with what you
CAN do, because the pane exists to offer that. Worded once, in `fieldClass.ts`. */}
<span className="cg-field-hint">{PRESET_DESCRIPTION_ONLY_HINT}</span>
<label className="cg-edit-description">
<span>Description</span>
{/* `field.description` is schema metadata and `field.note` is the workspace edit.
The editor owns the latter; inherited implementation copy does not belong above
a user's description input. */}
{/* ββ MARKED UNCONDITIONALLY, and the full pane's conditional is exactly why.
There it reads `!nameIsFocusTarget && !swapOffered`, and `nameIsFocusTarget` is
`!!onRename || editingRelational` β true for a pre-set `link` column, which
`isSchemaLocked` does not exclude. Copied verbatim the attribute would evaluate
to `undefined` on that column, `initialFocus`'s `querySelector` would match
nothing, and the dialog would open with the keyboard still on the grid header
behind it (the W40-T24 defect, and one no gate in this repo can see). Here the
textarea is the ONLY control before the actions, so it is the focus target
unconditionally and exactly one element carries the attribute. */}
<textarea
className="cg-input"
rows={3}
data-overlay-autofocus
value={note}
placeholder="Add a descriptionβ¦"
onChange={(event) => setNote(event.target.value)}
/>
</label>
{/* R19 β A USER'S EDIT WINS FOREVER, so there has to be a way to give it up.
β GATED ON C8's MARK, STRICTLY (`descriptionResetOffered` in `fieldClass.ts`):
absent means "not built yet", never "false", so an unbuilt server renders no link
rather than one claiming an edit exists. It clears the DRAFT and leaves the
committing to Save, which is this pane's one-Save model everywhere else β and
clearing makes the draft dirty, so Save lights up the moment you click it.
β THE SECOND CLAUSE READS THE DRAFT, and the first reads the SAVED field, which is
why both are here. `descriptionResetOffered` answers "is there a committed edit to
give up"; once the box is empty β cleared by this link, or by hand β the link has
nothing left to do, so it goes rather than sitting there doing visibly nothing on a
second click. */}
{descriptionResetOffered(field) && note.trim() !== "" && (
<button
type="button"
className="cg-desc-reset"
onClick={() => setNote("")}
>
{DESCRIPTION_RESET_LABEL}
</button>
)}
<div className="cg-form-actions">
<button
type="button"
className="cg-btn cg-btn--primary"
disabled={!canSaveEdit}
onClick={applyEdit}
>
Save
</button>
<button
type="button"
className="cg-btn"
// Item 12's rule, and this pane can be opened directly too (`viewModes` passes
// `initialPane="edit"`): Back means close when there is no action list behind it.
onClick={() => (initialPane ? onClose() : setPane("menu"))}
>
Back
</button>
</div>
</div>
</AnchoredOverlay>
);
}
// ------------------------------------------------------------ EDIT FIELD pane (item 8)
// Owner item 8 (2026-07-31): ONE window owning the field's identity β name, type (with the
// per-type choices/stars/formula editors), and the Change-field control. Absorbs the former
// Rename and Change-field panes.
if (pane === "edit") {
return (
<AnchoredOverlay
anchor={state.anchor}
className="cg-column-menu"
onDismiss={onClose}
role="dialog"
ariaLabel={`Edit field ${field.label}`}
initialFocus="[data-overlay-autofocus]"
dataKind="column-menu"
>
<PaneHead title="Edit field" sub={typeLine} onClose={onClose} />
<div className="cg-column-create cg-field-edit">
{nameIsFocusTarget ? (
<label>
<span>Name</span>
<input
className="cg-input"
autoFocus
data-overlay-autofocus
value={renameDraft}
onChange={(event) => setRenameDraft(event.target.value)}
onKeyDown={(event) => event.key === "Enter" && applyEdit()}
/>
</label>
) : (
<label>
<span>Name</span>
<input
className="cg-input"
value={field.label}
disabled
aria-label="Field name (read-only)"
/>
<span className="cg-field-hint">
A source field keeps its name and type from the data source.
</span>
</label>
)}
<label className="cg-edit-description">
<span>Description</span>
{/* ββ W40-T24 β LAST IN THE FOCUS PRECEDENCE, and the only reason it is marked at
all: on a pre-set column the Name box is disabled and the swap picker is now
gone, so without this the pane would open with `[data-overlay-autofocus]` matching
nothing and the keyboard left outside the dialog. The Description is the one
control a pre-set column still owns, which makes it the honest landing spot as
well as the available one. `undefined` REMOVES the attribute (React drops it), so
exactly one element in the pane ever carries it. */}
<textarea
className="cg-input"
rows={3}
data-overlay-autofocus={
!nameIsFocusTarget && !swapOffered ? true : undefined
}
value={note}
placeholder="Add a descriptionβ¦"
onChange={(event) => setNote(event.target.value)}
/>
</label>
{!onRetype && needsOptions(field.type) && <ChoicePreview field={field} />}
{editDefaultOffered && <DefaultValueEditor type={editType}
enabled={editDefaultEnabled} value={editDefaultValue} options={editOptions}
onEnabled={setEditDefaultEnabled} onValue={setEditDefaultValue} />}
{/* C5-AUTOFIELD β an EXISTING automation column edits its CONFIG, not its type.
β This guard is load-bearing, not tidiness. `automation` is excluded from
RETYPE_TYPES (see its note), so rendering the picker for one would show a
listbox whose current value is not among its options β the failure recorded in
[[cg-condition-builder-items]], where a control missing its own value silently
presents the FIRST option as if it were the selection. One Save later the column
is a different type and its statuses are editable text. */}
{/*
ββ 2026-08-09 (owner) β AN EXISTING ROLLUP/LINK EDITS ITS CONFIGURATION HERE.
Owner: *"even when i click edit field for rollup, it doesn't actually show me the
configuration that I use to generate it, it only shows change to a different field."*
This branch is that configuration, seeded from the stored bag, and it takes the same
`ExtraTypeEditor` the create pane uses so the two can never offer different controls
for the same column.
β IT REPLACES THE TYPE PICKER, exactly as `automation` does one branch down, and for
the sharper version of that reason. `RETYPE_TYPES` contains `rollup`, so the picker
rendered here would have let Save re-emit the column with no bag β and the host's
`retypeField` refuses a non-`custom` field outright, so on a pre-set rollup the Save
button was wired to nothing at all. Changing a rollup INTO another type stays
available through "Change field" below, which is the door that means "show something
else in this column".
*/}
{editingRelational ? (
<div className="cg-type-block">
<span className="cg-type-title">
{field.type === "rollup" ? "Rollup" : "Linked records"}
</span>
<ExtraTypeEditor
aiEnrich={aiEnrich}
onAiEnrich={patchAiEnrich}
kind={field.type}
fields={fields}
linkTargets={linkTargets}
formulaText={editFormulaText}
onFormulaText={setEditFormulaText}
formulaError={null}
maxValue={retypeMaxValue}
onMaxValue={setRetypeMaxValue}
codeLanguage={editCodeLanguage}
onCodeLanguage={setEditCodeLanguage}
idPrefix="cg-edit"
linkTable={editLinkTable}
onLinkTable={setEditLinkTable}
linkSingle={editLinkSingle}
onLinkSingle={setEditLinkSingle}
linkSelectionMode={editLinkSelectionMode}
onLinkSelectionMode={setEditLinkSelectionMode}
linkSelectionFilter={editLinkSelectionFilter}
onLinkSelectionFilter={setEditLinkSelectionFilter}
hop={{
topics: hopTopics,
windows: hopTopicOffer.windows,
scopeKey: hopScopeKey,
draft: editHopDraft,
onDraft: patchEditHopDraft,
}}
rollupPreset={rollupPresetOf(editRollup)}
rollupSourceOffer={rollupSourceOffer}
rollupMode={editRollup.source ? "source" : "link"}
// β A MODE SWITCH REPLACES THE BAG, it does not merge into it. `_clean_rollup`
// reads `source` first and returns before it ever looks at `link`, so a bag
// carrying both would ship keys the store silently drops β dead payload that
// later reads as configuration.
onRollupMode={(mode) =>
setEditRollup(mode === "source"
? { source: { topic: "", measure: "", groupBy: "", on: "", window: "ytd" } }
: { link: "", fn: "sum" })
}
rollupSource={editRollup.source ?? {
topic: "", measure: "", groupBy: "", on: "", window: "ytd",
}}
onRollupSource={(source) => patchEditRollup({ source })}
rollupLink={editRollup.link ?? ""}
onRollupLink={(value) =>
// Same reset the create pane performs: every other key names a column of the
// OLD target, and a leaf pointing at a field the new table lacks is a filter
// that can only ever match nothing.
setEditRollup({ link: value, fn: editRollup.fn ?? "sum" })
}
rollupField={editRollup.field ?? ""}
onRollupField={(value) => patchEditRollup({ field: value })}
rollupFn={editRollup.fn ?? "sum"}
onRollupFn={(value) => patchEditRollup({ fn: value })}
rollupLimit={editRollup.limit ?? 0}
onRollupLimit={(value) => patchEditRollup({ limit: value })}
rollupSortBy={editRollup.sortBy ?? ""}
onRollupSortBy={(value) =>
patchEditRollup(value
? { sortBy: value, sortDir: editRollup.sortDir ?? "desc",
limit: editRollup.limit || 1 }
: { sortBy: "" })
}
rollupDistinctBy={editRollup.distinctBy ?? ""}
onRollupDistinctBy={(value) => patchEditRollup({ distinctBy: value })}
rollupWhere={editRollup.where ?? []}
onRollupWhere={(value) =>
patchEditRollup({ where: value,
whereConj: editRollup.whereConj ?? "and" })
}
rollupWhereConj={editRollup.whereConj ?? "and"}
onRollupWhereConj={(value) => patchEditRollup({ whereConj: value })}
rollupConditions={editRollup.conditions ?? []}
onRollupConditions={(value) =>
patchEditRollup({ conditions: value,
conditionConj: editRollup.conditionConj ?? "and" })
}
rollupConditionConj={editRollup.conditionConj ?? "and"}
onRollupConditionConj={(value) => patchEditRollup({ conditionConj: value })}
/>
</div>
) : field.type === "autonumber" ? (
<div className="cg-type-block">
<span className="cg-type-title">Autonumber</span>
</div>
) : AUDIT_FIELD_TYPES.includes(field.type) ? (
<div className="cg-type-block">
<span className="cg-type-title">{TYPE_LABELS[field.type]}</span>
<div className="cg-field-hint">Read-only. {TYPE_DESCRIPTIONS[field.type]}</div>
</div>
) : editingIf ? (
<IfStatementEditor definition={editIf} fields={editIfSourceFields} onChange={setEditIf} />
) : onRetype && field.type === "automation" ? (
<div className="cg-type-block">
<span className="cg-type-title">Automation</span>
<ExtraTypeEditor
aiEnrich={aiEnrich}
onAiEnrich={patchAiEnrich}
kind="automation"
fields={fields}
formulaText={editFormulaText}
onFormulaText={setEditFormulaText}
formulaError={null}
maxValue={retypeMaxValue}
onMaxValue={setRetypeMaxValue}
codeLanguage={editCodeLanguage}
onCodeLanguage={setEditCodeLanguage}
idPrefix="cg-edit"
automationKind={editAutomationKind}
onAutomationKind={setEditAutomationKind}
automationUrlField={editAutomationUrlField}
onAutomationUrlField={setEditAutomationUrlField}
/>
</div>
) : onRetype ? (
<>
<div className="cg-type-block">
<span className="cg-type-title">Field type</span>
{/* The same find-box-over-icon-listbox the create pane wears (owner item 8 of
the PREVIOUS wave) β one control for "pick a type" everywhere. */}
<TypePicker
value={editType}
onPick={(k) => setEditType(k as FieldType)}
offerMeasure={false}
offerPresets={false}
isUserTable={isUserTable}
offerGeocode={
/* β FALSE ON PURPOSE, and stated rather than omitted: this is the RETYPE
picker, and a geocode column is not a type an existing column can BECOME.
Its bag has to be authored, and `canCreateSwap` passes none of the
pseudo-kind setters (a pre-existing defect its own comment books). */
false
}
only={RETYPE_TYPES}
/>
</div>
{/*
ββ 2026-08-07 (D-79's last half) β MARK THIS COLUMN AS AN INSTAGRAM PROFILE.
Wave 25 shipped this flag's READER everywhere (the type line above, the cell
validator, R6's clear-on-write, the one-per-table refusal) and never its WRITER,
so `enrich_instagram` could not be bound to any database somebody made
themselves β the owner's *"on a schedule, enrich these sets of influencer
names"*. One checkbox; the server door already existed.
β `text` ONLY, and it mirrors `_clean_field` rather than restating a rule: a
flag on a select or an int would promise a validated handle to a cell nothing
validates, and the server REFUSES it. Offering it there would be a control whose
only outcome is a 400.
β The one-per-table rule is NOT re-implemented here. The server refuses a second
one with a sentence naming the column that already has it, and `patchTableField`
surfaces that sentence verbatim β a client copy of the rule is how two doors
start disagreeing about which column is the profile.
*/}
{onProfileFlag && editType === "text" && (
<label className="cg-check-row">
<input
type="checkbox"
checked={isProfileField(field)}
onChange={(event) => onProfileFlag(field.key, event.target.checked)}
/>
<span>Instagram profile column</span>
</label>
)}
{onProfileFlag && editType === "text" && (
<div className="cg-field-hint">
{isProfileField(field)
? "Automations enrich from this column. Clearing a cell also clears that "
+ "row's enriched columns."
: "Lets an Enrich step know which column holds the handle. A database has "
+ "at most one."}
</div>
)}
{editType === "code" && (
<label>
<span>Language</span>
<select
className="cg-select"
value={editCodeLanguage}
aria-label="Code language"
onChange={(event) => setEditCodeLanguage(event.target.value)}
>
{/* Explicit `value` on every option: a <select> whose value names nothing
renders its FIRST option and reports a choice nobody made. */}
{CODE_LANGUAGES.map((lang) => (
<option key={lang} value={lang}>
{CODE_LANGUAGE_LABELS[lang]}
</option>
))}
</select>
<span className="cg-field-hint">
Chooses how the snippet is coloured. It is never run.
</span>
</label>
)}
{editType === "rating" && (
<label>
<span>Number of stars</span>
<input
className="cg-input cg-rating-max"
type="number"
min={2}
max={10}
value={retypeMaxValue}
aria-label="Number of stars"
onChange={(event) => {
const n = Math.round(Number(event.target.value));
setRetypeMaxValue(
Number.isFinite(n) ? Math.max(2, Math.min(10, n)) : 5
);
}}
/>
</label>
)}
{needsOptions(editType) && (
<OptionsEditor
idPrefix="cg-edit-option"
drafts={editOptionDrafts}
onDrafts={setEditOptionDrafts}
colorCode={editColorCode}
onColorCode={setEditColorCode}
type={editType}
maxOptions={optionLimit}
onRemove={onChoiceRemove ? (draft) => void requestOptionRemoval(draft) : undefined}
/>
)}
{needsOptions(editType) && (pendingRemoval || removalError) && (
<div className="cg-option-confirm" role="alert">
{pendingRemoval ? (
<>
<strong>Remove {pendingRemoval.label}?</strong>
<span>{choiceRemovalMessage(pendingRemoval.cells)}</span>
<div className="cg-option-confirm-actions">
<button
type="button"
className="cg-btn"
disabled={removalBusy}
onClick={() => setPendingRemoval(null)}
>
Cancel
</button>
<button
type="button"
className="cg-btn cg-btn--primary"
disabled={removalBusy}
onClick={() => void confirmOptionRemoval()}
>
{removalBusy ? "Removing" : "Remove option"}
</button>
</div>
</>
) : (
<span>{removalError}</span>
)}
</div>
)}
{editType !== field.type && (
<div className="cg-field-hint">
Changes {field.label} into a {TYPE_LABELS[editType].toLowerCase()} field,
keeping its name and its values as entered. Cells that cannot be read in
the new type show blank.
</div>
)}
</>
) : null}
{/* Item 21 (owner, 2026-08-02) β the PERIOD lives here, with the field's other
properties, instead of floating above the action list on the menu pane. A metric
column IS "a number over a period": the window is as much a part of its
definition as its name is, and it was the one property you edited from a
different window than every other one.
It shares this pane's ONE Save (`applyEdit` applies it alongside a rename) β
the old "Apply period" button became a second primary action in a pane that
already had one, which is the ambiguity the move was supposed to remove. */}
{canPeriod && measures.length > 0 && (
<label className="cg-edit-measure">
<span>Number</span>
{/* W48C-T12 - the SAME picker the create pane renders, same aria-label, so the
two flows are equivalent by construction rather than by resemblance. */}
<FieldSelectButton
ariaLabel="Number to summarise"
placeholder="Choose a numberβ¦"
value={editMeasureKey || undefined}
onChange={setEditMeasureKey}
fields={measures.map((m) => ({
key: m.key, label: m.label, type: "measure" as const,
}))}
/>
</label>
)}
{canPeriod && (
<label className="cg-edit-period">
<span>Period</span>
<span className="cg-measure-window">
<WindowPicker
window={periodDraft ?? field.measure!.window}
onWindow={setPeriodDraft}
/>
</span>
<span className="cg-field-hint">
The window this number is computed over, for every customer.
</span>
</label>
)}
{!onRetype && field.type === "formula" && onFormula && (
<ExtraTypeEditor
aiEnrich={aiEnrich}
onAiEnrich={patchAiEnrich}
kind="formula"
fields={fields}
formulaText={editFormulaText}
onFormulaText={setEditFormulaText}
formulaError={editFormulaCheck.ok ? null : editFormulaCheck.error ?? null}
maxValue={retypeMaxValue}
onMaxValue={setRetypeMaxValue}
codeLanguage={editCodeLanguage}
onCodeLanguage={setEditCodeLanguage}
idPrefix="cg-edit"
/>
)}
<div className="cg-form-actions">
<button
type="button"
className="cg-btn cg-btn--primary"
disabled={!canSaveEdit}
onClick={applyEdit}
>
Save
</button>
<button
type="button"
className="cg-btn"
// Item 12 β opened STRAIGHT into this pane (the kanban's "Add option")? Back means
// close, exactly as Cancel does in the directly-opened create form: there is no
// action list behind a pane nobody navigated to.
onClick={() => (initialPane ? onClose() : setPane("menu"))}
>
Back
</button>
</div>
{/* -------- Change field (owner item 9, folded in here by owner item 8) --------
ββ W40-T24 (owner instruction 18, contract C2) β GATED ON THE PRE-SET LOCK, which
it never was. The condition here used to be `!locked` alone, and `locked` means
"is the pinned primary column" β so every contract column on every grid offered to
be redefined into something else, which is the "choose a field dropdown that makes
no sense" the owner reported about Supplier and was never only about Supplier.
It is the SAME predicate that already withholds the Field-type picker and the
editable Name box, which is what makes this pane say one thing about the column
instead of three. `offer.swap` carries the `!locked` half (the primary column is the
row identity and can never be swapped away); `swapOptions.length > 0` stays because
an empty picker is its own fake affordance. */}
{swapOffered && (
<div className="cg-edit-swap">
<span className="cg-type-title">Change field</span>
<div className="cg-field-hint">
Show a different field in this column. The current one is hidden, not lost.
</div>
<div className="cg-column-swap">
{/* Item 20 β the ONE picker on this surface that keeps its groups, and it is
not a contradiction of the filter list's flatness: those three headings
separate DIFFERENT KINDS OF ACT (show a pre-set column Β· show one of yours Β·
make a new one), not three flavours of the same noun. The type mark does
the work the "New field" labels were doing on their own. */}
<FieldSelectButton
className="cg-swap-select"
ariaLabel="Change this column to another field"
placeholder="Choose a fieldβ¦"
// Focus falls here when the pane has no editable Name (a read-only source
// field): the swap picker is then the pane's first live control. Second in the
// precedence `nameIsFocusTarget` documents, and reading THAT rather than
// `!onRename` is what keeps the attribute on exactly one element.
overlayAutofocus={!nameIsFocusTarget}
value={swapTo || undefined}
onChange={setSwapTo}
fields={[
...presetSwap.map((f) => ({
key: f.key, label: f.label, type: f.type, group: "Pre-set fields",
})),
...yourSwap.map((f) => ({
key: f.key, label: f.label, type: f.type, group: "Your fields",
})),
...FIELD_TYPES.map((t) => ({
key: NEW_PREFIX + t.value,
label: t.label,
type: t.value,
group: "New field",
})),
]}
/>
{!swapToNewType && (
<button
type="button"
className="cg-btn cg-btn--primary"
disabled={!swapTo}
onClick={() => {
onChangeField(swapTo);
onClose();
}}
>
Change
</button>
)}
</div>
{/* The "New field" half: name it (and give it choices/its formula/its stars
when the type needs them), then create-and-swap in one motion. */}
{swapToNewType && (
<div className="cg-column-create cg-swap-create">
<label>
<span>New {(swapToNewType === "if" ? "If statement" : TYPE_LABELS[swapToNewType]).toLowerCase()} field</span>
<input
className="cg-input"
autoFocus
value={swapLabel}
placeholder="Field name"
onChange={(event) => setSwapLabel(event.target.value)}
onKeyDown={(event) => event.key === "Enter" && createAndSwap()}
/>
</label>
{swapToNewType === "if" && <IfStatementEditor definition={ifDraft} fields={ifSourceFields}
onChange={setIfDraft} />}
<ExtraTypeEditor
aiEnrich={aiEnrich}
onAiEnrich={patchAiEnrich}
kind={swapToNewType}
fields={fields}
formulaText={swapFormulaText}
onFormulaText={setSwapFormulaText}
formulaError={
swapFormulaCheck.ok ? null : swapFormulaCheck.error ?? null
}
maxValue={swapMaxValue}
onMaxValue={setSwapMaxValue}
codeLanguage={swapCodeLanguage}
onCodeLanguage={setSwapCodeLanguage}
idPrefix="cg-swap"
/>
{needsOptions(swapToNewType) && (
<OptionsEditor
idPrefix="cg-swap-option"
drafts={swapOptionDrafts}
onDrafts={setSwapOptionDrafts}
colorCode={swapColorCode}
onColorCode={setSwapColorCode}
type={swapToNewType}
maxOptions={optionLimit}
/>
)}
{swapToNewType === "user" && (
<div className="cg-field-hint">
{userOptions.length
? `${userOptions.length} people can be assigned.`
: "No user list was supplied by the host yet."}
</div>
)}
{scopeChoice && (
<ScopeControl value={scopeDraft} onValue={setScopeDraft} />
)}
<div className="cg-form-actions">
<button
type="button"
className="cg-btn cg-btn--primary"
disabled={!canCreateSwap}
onClick={createAndSwap}
>
Create and change
</button>
<button
type="button"
className="cg-btn"
onClick={() => setSwapTo("")}
>
Cancel
</button>
</div>
</div>
)}
</div>
)}
</div>
</AnchoredOverlay>
);
}
// ------------------------------------------------------------------ FORMAT pane (item 10)
/**
* ββ WAVE-29 T33 (owner item 17) β THE COLUMN SUMMARY PANE.
*
* A flat list of the six aggregates plus "None", because that is the whole decision β there is
* no draft to reconcile and no Save button to press, so the click IS the answer and the pane
* closes on it (the same shape as Sort, one group up, and unlike Format, which composes four
* settings into one bag).
*
* β THE OPTIONS COME FROM `aggOptions`, never from a list written here. `sum Β· average Β·
* median Β· min Β· max` are numeric-only and `count` counts ROWS, so a text column offers exactly
* one row β and it offers it, rather than hiding the pane, because "how many records is this
* group" is the summary a text column CAN answer.
*/
if (pane === "summary" && onSummary) {
const options = summaryOptions(field);
/* ββ W50-T05 / R2 β THE RESOLVED choice, not `field.agg`. `resolveSummary` answers with the
view's key first, the legacy field `agg` second and R2's Sum-on-a-numeric-family default
third, so a column the reader has never touched shows the mark against the aggregate the
bar is ACTUALLY folding rather than against "None". Reading `field.agg` here is what made
the header menu and the bottom bar two opinions of one column. */
const current = resolveSummary(field, summary ?? {});
return (
<AnchoredOverlay
anchor={state.anchor}
className="cg-column-menu"
onDismiss={onClose}
role="dialog"
ariaLabel={`Summarize ${field.label}`}
initialFocus="[data-overlay-autofocus]"
dataKind="column-menu"
>
<PaneHead title="Summarize" sub={field.label} onClose={onClose} />
<div className="cg-menu-list" role="none">
<button
type="button"
data-overlay-autofocus={current.agg === "none" ? true : undefined}
aria-pressed={current.agg === "none"}
onClick={() => {
/* β `{ agg: "none" }`, never `undefined`. An absent key means "nobody has chosen",
which `resolveSummary` answers with R2's Sum default β so clearing by omission
would put the total straight back on a numeric column. */
onSummary({ agg: "none" });
onClose();
}}
>
<MenuLabel icon="off" text="None" />
</button>
{options.map((name) => (
<button
key={name}
type="button"
data-overlay-autofocus={current.agg === name ? true : undefined}
aria-pressed={current.agg === name}
onClick={() => {
/* Percentile carries its point; every other name is the whole choice. The `p`
already in scope is kept so re-picking p75 does not silently become p50. */
onSummary(name === "percentile" ? { agg: name, p: current.p } : { agg: name });
onClose();
}}
>
<MenuLabel icon="format" text={summaryLabel({ agg: name, p: current.p })} />
</button>
))}
</div>
</AnchoredOverlay>
);
}
/**
* ββ WAVE 50 Β· W50-T05 (instruction 4, R4) β **SHOW AS: Value, % of total, or Both.**
*
* A flat list of three, the same shape as Summarize one group up: there is no draft to
* reconcile, so the click IS the answer and the pane closes on it. Sentence case per
* DESIGN.md Β§2, and the words come from `SHOW_AS_LABELS` so this pane cannot invent a fourth
* spelling of a mode the formatter already names.
*
* β ELIGIBILITY IS `isNumericFieldType`, ASKED AT THE MENU ROW BELOW AND NOWHERE ELSE. The
* done-when lists "number, currency, int, formula, Metric and rollup"; that sentence is the
* numeric FAMILY, and a list written kind by kind here is the ERROR-20 blank reproduced the
* first time a kind is added (`resolveSummary`'s note says the same thing about summaries).
*
* β % OF TOTAL IS THE VIEW'S GRAND TOTAL (R4), NOT THE GROUP'S β which is what makes the rows
* and the group headers add to 100% down the grid and the bar read 100%. The base is chosen by
* `CustomerGrid`, and a column whose summary does not COMPOSE (`SHARE_AGGS` is `sum` and
* `count` only) shows its value with no share rather than a ratio of two averages.
*/
if (pane === "showAs" && onShowAs) {
const current = field.showAs ?? "value";
return (
<AnchoredOverlay
anchor={state.anchor}
className="cg-column-menu"
onDismiss={onClose}
role="dialog"
ariaLabel={`Show ${field.label} as`}
initialFocus="[data-overlay-autofocus]"
dataKind="column-menu"
>
<PaneHead title="Show as" sub={field.label} onClose={onClose} />
<div className="cg-menu-list" role="none">
{SHOW_AS_MODES.map((mode) => (
<button
key={mode}
type="button"
data-overlay-autofocus={current === mode ? true : undefined}
aria-pressed={current === mode}
onClick={() => {
onShowAs(mode);
onClose();
}}
>
<MenuLabel icon="format" text={SHOW_AS_LABELS[mode]} />
</button>
))}
</div>
</AnchoredOverlay>
);
}
if (pane === "format" && formatKind) {
return (
<AnchoredOverlay
anchor={state.anchor}
className="cg-column-menu"
onDismiss={onClose}
role="dialog"
ariaLabel={`Format ${field.label}`}
initialFocus="[data-overlay-autofocus]"
dataKind="column-menu"
>
<PaneHead title="Field format" sub={field.label} onClose={onClose} />
<div className="cg-column-create">
{formatKind === "number" ? (
<>
<label>
<span>Currency symbol</span>
<select
className="cg-select"
value={fmtDraft.currencySymbol ?? (field.type === "currency" ? "$" : "")}
aria-label="Currency symbol"
onChange={(e) => setFmtDraft((d) => ({
...d, currencySymbol: e.target.value as FieldFormat["currencySymbol"],
}))}
>
<option value="">None</option>
{["$", "EUR", "GBP", "IDR"].map((symbol) => (
<option key={symbol} value={symbol}>{symbol}</option>
))}
</select>
</label>
{/* Allow negative is a write policy, so a pre-set field never shows it. */}
{!schemaLocked && (field.type === "int" || field.type === "currency" || field.type === "pct") && (
<label className="cg-radio-row" style={{ flexDirection: "row" }}>
<input
type="checkbox"
checked={fmtDraft.allowNegative !== false}
disabled={!canEditNumberPolicy}
onChange={(e) => setFmtDraft((d) => ({ ...d, allowNegative: e.target.checked }))}
/>
<span>Allow negative numbers</span>
</label>
)}
<label className="cg-radio-row" style={{ flexDirection: "row" }}>
<input
type="checkbox"
data-overlay-autofocus
checked={fmtDraft.thousands !== false}
onChange={(e) =>
setFmtDraft((d) => ({ ...d, thousands: e.target.checked }))
}
/>
<span>Thousands separator (12,345)</span>
</label>
<label>
<span>Decimals</span>
<select
className="cg-select"
value={
Number.isInteger(fmtDraft.decimals) ? String(fmtDraft.decimals) : ""
}
aria-label="Decimals"
onChange={(e) =>
setFmtDraft((d) => {
const next = { ...d };
if (e.target.value === "") delete next.decimals;
else next.decimals = Number(e.target.value);
return next;
})
}
>
{/* No decimals key shows the full value; the setting never rounds stored data. */}
<option value="">Full value</option>
{[0, 1, 2, 3, 4].map((n) => (
<option key={n} value={n}>
{n}
</option>
))}
</select>
</label>
<label className="cg-radio-row" style={{ flexDirection: "row" }}>
<input
type="checkbox"
checked={fmtDraft.abbrev === true}
onChange={(e) =>
setFmtDraft((d) => ({ ...d, abbrev: e.target.checked }))
}
/>
<span>Abbreviate large numbers (34.0M)</span>
</label>
</>
) : (
<>
<label className="cg-radio-row">
<input
type="checkbox"
data-overlay-autofocus
checked={fmtDraft.time ?? (field.type === "created_time" || field.type === "last_modified_time")}
onChange={(e) => setFmtDraft((d) => ({ ...d, time: e.target.checked }))}
/>
<span>Include the time of day</span>
</label>
<label>
<span>Time zone</span>
<select
className="cg-select"
value={fmtDraft.tz === "utc" ? "utc" : "local"}
aria-label="Time zone"
onChange={(e) =>
setFmtDraft((d) => ({ ...d, tz: e.target.value as "local" | "utc" }))
}
>
<option value="local">Your local time</option>
<option value="utc">UTC</option>
</select>
</label>
</>
)}
<div className="cg-form-actions">
<button
type="button"
className="cg-btn cg-btn--primary"
disabled={JSON.stringify(fmtDraft) === JSON.stringify(field.format ?? {})}
onClick={() => {
if (canEditNumberPolicy && fmtDraft.allowNegative !== field.format?.allowNegative)
onFieldConfig?.({ format: fmtDraft });
else onFormat?.(fmtDraft);
onClose();
}}
>
Save
</button>
<button type="button" className="cg-btn" onClick={() => setPane("menu")}>
Back
</button>
</div>
</div>
</AnchoredOverlay>
);
}
}
if (embedded && pane === "width" && onColumnWidth) {
const width = Number(widthDraft);
const validWidth = widthDraft.trim() !== "" && Number.isFinite(width) && width >= 50 && width <= 600;
return (
<AnchoredOverlay
anchor={state.anchor}
className="cg-column-menu"
onDismiss={onClose}
dismissOnOutside={false}
role="dialog"
ariaLabel={`Column width for ${field.label}`}
initialFocus="[data-overlay-autofocus]"
dataKind="column-menu"
>
<PaneHead title="Column width" sub={field.label} onClose={onClose} />
<form className="cg-column-create cg-field-edit" onSubmit={(event) => {
event.preventDefault();
if (!validWidth) return;
onColumnWidth(Math.round(width));
onClose();
}}>
<label>
<span>Width (px)</span>
<input
className="cg-input"
type="number"
min={50}
max={600}
step={1}
required
data-overlay-autofocus
value={widthDraft}
onChange={(event) => setWidthDraft(event.target.value)}
/>
</label>
<div className="cg-form-actions">
<button type="submit" className="cg-btn cg-btn--primary" disabled={!validWidth}>Apply</button>
<button type="button" className="cg-btn" onClick={() => setPane("menu")}>Back</button>
</div>
</form>
</AnchoredOverlay>
);
}
// ------------------------------------------------------------------ the MENU pane
// Wave-5 items 1/2/3: a flat action list. Editors open their OWN windows (the panes above);
// nothing edits inline here. Conditional entries render IFF they apply to the current view.
/**
* ββ W39-T17 β THE SHARE ID FOR THIS COLUMN, or `null` if one cannot honestly be built.
*
* β THREE WAYS IT REFUSES, and every one of them would otherwise produce an id the server
* accepts and then cannot resolve:
* Β· no `tableKey` β the host has no SERVER-issued key (see that prop's note: the local
* fallback is a key the server never issues, and a grant on one notifies nobody);
* Β· an empty one β `shares.field_oid` raises on a blank half, so the row must not offer it;
* Β· a field key containing `:` β `split_field_oid` refuses any oid whose FIELD half carries
* the separator, so such a column is not shareable and saying so by omission beats a row
* that 404s.
*/
const shareTable = (tableKey ?? "").trim();
const shareOid =
(field.custom || field.shared) && shareTable && field.key && !field.key.includes(":")
? `${shareTable}:${field.key}`
: null;
/**
* Open the SHELL's access editor for this column β the same dialog, roles and people picker a
* view or a folder gets (W39-T17's done-when; `shell/ShareDialog.tsx` renders all four kinds).
*
* ββ THE EVENT NAME IS A HARD-CODED LITERAL AND MUST STAY ONE. `customer-grid/**` MUST NOT
* import `shell/**` (this tree is host-neutral β the same rule `ViewSidebar.tsx::openShare`
* states and obeys), so `shareModel.SHARE_OPEN_EVENT` is unreachable from here by design.
* The literal is spelled once there and once here, and `verify_wiring.py`'s W39-W1 row pins
* BOTH ENDS precisely because no shared constant can keep them in step.
* β It degrades to NOTHING when no shell is listening: an event nobody hears opens no dialog
* and throws no error, which is the right failure for a frame-level surface reached from a
* column menu.
*/
const openFieldShare = () => {
if (!shareOid) return;
window.dispatchEvent(
new CustomEvent("aios:share-open", {
detail: { kind: "field", id: shareOid, label: field.label },
})
);
};
/**
* ββ W39-T17 / R8 β MAY THIS VIEWER DELETE THIS COLUMN? The client half of the server's wall,
* spelled with the same creator/admin identity rule as the server rather than a second
* one: `createdBy` is a login username while the people picker deals in display names
* ([[login-resolves-email-writes-do-not]]), and one spelling means a mismatch lands identically
* in both places instead of differently in each.
*
* β THE UNSTAMPED CASE ANSWERS "YES" ON PURPOSE, and it is a deliberate under-reach.
* `routes_tables.delete_shared_field` reads `owner = str(defn.get("createdBy") or "")` and
* refuses a non-admin when it is blank, so an UNSTAMPED shared column is really admin-only. But
* the client cannot tell one from a base Odoo column, which carries no `createdBy` either and
* is deletable by nobody at all β firing there would put a refusal on every source field on the
* grid. So the sentence appears only where the client can NAME the person, which is the only
* shape in which it is useful.
* β IT DOES NOT DISABLE THE DELETE BUTTON, AND THE REASON IS THE `viewer === undefined` LEG,
* not the stratum. The predicate can only fire where `createdBy` is stamped and differs from
* the viewer, which IS the server-walled path β so "a `custom_` delete is client-side" would be
* a rationale describing a case that never reaches here. What does reach here is a host that
* supplied no `viewer` (the payload's field is optional): `mayDeleteField` then answers false
* for the column's OWN CREATOR, and a disable on that would take a delete away from the one
* person who certainly has it. Fail-closed is right for a SENTENCE and wrong for a CONTROL.
* β So a `ut_*` link/rollup/formula created by somebody else shows this line WITH a live Delete
* button beside it, and that button 403s. Stated rather than hidden: the server is the wall,
* this is the courtesy half, and narrowing the button is a separate decision.
*/
const deleteOwner = (field.createdBy ?? "").trim();
const mayDeleteField =
!deleteOwner || (!!viewer && (viewer.isAdmin || deleteOwner === viewer.name));
/**
* ββ W41-T29 (R6, contract C2) β WHAT C1 SAYS ABOUT THIS COLUMN, and what C2 concludes from
* it. Four consts, read once, consumed only by the Delete row far below.
*
* β THE BLOCK ABOVE IS UNTOUCHED, ON PURPOSE. `mayDeleteField` there is the wave-39
* `createdBy` courtesy predicate whose `!deleteOwner` short-circuit is what keeps its sentence
* off every base Odoo column; swapping it for `mayDeleteFieldRight` would print "Only or an
* administrator can delete this field" with a blank name on the entire grid, because C1's
* `class` key is not on the wire yet (C8). The new predicates NARROW; they replace nothing.
*
* β C8, AND THE SPLIT IS DELIBERATE. `presetRefusal` is viewer-INDEPENDENT, so R6(a) bites the
* moment lane A stamps `class` β an absolute rule must not wait on a viewer. `canRemove` and
* the rights check need both halves, and `rightsKnown` is what tells "the predicate said no"
* from "there was nothing to ask": with no classification the Delete row stands exactly as it
* does today rather than vanishing because the server half is late.
*
* β R6(a) VS THE 2026-08-09 PRE-SET-ROLLUP RULING, STATED RATHER THAN HIDDEN. That ruling let
* a pre-set ROLLUP keep its Delete; R6 (wave 41) says a pre-set is deletable by nobody, and it
* is the newer word, so `class.origin` wins here. If lane A classifies a pre-set rollup as
* `preset`, its Delete goes β which is R6(a) working, and worth a look before the wave closes.
*/
const fieldC1 = fieldClassOf(field);
const deletionLocked = fieldDeletionLocked(field);
const presetRefusal = deleteRefusalReason(fieldC1, viewer);
const canRemoveFromMine = mayRemoveField(fieldC1, viewer);
const rightsKnown = fieldC1 !== null && !!viewer;
const c1AllowsDelete =
!deletionLocked && !presetRefusal && !canRemoveFromMine &&
(!rightsKnown || mayDeleteFieldRight(fieldC1, viewer));
return (
<AnchoredOverlay
anchor={state.anchor}
className="cg-column-menu"
onDismiss={onClose}
role="dialog"
ariaLabel={`Column settings for ${field.label}`}
initialFocus={embedded ? "first" : "[data-overlay-autofocus]"}
dismissOnOutside={!embedded}
dataKind="column-menu"
>
<PaneHead title={field.label} sub={embedded ? undefined : typeLine} onClose={onClose} />
{/* Item 8c β any measure-carrying column exposes its PERIOD, the property that defines
it. Item 21 (2026-08-02) moved the EDITOR into the Edit-field pane; what stays here
is one line that STATES the period and opens that pane, because the window is the
first thing you want to know about a metric column and the menu had become the only
place it was written down. A row, not a control: the menu pane edits nothing inline. */}
{canPeriod && canEditDefinition && !schemaLocked && (
<button
type="button"
className="cg-column-periodline"
onClick={() => {
setRenameDraft(field.label);
setPane("edit");
}}
>
<span className="cg-swap-label">Period</span>
<span className="cg-column-periodval">{windowLabel(field.measure!.window)}</span>
</button>
)}
{/* Wave-7 item W4 (contract C6): Airtable's grouping, thin dividers between groups,
an icon on EVERY action. Presentation only β every handler and event is the one it
was before; entries not in Airtable's list slot into the nearest sensible group. */}
<div className="cg-column-actions">
{!embedded && <>
{/* Owner item 8 (2026-07-31) β EDIT FIELD sits at the very top, above Duplicate:
the one window for the field's name, type (with per-type choices/stars/formula)
and the Change-field control. Offered on EVERY field β what a read-only field
cannot change, the pane says honestly instead of hiding the door. */}
{/* ββ W41-T31 β `editPaneOffered`, the THIRD of the three gates that used to hide this
row from a pre-set column (the other two are `canEditDefinition` itself and the pane
seed). A pre-set gets the same row and lands on the description-only pane; every
other field is unaffected, because `canEditDescription` is false for all of them.
β It also gives the MENU pane a focus target on a pre-set for the first time: this
button carries the only `data-overlay-autofocus` in the action list, so while the
row was withheld the menu opened with the keyboard left outside the dialog. */}
{editPaneOffered && (
<button type="button" data-overlay-autofocus onClick={() => {
setRenameDraft(field.label);
setPane("edit");
}}>
<MenuLabel icon="rename" text="Edit field" />
</button>
)}
{/* ββ W39-T17 β SHARE FIELD, directly beneath Edit field, and it opens the SAME dialog
views and folders already use (one editor, one vocabulary: the R10 ruling behind
`shell/ShareDialog.tsx`). NOT gated on `schemaLocked`: sharing a column changes no
schema, it decides who can SEE it, which is the same reason Summary, Sort and Filter
sit below without that gate.
β NO `data-overlay-autofocus` HERE. The overlay's `initialFocus` selector is exactly
that attribute, and a second row wearing it makes the opening focus ambiguous.
β NOT GATED ON THE VIEWER EITHER, deliberately. The dialog itself states the refusal
when `mayAdminister` is false ("NOT A HIDDEN EDITOR β a stated refusal"), and a hidden
row would leave a collaborator guessing why the column they can see is not theirs to
pass on. The one thing that DOES withdraw it is a missing server table key, because
without one the id cannot be built. */}
{onSetDeletionLock && (
<button type="button" onClick={() => onSetDeletionLock(!deletionLocked)}>
<MenuLabel
icon={deletionLocked ? "unlock" : "permissions"}
text={deletionLocked ? "Clear deletion lock" : "Lock deletion"}
/>
</button>
)}
{onCopyFieldLink && (
<button type="button" onClick={onCopyFieldLink}>
<MenuLabel icon="duplicate" text="Copy link to field" />
</button>
)}
{shareOid && (
<button
type="button"
onClick={() => {
openFieldShare();
onClose();
}}
>
{/* β AN INLINE NODE, NOT A `MenuIcon` NAME, and that is forced rather than chosen.
`MenuLabel`'s prop is `MenuIconName | ReactNode` and `ReactNode` admits any
string, so `icon="share"` would COMPILE and paint an empty 16px box forever
(`MENU_ICONS` has no such key, and `icons.tsx` is not this ticket's file).
ββ W40-T24 β THE GEOMETRY IS `SHARE_SHAPE`, NOT A THREE-NODE GRAPH ANY MORE.
The argument that stood here β that the graph is "the mark every product uses for
this verb" β was true of a product where it was the only share drawing. It is not
any more: W40-T20 put `SHARE_SHAPE` (two people) on the grid header's shared-field
sprite and W40-T21 put it on Share view and Share folder, so this row was the last
place one verb spoke in a second drawing β a field whose HEADER wears two people,
shared from a row wearing a graph. DESIGN.md Β§4's "one mark, one meaning" is the
rule and `iconShapes.ts` is the vocabulary; paths as DATA is what stops the two
painters drifting, which is exactly what a hand-written copy here would restart.
β Rendered the way `ViewSidebar.ShareMark` renders it β same viewBox, same 1.35
stroke, same round caps β so the rail's share and this one are one mark and not
two readings of one array. */}
<MenuLabel
icon={
<svg width={16} height={16} viewBox="0 0 16 16" aria-hidden>
{SHARE_SHAPE.map((s) =>
s.fill ? (
<path key={s.d} d={s.d} fill="currentColor" />
) : (
<path
key={s.d}
d={s.d}
fill="none"
stroke="currentColor"
strokeWidth={1.35}
strokeLinecap="round"
strokeLinejoin="round"
/>
)
)}
</svg>
}
text="Share field"
/>
</button>
)}
<div className="cg-menu-sep" role="separator" aria-hidden />
{/* ββ W51-T03 / OWNER RULING R6 + INSTRUCTION 5 β ONE DOOR, NOT TWO VERBS.
W48-T17 shipped "Duplicate definition" and "Duplicate with permitted values" side by
side, which made the reader answer a question about copy semantics before they had
seen the column. Cloning a source-backed definition is still safe for W48-T17's
reason (the result is a new tenant-owned custom field, and the host independently
intersects any submitted cells with this viewer's scope) β what changed is WHERE the
value question is asked. The host opens the shared confirm dialog with a "Duplicate
cells" toggle when the column holds values, and duplicates in one click when it holds
none: a dialog with only one possible answer is a click tax, not a safeguard. */}
{onDuplicate && (
<button type="button" onClick={() => { onDuplicate(); onClose(); }}>
<MenuLabel icon="duplicate" text="Duplicate field" />
</button>
)}
{!viewControlsReadOnly && onMoveLeft && (
<button type="button" onClick={() => { onMoveLeft(); onClose(); }}>
<MenuLabel icon="insertLeft" text="Move left" />
</button>
)}
{!viewControlsReadOnly && onMoveRight && (
<button type="button" onClick={() => { onMoveRight(); onClose(); }}>
<MenuLabel icon="insertRight" text="Move right" />
</button>
)}
{canAddField && <>
<button type="button" onClick={() => setPosition("left")}>
<MenuLabel icon="insertLeft" text="Insert field left" />
</button>
<button type="button" onClick={() => setPosition("right")}>
<MenuLabel icon="insertRight" text="Insert field right" />
</button>
<button type="button" onClick={() => setPosition("end")}>
<MenuLabel icon="addEnd" text="Add field at end" />
</button>
</>}
<div className="cg-menu-sep" role="separator" aria-hidden />
{/* Group 2 β display format. Description now lives in Edit field directly below Name,
so there is one definition editor instead of two nearby doors. */}
{/* Field format is display only, so a pre-set column offers it too. */}
{formatKind && (
<button type="button" onClick={() => setPane("format")}>
<MenuLabel icon="format" text="Field format" />
</button>
)}
{/* β WAVE-29 T33 (owner item 17) β the COLUMN SUMMARY. Offered on every column, because
`count` applies to any type; the numeric folds are filtered per type inside the pane
by `aggOptions`. β NOT gated on `schemaLocked`: a summary is a reading of the column,
not a change to its schema, so it belongs on a pre-set column too β the same reason
Sort and Filter sit below without that gate. */}
{onSummary && (
<button type="button" onClick={() => setPane("summary")}>
{/* ββ W50-T05 / R2 β THE ROW READS THE RESOLVED CHOICE, NOT `field.agg`. The old
label said "Summarize this column" whenever the FIELD carried no `agg`, which
after W50-T03 was true of every column the bar was already totalling by default:
the menu offered to start something that had been running since the view opened.
β "None" is a state a reader chose, so it is named rather than hidden behind the
invitation β the row says what the column does now, in both directions. */}
<MenuLabel
icon="format"
text={`Summary: ${summaryLabel(resolveSummary(field, summary ?? {}))}`}
/>
</button>
)}
{/* ββ WAVE 50 Β· W50-T05 (instruction 4) β SHOW AS, beside Field format and in the same
control vocabulary: one menu row that opens one pane, exactly as Format and Summarize
do (DESIGN.md Β§4 β one control shape per rail). β NOT gated on `schemaLocked`, for
Summarize's reason: how a number READS is not a change to the column's schema, so it
belongs on a pre-set column too.
β `isNumericFieldType` IS THE ELIGIBILITY TEST. A share of a total is meaningless on
text, a date or a checkbox, and a kind list written here would drop `formula`,
`metric` or `rollup` the way ERROR 20 dropped a formula column from the summary. */}
{onShowAs && isNumericFieldType(field.type) && (
<button type="button" onClick={() => setPane("showAs")}>
<MenuLabel
icon="format"
text={`Show as: ${SHOW_AS_LABELS[field.showAs ?? "value"]}`}
/>
</button>
)}
<div className="cg-menu-sep" role="separator" aria-hidden />
</>}
{/* Group 3 β sort. Direction wording stays the shipped per-type directionLabel. */}
{!viewControlsReadOnly && onSort && fieldOfferable && <>
<button type="button" onClick={() => { onSort("asc"); onClose(); }}>
<MenuLabel
icon="sortAsc"
text={`Sort ${directionLabel(field.type, "asc")}`}
/>
</button>
<button type="button" onClick={() => { onSort("desc"); onClose(); }}>
<MenuLabel
icon="sortDesc"
text={`Sort ${directionLabel(field.type, "desc")}`}
/>
</button>
</>}
{!viewControlsReadOnly && onClearSort && sortedDir != null && (
<button type="button" onClick={() => { onClearSort(); onClose(); }}>
<MenuLabel icon="off" text="Don't sort by this field" />
</button>
)}
<div className="cg-menu-sep" role="separator" aria-hidden />
{/* Group 4 β the view-config group: filter Β· group (+ pin, which also shapes
the view). */}
{/* Item 6c: a measure-carrying column's Filter-by seeds the equivalent MEASURE
condition β the designed replacement for filtering the (filterable:false)
column itself (offered only while the host serves measures, the same
availability rule as measure conditions). Everything else keeps the plain
filterable check. */}
{!viewControlsReadOnly && onFilterBy && fieldOfferable && (field.filterable !== false ||
(field.measure != null && measures.length > 0)) && (
<button type="button" onClick={() => { onFilterBy(); onClose(); }}>
<MenuLabel icon="filter" text="Filter by this field" />
</button>
)}
{!viewControlsReadOnly && onClearFilter && isFiltered && (
<button type="button" onClick={() => { onClearFilter(); onClose(); }}>
<MenuLabel icon="off" text="Don't filter by this field" />
</button>
)}
{!viewControlsReadOnly && groupable && !isGrouped && (
<button type="button" onClick={() => { onGroupByField(); onClose(); }}>
<MenuLabel icon="group" text="Group by this field" />
</button>
)}
{!viewControlsReadOnly && isGrouped && (
<button type="button" onClick={() => { onClearGroup(); onClose(); }}>
<MenuLabel icon="off" text="Don't group by this field" />
</button>
)}
{/* Item 11c β pin: freeze the columns up to this one; Unpin restores the identity
column alone. */}
{!viewControlsReadOnly && !embedded && onPinTo && !pinnedTo && (
<button type="button" onClick={() => { onPinTo(); onClose(); }}>
<MenuLabel icon="pin" text="Pin up to this field" />
</button>
)}
{!viewControlsReadOnly && !embedded && onUnpin && (
<button type="button" onClick={() => { onUnpin(); onClose(); }}>
<MenuLabel icon="unpin" text="Unpin all fields" />
</button>
)}
<div className="cg-menu-sep" role="separator" aria-hidden />
{!viewControlsReadOnly && embedded && onColumnWidth && (
<button type="button" onClick={() => {
setWidthDraft(String(Math.round(columnWidth)));
setPane("width");
}}>
<MenuLabel icon="format" text="Column width" />
</button>
)}
{/* Group 5 β hide Β· delete. */}
{!viewControlsReadOnly && <button
type="button"
disabled={locked}
title={locked ? "The primary field stays visible" : undefined}
onClick={onHide}
>
<MenuLabel icon="hide" text="Hide field" />
</button>}
{!embedded && <>
{/* ββ WAVE-34 (owner ruling R13) β THE BULK RUN, and it is TWO rows rather than one
because "run this column" is two different questions with two different bills.
β NEITHER LABEL SAYS "everything". `ai_enrich_may_write` refuses a human-edited cell
under every policy, so "All rows" means every row the AI wrote; saying "all" flat
would be a control that quietly means less than it says, which is worse than a
narrower control. The server takes these as `scope: "blank" | "always"`.
β `onEnrich` is OPTIONAL, exactly as `onDelete` above it is: a host that has not
wired the door renders no row rather than a row that does nothing.
β THE GLYPH IS `FieldTypeIcon`, NOT A `MenuIcon` NAME, and that is not a style
choice. `MenuLabel`'s prop is `MenuIconName | ReactNode`, and `ReactNode` admits
any string, so `icon="sparkle"` COMPILES and renders an empty glyph box forever
(`MENU_ICONS` has no such key). Reusing the type icon paints the same mark the
column header and the add-field picker already wear, from one geometry source, and
needs no new key in a file no lane owns. [[schema-role-is-not-a-value-wall]] */}
{field.type === "ai_enrich" && onEnrich && (
<>
<button
type="button"
title="Fills only the cells that are still empty. Costs nothing for rows that already have an answer."
onClick={() => onEnrich("blank")}
>
<MenuLabel icon={<FieldTypeIcon type="ai_enrich" size={16} />}
text="Fill rows never filled" />
</button>
<button
type="button"
title="Re-asks the model for every row the AI wrote. A cell you have typed into is left alone."
onClick={() => onEnrich("always")}
>
<MenuLabel icon={<FieldTypeIcon type="ai_enrich" size={16} />}
text="Fill all rows again" />
</button>
</>
)}
{/* ββ W40-T24 (contract C2) β `offer.remove` IS THE PRE-SET LOCK, ADDED BESIDE the two
conditions that were already here rather than replacing either. `onDelete` asks
whether the host wired a delete DOOR at all (it has three, one per stratum) and
`schemaLocked` is `CustomerGrid.isSchemaLocked`; AND-ing a third refusal can only
subtract, so nothing is duplicated and no working delete is widened.
β On the Odoo grids this is behaviour-neutral: a pre-set column already had no door,
so Delete never rendered. What changes is that the absence is now the LOCK's answer
rather than a coincidence of wiring, which is the half of D-413 the client can settle.
β The pre-set ROLLUP keeps its Delete, by the 2026-08-09 owner ruling `isSchemaLocked`
already carries. `columnDefinitionOffer` restates that exception rather than dropping
it β see its note. */}
{/* ββ W41-T29 (R6(b)) β REMOVE FROM MY FIELDS, and it stands WHERE Delete would have
stood. `canRemoveFromMine` has already withdrawn the Delete row below, so the two are
mutually exclusive by construction rather than by ordering: a column a colleague
shared with me is theirs to destroy and mine only to hand back.
β NOT `is-danger`, and not `onDelete`. Dropping a share deletes nothing, so it takes
neither the destructive colour nor the destructive door. Wiring this label to
`onDelete` would be the one failure this ticket must not ship. */}
{!schemaLocked && canRemoveFromMine && onRemoveFromMine && (
<button type="button" title={REMOVE_FIELD_HINT} onClick={onRemoveFromMine}>
{/* β A NODE, NOT A NAME, AND `MenuLabel` DOCUMENTS THIS ESCAPE HATCH FOR IT. The
nearest name in the vocabulary is `hide`, and hiding is a DIFFERENT act this very
panel already offers on the checkbox: one glyph for both would say a removal is
reversible from the same place a hide is. The minus mark is the Fields manager's
own remove mark, so the two surfaces wear one picture. */}
<MenuLabel
icon={
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden>
<circle cx="8" cy="8" r="5.7" stroke="currentColor" strokeWidth={1.3} />
<path d="M5.5 8h5" stroke="currentColor" strokeWidth={1.3} strokeLinecap="round" />
</svg>
}
text={REMOVE_FIELD_LABEL}
/>
</button>
)}
{/* ββ W41-T29 (R6(a)) β A PRE-SET SAYS IT CANNOT BE DELETED, instead of a Delete row
that is simply absent. `c1AllowsDelete` below is what withdraws the row; this is the
sentence that stops the absence reading as a wiring accident.
β DESIGN Β§4, THE THREE LOCKS: the copy is about the DEFINITION (this column came with
the database). It is NOT "you cannot type here" β that is a LOCKED DATABASE, another
lock entirely β and it is not a locked view. A pre-set field's cells stay typeable.
β `.cg-field-hint`, NOT A `MenuLabel` ROW, for the reason W39-T17 measured two rows
down: `.cg-column-actions button` is `white-space: nowrap` and `.cg-mi-text`
ellipsises, so a sentence in a menu row is clipped at exactly the half that carries
the reason. The 8px inset matches that hint's, so the two align. */}
{/* β GATED ON THE DELETE ROW'S OWN THREE CONDITIONS, and that is the difference between
an answer and chrome. `columnDefinitionOffer.remove` is FALSE for every base Odoo
column (`ownShape` false, no `route_order` kind, not a rollup), so those columns never
had a Delete row for this sentence to explain, and an ungated refusal would grow one
paragraph on every pre-set column in the product the day lane A stamps `class`.
The refusal belongs only where a delete WOULD otherwise have stood. Same narrowing
the Fields manager makes with `deletableKeys?.has(f.key)`, for the same reason. */}
{presetRefusal && !schemaLocked && offer.remove && onDelete && (
<p className="cg-field-hint" style={{ padding: "2px 8px 4px" }}>
{presetRefusal}
</p>
)}
{deletionLocked && !schemaLocked && offer.remove && onDelete && (
<p className="cg-field-hint" style={{ padding: "2px 8px 4px" }}>
Deletion is locked. An Owner must clear the deletion lock before this field can be deleted.
</p>
)}
{!schemaLocked && offer.remove && onDelete && c1AllowsDelete && (
<button
type="button"
className="is-danger"
title={
/**
* β 2026-08-10 β THE PRE-SET ROLLUP COMES BACK, and the honest place to say so is
* here rather than in a tombstone.
*
* A pre-set column carries `automation.preset`, and BOTH reconcilers
* (`_reconcile_ig_graph_fields`, `odoo_relational`'s forward migration) re-declare
* every field they own on the next run. RECONFIGURING one sticks β the custody
* stamp (`userEdited`) switches the reconciler off for that column β but DELETING
* one leaves nothing behind to carry a stamp, so it is re-added within a tick.
* β NOT FIXED WITH A TOMBSTONE, deliberately: that is a new store key two
* reconcilers must both consult, and the custody stamp is the precedent for how
* that goes wrong when only one of them reads it. The delete is not broken β it is
* a delete of something the product re-declares, and the user is told which.
*/
/**
* ββ W41-T29 (R6(c)) β THE ARMED STATE NAMES WHO LOSES IT, and it is prepended as
* one more branch rather than replacing the four below: unarmed, the question is
* still "what does this button do to my values", and that is what they answer.
* β NO INDIVIDUAL IS NAMED AND THE COPY SAYS SO. C1 carries no grantee list and C8
* carries five integers and not one identity, so the impact is the OWNER plus the
* audience CATEGORY plus counts, closing on "counted rather than named". A tally
* that reads as exhaustive beside a delete button is worse than no tally.
*/
field.measure
? "Removes this formula column from the workspace."
: field.automation?.preset === true
? "Part of this database's built-in schema. It will be re-created on the " +
"next run. Hide it to keep it off the grid."
: field.type === "rollup" || field.type === "link" ||
field.type === "formula"
? "Removes this column. No values are lost. It holds none of its own."
: "Removes this field AND its values on every row."
}
/* R6(c) for a reader who cannot hover: `title` is not an accessible name, so the
armed impact is given one. Unarmed, the visible label is the name it always was. */
onClick={onDelete}
>
<MenuLabel
icon="trash"
text="Delete field"
/>
</button>
)}
{/* ββ W39-T17 / R8 β A FIELD YOU CANNOT DELETE SAYS WHO CAN, which nothing in this menu
did: the only place a creator was ever named is the permissions pane's parenthetical
`(created by X)`, which a person has to open a different window to read.
`routes_tables.delete_shared_field` refuses everyone but the stamped `createdBy` and
an admin, and it refuses at the SERVER β so without this the menu either hides the row
with no reason given or offers a button whose only outcome is a 403.
β NOT A `MenuLabel` ROW, and the reason is measured in `index.css`:
`.cg-column-actions button` is `white-space: nowrap` and `.cg-mi-text` ellipsises, so
a sentence in a menu row would render as "Only alice or an administrβ¦" β the half that
names the person is exactly the half that gets cut. `.cg-field-hint` is this file's
existing wrapping prose class (36 uses), so no rule is owed in a stylesheet this
ticket does not own.
β NO DASH IN IT (standing rule 2): the nearest precedent, `ShareDialog`'s own
refusal, carried two em dashes, and copying its shape is how the dash travels. */}
{!mayDeleteField && (
/* β The 8px inset is INLINE because it is the only thing this row needs from a
stylesheet and `index.css` is not this ticket's file. `.cg-column-actions` has no
horizontal padding of its own (its BUTTONS carry `0 8px`), so a bare hint would sit
8px left of every label above it and read as belonging to the panel rather than to
the Delete row it explains. */
<p className="cg-field-hint" style={{ padding: "2px 8px 4px" }}>
Only {deleteOwner} or an administrator can delete this field.
</p>
)}
</>}
</div>
</AnchoredOverlay>
);
}
import { Fragment, useMemo, useRef, useState } from "react";
// ββ W46-T31 (contract C6) β the lane's sheet, imported from the COMPONENT rather than added to
// `index.css`. An @imported sheet is inlined at the top of the cascade and loses every
// equal-specificity fight below it. [[a-lane-stylesheet-cannot-override-index-css]]
import "../styles/wave46/field-panels.css";
// β W36-T07 (owner item 10) β the field agent. Its own module for `ColumnMenu`'s own reason:
// this file pulls the whole grid and cannot load under a node gate, so the chat had to sit
// where a test can render it.
import { FieldAgentChat } from "./FieldAgentChat";
import type { FieldProposal } from "./fieldAgent";
// ββ W50-T06 (owner instruction 5 / R5) β the formula editor. Its own module for the same
// reason `FieldAgentChat` is: this file cannot load under a node gate, and `verify_ui.py`
// compiles `FormulaEditor.tsx` ALONE to run its catalogue reader against a frozen C2 fixture.
import { FormulaEditor, stripLeadingEquals } from "./FormulaEditor";
import { emptyIfDefinition, IfStatementEditor } from "./IfStatementEditor";
import { AnchoredOverlay } from "./OverlaySurface";
import type { AnchorRect } from "./OverlaySurface";
import { FieldTypeIcon, MenuLabel } from "./icons";
import { FieldSelectButton } from "./FieldSelect";
// ββ W40-T24 β the pre-set definition lock. It lives in `display.ts` rather than here because a
// rule stated inside JSX cannot be LOADED by a node gate; `display.ts`'s header carries the full
// argument, and `_test/gridUx.test.ts` is what runs it.
import { columnDefinitionOffer } from "./display";
// ββ W40-T29 β the ADVANCED grouping is a pure function in `types.ts` for the reason
// `columnDefinitionOffer` sits in `display.ts`: this file imports React, so nothing stated inside
// it can be LOADED by a node gate, and "which types are advanced" is exactly the kind of decision
// that must be runnable rather than read back to itself as source text.
import { AUDIT_FIELD_TYPES, CODE_LANGUAGE_LABELS, CODE_LANGUAGES, CREATABLE_TYPES, choiceOptions, choiceRemovalMessage, choiceRenames,
codeLanguageOf, directionLabel, groupTypePickerRows, isDerivedLink, isMachineOwned,
isNumericFieldType, isOfferableField, isProfileField, offerableCreateKind, parseOptions, ratingMax,
ROLLUP_FN_LABELS, ROLLUP_FNS, ROLLUP_PRESET_FNS, ROLLUP_PRESETS, rollupPresetOf,
serverOptionLimit,
filterTreeConj, filterTreeNodes, linkSelectionFilterIssue, offerableFields, TYPE_DESCRIPTIONS,
ROLLUP_REF_OPS, mayEditFieldDefinition, ifDefinitionIssue } from "./types";
import type { Conjunction, Field, FieldFormat, FieldScope, FieldType, FilterNode, FilterTree, Measure,
IfDefinition, RollupCondition, RollupFn, RollupPreset, RollupRefOp, RollupSource, ShowAs, SummaryChoice,
SummaryMap, Viewer } from "./types";
import type { HopTopic, HopTopicOffer, LinkTarget, RollupSourceOffer } from "./apiBridge";
import type { WindowSpec } from "./windows";
import { normalizeWindow, windowLabel } from "./windows";
import { FilterBuilderPanel, WindowPicker } from "../filter-kit";
// ββ W41-T29 (R6, contract C2) β the ONE pair of rights predicates plus the copy that says what
// they refused, read from the same module the Fields manager reads. C2: no surface re-implements
// either test, so this menu asks rather than deriving a second answer of its own.
// β `mayDeleteField` IS IMPORTED UNDER AN ALIAS. This file already binds that identifier as a
// local `const` (the wave-39 `createdBy` courtesy sentence, ~40 lines below), and shadowing an
// import with a same-named local is a `tsc` error rather than a silent win.
// β W41-T31 (instruction 1, R19) β the description-only arm's THREE strings and its two
// predicates come from the same module, for the same C2 reason: this pane is not a second
// producer of a sentence, and `descriptionEditedOf` is C8's strict reader (absent is not false).
import {
DESCRIPTION_RESET_LABEL,
deleteRefusalReason,
descriptionResetOffered,
fieldClassOf,
mayRemoveField,
mayDeleteField as mayDeleteFieldRight,
PRESET_DESCRIPTION_ONLY_HINT,
REMOVE_FIELD_HINT,
REMOVE_FIELD_LABEL,
} from "../filter-kit/fieldClass";
import { SHARE_SHAPE, TYPE_LABELS } from "./iconShapes";
// ββ W50-T05 / R2 β **`aggOptions` AND `AGG_LABELS` ARE GONE FROM THIS FILE, DELIBERATELY.**
// R2 moved the column summary off `field.agg` and onto `ViewConfig.summary`, and this menu was
// named in W50-T03's own note as the last writer of the retired store. It now offers the SAME
// vocabulary the bottom bar offers (`summaryOptions`) and reads the SAME resolution
// (`resolveSummary`), so one column cannot say "Summary: Sum" in its header menu while the bar
// under it folds something else β which is exactly what two doors onto one stored value costs
// when they are two vocabularies as well.
import { resolveSummary, summaryLabel, summaryOptions } from "./aggregations";
// β W50-T05 β the "Show as" vocabulary and its words, from the module that owns the
// composition (`withShare`). Written here would be a fourth spelling of three modes.
import { SHOW_AS_LABELS, SHOW_AS_MODES } from "../ui/fmt";
import { validateFormula } from "./formulaEngine";
import { BRAND_SWATCHES, defaultOptionColor, nearestSwatch, normalizeOptionColor,
OPTION_PALETTE } from "./choiceColors";
import { fieldDeletionLocked } from "./FieldProperties";
import type { ChoiceRemoval } from "./apiBridge";
export interface ColumnMenuState {
fieldKey: string;
anchor: AnchorRect;
/**
* Item 12 (R8) β which pane this opening lands on. Absent = the action list, i.e. every
* pre-wave-26 opening. `"edit"` is the kanban's "Add option" door.
*
* β Narrowed to the ONE pane that has a door rather than the whole `MenuPane` union: widening
* it would let any future caller deep-link into `permissions`, whose entry is gated on the
* viewer inside the menu's own action list β a state you can only reach through a check would
* become a state you can reach around it.
*/
pane?: "edit";
}
interface FieldConfigExtra {
defaultValue?: Field["defaultValue"] | null;
if?: IfDefinition;
formula?: string;
max?: number;
scope?: FieldScope;