Deploy AIOS web (React glide grid + FastAPI slice)
Browse filesFiles changed (10)
123456{"current": "4da0f5e","releases": [{"version": "v70","sha": "eedfb6a",123456789101112{"current": "fb77fa5","releases": [{"version": "v71","sha": "96143dc","date": "2026-09-04","subject": "release v71 - wave 51, QA'd 24 PASS / 6 FAIL / 5 UNPROVEN"},{"version": "v70","sha": "eedfb6a",
14da0f5e1fb77fa5
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576"""routes_connected_tables.py β the SOURCE-NEUTRAL door to a connected grid (W31-T49, contract C4).`GET /api/v1/connected-tables/{table_key}/rows` β one window over any grid whose rows come from aconnector and are read THROUGH the per-tenant DuckDB mirror rather than copied into the tenantdocument. Odoo's four locked databases and its two line grains today; Meta Ads' entity and Insightsgrids when `meta_relational` registers its specs (R2).β WHY THIS FILE EXISTS. The read-through window shipped in wave 30 inside `routes_odoo_tables.py`,Odoo-named down to the URL β `/api/v1/odoo-tables/{key}/rows`. R2 puts a SECOND connector on thesame mirror, and a Meta campaign served from a URL with `odoo` in it is a name that lies to everyreader of a network tab, a log line and a bug report. So the capability gets a name that describeswhat it IS.ββ IT IS AN ALIAS, NOT A REIMPLEMENTATION, AND THAT IS THE WHOLE DESIGN. T49's `done-when` is*"the Odoo path behaves byte-identically, proven by an NC"*. There are two ways to make that true:write a second handler and test that the two agree, or have ONE handler behind two URLs. Only thesecond is true BY CONSTRUCTION β the first is true on the day it is written and drifts the firsttime somebody fixes a bug in one of them. Every request here lands in`routes_odoo_tables.odoo_table_rows`, unchanged, so the two doors cannot disagree without a linebeing deleted. [[one-question-two-normalizers]]β THE OLD URL STAYS, and that is not politeness to a client we control. `CustomerGrid`'s bridge,saved views and anything an operator has in a browser tab all name it; retiring it in the same wavethat introduces the new one would turn a rename into an outage for a feature that is alreadyhalf-proven (D-174). The Odoo-named route is kept as a deliberate alias with a stated retirementcondition rather than as a leftover: it goes when nothing in `web/src` names it.β THE MOUNT IS THE POINT AND IT HAS BEEN MISSED BEFORE β three finished routers shipped 404-deadbehind green gates in wave 23, and wave 28 proved a MOUNTED router can still be uncallable(`session.is_admin`, an attribute that does not exist, raising above the route's own `try`). So`verify_meta` both enumerates `main.app.routes` for this path AND calls it."""from fastapi import APIRouter, Depends, Queryfrom deps import Session, require_sessionrouter = APIRouter(prefix="/api/v1")@router.get("/connected-tables/{table_key}/rows")def connected_table_rows(table_key: str,offset: int = Query(default=0, ge=0),limit: int = Query(default=0),filters: str = Query(default=None),filterConj: str = Query(default="and"),sorts: str = Query(default=None),search: str = Query(default=None),related: str = Query(default=None),session: Session = Depends(require_session)):"""ONE WINDOW over a connected grid β `{fields, rows, total, totalUnfiltered, offset, limit,limits, identity, recordsMutable}`, whichever connector the rows come from.β EVERY GUARANTEE IS INHERITED, NOT RESTATED, because the body below is one call. `total` is a`SELECT count(*)` and never `len(rows)`; the filter, sort and search resolve in SQL over thewhole table; anything that cannot be answered is reported in `limits` with a cause and arecommendation (R6's second sentence); the permission wall is `_defn_or_refuse`; and thecross-tenant mirror guard (D-169) refuses with `409 cross_tenant_store` before a cursor ishanded out. Documenting them again HERE would be a second statement of a contract that has onehome β and the day the two drifted, this file would be the one that lied."""# ββ `related` MUST BE FORWARDED, AND OMITTING IT DID NOT MERELY DROP THE PIN -- IT 400ed# THE WHOLE DOOR. This body calls `odoo_table_rows` as a PLAIN PYTHON FUNCTION, so an argument# left out does not become `None`: it becomes the `Query(default=None)` SENTINEL OBJECT that# FastAPI would have replaced. W51-T05 added `related` to that signature, and its guard reads# `related in (None, "", {})` then `isinstance(related, dict)` -- a `Query` instance is none of# those, so every ordinary paged read of a connected table raised# `400 bad_relation` on the merged tree. NINE `api_meta` legs, 480/480 -> 471/480.# β NEITHER LANE COULD SEE IT. Lane A owned the new parameter and its own gates never call# this door; `api_meta` owns this door and was green at the lane base. It exists only in the# combination -- the wave-50 `api_scopes` shape [[a-cached-value-outruns-the-permission-wall]].# β The harvest predicted the SMALLER version of this (lane A booked "connected_table_rows# silently DROPS the param"); the measured consequence was a refusal, not a silent drop.import routes_odoo_tablesreturn routes_odoo_tables.odoo_table_rows(table_key, offset=offset, limit=limit, filters=filters, filterConj=filterConj,sorts=sorts, search=search, related=related, session=session)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576"""routes_connected_tables.py β the SOURCE-NEUTRAL door to a connected grid (W31-T49, contract C4).`GET /api/v1/connected-tables/{table_key}/rows` β one window over any grid whose rows come from aconnector and are read THROUGH the per-tenant DuckDB mirror rather than copied into the tenantdocument. Odoo's four locked databases and its two line grains today; Meta Ads' entity and Insightsgrids when `meta_relational` registers its specs (R2).β WHY THIS FILE EXISTS. The read-through window shipped in wave 30 inside `routes_odoo_tables.py`,Odoo-named down to the URL β `/api/v1/odoo-tables/{key}/rows`. R2 puts a SECOND connector on thesame mirror, and a Meta campaign served from a URL with `odoo` in it is a name that lies to everyreader of a network tab, a log line and a bug report. So the capability gets a name that describeswhat it IS.ββ IT IS AN ALIAS, NOT A REIMPLEMENTATION, AND THAT IS THE WHOLE DESIGN. T49's `done-when` is*"the Odoo path behaves byte-identically, proven by an NC"*. There are two ways to make that true:write a second handler and test that the two agree, or have ONE handler behind two URLs. Only thesecond is true BY CONSTRUCTION β the first is true on the day it is written and drifts the firsttime somebody fixes a bug in one of them. Every request here lands in`routes_odoo_tables.odoo_table_rows`, unchanged, so the two doors cannot disagree without a linebeing deleted. [[one-question-two-normalizers]]β THE OLD URL STAYS, and that is not politeness to a client we control. `CustomerGrid`'s bridge,saved views and anything an operator has in a browser tab all name it; retiring it in the same wavethat introduces the new one would turn a rename into an outage for a feature that is alreadyhalf-proven (D-174). The Odoo-named route is kept as a deliberate alias with a stated retirementcondition rather than as a leftover: it goes when nothing in `web/src` names it.β THE MOUNT IS THE POINT AND IT HAS BEEN MISSED BEFORE β three finished routers shipped 404-deadbehind green gates in wave 23, and wave 28 proved a MOUNTED router can still be uncallable(`session.is_admin`, an attribute that does not exist, raising above the route's own `try`). So`verify_meta` both enumerates `main.app.routes` for this path AND calls it."""from fastapi import APIRouter, Depends, Queryfrom deps import Session, require_sessionrouter = APIRouter(prefix="/api/v1")@router.get("/connected-tables/{table_key}/rows")def connected_table_rows(table_key: str,offset: int = Query(default=0, ge=0),limit: int = Query(default=0),filters: str = Query(default=None),filterConj: str = Query(default="and"),sorts: str = Query(default=None),search: str = Query(default=None),related: str = Query(default=None),session: Session = Depends(require_session)):"""ONE WINDOW over a connected grid β `{fields, rows, total, totalUnfiltered, offset, limit,limits, identity, recordsMutable}`, whichever connector the rows come from.β EVERY GUARANTEE IS INHERITED, NOT RESTATED, because the body below is one call. `total` is a`SELECT count(*)` and never `len(rows)`; the filter, sort and search resolve in SQL over thewhole table; anything that cannot be answered is reported in `limits` with a cause and arecommendation (R6's second sentence); the permission wall is `_defn_or_refuse`; and thecross-tenant mirror guard (D-169) refuses with `409 cross_tenant_store` before a cursor ishanded out. Documenting them again HERE would be a second statement of a contract that has onehome β and the day the two drifted, this file would be the one that lied."""# ββ `related` MUST BE FORWARDED, AND OMITTING IT DID NOT MERELY DROP THE PIN -- IT 400ed# THE WHOLE DOOR. This body calls `odoo_table_rows` as a PLAIN PYTHON FUNCTION, so an argument# left out does not become `None`: it becomes the `Query(default=None)` SENTINEL OBJECT that# FastAPI would have replaced. W51-T05 added `related` to that signature, and its guard reads# `related in (None, "", {})` then `isinstance(related, dict)` -- a `Query` instance is none of# those, so every ordinary paged read of a connected table raised# `400 bad_relation` on the merged tree. NINE `api_meta` legs, 480/480 -> 471/480.# β NEITHER LANE COULD SEE IT. Lane A owned the new parameter and its own gates never call# this door; `api_meta` owns this door and was green at the lane base. It exists only in the# combination -- the wave-50 `api_scopes` shape [[a-cached-value-outruns-the-permission-wall]].# β The harvest predicted the SMALLER version of this (lane A booked "connected_table_rows# silently DROPS the param"); the measured consequence was a refusal, not a silent drop.import routes_odoo_tablesreturn routes_odoo_tables.odoo_table_rows(table_key, offset=offset, limit=limit, filters=filters, filterConj=filterConj,sorts=sorts, search=search, related=related, session=session)
489 unmodified lines490491492493494495489 unmodified linesst=session.runtime))except Exception: # noqa: BLE001return Falsetry:import core.table_store as table_storeexcept Exception: # noqa: BLE001489 unmodified lines490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519489 unmodified linesst=session.runtime))except Exception: # noqa: BLE001return Falseif kind == "workbook":# ββ W51 GO-LIVE QA β WITHOUT THIS BRANCH THE SHARE DIALOG COULD NEVER POPULATE, FOR# ANYBODY, INCLUDING THE PERSON WHO MADE THE WORKBOOK.# W51-T25 widened `core.shares.KINDS` with `workbook` and gave `routes_sheet` its own# POST/DELETE `/sheets/{id}/shares` doors, but the dialog READS through this generic# route. A workbook that has never been shared has no grant record, so `role_for`# answers None and `get_share` falls to this predicate β which had no `workbook` case# and dropped through to the view/folder loop below, where `find_folder` can never# match a workbook id. Every caller got `404 no_object`, and `ShareDialog.tsx`'s# own 4xx guard rendered "cannot be shared yet" over a feature that had shipped.## β ONE ANSWER TO "WHO OWNS A WORKBOOK", which is the same discipline the `database`# branch states one block up. `routes_sheet._role_on_workbook` is what `_require_owner`# β C5's write wall on the share doors β consults, so reusing it means the dialog and# the doors it drives cannot come to hold two opinions about who may administer.# Re-deriving ownership from `created_by` here would be that second definition.try:import routes_sheet as _rsfrom core import sheets as _sheetsbook = _sheets.get_workbook(_rs._store(session), oid)return bool(book) and _rs._role_on_workbook(session, book) == "owner"except Exception: # noqa: BLE001# Fail CLOSED, like every sibling branch: an unreadable workbook is not an owned one.return Falsetry:import core.table_store as table_storeexcept Exception: # noqa: BLE001
26 unmodified lines27282930313233343536373826 unmodified lines#: months). A BU grant admits its own brand AND the dual-brand customers: a Both customer IS a#: Fisch customer. Mirrors `perm_scope._DBA_TEAM`, inverted.#:#: β TWO VALUES, AND THE COLUMN VOCABULARY HAS NO "IS ANY OF". `FILTER_OPS` is single-valued by#: design (`eq`, `neq`, `contains`, β¦) β `anyOf` belongs to the COHORT vocabulary and is#: deliberately DISJOINT from it, so a column leaf carrying `anyOf` is refused by every engine#: (`filter_eval` returns False, `clean_filter_tree` drops it). This migration's first draft#: emitted exactly that and `reconcile()` caught it as two lost customers. So the BU condition#: is an OR GROUP of `eq` leaves, which is what the condition builder itself produces._TEAM_DBA = {5: ('Fisch', 'Both'), 6: ('Royal', 'Both')}26 unmodified lines2728293031323334353637383940414243444526 unmodified lines#: months). A BU grant admits its own brand AND the dual-brand customers: a Both customer IS a#: Fisch customer. Mirrors `perm_scope._DBA_TEAM`, inverted.#:#: β TWO VALUES, AND THIS MIGRATION EMITS AN OR GROUP OF `eq` LEAVES.#: Its first draft emitted a cohort-vocabulary `anyOf` leaf, which every engine refused#: (`filter_eval` returned False, `clean_filter_tree` dropped it), and `reconcile()` caught it#: as two lost customers. The OR group is what the condition builder produced then, it is what#: `perm_scope._group_dba_team` recognises, and it is left alone: a migration is not the place#: to change a stored wall's shape.#:#: ββ WHAT CHANGED UNDER THIS COMMENT: **W51-T07 GAVE THE COLUMN VOCABULARY ITS OWN "IS ANY#: OF"** β `aios_grid.FILTER_OPS` now carries `isAnyOf, isNoneOf, hasAnyOf, hasAllOf, hasNoneOf`#: with the operand in a `values` LIST. So the old claim that `FILTER_OPS` is single-valued and#: that only cohorts have `anyOf` is FALSE, and reading it as still true is how the wave-51#: go-live QA found `dba isAnyOf [...]` pinning no pool at all. `perm_scope._PUSHDOWN_OPS` now#: admits `isAnyOf`; this migration's output shape is unchanged._TEAM_DBA = {5: ('Fisch', 'Both'), 6: ('Royal', 'Both')}
1144 unmodified lines114511461147114811491150115111521153115486 unmodified lines1241124212431244124512461247124812491250125112522 unmodified lines125512561257125812591260126112621263126412651144 unmodified lines#: filter admitting Fisch admits {Fisch, Both} β a Both customer IS a Fisch customer._DBA_TEAM = ((frozenset({'fisch', 'both'}), 5), (frozenset({'royal', 'both'}), 6))#: Only equality pushes down. `FILTER_OPS` is single-valued (there is no column-level "is any#: of" β that vocabulary belongs to cohort leaves and is disjoint), so a multi-value BU#: condition arrives as an OR GROUP of `eq` leaves, handled by `_group_dba_team` below._PUSHDOWN_OPS = frozenset({'eq'})#: β THE MODULES WHOSE FIELD VOCABULARY CAN EXPRESS A BUSINESS UNIT β i.e. whose canonical#: contract carries a `dba` column. R1's "BU access is just a permanent filter" holds only on86 unmodified linesif tid is not None:team_id = tid if team_id in (None, tid) else Nonecontinueif n.get('op') not in _PUSHDOWN_OPS:continuecol = n.get('colId')raw = n.get('value')if col == 'dba':vals = {v.strip().lower() for v in str(raw or '').split(',') if v.strip()}if not vals:continuefor allowed, tid in _DBA_TEAM:2 unmodified linesteam_id = tid if team_id in (None, tid) else Nonebreakelif col == 'agent':v = str(raw or '').strip()# A SET of agents cannot become the pool's single `agent_name`; the post-filter# handles it. Only an unambiguous single value pushes down.if v and ',' not in v:agent = vreturn team_id, agent1144 unmodified lines114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119386 unmodified lines1280128112821283128412851286128712881289129012911292129312942 unmodified lines129712981299130013011302130313041305130613071144 unmodified lines#: filter admitting Fisch admits {Fisch, Both} β a Both customer IS a Fisch customer._DBA_TEAM = ((frozenset({'fisch', 'both'}), 5), (frozenset({'royal', 'both'}), 6))#: The operators a leaf may pin a pool with.#:#: ββ THIS COMMENT USED TO SAY `FILTER_OPS` IS SINGLE-VALUED AND THAT THERE IS NO COLUMN-LEVEL#: "IS ANY OF". **W51-T07 FALSIFIED BOTH HALVES** (`aios_grid.FILTER_OPS` now carries#: `isAnyOf, isNoneOf, hasAnyOf, hasAllOf, hasNoneOf`), and the stale sentence is exactly why#: nobody saw what it cost: `ModulePermsList.tsx:254` mounts the SAME `FilterBuilderPanel` the#: grid toolbar does, so `dba is any of Fisch, Both` β the obvious way to write the BU rule now β#: became authorable while this set still refused to read it.#:#: β AND THE FAILURE IS ON THE VALUES AXIS, NOT THE ROWS AXIS, WHICH IS WHY IT LOOKS FINE.#: `permits()` evaluates the whole tree, so the row LIST stays correct; but an unrecognised leaf#: leaves `team_id` None, and `customer_data._pool_build` then computes `rev`, `ly`, `ltm`, `aov`,#: `est_missed` and the derived `status` over BOTH business units under that correct-looking#: list. That is the amendment-3 defect this module's own `derive_pool_scope` docstring names.#:#: `isAnyOf` is admitted because it is the SAME NARROWING as the OR group of `eq` leaves#: `perm_migrate.filter_for` writes and `_group_dba_team` already recognises β a positive subset#: test over a closed value set. Its operand is the leaf's `values` LIST, never `value`.#: β `isNoneOf` / `contains` are deliberately NOT here: reading an exclusion needs the closed#: brand universe, which is a second inference with its own failure mode. They fall to the#: documented default β not recognised, not pushed down, rows still walled β and are booked._PUSHDOWN_OPS = frozenset({'eq', 'isAnyOf'})#: The subset of `_PUSHDOWN_OPS` whose operand is `values` rather than `value`._MULTI_VALUE_PUSHDOWN_OPS = frozenset({'isAnyOf'})def _leaf_values(node, op):"""The leaf's operand as a list of stripped strings, whichever spelling it uses.β THE TWO SPELLINGS ARE NOT INTERCHANGEABLE AND READING THE WRONG ONE IS SILENT.A multi-value leaf persists `values` as a REAL LIST and leaves `value` blank(`aios_grid.clean_filter_tree`), so `str(node.get('value'))` on an `isAnyOf` leaf yields`''` β an empty set, which every test below then skips rather than refuses.A single-valued leaf keeps the historical comma-split, because that is what the `eq` branchhas always accepted here."""if op in _MULTI_VALUE_PUSHDOWN_OPS:raw = node.get('values')if not isinstance(raw, list):return []return [str(v).strip() for v in raw if str(v).strip()]return [v.strip() for v in str(node.get('value') or '').split(',') if v.strip()]#: β THE MODULES WHOSE FIELD VOCABULARY CAN EXPRESS A BUSINESS UNIT β i.e. whose canonical#: contract carries a `dba` column. R1's "BU access is just a permanent filter" holds only on86 unmodified linesif tid is not None:team_id = tid if team_id in (None, tid) else Nonecontinueop = n.get('op')if op not in _PUSHDOWN_OPS:continuecol = n.get('colId')# ββ ONE READ FOR BOTH SPELLINGS. `eq` carries `value`, `isAnyOf` carries `values`;# see `_leaf_values` for why reading the wrong one fails silently rather than loudly.parts = _leaf_values(n, op)if col == 'dba':vals = {v.lower() for v in parts}if not vals:continuefor allowed, tid in _DBA_TEAM:2 unmodified linesteam_id = tid if team_id in (None, tid) else Nonebreakelif col == 'agent':# A SET of agents cannot become the pool's single `agent_name`; the post-filter# handles it. Only an unambiguous single value pushes down β which is the same# test for `agent eq "Tara"` and for `agent isAnyOf ["Tara"]`.if len(parts) == 1:agent = parts[0]return team_id, agent
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586// ---------------------------------------------------------------------------// customer-grid / SwipeView.tsx// β WAVE-27 item 8 (owner ruling R2, contract C3) β the SWIPE deck.//// One record at a time, decided left or right into two options of ONE// single-select. R2 fixes the shape and it is narrow on purpose:// Β· SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.// Β· the deck holds only the records whose bound field is EMPTY β a record// that already has a value has been decided, and re-asking is not triage.// Β· a swipe writes through the NORMAL cell door (`onSwipe`, which the host// maps to the same `patchAndRecord` a kanban card move uses), so undo,// echo-suppression and the permission wall all hold without being// re-implemented here.//// Honesty rules carried from the other modes:// Β· nothing is silently hidden β the deck states what is left, and the// empty state names the bound field rather than saying "all done".// Β· a lost binding is SHOWN, never repaired by guessing. `_clean_display`// validates that `fieldKey` names a field the table HAS and stops there;// it cannot know the field is still a select, or that the two options are// still in its vocabulary (its docstring draws that line explicitly). So// those three losses land here, and each one says what happened and// re-opens the picker β the `viewModes.tsx:190-194` rule, which exists// because the wave-7 trap was a picker silently falling back to its first// option.// ---------------------------------------------------------------------------import { useCallback, useEffect, useMemo, useRef, useState } from "react";// ββ W41-T48 (owner instruction 22) β opening a record from the swipe deck folds the shell's// navigation rail exactly as a grid cell click does. Guard rationale: `MapView.tsx:2755`.import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";import { choiceOptions } from "./types";import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";// β `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is// loaded here) β the same import `RecordComments` takes for the same prop.import type { SurfaceScope } from "./apiBridge";import RecordComments from "./RecordComments";import { Documents } from "./Documents";import { formatDisplay } from "./cells";import { actionHref } from "./display";import { optionTint } from "./choiceColors";import { ModeIcon } from "./icons";// β W29-T73 β the line its three siblings all have, and the one this file shipped without.// `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered// unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right β// a partially-styled surface reads as a design choice, which is why nobody reported it and no// gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).import "./SwipeView.css";export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;/** The three ways a stored binding can rot that the host cannot see (see the header note). */type BindingFault =| { kind: "unbound" }| { kind: "field-gone"; fieldKey: string }| { kind: "not-select"; field: Field }| { kind: "option-gone"; field: Field; missing: string[] };function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map<string, Field>):{ ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {if (!spec) return { ok: false, fault: { kind: "unbound" } };const field = fieldByKey.get(spec.fieldKey);if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };// R2 β SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,// so "write this option" would mean append-or-replace, and a triage gesture that sometimes// adds and sometimes overwrites is two gestures wearing one button.if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };const options = choiceOptions(field);const has = new Set(options.map((o) => o.toLowerCase()));const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };return { ok: true, field, spec };}/** The bound cell is EMPTY β the one predicate that decides deck membership (R2). */const isUndecided = (row: Row, key: string): boolean =>String(row[key] ?? "").trim() === "";export function SwipeView({rows,fields,fieldByKey,spec,cardKeys,detailKeys,scope,viewer,docs,docPayload,onDocAdd,onDocFetch,onDocDelete,titleKey,canWrite,readOnlyReason,canBind,onSpec,onSwipe,onOpen,}: {/** DISTINCT data rows from the full pipeline, overlay edits layered β the kanban's contract.* The deck re-derives from these, so a written record leaves it as soon as the optimistic* patch lands; there is no local cursor to drift out of step with the data. */rows: Row[];/** Every field, for the picker's field list. */fields: Field[];fieldByKey: Map<string, Field>;/** The stored binding, or undefined for a deck nobody has configured yet. */spec: SwipeSpec | undefined;/** The handful of visible fields the card lists under its title. */cardKeys: string[];titleKey: string;/** May this viewer write the BOUND field's value? (the kanban's `canMove`) */canWrite: boolean;/** Stated when the deck cannot be decided β permissions, or a computed column. */readOnlyReason: string | null;/** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the* view-editing permission and NOT `canWrite` β conflating the two is* [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does* nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */canBind: boolean;/** `undefined` DELETES the binding β absent is the honest unconfigured state, and storing a* half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */onSpec: (next: SwipeSpec | undefined) => void;onSwipe: (pid: number, value: string) => void;onOpen: (pid: number) => void;/*** ββ WAVE-29 T26 (owner R9) β WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY.** R9: *"the swipe CARD itself renders the record detail inline β fields, comments and* attachments β so a reviewer decides without leaving the deck."* Everything below is that,* and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply* different amounts. A card must render with none of them rather than throw β the standalone* embed has no `scope`, and a deployment with no document storage serves no handlers.*//** Every field the VIEW shows, in its order β not the three-key card summary. */detailKeys?: string[];/** The surface these records live on. Comments are keyed by it; absent β no comments section,* which is the pre-existing precondition `RecordDetail` already carries. */scope?: SurfaceScope;viewer?: Viewer;/** This record's attachments, and the plumbing. Handlers absent β the section is not rendered* at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app* cannot keep). *//** Keyed by pid, because a deck shows many records β `RecordDetail` takes ONE record's list* and that shape cannot serve a deck. */docs?: Record<string, CustomerDoc[]>;docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string };/** β EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE* open record. A deck paints many records at once, so a handler bound to a single pid would* attach every reviewer's upload to whichever card happened to be open. */onDocAdd?: (pid: number,file: { name: string; mime: string; size: number; data_b64: string }) => void;onDocFetch?: (pid: number, docId: string) => void;onDocDelete?: (pid: number, docId: string) => void;}) {// "Later" β session-only, never stored. A deck with no way past a record you cannot decide// blocks on that record forever, so this is navigation WITHIN the deck rather than a third// gesture: it writes nothing, survives no reload, and the count is disclosed in the empty// state rather than quietly shrinking the deck (rule 8b).const [later, setLater] = useState<Set<number>>(new Set());const deckRef = useRef<HTMLDivElement>(null);const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);const boundKey = binding.ok ? binding.field.key : null;const undecided = useMemo(() => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),[rows, boundKey]);const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);const card = deck[0];// A record decided elsewhere (the grid, another user's echo) must not stay "later" forever β// otherwise the disclosed skip count drifts away from what is actually on the deck.useEffect(() => {setLater((prev) => {if (prev.size === 0) return prev;const live = new Set(undecided.map((r) => r.pid));const next = new Set([...prev].filter((pid) => live.has(pid)));return next.size === prev.size ? prev : next;});}, [undecided]);const decide = useCallback((value: string) => {if (!card || !canWrite) return;onSwipe(card.pid, value);},[card, canWrite, onSwipe]);// β / β decide, and they are the SAME two actions the buttons are rather than a second code// path: the whole point of the mode is that one hand can clear a queue.useEffect(() => {if (!binding.ok || !canWrite || !card) return;const onKey = (e: KeyboardEvent) => {if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;const el = document.activeElement as HTMLElement | null;// Never steal an arrow key from a text field or a native control the user is inside.if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))return;if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;e.preventDefault();decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);};window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);}, [binding, canWrite, card, decide]);if (!binding.ok) {return (<div className="cg-swipe" ref={deckRef}><SwipeBinderfault={binding.fault}fields={fields}fieldByKey={fieldByKey}spec={spec}canBind={canBind}onSpec={onSpec}/></div>);}const { field } = binding;const leftTint = optionTint(field, binding.spec.leftOption);const rightTint = optionTint(field, binding.spec.rightOption);return (<div className="cg-swipe" ref={deckRef} tabIndex={-1}><div className="cg-swipe-bar"><span className="cg-swipe-bound"><ModeIcon mode="swipe" />Sorting into <strong>{field.label}</strong></span><span className="cg-swipe-left">{deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort</span>{canBind && (<buttontype="button"className="cg-link-btn"onClick={() => onSpec(undefined)}title="Choose a different field or different options for this deck">Change</button>)}</div>{readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}{card ? (<div className="cg-swipe-deck"><buttontype="button"className="cg-swipe-side cg-swipe-side--left"disabled={!canWrite}style={leftTint ? { background: leftTint.bg, color: leftTint.fg } : undefined}onClick={() => decide(binding.spec.leftOption)}title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}><span aria-hidden className="cg-swipe-arrow"><svg width="16" height="16" viewBox="0 0 16 16"><pathd="M11 3.2 6.2 8l4.8 4.8"fill="none"stroke="currentColor"strokeWidth="1.6"strokeLinecap="round"strokeLinejoin="round"/></svg></span>{binding.spec.leftOption}</button><articleclassName="cg-swipe-card"role="button"tabIndex={0}onClick={(e) => {// β W41-T48 β the card IS the deck's record open, so it folds the rail.// β Nothing that is NOT an open can reach this line: every control inside the// card (a url cell, the comments box, the document tray) already stops its own// click, and the left/right decision buttons are siblings of the card, not// children of it. The deck also has no pointer drag to disambiguate β its swipe// is the two buttons and the arrow keys, neither of which opens anything.// β `<article role="button">`, not a native button, so a keyboard activation// never arrives here as a synthetic click; the keydown path below is the whole// keyboard story and the two cannot both fire for one gesture.if (e.detail <= 1) signal(NAV_MINIMIZE_EVENT);onOpen(card.pid);}}onKeyDown={(e) => {if (e.key !== "Enter" && e.key !== " ") return;e.preventDefault();// W41-T48 β `!e.repeat` is this path's `e.detail <= 1`: a HELD Enter or Space// auto-repeats keydown, and every one of those repeats is the SAME gesture.if (!e.repeat) signal(NAV_MINIMIZE_EVENT);onOpen(card.pid);}}><h3 className="cg-swipe-title">{String(card[titleKey] ?? "")}</h3><div className="cg-swipe-cells">{/* β WAVE-29 T26 (R9) β the RECORD's visible fields, not the three-key summary thekanban card lends. `detailKeys` falls back to `cardKeys` so a host that has notbeen widened yet renders exactly what it rendered before. */}{(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => {const f = fieldByKey.get(k);if (!f) return null;const text = formatDisplay(f, card[k]);if (!text) return null;// A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one// scheme guard β and every gesture that reaches it must be stopped from also// reaching the card, which is a button (the kanban card's note, same trap).const href = actionHref(f, card[k]);return (<div key={k} className="cg-swipe-cell"><span className="cg-lv-k">{f.label}</span>{href ? (<aclassName="cg-lv-v"href={href}target="_blank"rel="noopener noreferrer"title={text}onClick={(e) => e.stopPropagation()}onKeyDown={(e) => e.stopPropagation()}>{text}</a>) : (<span className="cg-lv-v">{text}</span>)}</div>);})}</div>{/* β R9's other two thirds. Both stop their own events: the card is a `role="button"`that opens the record, and a click on a comment box or an upload control must notalso open the modal it exists to make unnecessary (the kanban card's link trap,one surface over). */}{onDocAdd && onDocFetch && onDocDelete && (<divclassName="cg-swipe-docs"onClick={(e) => e.stopPropagation()}onKeyDown={(e) => e.stopPropagation()}role="presentation"><Documentspid={Number(card.pid)}docs={docs?.[String(card.pid)] ?? []}docPayload={docPayload}onAdd={(file) => onDocAdd(card.pid, file)}onFetch={(docId) => onDocFetch(card.pid, docId)}onDelete={(docId) => onDocDelete(card.pid, docId)}/></div>)}{scope != null && (<divclassName="cg-swipe-comments"onClick={(e) => e.stopPropagation()}onKeyDown={(e) => e.stopPropagation()}role="presentation">{/* β KEYED ON scope+pid, the same key `RecordDetail` uses: without it Reactreuses the mounted instance across a card change and paints one record'scomments under another's name until the fetch returns. */}<RecordCommentskey={`${scope}:${Number(card.pid)}`}scope={scope}pid={Number(card.pid)}viewer={viewer}/></div>)}{canWrite && (<buttontype="button"className="cg-link-btn cg-swipe-later"onClick={(e) => {e.stopPropagation();setLater((prev) => new Set(prev).add(card.pid));}}>Decide later</button>)}</article><buttontype="button"className="cg-swipe-side cg-swipe-side--right"disabled={!canWrite}style={rightTint ? { background: rightTint.bg, color: rightTint.fg } : undefined}onClick={() => decide(binding.spec.rightOption)}title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}>{binding.spec.rightOption}<span aria-hidden className="cg-swipe-arrow"><svg width="16" height="16" viewBox="0 0 16 16"><pathd="M5 3.2 9.8 8 5 12.8"fill="none"stroke="currentColor"strokeWidth="1.6"strokeLinecap="round"strokeLinejoin="round"/></svg></span></button></div>) : (// The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous// between "the deck is finished" and "the filter hid everything", and the two want// different next actions. `later` is disclosed rather than quietly subtracted.<div className="cg-mode-empty cg-swipe-empty">{later.size > 0 ? (<><p>{later.size.toLocaleString()}{" "}{later.size === 1 ? "record is" : "records are"} set aside for later. Nothing elsein this view is missing a <strong>{field.label}</strong>.</p><button type="button" className="cg-btn" onClick={() => setLater(new Set())}>Bring them back</button></>) : (<p>Every record in this view already has a <strong>{field.label}</strong>. Widen theview's filters to sort more.</p>)}</div>)}</div>);}/*** The binding picker: field + two options. It is also the surface every LOST binding lands on,* with the loss stated above it β one place that answers "what is this deck for", rather than an* error screen beside a separate setup screen.*/function SwipeBinder({fault,fields,fieldByKey,spec,canBind,onSpec,}: {fault: BindingFault;fields: Field[];fieldByKey: Map<string, Field>;spec: SwipeSpec | undefined;canBind: boolean;onSpec: (next: SwipeSpec | undefined) => void;}) {const selects = useMemo(() => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),[fields]);const [fieldKey, setFieldKey] = useState<string>(() => {if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;return selects[0]?.key ?? "";});const chosen = fieldByKey.get(fieldKey);const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);const [left, setLeft] = useState<string>("");const [right, setRight] = useState<string>("");// The two option selects follow the FIELD. Kept in an effect rather than derived so the user's// pick survives re-renders, and reset whenever the field changes β carrying an option from the// previous field would offer a value the new field cannot hold.useEffect(() => {setLeft(options[0] ?? "");setRight(options.find((o) => o !== options[0]) ?? "");}, [options]);const message = ((): string => {switch (fault.kind) {case "field-gone":return "The field this deck sorted into has been deleted. Pick another one.";case "not-select":return `β${fault.field.label}β is no longer a single-select, so it has no options to`+ " sort into. Pick another field.";case "option-gone":return `${fault.missing.map((m) => `β${m}β`).join(" and ")} ${fault.missing.length === 1 ? "is" : "are"} no longer ${fault.missing.length === 1 ? "an option" : "options"} on β${fault.field.label}β. Pick the sides again.`;default:return "Sort records one at a time into two options of a single-select field.";}})();if (!canBind) {return (<div className="cg-mode-empty"><p>{message}</p><p>Its creator or an admin can set this view up.</p></div>);}if (selects.length === 0) {// Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the// requirement is what turns a dead end into a next action.return (<div className="cg-mode-empty"><p>A swipe deck sorts into a single-select field with at least two options. This databasedoes not have one yet β add a single-select column, then come back.</p></div>);}const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();return (<div className="cg-swipe-setup"><p className="cg-swipe-setup-note">{message}</p><label className="cg-swipe-setup-row"><span>Sort into</span><selectclassName="cg-select"value={fieldKey}onChange={(e) => setFieldKey(e.target.value)}>{/* Every option carries an explicit `value`: a <select> whose value names nothingrenders its FIRST option and reports a choice the user never made([[cg-condition-builder-items]]). */}{selects.map((f) => (<option key={f.key} value={f.key}>{f.label}</option>))}</select></label><div className="cg-swipe-setup-sides"><label className="cg-swipe-setup-row"><span>Swipe left</span><select className="cg-select" value={left} onChange={(e) => setLeft(e.target.value)}>{options.map((o) => (<option key={o} value={o}>{o}</option>))}</select></label><label className="cg-swipe-setup-row"><span>Swipe right</span><select className="cg-select" value={right} onChange={(e) => setRight(e.target.value)}>{options.map((o) => (<option key={o} value={o}>{o}</option>))}</select></label></div>{!ready && left && right && (// Stated, not silently refused: both engines DROP a binding whose sides are the same// option, so a Save that looked like it worked would simply not persist.<p className="cg-swipe-setup-warn">The two sides must be different options β otherwise both gestures do the same thing.</p>)}<buttontype="button"className="cg-btn cg-btn--primary"disabled={!ready}onClick={() =>chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })}>Start sorting</button></div>);}export default SwipeView;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586// ---------------------------------------------------------------------------// customer-grid / SwipeView.tsx// β WAVE-27 item 8 (owner ruling R2, contract C3) β the SWIPE deck.//// One record at a time, decided left or right into two options of ONE// single-select. R2 fixes the shape and it is narrow on purpose:// Β· SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.// Β· the deck holds only the records whose bound field is EMPTY β a record// that already has a value has been decided, and re-asking is not triage.// Β· a swipe writes through the NORMAL cell door (`onSwipe`, which the host// maps to the same `patchAndRecord` a kanban card move uses), so undo,// echo-suppression and the permission wall all hold without being// re-implemented here.//// Honesty rules carried from the other modes:// Β· nothing is silently hidden β the deck states what is left, and the// empty state names the bound field rather than saying "all done".// Β· a lost binding is SHOWN, never repaired by guessing. `_clean_display`// validates that `fieldKey` names a field the table HAS and stops there;// it cannot know the field is still a select, or that the two options are// still in its vocabulary (its docstring draws that line explicitly). So// those three losses land here, and each one says what happened and// re-opens the picker β the `viewModes.tsx:190-194` rule, which exists// because the wave-7 trap was a picker silently falling back to its first// option.// ---------------------------------------------------------------------------import { useCallback, useEffect, useMemo, useRef, useState } from "react";// ββ W41-T48 (owner instruction 22) β opening a record from the swipe deck folds the shell's// navigation rail exactly as a grid cell click does. Guard rationale: `MapView.tsx:2755`.import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";import { choiceOptions } from "./types";import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";// β `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is// loaded here) β the same import `RecordComments` takes for the same prop.import type { SurfaceScope } from "./apiBridge";import RecordComments from "./RecordComments";import { Documents } from "./Documents";import { formatDisplay } from "./cells";import { actionHref } from "./display";import { optionTint } from "./choiceColors";import { ModeIcon } from "./icons";// β W29-T73 β the line its three siblings all have, and the one this file shipped without.// `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered// unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right β// a partially-styled surface reads as a design choice, which is why nobody reported it and no// gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).import "./SwipeView.css";export type SwipeSpec = NonNullable<DisplaySpec["swipe"]>;/** The three ways a stored binding can rot that the host cannot see (see the header note). */type BindingFault =| { kind: "unbound" }| { kind: "field-gone"; fieldKey: string }| { kind: "not-select"; field: Field }| { kind: "option-gone"; field: Field; missing: string[] };function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map<string, Field>):{ ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {if (!spec) return { ok: false, fault: { kind: "unbound" } };const field = fieldByKey.get(spec.fieldKey);if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };// R2 β SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,// so "write this option" would mean append-or-replace, and a triage gesture that sometimes// adds and sometimes overwrites is two gestures wearing one button.if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };const options = choiceOptions(field);const has = new Set(options.map((o) => o.toLowerCase()));const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };return { ok: true, field, spec };}/** The bound cell is EMPTY β the one predicate that decides deck membership (R2). */const isUndecided = (row: Row, key: string): boolean =>String(row[key] ?? "").trim() === "";export function SwipeView({rows,fields,fieldByKey,spec,cardKeys,detailKeys,scope,viewer,docs,docPayload,onDocAdd,onDocFetch,onDocDelete,titleKey,canWrite,readOnlyReason,canBind,onSpec,onSwipe,onOpen,}: {/** DISTINCT data rows from the full pipeline, overlay edits layered β the kanban's contract.* The deck re-derives from these, so a written record leaves it as soon as the optimistic* patch lands; there is no local cursor to drift out of step with the data. */rows: Row[];/** Every field, for the picker's field list. */fields: Field[];fieldByKey: Map<string, Field>;/** The stored binding, or undefined for a deck nobody has configured yet. */spec: SwipeSpec | undefined;/** The handful of visible fields the card lists under its title. */cardKeys: string[];titleKey: string;/** May this viewer write the BOUND field's value? (the kanban's `canMove`) */canWrite: boolean;/** Stated when the deck cannot be decided β permissions, or a computed column. */readOnlyReason: string | null;/** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the* view-editing permission and NOT `canWrite` β conflating the two is* [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does* nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */canBind: boolean;/** `undefined` DELETES the binding β absent is the honest unconfigured state, and storing a* half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */onSpec: (next: SwipeSpec | undefined) => void;onSwipe: (pid: number, value: string) => void;onOpen: (pid: number) => void;/*** ββ WAVE-29 T26 (owner R9) β WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY.** R9: *"the swipe CARD itself renders the record detail inline β fields, comments and* attachments β so a reviewer decides without leaving the deck."* Everything below is that,* and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply* different amounts. A card must render with none of them rather than throw β the standalone* embed has no `scope`, and a deployment with no document storage serves no handlers.*//** Every field the VIEW shows, in its order β not the three-key card summary. */detailKeys?: string[];/** The surface these records live on. Comments are keyed by it; absent β no comments section,* which is the pre-existing precondition `RecordDetail` already carries. */scope?: SurfaceScope;viewer?: Viewer;/** This record's attachments, and the plumbing. Handlers absent β the section is not rendered* at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app* cannot keep). *//** Keyed by pid, because a deck shows many records β `RecordDetail` takes ONE record's list* and that shape cannot serve a deck. */docs?: Record<string, CustomerDoc[]>;docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string };/** β EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE* open record. A deck paints many records at once, so a handler bound to a single pid would* attach every reviewer's upload to whichever card happened to be open. */onDocAdd?: (pid: number,file: { name: string; mime: string; size: number; data_b64: string }) => void;onDocFetch?: (pid: number, docId: string) => void;onDocDelete?: (pid: number, docId: string) => void;}) {// "Later" β session-only, never stored. A deck with no way past a record you cannot decide// blocks on that record forever, so this is navigation WITHIN the deck rather than a third// gesture: it writes nothing, survives no reload, and the count is disclosed in the empty// state rather than quietly shrinking the deck (rule 8b).const [later, setLater] = useState<Set<number>>(new Set());const deckRef = useRef<HTMLDivElement>(null);const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);const boundKey = binding.ok ? binding.field.key : null;const undecided = useMemo(() => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),[rows, boundKey]);const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);const card = deck[0];// A record decided elsewhere (the grid, another user's echo) must not stay "later" forever β// otherwise the disclosed skip count drifts away from what is actually on the deck.useEffect(() => {setLater((prev) => {if (prev.size === 0) return prev;const live = new Set(undecided.map((r) => r.pid));const next = new Set([...prev].filter((pid) => live.has(pid)));return next.size === prev.size ? prev : next;});}, [undecided]);const decide = useCallback((value: string) => {if (!card || !canWrite) return;onSwipe(card.pid, value);},[card, canWrite, onSwipe]);// β / β decide, and they are the SAME two actions the buttons are rather than a second code// path: the whole point of the mode is that one hand can clear a queue.useEffect(() => {if (!binding.ok || !canWrite || !card) return;const onKey = (e: KeyboardEvent) => {if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;const el = document.activeElement as HTMLElement | null;// Never steal an arrow key from a text field or a native control the user is inside.if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))return;if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;e.preventDefault();decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);};window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);}, [binding, canWrite, card, decide]);if (!binding.ok) {return (<div className="cg-swipe" ref={deckRef}><SwipeBinderfault={binding.fault}fields={fields}fieldByKey={fieldByKey}spec={spec}canBind={canBind}onSpec={onSpec}/></div>);}const { field } = binding;const leftTint = optionTint(field, binding.spec.leftOption);const rightTint = optionTint(field, binding.spec.rightOption);return (<div className="cg-swipe" ref={deckRef} tabIndex={-1}><div className="cg-swipe-bar"><span className="cg-swipe-bound"><ModeIcon mode="swipe" />Sorting into <strong>{field.label}</strong></span><span className="cg-swipe-left">{deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort</span>{canBind && (<buttontype="button"className="cg-link-btn"onClick={() => onSpec(undefined)}title="Choose a different field or different options for this deck">Change</button>)}</div>{readOnlyReason && <div className="cg-kb-note">{readOnlyReason}</div>}{card ? (<div className="cg-swipe-deck"><buttontype="button"className="cg-swipe-side cg-swipe-side--left"disabled={!canWrite}style={leftTint ? { background: leftTint.bg, color: leftTint.fg } : undefined}onClick={() => decide(binding.spec.leftOption)}title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}><span aria-hidden className="cg-swipe-arrow"><svg width="16" height="16" viewBox="0 0 16 16"><pathd="M11 3.2 6.2 8l4.8 4.8"fill="none"stroke="currentColor"strokeWidth="1.6"strokeLinecap="round"strokeLinejoin="round"/></svg></span>{binding.spec.leftOption}</button><articleclassName="cg-swipe-card"role="button"tabIndex={0}onClick={(e) => {// β W41-T48 β the card IS the deck's record open, so it folds the rail.// β Nothing that is NOT an open can reach this line: every control inside the// card (a url cell, the comments box, the document tray) already stops its own// click, and the left/right decision buttons are siblings of the card, not// children of it. The deck also has no pointer drag to disambiguate β its swipe// is the two buttons and the arrow keys, neither of which opens anything.// β `<article role="button">`, not a native button, so a keyboard activation// never arrives here as a synthetic click; the keydown path below is the whole// keyboard story and the two cannot both fire for one gesture.if (e.detail <= 1) signal(NAV_MINIMIZE_EVENT);onOpen(card.pid);}}onKeyDown={(e) => {if (e.key !== "Enter" && e.key !== " ") return;e.preventDefault();// W41-T48 β `!e.repeat` is this path's `e.detail <= 1`: a HELD Enter or Space// auto-repeats keydown, and every one of those repeats is the SAME gesture.if (!e.repeat) signal(NAV_MINIMIZE_EVENT);onOpen(card.pid);}}><h3 className="cg-swipe-title">{String(card[titleKey] ?? "")}</h3><div className="cg-swipe-cells">{/* β WAVE-29 T26 (R9) β the RECORD's visible fields, not the three-key summary thekanban card lends. `detailKeys` falls back to `cardKeys` so a host that has notbeen widened yet renders exactly what it rendered before. */}{(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => {const f = fieldByKey.get(k);if (!f) return null;const text = formatDisplay(f, card[k]);if (!text) return null;// A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one// scheme guard β and every gesture that reaches it must be stopped from also// reaching the card, which is a button (the kanban card's note, same trap).const href = actionHref(f, card[k]);return (<div key={k} className="cg-swipe-cell"><span className="cg-lv-k">{f.label}</span>{href ? (<aclassName="cg-lv-v"href={href}target="_blank"rel="noopener noreferrer"title={text}onClick={(e) => e.stopPropagation()}onKeyDown={(e) => e.stopPropagation()}>{text}</a>) : (<span className="cg-lv-v">{text}</span>)}</div>);})}</div>{/* β R9's other two thirds. Both stop their own events: the card is a `role="button"`that opens the record, and a click on a comment box or an upload control must notalso open the modal it exists to make unnecessary (the kanban card's link trap,one surface over). */}{onDocAdd && onDocFetch && onDocDelete && (<divclassName="cg-swipe-docs"onClick={(e) => e.stopPropagation()}onKeyDown={(e) => e.stopPropagation()}role="presentation"><Documentspid={Number(card.pid)}docs={docs?.[String(card.pid)] ?? []}docPayload={docPayload}onAdd={(file) => onDocAdd(card.pid, file)}onFetch={(docId) => onDocFetch(card.pid, docId)}onDelete={(docId) => onDocDelete(card.pid, docId)}/></div>)}{scope != null && (<divclassName="cg-swipe-comments"onClick={(e) => e.stopPropagation()}onKeyDown={(e) => e.stopPropagation()}role="presentation">{/* β KEYED ON scope+pid, the same key `RecordDetail` uses: without it Reactreuses the mounted instance across a card change and paints one record'scomments under another's name until the fetch returns. */}<RecordCommentskey={`${scope}:${Number(card.pid)}`}scope={scope}pid={Number(card.pid)}viewer={viewer}/></div>)}{canWrite && (<buttontype="button"className="cg-link-btn cg-swipe-later"onClick={(e) => {e.stopPropagation();setLater((prev) => new Set(prev).add(card.pid));}}>Decide later</button>)}</article><buttontype="button"className="cg-swipe-side cg-swipe-side--right"disabled={!canWrite}style={rightTint ? { background: rightTint.bg, color: rightTint.fg } : undefined}onClick={() => decide(binding.spec.rightOption)}title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}>{binding.spec.rightOption}<span aria-hidden className="cg-swipe-arrow"><svg width="16" height="16" viewBox="0 0 16 16"><pathd="M5 3.2 9.8 8 5 12.8"fill="none"stroke="currentColor"strokeWidth="1.6"strokeLinecap="round"strokeLinejoin="round"/></svg></span></button></div>) : (// The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous// between "the deck is finished" and "the filter hid everything", and the two want// different next actions. `later` is disclosed rather than quietly subtracted.<div className="cg-mode-empty cg-swipe-empty">{later.size > 0 ? (<><p>{later.size.toLocaleString()}{" "}{later.size === 1 ? "record is" : "records are"} set aside for later. Nothing elsein this view is missing a <strong>{field.label}</strong>.</p><button type="button" className="cg-btn" onClick={() => setLater(new Set())}>Bring them back</button></>) : (<p>Every record in this view already has a <strong>{field.label}</strong>. Widen theview's filters to sort more.</p>)}</div>)}</div>);}/*** The binding picker: field + two options. It is also the surface every LOST binding lands on,* with the loss stated above it β one place that answers "what is this deck for", rather than an* error screen beside a separate setup screen.*/function SwipeBinder({fault,fields,fieldByKey,spec,canBind,onSpec,}: {fault: BindingFault;fields: Field[];fieldByKey: Map<string, Field>;spec: SwipeSpec | undefined;canBind: boolean;onSpec: (next: SwipeSpec | undefined) => void;}) {const selects = useMemo(() => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),[fields]);const [fieldKey, setFieldKey] = useState<string>(() => {if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;return selects[0]?.key ?? "";});const chosen = fieldByKey.get(fieldKey);const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);const [left, setLeft] = useState<string>("");const [right, setRight] = useState<string>("");// The two option selects follow the FIELD. Kept in an effect rather than derived so the user's// pick survives re-renders, and reset whenever the field changes β carrying an option from the// previous field would offer a value the new field cannot hold.useEffect(() => {setLeft(options[0] ?? "");setRight(options.find((o) => o !== options[0]) ?? "");}, [options]);const message = ((): string => {switch (fault.kind) {case "field-gone":return "The field this deck sorted into has been deleted. Pick another one.";case "not-select":return `β${fault.field.label}β is no longer a single-select, so it has no options to`+ " sort into. Pick another field.";case "option-gone":return `${fault.missing.map((m) => `β${m}β`).join(" and ")} ${fault.missing.length === 1 ? "is" : "are"} no longer ${fault.missing.length === 1 ? "an option" : "options"} on β${fault.field.label}β. Pick the sides again.`;default:return "Sort records one at a time into two options of a single-select field.";}})();if (!canBind) {return (<div className="cg-mode-empty"><p>{message}</p><p>Its creator or an admin can set this view up.</p></div>);}if (selects.length === 0) {// Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the// requirement is what turns a dead end into a next action.return (<div className="cg-mode-empty"><p>A swipe deck sorts into a single-select field with at least two options. This databasedoes not have one yet β add a single-select column, then come back.</p></div>);}const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();return (<div className="cg-swipe-setup"><p className="cg-swipe-setup-note">{message}</p><label className="cg-swipe-setup-row"><span>Sort into</span><selectclassName="cg-select"value={fieldKey}onChange={(e) => setFieldKey(e.target.value)}>{/* Every option carries an explicit `value`: a <select> whose value names nothingrenders its FIRST option and reports a choice the user never made([[cg-condition-builder-items]]). */}{selects.map((f) => (<option key={f.key} value={f.key}>{f.label}</option>))}</select></label><div className="cg-swipe-setup-sides"><label className="cg-swipe-setup-row"><span>Swipe left</span><select className="cg-select" value={left} onChange={(e) => setLeft(e.target.value)}>{options.map((o) => (<option key={o} value={o}>{o}</option>))}</select></label><label className="cg-swipe-setup-row"><span>Swipe right</span><select className="cg-select" value={right} onChange={(e) => setRight(e.target.value)}>{options.map((o) => (<option key={o} value={o}>{o}</option>))}</select></label></div>{!ready && left && right && (// Stated, not silently refused: both engines DROP a binding whose sides are the same// option, so a Save that looked like it worked would simply not persist.<p className="cg-swipe-setup-warn">The two sides must be different options β otherwise both gestures do the same thing.</p>)}<buttontype="button"className="cg-btn cg-btn--primary"disabled={!ready}onClick={() =>chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })}>Start sorting</button></div>);}export default SwipeView;
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750// The Sheet workbook and cell model (wave 49, W49-T02, contract C1).//// β W51-T20 (C7), WIRED AT THE COMBINE. This is the file's ONLY import, and its absence// was the whole reason the handover existed: `sheetState.ts` is compiled to CommonJS and// RUN by `verify_api.py`, and tsc's emitted ROOT moves with the import graph, so a// `../ui/*` import taken on `wave51/E` alone would have dropped every emitted module a// level down and broken every `require` path the battery's existing proofs use// ([[tsc-outdir-root-moves-with-the-import-graph]]). Lane F's module only exists on the// merged tree, so the import lands here and nowhere earlier.import { formatWithCode } from "../ui/numberFormat";//// β THIS FILE IS ONE HALF OF A PARITY GATE. `platform/core/sheets.py` declares CELL_KINDS and// CELL_STATES, and a check in `aios-web/api/verify_api.py` asserts that the two lists below match// them NAME FOR NAME. Adding a name on one side only is exactly what that check exists to catch,// so a new kind or state is a contract change made in both places at once, never here alone.//// β THERE IS NO `chart` KIND. W49-T08 stores a chart as a sibling `charts` array on the sheet,// so a chart never has to pretend to be a cell. Only the ROOT may amend C1./*** β Mirrored in `platform/core/sheets.py::CELL_KINDS`, name for name.** ββ W51-T16 / CONTRACT C2 ADDS `empty`, AND IT IS THE ONLY NAME C1's THREE HAVE EVER GAINED.* A cell may now carry `style` AND NOTHING ELSE: no value, no text, no formula, no binding. That* is what makes "select three blank cells and press Borders" paintable at all, and the reason it* could not be a fourth `literal` is one number on the screen. `sheetState.ts::handTypedCount`* counts every `literal` and the sheet PRINTS the count, so bolding a blank block of twenty* cells would have claimed twenty hand typed values nobody typed.** β THE SERVER HALF IS W51-T21's (lane D), AND UNTIL IT LANDS THE PARITY LEG IN* `verify_api.py::section_w49_sheet_contract` IS RED BY DESIGN: `core/sheets.py::clean_cell`* refuses an unknown kind BY NAME, so an empty styled cell cannot be SAVED yet. Everything below* is therefore proven in local state, which is exactly what C2 says each side owes the other.*/export const CELL_KINDS = ["literal", "formula", "bound", "empty"] as const;/** β FROZEN by contract C1. Mirrored in `platform/core/sheets.py::CELL_STATES`. */export const CELL_STATES = ["fresh", "stale", "typed", "refused"] as const;export type CellKind = (typeof CELL_KINDS)[number];export type CellState = (typeof CELL_STATES)[number];/*** R19's three states, said once so no component re-derives them:* bound and fresh (`bound` + `fresh`), bound and stale (`bound` + `stale`), and hand typed* (`literal`, which is always `typed`). `refused` is the fourth state and it is not one of the* three marks: it replaces the value rather than qualifying it.*/export interface CellRefusal {code: string;message: string;}/** A cell's provenance, filled in by the resolver (W49-T04), never by the client. */export interface CellSource {database: string;view_id?: string;filter?: unknown;}/*** C2's binding. Its INTERIOR is W49-T04's and W49-T06's business; it is carried here as an opaque* object so this file does not become a second declaration of the filter language.** ββ W51-T19 / C2 GAVE `period` AND `onDrag` REAL SHAPES AND STILL LEFT THIS ALIAS LOOSE, WHICH* IS A TYPE DECISION WITH A REASON RATHER THAN AN OMISSION. An index signature over `unknown`* paired with `period?: BindingPeriod` is NOT assignable from a plain `Record<string, unknown>`:* the source's index signature offers `unknown` where the target demands `BindingPeriod`, so* every existing consumer that hands a loose record to a binding slot would have become a* compile error in files this ticket does not own (`SheetPage.tsx:526`, `sheetApi.ts:134`,* `BindingEditor.tsx`'s `onSave`). The shapes are declared BESIDE the alias instead and narrowed* from `unknown` at one door each, exactly as {@link isFormatCode} narrows the code format. One* widening door, no consumer edited, and every C2 name still declared in this file.*/export type CellBinding = Record<string, unknown>;// ββ W51-T19, contract C2: the DRAG vocabulary (rulings R9 and R10) ββββββββββββββββββββββββββ//// ββ WHAT THESE NAMES ARE FOR. R9 and R10 make a bound cell DRAGGABLE: pulling it across// columns walks its period by one unit per column, pulling it down rows walks a chosen filter to// its next option, and a LOCKED period does neither. Before this, a bulk door simply refused to// copy a binding at all. The arithmetic is `sheetState.ts`'s and is pure; what lives here is the// VOCABULARY the document stores, because `verify_api.py` reads this file for it and// `platform/core/sheets.py` (lane D) has to accept exactly these names and no others.//// β THE READERS BELOW TOLERATE WHAT IS ALREADY STORED. `BindingEditor.tsx:134` writes// `period = { ref }` today: no `unit`, no `start`, no `locked`. C2 declares all three as required// and a reader that INSISTED on them would silently drop every binding shipping right now, which// is a verbatim copy where a shift was asked for and no error anywhere. So the readers fill the// contract's own defaults instead, and each default is pinned by a node leg./** β C2: the three units a period may be measured in. Mirrored in `core/sheets.py` by lane D. */export const PERIOD_UNITS = ["month", "quarter", "year"] as const;export type PeriodUnit = (typeof PERIOD_UNITS)[number];/** β C2 / R10: what an ACROSS COLUMNS drag does. `period` walks it; `none` copies it verbatim. */export const DRAG_ACROSS = ["period", "none"] as const;export type DragAcross = (typeof DRAG_ACROSS)[number];/*** C2's period. `start` is `YYYY-MM` for all three units, because a quarter and a year are both* said by the month they begin in and a second encoding would be a second thing to keep in step.*/export interface BindingPeriod {unit: PeriodUnit;/** `YYYY-MM`. Empty on a period that names only a {@link BindingPeriod.ref}. */start: string;/** β R9: locked means ANY copy keeps this period, in every direction, through every door. */locked: boolean;/** R14: a period read out of another CELL. Plain A1, `$` anchors honoured on a drag. */ref?: string;}/** C2 / R10: the field whose options a DOWN ROWS drag walks, one option per row of offset. */export interface BindingDragDown {field: string;}/** β C2 / R10: the two directional settings. Defaults are `across: "period"`, `down: "none"`. */export interface BindingOnDrag {across: DragAcross;down: BindingDragDown | "none";}/** C2: the view a cell's scope was ADOPTED from, kept so the cell can say where it came from. */export interface BindingAdoptedFrom {view_id: string;name: string;at: string;}const asRecord = (value: unknown): Record<string, unknown> | null =>value && typeof value === "object" && !Array.isArray(value)? (value as Record<string, unknown>): null;/*** Read a binding's C2 period, or `null` when it carries none.** β IT TAKES `unknown` FOR THE SAME REASON {@link isFormatCode} DOES: {@link CellBinding} is a* loose record, so a caller that asked the compiler would be told there is no period there while* the document plainly carries one. This is the one door that widens.** β `locked` DEFAULTS TO FALSE, WHICH IS THE PERMISSIVE ANSWER AND IS DELIBERATE. R9's lock is* something a person turns ON; a stored period with no `locked` key was written before the toggle* existed, so treating it as locked would make every period already on a sheet refuse to shift* with nothing on screen saying why.*/export const bindingPeriod = (binding: unknown): BindingPeriod | null => {const record = asRecord(binding);const period = record && asRecord(record.period);if (!period) return null;const unit = String(period.unit ?? "");const ref = typeof period.ref === "string" ? period.ref.trim() : "";const out: BindingPeriod = {unit: (PERIOD_UNITS as readonly string[]).includes(unit) ? (unit as PeriodUnit) : "month",start: typeof period.start === "string" ? period.start.trim() : "",locked: period.locked === true,};if (ref) out.ref = ref;return out;};/*** Read a binding's C2 drag rules, ALWAYS returning both, with R10's defaults filled in.** ββ THE DEFAULTS ARE THE RULING AND THEY ARE NOT SYMMETRIC. Across columns defaults to* `period`; down rows defaults to `none`. A reader that guessed the same answer for both axes* would make a cell dragged DOWN walk its period, which is the likeliest defect in this feature* and the one that looks correct in every screenshot of a single row.*/export const bindingOnDrag = (binding: unknown): BindingOnDrag => {const record = asRecord(binding);const rules = record && asRecord(record.onDrag);const across = String(rules?.across ?? "");const down = rules && asRecord(rules.down);const field = typeof down?.field === "string" ? down.field.trim() : "";return {across: (DRAG_ACROSS as readonly string[]).includes(across)? (across as DragAcross): "period",down: field ? { field } : "none",};};/** Read a binding's `scope.adoptedFrom` (C2), or `null`. Carried through a drag untouched. */export const bindingAdoptedFrom = (binding: unknown): BindingAdoptedFrom | null => {const record = asRecord(binding);const scope = record && asRecord(record.scope);const adopted = scope && asRecord(scope.adoptedFrom);if (!adopted) return null;return {view_id: String(adopted.view_id ?? ""),name: String(adopted.name ?? ""),at: String(adopted.at ?? ""),};};// ββ the cell STYLE slot (wave 50, W50-T19, amendment A1) ββββββββββββββββββββββββββββββββββββ//// β A1 ADDS A SLOT, NOT A NAME. `style` is a new FIELD on `Cell`; it adds nothing to// `CELL_KINDS` or `CELL_STATES`, which stay frozen exactly as C1 left them. That is why the// ribbon could be built without amending the vocabulary the four wave-49 tickets consume.//// ββ THE ASYMMETRY IS THE CONTRACT, AND IT IS DELIBERATE. `core/sheets.py::_clean_style` DROPS// an unknown style key in silence and REFUSES an unknown `format.kind` by name. The reason is// what each one costs: an unknown style key is a decoration the server cannot paint, and// discarding it loses nothing a reader would miss; an unknown `format.kind` decides how a NUMBER// reads, so accepting one the server cannot apply would show a value formatted differently from// what was asked, with nobody told. One is cosmetic, the other is a wrong number on a screen.//// β COLOURS ARE STORED AS TOKEN NAMES (`--lp-red-deep`), never as hex. DESIGN.md 3 is token// only, and a hex written into a stored document is a palette decision that outlives every// palette change. `SheetGrid.tsx` resolves the token against the document at paint time./** β Mirrored in `platform/core/sheets.py::CELL_FORMAT_KINDS`, and parity checked. */export const CELL_FORMAT_KINDS = ["general", "number", "currency", "percent", "date"] as const;/** β Mirrored in `platform/core/sheets.py::CELL_ALIGNS`. */export const CELL_ALIGNS = ["left", "center", "right"] as const;/** β C2: the VERTICAL three. Mirrored in `core/sheets.py::CELL_VALIGNS` by W51-T21. */export const CELL_VALIGNS = ["top", "middle", "bottom"] as const;/*** β C2's four step size scale, and it is a SIZE rather than a typeface: the app is Inter only,* so offering a font family would be offering a decision the design constitution already made.* `m` is the default and is stored as an ABSENCE, exactly as `format.kind === "general"` is.*/export const CELL_SIZES = ["s", "m", "l", "xl"] as const;export type CellFormatKind = (typeof CELL_FORMAT_KINDS)[number];export type CellAlign = (typeof CELL_ALIGNS)[number];export type CellValign = (typeof CELL_VALIGNS)[number];export type CellSize = (typeof CELL_SIZES)[number];/** C2: how far a cell's text is pushed in from its own edge, in steps rather than in pixels. */export const MAX_CELL_INDENT = 8;/** C2: a custom format code is at most this long, and carries at most four `;` sections. */export const MAX_FORMAT_CODE = 64;export const MAX_FORMAT_SECTIONS = 4;/** C2: a cell's list validation carries at most this many entries. */export const MAX_VALIDATION_LIST = 200;/** C2: a sheet carries at most this many conditional formatting rules. */export const MAX_SHEET_RULES = 100;export interface CellFormat {kind: CellFormatKind;/** Fixed decimal places. Clamped to 0 through 10 by the server. */decimals?: number;/** Thousands grouping. `number` only; a currency carries its own locale grouping. */thousands?: boolean;/** An ISO 4217 code. Absent means USD, which is the one the store's tenants price in. */currency?: string;}/*** ββ C2's CUSTOM FORMAT CODE, AND WHY IT IS A SEPARATE MEMBER RATHER THAN A SIXTH KIND.** `CELL_FORMAT_KINDS` is parity checked against `core/sheets.py::CELL_FORMAT_KINDS` name for* name, and every one of those five is a kind the client can RENDER ON ITS OWN through* `Intl.NumberFormat`. A code is not: `#,##0.00;(#,##0.00)` needs a parser, which is contract* C7's `ui/numberFormat.ts::formatWithCode` and belongs to W51-T20. So the code is admitted to* the DOCUMENT here, where the server can store it, without claiming this file can paint it.** β Excel's own accounting shape is the reason a code has SECTIONS: positive, negative, zero and* text, split on `;`. That is why the limit is a count of sections and not merely a length.*/export interface CellFormatCode {kind: "code";/** At most {@link MAX_FORMAT_CODE} characters and {@link MAX_FORMAT_SECTIONS} sections. */code: string;}/** What a cell's `format` slot may hold: one of the five kinds, or C2's custom code. */export type CellFormatSpec = CellFormat | CellFormatCode;/** C2: the accounting code R8's Number menu offers, said once so two sites cannot disagree. */export const ACCOUNTING_FORMAT_CODE = "#,##0.00;(#,##0.00);\"-\"";/*** Is this format C2's code format? ONE predicate, so no consumer re-derives the discriminant.** β IT TAKES `unknown` DELIBERATELY. `CellStyle.format` is still ANNOTATED as the five kinds (see* the note on that slot), so a reader that asked the compiler would be told the code format* cannot be there while the document plainly carries it. Widening at this one door is what lets* every consumer stay honest without editing a file this ticket does not own.*/export const isFormatCode = (format: unknown): format is CellFormatCode =>!!format && (format as CellFormatCode).kind === "code"&& typeof (format as CellFormatCode).code === "string";/** C2: a cell may offer a fixed list of values. The interior is W51-T17's; the slot is C2's. */export interface CellValidation {/** At most {@link MAX_VALIDATION_LIST} entries. */list: string[];}/** Only the sides that are ON are carried. An absent side has no border, said by its absence. */export interface CellBorder {top?: boolean;right?: boolean;bottom?: boolean;left?: boolean;}export interface CellStyle {bold?: boolean;italic?: boolean;underline?: boolean;/** A `--lp-*` token name for the ink. */color?: string;/** A `--lp-*` token name for the cell background. */fill?: string;align?: CellAlign;/*** β β TYPED AS `CellFormat` AND NOT AS `CellFormatSpec`, ON PURPOSE, AND THE REASON IS A FENCE* RATHER THAN A DESIGN. `Ribbon.tsx` narrows `style.format.kind` to `CellFormatKind` in seven* places and holds a `Record<CellFormatKind, string>` of labels, so widening this slot is a* compile error in a file W51-T15 owns and W51-T16 may not edit. THE DOCUMENT ALREADY CARRIES* THE CODE FORMAT (C2): {@link CellFormatCode} declares it, {@link formatCellText} reads it* through {@link CellFormatSpec}, and the store keeps it. What is deferred is only the* ANNOTATION, and with it the ribbon's Custom code label, both of which belong to W51-T20 when* it lands `formatWithCode`. Until then the ribbon's two code items say so rather than writing* a format nothing can paint.*/format?: CellFormat;border?: CellBorder;// ββ W51-T16, contract C2: the four R8 names that had no key to land in ββββββββββββββββββββ/** Where the value sits in the cell's own height. Absent means the middle, as glide paints. */valign?: CellValign;/** Whether a long value wraps onto more lines instead of clipping at the column edge. */wrap?: boolean;/** 0 through {@link MAX_CELL_INDENT}. Zero is stored as an ABSENCE, like every falsey mark. */indent?: number;/** The step size. `m` is the default and is stored as an ABSENCE. */size?: CellSize;}/*** One ribbon act. `null` REMOVES the key, which is how a toggle turns off: the server drops a* falsey mark rather than storing `false`, so "not bold" and "bold: false" must be the same* document or an undo would compare unequal to the thing it undid.*/export type CellStylePatch = { [K in keyof CellStyle]?: CellStyle[K] | null };/*** Does this style change how the cell is PAINTED, as opposed to only how its value reads?** ββ EVERY C2 KEY THAT MOVES A PIXEL IS LISTED HERE OR ITS CONTROL LOOKS INERT WITH EVERY GATE* GREEN. `SheetGrid.tsx::drawCell` asks this ONE question to decide whether it owns the cell's* paint: `false` hands the cell back to glide, which knows nothing about a vertical align, a* wrap, an indent or a size step. So a key added to `CellStyle` and forgotten here is a ribbon* button that applies a real style the reader never sees.*/export const stylePaints = (style: CellStyle | null | undefined): boolean =>!!style && (style.bold === true || style.italic === true || style.underline === true|| !!style.color || !!style.fill || !!style.align|| !!style.valign || style.wrap === true || !!style.size|| (typeof style.indent === "number" && style.indent > 0)|| Object.values(style.border ?? {}).some(Boolean));/*** Apply a patch, returning a NEW style or `undefined` when nothing is left.** β IT PRUNES. A key set to `null`, to `false` or to an empty border is removed rather than* stored falsey, so a cell that has been bolded and unbolded is byte for byte the cell it was.*/export const applyStylePatch = (style: CellStyle | null | undefined,patch: CellStylePatch,): CellStyle | undefined => {const next: Record<string, unknown> = { ...(style ?? {}) };for (const [key, value] of Object.entries(patch)) {if (value === null || value === false || value === undefined) delete next[key];else next[key] = value;}const border = next.border as CellBorder | undefined;if (border && !Object.values(border).some(Boolean)) delete next.border;const format = next.format as CellFormatSpec | undefined;if (format && format.kind === "general") delete next.format;// ββ THE TWO C2 DEFAULTS THE LOOP ABOVE CANNOT SEE. Its test is `null`, `false` or// `undefined`, and neither `0` nor `"m"` is any of the three. An indent of zero and a size of// `m` ARE the absence of a decision, so storing them would leave a cell that has been indented// and outdented comparing unequal to the cell it started as, which breaks an undo, a paste// comparison and a `rev` diff at once while looking completely reasonable in a payload.if (next.indent === 0) delete next.indent;if (next.size === "m") delete next.size;return Object.keys(next).length > 0 ? (next as CellStyle) : undefined;};export interface Cell {/*** β `empty` IS A REAL KIND WITH REAL RULES (C2). Such a cell carries `style` and nothing else:* it is not editable content, it was not hand typed, it has no value, and it must never be* counted by `handTypedCount`, drilled, or exported as a value. `state` is `fresh` on one,* meaning nothing is pending, because `CELL_STATES` is frozen and none of the four says* "there is nothing here" - the KIND already says that.*/kind: CellKind;state: CellState;/** A1: how this cell is painted and how its value reads. Absent on every wave-49 cell. */style?: CellStyle;/** C2: a fixed list of values this cell accepts. The editor is W51-T17's. */validation?: CellValidation;/** A hand typed literal's text. */text?: string;/** An A1 formula, including the leading `=`. */formula?: string;/** R10: the value as LAST COMPUTED. Nothing recomputes it on read. */value?: unknown;display?: string;binding?: CellBinding;source?: CellSource;refusal?: CellRefusal;refreshed_at?: string;}/** Cells are keyed by plain A1 address with no `$`; anchoring belongs to a formula's text. */export type CellMap = Record<string, Cell>;/*** A chart OCCUPIES a rectangle of cells and READS them (R9, R15). It is a sibling array on the* sheet, deliberately, and NOT a cell kind.** β C1 freezes `kind` to `literal | formula | bound`, and a `chart` kind would have meant amending* a contract that four other tickets already build against - which only the ROOT may do. Keeping* charts beside the cells also says something true: a chart has no value, no state and no binding,* so every field a `Cell` carries would have been dead weight on it.*/export interface SheetChartSpec {id: string;/** Zero-based inclusive rectangle. The header ROW is the axis (R15). */range: { col0: number; row0: number; col1: number; row1: number };kind: "bar" | "line" | "area" | "donut";}// ββ the sheet's GEOMETRY (wave 50, W50-T20, amendment A2) βββββββββββββββββββββββββββββββββββ//// ββ A2 MOVES THE GRID'S SHAPE OUT OF THE COMPONENT AND INTO THE DOCUMENT. `SheetGrid.tsx` held// `COLS = 26`, `ROWS = 200` and `COL_WIDTH = 120` as module constants, which is exactly why a// sheet could not grow and a dragged column could not be remembered: there was nowhere to put the// answer. The three below are the DEFAULTS a new sheet is created with, mirrored from// `platform/core/sheets.py::DEFAULT_SHEET_COLS` / `DEFAULT_SHEET_ROWS` / `DEFAULT_COL_WIDTH`, and// `verify_api.py` compares the two sides exactly as it does for the cell vocabulary.//// β THEY ARE DEFAULTS, NOT BOUNDS. Read the OPEN SHEET's `cols` / `rows` for what the grid can// show; a reader who reaches for these constants instead will refuse an address on a grown sheet./** β Mirrored in `platform/core/sheets.py::DEFAULT_SHEET_COLS`. */export const DEFAULT_SHEET_COLS = 26;/** β Mirrored in `platform/core/sheets.py::DEFAULT_SHEET_ROWS`. */export const DEFAULT_SHEET_ROWS = 200;/** β Mirrored in `platform/core/sheets.py::DEFAULT_COL_WIDTH`. */export const DEFAULT_COL_WIDTH = 120;/** β The ceiling a sheet may grow to. Mirrored in `platform/core/sheets.py::MAX_SHEET_COLS`. */export const MAX_SHEET_COLS = 702;/** β Mirrored in `platform/core/sheets.py::MAX_SHEET_ROWS`. */export const MAX_SHEET_ROWS = 100000;/** β Mirrored in `platform/core/sheets.py::MIN_COL_WIDTH` / `MAX_COL_WIDTH`. */export const MIN_COL_WIDTH = 40;export const MAX_COL_WIDTH = 1000;/*** How many leading columns and rows stay put while the rest scrolls. Absent means none.** ββ W51-T34 / R17 β BOTH HALVES RENDER NOW, AND THEY RENDER BY DIFFERENT MEANS. `cols` is* glide's own `freezeColumns` prop; `rows` has no equivalent in glide 6.0.3 at all* (`freezeTrailingRows` pins rows at the BOTTOM), so the frozen rows are drawn by a SECOND grid* mounted above the first and scrolled with it. `SheetGrid.tsx`'s own note carries the mechanism.* β Contract C2 freezes these two key names: `verify_sheet.py` and `verify_api.py` each grep the* other side's literal vocabulary, so renaming either reds a gate in a lane that never touched it.*/export interface SheetFreeze {cols?: number;rows?: number;}export interface SheetTab {id: string;name: string;cells: CellMap;/** A2: how many columns this sheet shows. Absent only on a sheet not yet read by the server. */cols?: number;/** A2: how many rows this sheet shows. */rows?: number;/** A2: `{"C": 220}` for the columns somebody dragged. A default width is stored as an absence. */colWidths?: Record<string, number>;/** A2: the frozen panes. */freeze?: SheetFreeze;/** Absent on every sheet written before W49-T08, which is why it is optional. */charts?: SheetChartSpec[];// ββ W51, contract C2: the sheet-level slots the ribbon's Cells and Styles groups need ββββββ/** C2: conditional formatting, at most {@link MAX_SHEET_RULES}. The editor is W51-T18's. */rules?: SheetRule[];/*** β C2: the 1 BASED rows this sheet hides, and 1 based is not a detail. Every other index in* this module that reaches glide is zero based, so the two are told apart by their name and by* this sentence: `hiddenRows` and `hiddenCols` speak the SHEET's own coordinates, the ones a* person reads off the row marker and the column letter, exactly as `StructureOp.at` does.*/hiddenRows?: number[];hiddenCols?: number[];/** C2: what an import brought in, and what of it this app could not carry. W51-T19 writes it. */imported?: SheetImport;}/** β C2's comparison vocabulary, closed. Mirrored in `core/sheets.py::SHEET_RULE_OPS`. */export const SHEET_RULE_OPS = ["gt", "lt", "gte", "lte", "eq", "neq", "between", "contains", "empty", "notEmpty",] as const;export type SheetRuleOp = (typeof SHEET_RULE_OPS)[number];/*** C2: one conditional formatting rule. The STYLE it may paint is deliberately a subset of* `CellStyle`: a rule decides a fill, an ink and a weight, and nothing that would move the cell's* geometry, because a rule that changed a row's height would repaint the sheet as data arrived.*/export interface SheetRule {id: string;/** An A1 range, `B2:D40`. */range: string;op: SheetRuleOp;value?: string | number;value2?: string | number;style: { fill?: string; color?: string; bold?: boolean };}/** C2: the receipt an import leaves, including what it could NOT carry (R16's honesty rule). */export interface SheetImport {at: string;source: string;unsupported: string[];}/** The extent to render this sheet at, defaulted once so no component re-decides it. */export const sheetExtent = (tab: SheetTab | null | undefined,): { cols: number; rows: number } => ({cols: Math.max(1, Math.round(tab?.cols ?? DEFAULT_SHEET_COLS)),rows: Math.max(1, Math.round(tab?.rows ?? DEFAULT_SHEET_ROWS)),});export interface Workbook {id: string;name: string;sheets: SheetTab[];rev: number;refreshed_at: string | null;created_by?: string;created_at?: string;updated_at?: string;}/** What `GET /api/v1/sheets` returns: identity only, never cells. */export interface WorkbookRow {id: string;name: string;created_by: string;created_at: string;updated_at: string;rev: number;refreshed_at: string | null;}// ββ the rail's document (wave 50, W50-T17) ββββββββββββββββββββββββββββββββββββββββββββββββββ//// β ONE FOLDER SURFACE, and that is the whole difference from `customer-grid/folders.ts`, whose// tree is keyed by surface ("views" / "cohorts") because a grid rail carries two of them. The// Sheet rail carries exactly one kind of row (wave-49 R2), so a surface key here would be a// constant wearing a map, and every reader would have to remember which key to look under.//// β A WORKBOOK LIVES IN EXACTLY ONE FOLDER, which is why `itemFolders` is a MAP and not a list// of pairs: single-valued by construction, so "which folder is this in" has one answer.// `ROOT_FOLDER_ID` is the reserved value meaning "filed at the top level, on purpose"./** The reserved placement meaning the top level. Mirrors `core/sheets.py::ROOT_FOLDER_ID`. */export const ROOT_FOLDER_ID = "__root__";export interface SheetFolder {id: string;name: string;/** Absent or null means a root folder. A named parent must exist, or the server repairs it. */parent?: string | null;}/*** One change the server made to the payload it was handed.** β THE REASON THIS TYPE EXISTS AT ALL: a repair the client never sees is a folder that* reappears somewhere else with no explanation. `reason` is the machine name and the rail turns* it into a sentence; `folder_id` / `item_id` name the subject that moved (R16).*/export interface IndexRepair {reason: string;folder_id?: string;parent_id?: string;item_id?: string;}/** What `GET /api/v1/sheets/index` returns, and what `PUT` sends back with its repairs. */export interface WorkbookIndex {workbooks: WorkbookRow[];folders: SheetFolder[];itemFolders: Record<string, string>;starred: string[];repairs?: IndexRepair[];}export const emptyIndex = (): WorkbookIndex => ({workbooks: [],folders: [],itemFolders: {},starred: [],});export const isCellKind = (value: unknown): value is CellKind =>typeof value === "string" && (CELL_KINDS as readonly string[]).includes(value);export const isCellFormatKind = (value: unknown): value is CellFormatKind =>typeof value === "string" && (CELL_FORMAT_KINDS as readonly string[]).includes(value);/*** The number a format is applied to, or `null` when there is not one.** β A STORED VALUE MAY BE A STRING. `commitTyped` keeps what was typed, so `"1,240"` and `"12"`* both arrive here as text; stripping grouping and blanks is the whole of the coercion, and* anything that does not read as a finite number is refused a format rather than shown as NaN.*/export const asNumber = (value: unknown): number | null => {if (typeof value === "number") return Number.isFinite(value) ? value : null;if (typeof value !== "string") return null;const trimmed = value.replace(/[,\s]/g, "");if (trimmed === "") return null;const n = Number(trimmed);return Number.isFinite(n) ? n : null;};/*** How a formatted cell READS: on the canvas, in glide's clipboard, and therefore in an export.** ββ R10 IS NOT BENT BY THIS AND THE DISTINCTION MATTERS. A format PRESENTS the value the cell* already holds; it never asks the server for a new one and never recomputes anything. A sheet* stays a snapshot, and applying "Currency" to a stale cell shows the stale number in dollars,* which is exactly right.** β A REFUSED CELL IS NEVER FORMATTED. `displayText` hands back the refusal SENTENCE for one,* and running a sentence through a number formatter yields "NaN", which would replace the one* thing R16 exists to keep on the screen: the reason.*/export const formatCellText = (cell: Cell | null | undefined,fallback: string,): string => {const format = cell?.style?.format;if (!cell || !format) return fallback;if (cell.state === "refused") return fallback;// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ// β CONTRACT C7's SEAM, WIRED BY W51-T20 ON THE COMBINED TREE. The account below is// KEPT, because it is the reason this was a handover at all and a reader who deletes the// import will want it. What is no longer true is only the tense.//// ββ IT WAS DELIBERATELY UNWIRED ON `wave51/E`. A custom format CODE is parsed// by `ui/numberFormat.ts::formatWithCode(value, code, locale?)`, which is LANE F's file and// does not exist on this branch. Two things follow and both are on purpose://// 1. NOTHING IN THIS FILE IMPORTS IT. `sheetState.ts` is compiled to CommonJS and RUN by// `verify_api.py`, and tsc's emitted ROOT moves with the import graph: one `../ui/*`// import would drop every emitted module a level down and break every `require` path the// battery's existing proofs use. So the wiring waits for the merge rather than being// stubbed here against a file that is not in this tree.// 2. THE LEG THAT GUARDS IT IS RED ON PURPOSE. `verify_api.py` carries a check reading// "RED until W51-T20 wires it", and the five lines it is waiting for are the import plus// the `return formatWithCode(...)` that replaces the fallback below.//// β MEANWHILE A CODE FORMAT READS AS ITS OWN STORED VALUE rather than as a wrong number. That// is the honest direction: a person who asked for accounting brackets sees the plain figure// until the parser lands, and never sees a figure the code did not produce.// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ// β THE NARROWING GOES THROUGH AN `unknown` LOCAL, AND THAT IS THE POINT OF THE PREDICATE.// `CellStyle.format` is still ANNOTATED as the five kinds, so `isFormatCode(format)` narrows to// `CellFormat & CellFormatCode`, which tsc reduces to `never` (conflicting `kind`) and then// refuses `.code` outright. Widening the ANNOTATION is seven compile errors in `Ribbon.tsx` and// is deliberately still deferred, so this reads the spec through the one door built for it:// `isFormatCode` takes `unknown` precisely so a consumer can stay honest without editing a file// it does not own. No cast, and the predicate still does the proving.const spec: unknown = format;if (isFormatCode(spec)) {// β `Cell.value` is `unknown` and C7 takes `number | string | null | undefined`, so this is// a real guard rather than a cast either. Anything else -- a boolean, an object -- keeps the// behaviour this branch has always had and shows its own stored text, because handing a// formatter something it cannot render is how a cell starts painting a figure nobody stored.const raw = cell.value;if (typeof raw !== "number" && typeof raw !== "string") return fallback;return formatWithCode(raw, spec.code).text;}if (format.kind === "general") return fallback;if (format.kind === "date") {const raw = cell.value;const at = typeof raw === "number" ? new Date(raw) : new Date(String(raw ?? fallback));if (Number.isNaN(at.getTime())) return fallback;return at.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });}const n = asNumber(cell.value != null ? cell.value : fallback);if (n === null) return fallback;if (format.kind === "currency") {const digits = format.decimals != null ? format.decimals : 2;return new Intl.NumberFormat(undefined, {style: "currency",currency: format.currency || "USD",minimumFractionDigits: digits,maximumFractionDigits: digits,}).format(n);}if (format.kind === "percent") {const digits = format.decimals != null ? format.decimals : 0;return new Intl.NumberFormat(undefined, {style: "percent",minimumFractionDigits: digits,maximumFractionDigits: digits,}).format(n);}const digits = format.decimals != null ? format.decimals : 0;return new Intl.NumberFormat(undefined, {useGrouping: format.thousands === true,minimumFractionDigits: digits,maximumFractionDigits: digits,}).format(n);};export const isCellState = (value: unknown): value is CellState =>typeof value === "string" && (CELL_STATES as readonly string[]).includes(value);/** R19's count, said once: how many hand typed literals a workbook carries. */export const literalCount = (book: Workbook | null | undefined): number =>(book?.sheets ?? []).reduce((total, tab) =>total + Object.values(tab.cells ?? {}).filter((cell) => cell?.kind === "literal").length,0,);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750// The Sheet workbook and cell model (wave 49, W49-T02, contract C1).//// β W51-T20 (C7), WIRED AT THE COMBINE. This is the file's ONLY import, and its absence// was the whole reason the handover existed: `sheetState.ts` is compiled to CommonJS and// RUN by `verify_api.py`, and tsc's emitted ROOT moves with the import graph, so a// `../ui/*` import taken on `wave51/E` alone would have dropped every emitted module a// level down and broken every `require` path the battery's existing proofs use// ([[tsc-outdir-root-moves-with-the-import-graph]]). Lane F's module only exists on the// merged tree, so the import lands here and nowhere earlier.import { formatWithCode } from "../ui/numberFormat";//// β THIS FILE IS ONE HALF OF A PARITY GATE. `platform/core/sheets.py` declares CELL_KINDS and// CELL_STATES, and a check in `aios-web/api/verify_api.py` asserts that the two lists below match// them NAME FOR NAME. Adding a name on one side only is exactly what that check exists to catch,// so a new kind or state is a contract change made in both places at once, never here alone.//// β THERE IS NO `chart` KIND. W49-T08 stores a chart as a sibling `charts` array on the sheet,// so a chart never has to pretend to be a cell. Only the ROOT may amend C1./*** β Mirrored in `platform/core/sheets.py::CELL_KINDS`, name for name.** ββ W51-T16 / CONTRACT C2 ADDS `empty`, AND IT IS THE ONLY NAME C1's THREE HAVE EVER GAINED.* A cell may now carry `style` AND NOTHING ELSE: no value, no text, no formula, no binding. That* is what makes "select three blank cells and press Borders" paintable at all, and the reason it* could not be a fourth `literal` is one number on the screen. `sheetState.ts::handTypedCount`* counts every `literal` and the sheet PRINTS the count, so bolding a blank block of twenty* cells would have claimed twenty hand typed values nobody typed.** β THE SERVER HALF IS W51-T21's (lane D), AND UNTIL IT LANDS THE PARITY LEG IN* `verify_api.py::section_w49_sheet_contract` IS RED BY DESIGN: `core/sheets.py::clean_cell`* refuses an unknown kind BY NAME, so an empty styled cell cannot be SAVED yet. Everything below* is therefore proven in local state, which is exactly what C2 says each side owes the other.*/export const CELL_KINDS = ["literal", "formula", "bound", "empty"] as const;/** β FROZEN by contract C1. Mirrored in `platform/core/sheets.py::CELL_STATES`. */export const CELL_STATES = ["fresh", "stale", "typed", "refused"] as const;export type CellKind = (typeof CELL_KINDS)[number];export type CellState = (typeof CELL_STATES)[number];/*** R19's three states, said once so no component re-derives them:* bound and fresh (`bound` + `fresh`), bound and stale (`bound` + `stale`), and hand typed* (`literal`, which is always `typed`). `refused` is the fourth state and it is not one of the* three marks: it replaces the value rather than qualifying it.*/export interface CellRefusal {code: string;message: string;}/** A cell's provenance, filled in by the resolver (W49-T04), never by the client. */export interface CellSource {database: string;view_id?: string;filter?: unknown;}/*** C2's binding. Its INTERIOR is W49-T04's and W49-T06's business; it is carried here as an opaque* object so this file does not become a second declaration of the filter language.** ββ W51-T19 / C2 GAVE `period` AND `onDrag` REAL SHAPES AND STILL LEFT THIS ALIAS LOOSE, WHICH* IS A TYPE DECISION WITH A REASON RATHER THAN AN OMISSION. An index signature over `unknown`* paired with `period?: BindingPeriod` is NOT assignable from a plain `Record<string, unknown>`:* the source's index signature offers `unknown` where the target demands `BindingPeriod`, so* every existing consumer that hands a loose record to a binding slot would have become a* compile error in files this ticket does not own (`SheetPage.tsx:526`, `sheetApi.ts:134`,* `BindingEditor.tsx`'s `onSave`). The shapes are declared BESIDE the alias instead and narrowed* from `unknown` at one door each, exactly as {@link isFormatCode} narrows the code format. One* widening door, no consumer edited, and every C2 name still declared in this file.*/export type CellBinding = Record<string, unknown>;// ββ W51-T19, contract C2: the DRAG vocabulary (rulings R9 and R10) ββββββββββββββββββββββββββ//// ββ WHAT THESE NAMES ARE FOR. R9 and R10 make a bound cell DRAGGABLE: pulling it across// columns walks its period by one unit per column, pulling it down rows walks a chosen filter to// its next option, and a LOCKED period does neither. Before this, a bulk door simply refused to// copy a binding at all. The arithmetic is `sheetState.ts`'s and is pure; what lives here is the// VOCABULARY the document stores, because `verify_api.py` reads this file for it and// `platform/core/sheets.py` (lane D) has to accept exactly these names and no others.//// β THE READERS BELOW TOLERATE WHAT IS ALREADY STORED. `BindingEditor.tsx:134` writes// `period = { ref }` today: no `unit`, no `start`, no `locked`. C2 declares all three as required// and a reader that INSISTED on them would silently drop every binding shipping right now, which// is a verbatim copy where a shift was asked for and no error anywhere. So the readers fill the// contract's own defaults instead, and each default is pinned by a node leg./** β C2: the three units a period may be measured in. Mirrored in `core/sheets.py` by lane D. */export const PERIOD_UNITS = ["month", "quarter", "year"] as const;export type PeriodUnit = (typeof PERIOD_UNITS)[number];/** β C2 / R10: what an ACROSS COLUMNS drag does. `period` walks it; `none` copies it verbatim. */export const DRAG_ACROSS = ["period", "none"] as const;export type DragAcross = (typeof DRAG_ACROSS)[number];/*** C2's period. `start` is `YYYY-MM` for all three units, because a quarter and a year are both* said by the month they begin in and a second encoding would be a second thing to keep in step.*/export interface BindingPeriod {unit: PeriodUnit;/** `YYYY-MM`. Empty on a period that names only a {@link BindingPeriod.ref}. */start: string;/** β R9: locked means ANY copy keeps this period, in every direction, through every door. */locked: boolean;/** R14: a period read out of another CELL. Plain A1, `$` anchors honoured on a drag. */ref?: string;}/** C2 / R10: the field whose options a DOWN ROWS drag walks, one option per row of offset. */export interface BindingDragDown {field: string;}/** β C2 / R10: the two directional settings. Defaults are `across: "period"`, `down: "none"`. */export interface BindingOnDrag {across: DragAcross;down: BindingDragDown | "none";}/** C2: the view a cell's scope was ADOPTED from, kept so the cell can say where it came from. */export interface BindingAdoptedFrom {view_id: string;name: string;at: string;}const asRecord = (value: unknown): Record<string, unknown> | null =>value && typeof value === "object" && !Array.isArray(value)? (value as Record<string, unknown>): null;/*** Read a binding's C2 period, or `null` when it carries none.** β IT TAKES `unknown` FOR THE SAME REASON {@link isFormatCode} DOES: {@link CellBinding} is a* loose record, so a caller that asked the compiler would be told there is no period there while* the document plainly carries one. This is the one door that widens.** β `locked` DEFAULTS TO FALSE, WHICH IS THE PERMISSIVE ANSWER AND IS DELIBERATE. R9's lock is* something a person turns ON; a stored period with no `locked` key was written before the toggle* existed, so treating it as locked would make every period already on a sheet refuse to shift* with nothing on screen saying why.*/export const bindingPeriod = (binding: unknown): BindingPeriod | null => {const record = asRecord(binding);const period = record && asRecord(record.period);if (!period) return null;const unit = String(period.unit ?? "");const ref = typeof period.ref === "string" ? period.ref.trim() : "";const out: BindingPeriod = {unit: (PERIOD_UNITS as readonly string[]).includes(unit) ? (unit as PeriodUnit) : "month",start: typeof period.start === "string" ? period.start.trim() : "",locked: period.locked === true,};if (ref) out.ref = ref;return out;};/*** Read a binding's C2 drag rules, ALWAYS returning both, with R10's defaults filled in.** ββ THE DEFAULTS ARE THE RULING AND THEY ARE NOT SYMMETRIC. Across columns defaults to* `period`; down rows defaults to `none`. A reader that guessed the same answer for both axes* would make a cell dragged DOWN walk its period, which is the likeliest defect in this feature* and the one that looks correct in every screenshot of a single row.*/export const bindingOnDrag = (binding: unknown): BindingOnDrag => {const record = asRecord(binding);const rules = record && asRecord(record.onDrag);const across = String(rules?.across ?? "");const down = rules && asRecord(rules.down);const field = typeof down?.field === "string" ? down.field.trim() : "";return {across: (DRAG_ACROSS as readonly string[]).includes(across)? (across as DragAcross): "period",down: field ? { field } : "none",};};/** Read a binding's `scope.adoptedFrom` (C2), or `null`. Carried through a drag untouched. */export const bindingAdoptedFrom = (binding: unknown): BindingAdoptedFrom | null => {const record = asRecord(binding);const scope = record && asRecord(record.scope);const adopted = scope && asRecord(scope.adoptedFrom);if (!adopted) return null;return {view_id: String(adopted.view_id ?? ""),name: String(adopted.name ?? ""),at: String(adopted.at ?? ""),};};// ββ the cell STYLE slot (wave 50, W50-T19, amendment A1) ββββββββββββββββββββββββββββββββββββ//// β A1 ADDS A SLOT, NOT A NAME. `style` is a new FIELD on `Cell`; it adds nothing to// `CELL_KINDS` or `CELL_STATES`, which stay frozen exactly as C1 left them. That is why the// ribbon could be built without amending the vocabulary the four wave-49 tickets consume.//// ββ THE ASYMMETRY IS THE CONTRACT, AND IT IS DELIBERATE. `core/sheets.py::_clean_style` DROPS// an unknown style key in silence and REFUSES an unknown `format.kind` by name. The reason is// what each one costs: an unknown style key is a decoration the server cannot paint, and// discarding it loses nothing a reader would miss; an unknown `format.kind` decides how a NUMBER// reads, so accepting one the server cannot apply would show a value formatted differently from// what was asked, with nobody told. One is cosmetic, the other is a wrong number on a screen.//// β COLOURS ARE STORED AS TOKEN NAMES (`--lp-red-deep`), never as hex. DESIGN.md 3 is token// only, and a hex written into a stored document is a palette decision that outlives every// palette change. `SheetGrid.tsx` resolves the token against the document at paint time./** β Mirrored in `platform/core/sheets.py::CELL_FORMAT_KINDS`, and parity checked. */export const CELL_FORMAT_KINDS = ["general", "number", "currency", "percent", "date"] as const;/** β Mirrored in `platform/core/sheets.py::CELL_ALIGNS`. */export const CELL_ALIGNS = ["left", "center", "right"] as const;/** β C2: the VERTICAL three. Mirrored in `core/sheets.py::CELL_VALIGNS` by W51-T21. */export const CELL_VALIGNS = ["top", "middle", "bottom"] as const;/*** β C2's four step size scale, and it is a SIZE rather than a typeface: the app is Inter only,* so offering a font family would be offering a decision the design constitution already made.* `m` is the default and is stored as an ABSENCE, exactly as `format.kind === "general"` is.*/export const CELL_SIZES = ["s", "m", "l", "xl"] as const;export type CellFormatKind = (typeof CELL_FORMAT_KINDS)[number];export type CellAlign = (typeof CELL_ALIGNS)[number];export type CellValign = (typeof CELL_VALIGNS)[number];export type CellSize = (typeof CELL_SIZES)[number];/** C2: how far a cell's text is pushed in from its own edge, in steps rather than in pixels. */export const MAX_CELL_INDENT = 8;/** C2: a custom format code is at most this long, and carries at most four `;` sections. */export const MAX_FORMAT_CODE = 64;export const MAX_FORMAT_SECTIONS = 4;/** C2: a cell's list validation carries at most this many entries. */export const MAX_VALIDATION_LIST = 200;/** C2: a sheet carries at most this many conditional formatting rules. */export const MAX_SHEET_RULES = 100;export interface CellFormat {kind: CellFormatKind;/** Fixed decimal places. Clamped to 0 through 10 by the server. */decimals?: number;/** Thousands grouping. `number` only; a currency carries its own locale grouping. */thousands?: boolean;/** An ISO 4217 code. Absent means USD, which is the one the store's tenants price in. */currency?: string;}/*** ββ C2's CUSTOM FORMAT CODE, AND WHY IT IS A SEPARATE MEMBER RATHER THAN A SIXTH KIND.** `CELL_FORMAT_KINDS` is parity checked against `core/sheets.py::CELL_FORMAT_KINDS` name for* name, and every one of those five is a kind the client can RENDER ON ITS OWN through* `Intl.NumberFormat`. A code is not: `#,##0.00;(#,##0.00)` needs a parser, which is contract* C7's `ui/numberFormat.ts::formatWithCode` and belongs to W51-T20. So the code is admitted to* the DOCUMENT here, where the server can store it, without claiming this file can paint it.** β Excel's own accounting shape is the reason a code has SECTIONS: positive, negative, zero and* text, split on `;`. That is why the limit is a count of sections and not merely a length.*/export interface CellFormatCode {kind: "code";/** At most {@link MAX_FORMAT_CODE} characters and {@link MAX_FORMAT_SECTIONS} sections. */code: string;}/** What a cell's `format` slot may hold: one of the five kinds, or C2's custom code. */export type CellFormatSpec = CellFormat | CellFormatCode;/** C2: the accounting code R8's Number menu offers, said once so two sites cannot disagree. */export const ACCOUNTING_FORMAT_CODE = "#,##0.00;(#,##0.00);\"-\"";/*** Is this format C2's code format? ONE predicate, so no consumer re-derives the discriminant.** β IT TAKES `unknown` DELIBERATELY. `CellStyle.format` is still ANNOTATED as the five kinds (see* the note on that slot), so a reader that asked the compiler would be told the code format* cannot be there while the document plainly carries it. Widening at this one door is what lets* every consumer stay honest without editing a file this ticket does not own.*/export const isFormatCode = (format: unknown): format is CellFormatCode =>!!format && (format as CellFormatCode).kind === "code"&& typeof (format as CellFormatCode).code === "string";/** C2: a cell may offer a fixed list of values. The interior is W51-T17's; the slot is C2's. */export interface CellValidation {/** At most {@link MAX_VALIDATION_LIST} entries. */list: string[];}/** Only the sides that are ON are carried. An absent side has no border, said by its absence. */export interface CellBorder {top?: boolean;right?: boolean;bottom?: boolean;left?: boolean;}export interface CellStyle {bold?: boolean;italic?: boolean;underline?: boolean;/** A `--lp-*` token name for the ink. */color?: string;/** A `--lp-*` token name for the cell background. */fill?: string;align?: CellAlign;/*** β β TYPED AS `CellFormat` AND NOT AS `CellFormatSpec`, ON PURPOSE, AND THE REASON IS A FENCE* RATHER THAN A DESIGN. `Ribbon.tsx` narrows `style.format.kind` to `CellFormatKind` in seven* places and holds a `Record<CellFormatKind, string>` of labels, so widening this slot is a* compile error in a file W51-T15 owns and W51-T16 may not edit. THE DOCUMENT ALREADY CARRIES* THE CODE FORMAT (C2): {@link CellFormatCode} declares it, {@link formatCellText} reads it* through {@link CellFormatSpec}, and the store keeps it. What is deferred is only the* ANNOTATION, and with it the ribbon's Custom code label, both of which belong to W51-T20 when* it lands `formatWithCode`. Until then the ribbon's two code items say so rather than writing* a format nothing can paint.*/format?: CellFormat;border?: CellBorder;// ββ W51-T16, contract C2: the four R8 names that had no key to land in ββββββββββββββββββββ/** Where the value sits in the cell's own height. Absent means the middle, as glide paints. */valign?: CellValign;/** Whether a long value wraps onto more lines instead of clipping at the column edge. */wrap?: boolean;/** 0 through {@link MAX_CELL_INDENT}. Zero is stored as an ABSENCE, like every falsey mark. */indent?: number;/** The step size. `m` is the default and is stored as an ABSENCE. */size?: CellSize;}/*** One ribbon act. `null` REMOVES the key, which is how a toggle turns off: the server drops a* falsey mark rather than storing `false`, so "not bold" and "bold: false" must be the same* document or an undo would compare unequal to the thing it undid.*/export type CellStylePatch = { [K in keyof CellStyle]?: CellStyle[K] | null };/*** Does this style change how the cell is PAINTED, as opposed to only how its value reads?** ββ EVERY C2 KEY THAT MOVES A PIXEL IS LISTED HERE OR ITS CONTROL LOOKS INERT WITH EVERY GATE* GREEN. `SheetGrid.tsx::drawCell` asks this ONE question to decide whether it owns the cell's* paint: `false` hands the cell back to glide, which knows nothing about a vertical align, a* wrap, an indent or a size step. So a key added to `CellStyle` and forgotten here is a ribbon* button that applies a real style the reader never sees.*/export const stylePaints = (style: CellStyle | null | undefined): boolean =>!!style && (style.bold === true || style.italic === true || style.underline === true|| !!style.color || !!style.fill || !!style.align|| !!style.valign || style.wrap === true || !!style.size|| (typeof style.indent === "number" && style.indent > 0)|| Object.values(style.border ?? {}).some(Boolean));/*** Apply a patch, returning a NEW style or `undefined` when nothing is left.** β IT PRUNES. A key set to `null`, to `false` or to an empty border is removed rather than* stored falsey, so a cell that has been bolded and unbolded is byte for byte the cell it was.*/export const applyStylePatch = (style: CellStyle | null | undefined,patch: CellStylePatch,): CellStyle | undefined => {const next: Record<string, unknown> = { ...(style ?? {}) };for (const [key, value] of Object.entries(patch)) {if (value === null || value === false || value === undefined) delete next[key];else next[key] = value;}const border = next.border as CellBorder | undefined;if (border && !Object.values(border).some(Boolean)) delete next.border;const format = next.format as CellFormatSpec | undefined;if (format && format.kind === "general") delete next.format;// ββ THE TWO C2 DEFAULTS THE LOOP ABOVE CANNOT SEE. Its test is `null`, `false` or// `undefined`, and neither `0` nor `"m"` is any of the three. An indent of zero and a size of// `m` ARE the absence of a decision, so storing them would leave a cell that has been indented// and outdented comparing unequal to the cell it started as, which breaks an undo, a paste// comparison and a `rev` diff at once while looking completely reasonable in a payload.if (next.indent === 0) delete next.indent;if (next.size === "m") delete next.size;return Object.keys(next).length > 0 ? (next as CellStyle) : undefined;};export interface Cell {/*** β `empty` IS A REAL KIND WITH REAL RULES (C2). Such a cell carries `style` and nothing else:* it is not editable content, it was not hand typed, it has no value, and it must never be* counted by `handTypedCount`, drilled, or exported as a value. `state` is `fresh` on one,* meaning nothing is pending, because `CELL_STATES` is frozen and none of the four says* "there is nothing here" - the KIND already says that.*/kind: CellKind;state: CellState;/** A1: how this cell is painted and how its value reads. Absent on every wave-49 cell. */style?: CellStyle;/** C2: a fixed list of values this cell accepts. The editor is W51-T17's. */validation?: CellValidation;/** A hand typed literal's text. */text?: string;/** An A1 formula, including the leading `=`. */formula?: string;/** R10: the value as LAST COMPUTED. Nothing recomputes it on read. */value?: unknown;display?: string;binding?: CellBinding;source?: CellSource;refusal?: CellRefusal;refreshed_at?: string;}/** Cells are keyed by plain A1 address with no `$`; anchoring belongs to a formula's text. */export type CellMap = Record<string, Cell>;/*** A chart OCCUPIES a rectangle of cells and READS them (R9, R15). It is a sibling array on the* sheet, deliberately, and NOT a cell kind.** β C1 freezes `kind` to `literal | formula | bound`, and a `chart` kind would have meant amending* a contract that four other tickets already build against - which only the ROOT may do. Keeping* charts beside the cells also says something true: a chart has no value, no state and no binding,* so every field a `Cell` carries would have been dead weight on it.*/export interface SheetChartSpec {id: string;/** Zero-based inclusive rectangle. The header ROW is the axis (R15). */range: { col0: number; row0: number; col1: number; row1: number };kind: "bar" | "line" | "area" | "donut";}// ββ the sheet's GEOMETRY (wave 50, W50-T20, amendment A2) βββββββββββββββββββββββββββββββββββ//// ββ A2 MOVES THE GRID'S SHAPE OUT OF THE COMPONENT AND INTO THE DOCUMENT. `SheetGrid.tsx` held// `COLS = 26`, `ROWS = 200` and `COL_WIDTH = 120` as module constants, which is exactly why a// sheet could not grow and a dragged column could not be remembered: there was nowhere to put the// answer. The three below are the DEFAULTS a new sheet is created with, mirrored from// `platform/core/sheets.py::DEFAULT_SHEET_COLS` / `DEFAULT_SHEET_ROWS` / `DEFAULT_COL_WIDTH`, and// `verify_api.py` compares the two sides exactly as it does for the cell vocabulary.//// β THEY ARE DEFAULTS, NOT BOUNDS. Read the OPEN SHEET's `cols` / `rows` for what the grid can// show; a reader who reaches for these constants instead will refuse an address on a grown sheet./** β Mirrored in `platform/core/sheets.py::DEFAULT_SHEET_COLS`. */export const DEFAULT_SHEET_COLS = 26;/** β Mirrored in `platform/core/sheets.py::DEFAULT_SHEET_ROWS`. */export const DEFAULT_SHEET_ROWS = 200;/** β Mirrored in `platform/core/sheets.py::DEFAULT_COL_WIDTH`. */export const DEFAULT_COL_WIDTH = 120;/** β The ceiling a sheet may grow to. Mirrored in `platform/core/sheets.py::MAX_SHEET_COLS`. */export const MAX_SHEET_COLS = 702;/** β Mirrored in `platform/core/sheets.py::MAX_SHEET_ROWS`. */export const MAX_SHEET_ROWS = 100000;/** β Mirrored in `platform/core/sheets.py::MIN_COL_WIDTH` / `MAX_COL_WIDTH`. */export const MIN_COL_WIDTH = 40;export const MAX_COL_WIDTH = 1000;/*** How many leading columns and rows stay put while the rest scrolls. Absent means none.** ββ W51-T34 / R17 β BOTH HALVES RENDER NOW, AND THEY RENDER BY DIFFERENT MEANS. `cols` is* glide's own `freezeColumns` prop; `rows` has no equivalent in glide 6.0.3 at all* (`freezeTrailingRows` pins rows at the BOTTOM), so the frozen rows are drawn by a SECOND grid* mounted above the first and scrolled with it. `SheetGrid.tsx`'s own note carries the mechanism.* β Contract C2 freezes these two key names: `verify_sheet.py` and `verify_api.py` each grep the* other side's literal vocabulary, so renaming either reds a gate in a lane that never touched it.*/export interface SheetFreeze {cols?: number;rows?: number;}export interface SheetTab {id: string;name: string;cells: CellMap;/** A2: how many columns this sheet shows. Absent only on a sheet not yet read by the server. */cols?: number;/** A2: how many rows this sheet shows. */rows?: number;/** A2: `{"C": 220}` for the columns somebody dragged. A default width is stored as an absence. */colWidths?: Record<string, number>;/** A2: the frozen panes. */freeze?: SheetFreeze;/** Absent on every sheet written before W49-T08, which is why it is optional. */charts?: SheetChartSpec[];// ββ W51, contract C2: the sheet-level slots the ribbon's Cells and Styles groups need ββββββ/** C2: conditional formatting, at most {@link MAX_SHEET_RULES}. The editor is W51-T18's. */rules?: SheetRule[];/*** β C2: the 1 BASED rows this sheet hides, and 1 based is not a detail. Every other index in* this module that reaches glide is zero based, so the two are told apart by their name and by* this sentence: `hiddenRows` and `hiddenCols` speak the SHEET's own coordinates, the ones a* person reads off the row marker and the column letter, exactly as `StructureOp.at` does.*/hiddenRows?: number[];hiddenCols?: number[];/** C2: what an import brought in, and what of it this app could not carry. W51-T19 writes it. */imported?: SheetImport;}/** β C2's comparison vocabulary, closed. Mirrored in `core/sheets.py::SHEET_RULE_OPS`. */export const SHEET_RULE_OPS = ["gt", "lt", "gte", "lte", "eq", "neq", "between", "contains", "empty", "notEmpty",] as const;export type SheetRuleOp = (typeof SHEET_RULE_OPS)[number];/*** C2: one conditional formatting rule. The STYLE it may paint is deliberately a subset of* `CellStyle`: a rule decides a fill, an ink and a weight, and nothing that would move the cell's* geometry, because a rule that changed a row's height would repaint the sheet as data arrived.*/export interface SheetRule {id: string;/** An A1 range, `B2:D40`. */range: string;op: SheetRuleOp;value?: string | number;value2?: string | number;style: { fill?: string; color?: string; bold?: boolean };}/** C2: the receipt an import leaves, including what it could NOT carry (R16's honesty rule). */export interface SheetImport {at: string;source: string;unsupported: string[];}/** The extent to render this sheet at, defaulted once so no component re-decides it. */export const sheetExtent = (tab: SheetTab | null | undefined,): { cols: number; rows: number } => ({cols: Math.max(1, Math.round(tab?.cols ?? DEFAULT_SHEET_COLS)),rows: Math.max(1, Math.round(tab?.rows ?? DEFAULT_SHEET_ROWS)),});export interface Workbook {id: string;name: string;sheets: SheetTab[];rev: number;refreshed_at: string | null;created_by?: string;created_at?: string;updated_at?: string;}/** What `GET /api/v1/sheets` returns: identity only, never cells. */export interface WorkbookRow {id: string;name: string;created_by: string;created_at: string;updated_at: string;rev: number;refreshed_at: string | null;}// ββ the rail's document (wave 50, W50-T17) ββββββββββββββββββββββββββββββββββββββββββββββββββ//// β ONE FOLDER SURFACE, and that is the whole difference from `customer-grid/folders.ts`, whose// tree is keyed by surface ("views" / "cohorts") because a grid rail carries two of them. The// Sheet rail carries exactly one kind of row (wave-49 R2), so a surface key here would be a// constant wearing a map, and every reader would have to remember which key to look under.//// β A WORKBOOK LIVES IN EXACTLY ONE FOLDER, which is why `itemFolders` is a MAP and not a list// of pairs: single-valued by construction, so "which folder is this in" has one answer.// `ROOT_FOLDER_ID` is the reserved value meaning "filed at the top level, on purpose"./** The reserved placement meaning the top level. Mirrors `core/sheets.py::ROOT_FOLDER_ID`. */export const ROOT_FOLDER_ID = "__root__";export interface SheetFolder {id: string;name: string;/** Absent or null means a root folder. A named parent must exist, or the server repairs it. */parent?: string | null;}/*** One change the server made to the payload it was handed.** β THE REASON THIS TYPE EXISTS AT ALL: a repair the client never sees is a folder that* reappears somewhere else with no explanation. `reason` is the machine name and the rail turns* it into a sentence; `folder_id` / `item_id` name the subject that moved (R16).*/export interface IndexRepair {reason: string;folder_id?: string;parent_id?: string;item_id?: string;}/** What `GET /api/v1/sheets/index` returns, and what `PUT` sends back with its repairs. */export interface WorkbookIndex {workbooks: WorkbookRow[];folders: SheetFolder[];itemFolders: Record<string, string>;starred: string[];repairs?: IndexRepair[];}export const emptyIndex = (): WorkbookIndex => ({workbooks: [],folders: [],itemFolders: {},starred: [],});export const isCellKind = (value: unknown): value is CellKind =>typeof value === "string" && (CELL_KINDS as readonly string[]).includes(value);export const isCellFormatKind = (value: unknown): value is CellFormatKind =>typeof value === "string" && (CELL_FORMAT_KINDS as readonly string[]).includes(value);/*** The number a format is applied to, or `null` when there is not one.** β A STORED VALUE MAY BE A STRING. `commitTyped` keeps what was typed, so `"1,240"` and `"12"`* both arrive here as text; stripping grouping and blanks is the whole of the coercion, and* anything that does not read as a finite number is refused a format rather than shown as NaN.*/export const asNumber = (value: unknown): number | null => {if (typeof value === "number") return Number.isFinite(value) ? value : null;if (typeof value !== "string") return null;const trimmed = value.replace(/[,\s]/g, "");if (trimmed === "") return null;const n = Number(trimmed);return Number.isFinite(n) ? n : null;};/*** How a formatted cell READS: on the canvas, in glide's clipboard, and therefore in an export.** ββ R10 IS NOT BENT BY THIS AND THE DISTINCTION MATTERS. A format PRESENTS the value the cell* already holds; it never asks the server for a new one and never recomputes anything. A sheet* stays a snapshot, and applying "Currency" to a stale cell shows the stale number in dollars,* which is exactly right.** β A REFUSED CELL IS NEVER FORMATTED. `displayText` hands back the refusal SENTENCE for one,* and running a sentence through a number formatter yields "NaN", which would replace the one* thing R16 exists to keep on the screen: the reason.*/export const formatCellText = (cell: Cell | null | undefined,fallback: string,): string => {const format = cell?.style?.format;if (!cell || !format) return fallback;if (cell.state === "refused") return fallback;// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ// β CONTRACT C7's SEAM, WIRED BY W51-T20 ON THE COMBINED TREE. The account below is// KEPT, because it is the reason this was a handover at all and a reader who deletes the// import will want it. What is no longer true is only the tense.//// ββ IT WAS DELIBERATELY UNWIRED ON `wave51/E`. A custom format CODE is parsed// by `ui/numberFormat.ts::formatWithCode(value, code, locale?)`, which is LANE F's file and// does not exist on this branch. Two things follow and both are on purpose://// 1. NOTHING IN THIS FILE IMPORTS IT. `sheetState.ts` is compiled to CommonJS and RUN by// `verify_api.py`, and tsc's emitted ROOT moves with the import graph: one `../ui/*`// import would drop every emitted module a level down and break every `require` path the// battery's existing proofs use. So the wiring waits for the merge rather than being// stubbed here against a file that is not in this tree.// 2. THE LEG THAT GUARDS IT IS RED ON PURPOSE. `verify_api.py` carries a check reading// "RED until W51-T20 wires it", and the five lines it is waiting for are the import plus// the `return formatWithCode(...)` that replaces the fallback below.//// β MEANWHILE A CODE FORMAT READS AS ITS OWN STORED VALUE rather than as a wrong number. That// is the honest direction: a person who asked for accounting brackets sees the plain figure// until the parser lands, and never sees a figure the code did not produce.// βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ// β THE NARROWING GOES THROUGH AN `unknown` LOCAL, AND THAT IS THE POINT OF THE PREDICATE.// `CellStyle.format` is still ANNOTATED as the five kinds, so `isFormatCode(format)` narrows to// `CellFormat & CellFormatCode`, which tsc reduces to `never` (conflicting `kind`) and then// refuses `.code` outright. Widening the ANNOTATION is seven compile errors in `Ribbon.tsx` and// is deliberately still deferred, so this reads the spec through the one door built for it:// `isFormatCode` takes `unknown` precisely so a consumer can stay honest without editing a file// it does not own. No cast, and the predicate still does the proving.const spec: unknown = format;if (isFormatCode(spec)) {// β `Cell.value` is `unknown` and C7 takes `number | string | null | undefined`, so this is// a real guard rather than a cast either. Anything else -- a boolean, an object -- keeps the// behaviour this branch has always had and shows its own stored text, because handing a// formatter something it cannot render is how a cell starts painting a figure nobody stored.const raw = cell.value;if (typeof raw !== "number" && typeof raw !== "string") return fallback;return formatWithCode(raw, spec.code).text;}if (format.kind === "general") return fallback;if (format.kind === "date") {const raw = cell.value;const at = typeof raw === "number" ? new Date(raw) : new Date(String(raw ?? fallback));if (Number.isNaN(at.getTime())) return fallback;return at.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });}const n = asNumber(cell.value != null ? cell.value : fallback);if (n === null) return fallback;if (format.kind === "currency") {const digits = format.decimals != null ? format.decimals : 2;return new Intl.NumberFormat(undefined, {style: "currency",currency: format.currency || "USD",minimumFractionDigits: digits,maximumFractionDigits: digits,}).format(n);}if (format.kind === "percent") {const digits = format.decimals != null ? format.decimals : 0;return new Intl.NumberFormat(undefined, {style: "percent",minimumFractionDigits: digits,maximumFractionDigits: digits,}).format(n);}const digits = format.decimals != null ? format.decimals : 0;return new Intl.NumberFormat(undefined, {useGrouping: format.thousands === true,minimumFractionDigits: digits,maximumFractionDigits: digits,}).format(n);};export const isCellState = (value: unknown): value is CellState =>typeof value === "string" && (CELL_STATES as readonly string[]).includes(value);/** R19's count, said once: how many hand typed literals a workbook carries. */export const literalCount = (book: Workbook | null | undefined): number =>(book?.sheets ?? []).reduce((total, tab) =>total + Object.values(tab.cells ?? {}).filter((cell) => cell?.kind === "literal").length,0,);
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666// ---------------------------------------------------------------------------// shell/ShareDialog.tsx β WAVE 20 items 18 / 23 / 26 (R10, contract C-SHARE):// ONE dialog that shares a view, a folder or a database, and edits who already// has it.//// ONE dialog for three kinds is the ruling, not a convenience: R10 says folders// and databases share "with the SAME two-role vocabulary views use". Three// dialogs would drift into three vocabularies within a wave.//// It renders over the ALREADY-LOADED state and decides nothing itself β every// rule (what a junk entry means, who may administer, what the PUT carries) is in// `shareModel.ts`, where the access gate can run it.// ---------------------------------------------------------------------------import { useCallback, useEffect, useState } from "react";import { API_V1, CREDENTIALS } from "../apiContract";import PublishPanel from "../publish/PublishPanel";import {SHARE_ROLES,addablePeople,parseShare,sharePutBody,shareSummary,withEntry,withoutEntry,} from "./shareModel";import type { ShareEntry, ShareKind, ShareRole, ShareState } from "./shareModel";/*** ββ W39-T17 β THIS MAP DOES NOT DEGRADE, IT PRINTS THE WORD `undefined`. A kind with no entry* renders "Share undefined" in the heading AND "no longer has this undefined" in the revoke toast:* two live strings, not one. `Record<ShareKind, string>` is what stops that being a discovery β* add a member to `SHARE_KINDS` without one here and `tsc` names this line.*/const KIND_WORD: Record<ShareKind, string> = {view: "view",folder: "folder",database: "database",field: "field",workbook: "workbook",};// A newly-created field is posted through the standalone event queue. The// share dialog can open before that POST reaches the API, so give field lookups// a short, bounded chance to observe the definition before showing a 404.//// W50-T23 KEPT THIS DELIBERATELY, AND THE SERVER CHANGE IS WHAT SCOPED IT.// `GET /share/field/...` used to answer 404 for two different situations: a// column that does not exist yet (the create race above) and a column that// exists but is not this account's, which is far commoner. The route now// answers the second one with a 403 that names the column and its owner, so a// 404 on this kind means only "no definition in any stratum" -- which is the// race, and the one thing waiting can actually fix. Deleting the loop would// take the guard away from the race it was written for; the retry is now bounded// to that race by what the server can still answer, not by a client-side flag.const FIELD_SHARE_RETRY_MS = [150, 300, 600, 1000] as const;/** What each role MEANS on each kind, in the reader's own terms. A role picker* whose options are two nouns makes the reader guess; these sentences describe* the effective capability at the point where the role is chosen. */const ROLE_BLURB: Record<ShareKind, Record<ShareRole, string>> = {view: {view: "Can open this view. Cannot rename, refilter or delete it.",edit: "Can change this view's filters, sorts and columns.",},folder: {view: "Can open the folder and the views inside it.",edit: "Can rename the folder and move views in and out of it.",},database: {view: "Can open this database and read its records.",edit: "Can add, edit and delete its records.",},field: {view: "Can see this column. Cannot change its values or field settings.",edit: "Can change this column's values and field settings when the view is editable.",},/* R16, and the wording tracks the picker: a workbook's view role reads "View only", so thesentence under it says what "only" leaves out rather than restating the label. */workbook: {view: "View only: can open this workbook and read every sheet in it. Cannot change a cell, a formula or a binding.",edit: "Can change this workbook's cells, formulas and bindings.",},};/*** ββ W51-T10 / R16 β WHAT A WORKBOOK SHARE ACTUALLY HANDS OVER, AND THE HALF NOBODY EXPECTS.* A workbook's cells are not all values: a bound cell is a QUERY, and it is run again under* whoever is reading. So two people can open one shared workbook and honestly see two different* numbers, and the person doing the sharing has to be told that before they share.** β A `const`, NOT INLINE JSX, FOR THE REASON THIS FILE ALREADY RECORDS TWICE: `verify_prose`'s* JSX pass skips any run containing a newline, and a pinning regex cannot span a prettier line* wrap. `verify_wiring.py`'s W51-T10 section matches this literal.** β IT RENDERS ABOVE THE ROLE PICKER RATHER THAN INSIDE IT. The picker's blurb only paints once* the GET has answered, and the workbook share routes do not exist yet, so a sentence that lived* there alone would be absent in the only case that exists today.*/const WORKBOOK_BOUND_CELLS ="Bound cells show what each person may see: every bound cell is read again under the reader's own scope, so one workbook can honestly show two people different numbers.";/*** ββ THE DEGRADE, AND IT IS KEYED ON A RANGE RATHER THAN ON A LIST OF CODES. The workbook share* routes are contract C5's and land in W51-T25. Until they do, `GET /share/workbook/{id}` is an* UNBUILT route under a `/{kind}/{oid}` path param, which answers 405 as readily as 404, and* `core/shares.py` RAISES on a kind it does not know, which surfaces as a 400 or a 500. A code* list would therefore miss the very answer the server actually gives, and the reader would get* the generic "The server answered 405." instead: a status number, which is not a sentence and* tells them nothing they can act on. 403 stays on the ordinary path, because "you may not" is a* real answer about a route that exists.*/const WORKBOOK_NOT_SHAREABLE_YET ="This workbook cannot be shared yet. Workbook sharing is still being built, and this dialog will list who can reach it as soon as it is ready.";/*** ββ W42-T26 (owner instruction 8, R9, contract C7) β THE SHARER IS TOLD WHICH FIELDS TRAVEL.* Sharing a view grants every field the view NAMES, and until this landed the dialog said nothing* about fields at all. The trap the ticket names: T25 makes the behaviour correct and nothing on* screen changes, so the disclosure is the half that gets dropped.** β THESE ARE CONSTANTS, NOT INLINE JSX TEXT, FOR TWO REASONS. (1) `verify_prose`'s JSX pass skips* any run containing a newline [[web-prose-blind-to-wrapped-jsx]], and this file's own comments* record that blind spot twice; a `const` string literal is seen by the gate whatever prettier does* to the markup around it. (2) `wiring_rows/wave42_g.py` pins this copy by regex, and a regex* cannot span a JSX line wrap. Standing rule 2: no em dash and no en dash below.*/const VIEW_FIELD_TRAVEL ="Sharing a view also shares the fields it uses: the columns it shows, and the columns it groups by, colors by and sorts by.";/** β ITS OWN SENTENCE ON PURPOSE, and the non-obvious half of the disclosure. A sharer reasons* about the columns they can SEE; a condition may name one they never put on screen, and the* grant covers it all the same. The done-when calls this clause out separately, so it has to be* readable on its own rather than being a word inside a list.* β Do NOT restate the literal below in prose here: `wave42_g.py` pins it, and the WIRINGS loop* matches raw file text (comments included), so a paraphrase close enough to match would let the* row pass off its own explanation. */const VIEW_FILTER_FIELDS ="The filters count too. A filter can test a column that is not on screen, and sharing this view hands that column over as well.";/** β The grant is TOPIC-WIDE by construction (C7), so the dialog has to say so in the reader's* terms rather than let them assume it stops at this view. */const VIEW_FIELD_TOPIC_WIDE ="Each of those fields then shows on every view of this database, not only on this one.";const SHARED_FIELDS_LEAD = "Fields shared with this view:";const REFUSED_FIELDS_LEAD = "These fields could not be included:";/** One field the server named in its answer, with the reason it gave for refusing it. */type FieldNote = { key: string; reason: string };/*** `sharedFieldKeys` / `refusedFieldKeys` off the RAW PUT body, normalised.** β BOTH KEYS REMAIN OPTIONAL FOR BACKWARD COMPATIBILITY. Render nothing when either key is* missing or unusable and never throw. `shareModel.parseShare` cannot carry these (it builds a new* object with five fixed keys and drops the rest), so the raw response body remains the door.** β The shape is read defensively rather than assumed: `string[]`, `{key|colId|field, reason|why}[]`* and `Record<key, string | {reason}>` all normalise. The REASON TEXT IS THE SERVER'S, never* invented here, so a new refusal cause needs no client change.*/function fieldNotes(raw: unknown): FieldNote[] {const out: FieldNote[] = [];const push = (key: unknown, reason: unknown) => {const k = typeof key === "string" ? key.trim() : "";if (!k) return;out.push({ key: k, reason: typeof reason === "string" ? reason.trim() : "" });};if (Array.isArray(raw)) {for (const item of raw) {if (typeof item === "string") {push(item, "");} else if (item && typeof item === "object") {const rec = item as Record<string, unknown>;// The backend returns a stable reason code for machines and a complete message for the// person reading this dialog. Prefer that sentence; the code remains the safe fallback// for an older server or a future refusal shape that has not added copy yet.push(rec.key ?? rec.colId ?? rec.field, rec.message ?? rec.reason ?? rec.why);}}} else if (raw && typeof raw === "object") {for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {if (v && typeof v === "object") {const rec = v as Record<string, unknown>;push(k, rec.message ?? rec.reason ?? rec.why);} else {push(k, typeof v === "string" ? v : "");}}}return out;}export default function ShareDialog({kind,id,label,topic,me,onClose,onToast,}: {kind: ShareKind;id: string;label: string;/*** β W33-T27 (item 8b, R5) β the DATABASE a shared VIEW belongs to, so the publish control can* address it as `(topic, view)`. Empty for a folder or a database share, and empty is honest:* the panel simply does not render, which is also what happens on a view the server refuses to* publish. β Supplied by `Shell` at the mount (`shareModel.ShareRequest.topic`), not by this* dialog β see that field's note for why it is optional and how the mount is asserted.*/topic?: string;/** The signed-in account's username, so the reader recognises themselves in the* list. `people` is deliberately the OTHER accounts (it is the add-picker's* source), so without this the owner row prints a raw login where every other* row prints a name. */me: string;onClose: () => void;onToast: (message: string) => void;}) {const [state, setState] = useState<ShareState | null>(null);const [entries, setEntries] = useState<ShareEntry[]>([]);const [error, setError] = useState("");const [busy, setBusy] = useState(false);const [pick, setPick] = useState("");const [pickRole, setPickRole] = useState<ShareRole>("view");// W42-T26 β the RESULT half: what the last successful save actually granted, and what it// refused. Empty until a save answers, and empty again whenever one answers without the keys.const [sharedFields, setSharedFields] = useState<FieldNote[]>([]);const [refusedFields, setRefusedFields] = useState<FieldNote[]>([]);// W50-T23 / R7 -- the owner in the words a person reads, resolved by the server// through the account registry, with "System (Odoo)" standing in for a column// the connector wrote. `parseShare` builds a fixed five-key object and drops// everything else, so this rides off the raw body exactly as `fieldNotes` does.const [ownerLabel, setOwnerLabel] = useState("");const path = `${API_V1}/share/${encodeURIComponent(kind)}/${encodeURIComponent(id)}`;useEffect(() => {let dead = false;setError("");void (async () => {try {let res: Response;for (let attempt = 0; ; attempt += 1) {res = await fetch(path, { credentials: CREDENTIALS });if (res.status !== 404 ||kind !== "field" ||attempt >= FIELD_SHARE_RETRY_MS.length) {break;}await new Promise<void>((resolve) => {window.setTimeout(resolve, FIELD_SHARE_RETRY_MS[attempt]);});if (dead) return;}if (!res.ok) {// W51-T10: the workbook kind has no route yet. A sentence, never a status number, and// never a blank dialog. See `WORKBOOK_NOT_SHAREABLE_YET` for why the test is a range.if (kind === "workbook" && res.status >= 400 && res.status !== 403) {if (!dead) setError(WORKBOOK_NOT_SHAREABLE_YET);return;}// 4xx text is policy the reader needs; a 5xx's internals are not theirs.if (!dead) setError(res.status >= 500? "Something went wrong on our side. Try again in a moment.": `The server answered ${res.status}.`);return;}const body = (await res.json().catch(() => null)) as unknown;if (dead) return;const parsed = parseShare(body);setState(parsed);setEntries(parsed.entries);setOwnerLabel(body && typeof body === "object"&& typeof (body as { ownerLabel?: unknown }).ownerLabel === "string"? ((body as { ownerLabel?: string }).ownerLabel ?? "").trim(): "");} catch {if (!dead) setError("Cannot reach the server.");}})();return () => {dead = true;};}, [path]);// β ESCAPE CLOSES A MODAL, or its scrim becomes a trap β the wave-18 lesson this// shell already carries at its other two dialogs.useEffect(() => {const onKey = (e: KeyboardEvent) => {if (e.key === "Escape" && !busy) onClose();};window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);}, [busy, onClose]);const save = useCallback(async (next: ShareEntry[]) => {setBusy(true);setError("");// A new request invalidates the field report immediately. If it fails before receiving an// HTTP response, the dialog must not leave the previous save's result beside that failure.setSharedFields([]);setRefusedFields([]);try {const res = await fetch(path, {method: "PUT",credentials: CREDENTIALS,headers: { "Content-Type": "application/json" },// The WHOLE list, every time: the PUT replaces, so a body assembled from// a delta would revoke everyone it failed to mention.body: JSON.stringify(sharePutBody(next)),});if (!res.ok) {const body = (await res.json().catch(() => null)) as| { error?: { message?: string } }| null;setError(res.status >= 500? "Something went wrong on our side. Try again in a moment.": body?.error?.message || `The server answered ${res.status}.`);return false;}const body = (await res.json().catch(() => null)) as unknown;// Re-read the SERVER's copy rather than trusting the draft: `_clean_entries`// drops what it will not store, and an editor that kept showing a row the// store rejected would be the "shared, silently inert" failure this feature// exists to avoid.// β Only `.entries` is consumed here β the PUT answers with the stored record// (`{owner, entries}`) and says nothing about this session's standing, so the// literal below feeds the parser's required field and is never read back. The// editor's `mayAdminister` stays the one the GET established; a save cannot// promote anybody, and this line must never be the reason it looks like it can.const saved = parseShare({ ...(body as object), mayAdminister: true });setEntries(saved.entries);// β W42-T26 / C7 β read STRAIGHT OFF THE RAW BODY, because `parseShare` keeps five keys// and drops everything else, and `shareModel.ts` is another lane's file this wave.const answered = (body ?? null) as Record<string, unknown> | null;setSharedFields(fieldNotes(answered?.sharedFieldKeys));setRefusedFields(fieldNotes(answered?.refusedFieldKeys));return true;} catch {setError("Cannot reach the server.");return false;} finally {setBusy(false);}},[path]);const mayAdminister = !!state?.mayAdminister;const assign = useCallback(async (user: string) => {setBusy(true); setError("");try {const res = await fetch(`${path}/assign`, {method: "POST", credentials: CREDENTIALS,headers: { "Content-Type": "application/json" }, body: JSON.stringify({ user }),});if (!res.ok) { setError(`The server answered ${res.status}.`); return; }onToast(`${nameOf(user)} now has this assigned view.`);} catch { setError("Cannot reach the server."); }finally { setBusy(false); }}, [path, onToast]);const options = state ? addablePeople(state.people, entries) : [];const nameOf = (user: string) =>user === "*"? "Everyone": user && user === me.trim().toLowerCase()? "You": state?.people.find((p) => p.user === user)?.name ?? user;return (<div className="shell-newdb-scrim" onClick={() => (busy ? null : onClose())}><divclassName="shell-newdb shell-share"role="dialog"aria-label={`Share ${label}`}onClick={(e) => e.stopPropagation()}><h2>Share {KIND_WORD[kind]}</h2>{/* ββ W33-T30 / audit S-8 β THIS SENTENCE WAS FALSE FOR ONE OF THE THREE KINDS.It read, unconditionally, "Sharing never widens past this workspace: everyone herecan already open the surface it lives on." True for a VIEW or a FOLDER on a governedmodule, where the receiver's row scope and hidden-field closure run before anyforeign view is merged. FALSE for a `database` grant on a `ut_*` table: no row filterand no hidden field can even be DECLARED there (`_PERM_MODULES` is two keys and`_clean_perms` 400s the rest), so the grant registry IS the only wall and the grantis all-or-nothing. The audit's fix is "say so at BOTH doors"; `core/shares.py` and`routes_shares.py` are the other two, and this is the one a PERSON reads. */}{/* β STANDING RULE 2 (D-490, W39-T17) β THIS LINE CARRIED AN EM DASH TO THE SCREEN AND`verify_prose.py` SCORED THE FILE ZERO. The prose run WRAPS, and the gate's JSX passskips any run containing a newline [[web-prose-blind-to-wrapped-jsx]] β the same blindspot already recorded twenty lines below. REWRITTEN, not stripped: the question thedialog answers is now the sentence's subject, which needs no dash at all. */}<p className="shell-newdb-sub">Who can reach <strong>{label}</strong>, and what they can do with it.{" "}{kind === "workbook"? WORKBOOK_BOUND_CELLS: kind === "database"? "Sharing a database shares all of it: every record and every column. There is no per-row or per-column limit on a database grant.": kind === "field"? "A shared column starts out hidden from everybody else on this database. This is what lets the people you choose see it and its values.": "Sharing never widens past this workspace: everyone here can already open the surface it lives on."}</p>{kind === "view" ? (<><p className="shell-share-note">View access is the general rule. A field's own Share field access takes precedence, soa field shared as Can view stays read-only even inside an editable view.</p>{/* ββ W42-T26 / C7 β WHICH FIELDS TRAVEL, and how far. Two paragraphs, not one andnot four: the done-when reads for three statements (what travels, the FILTER'sfields by name, and the topic-wide reach), and a sharer must be able to point at asentence for each without reading an essay in a dialog subtitle. */}<p className="shell-share-note">{VIEW_FIELD_TRAVEL} {VIEW_FIELD_TOPIC_WIDE}</p><p className="shell-share-note">{VIEW_FILTER_FIELDS}</p></>) : kind === "field" ? (<p className="shell-share-note">Field access takes precedence over the view. Can view keeps values and field settingsread-only; Can edit allows changes when the view is editable.</p>) : null}{!state && !error ? (<div className="shell-share-wait"><span className="lp-spin" role="status" aria-label="Loading" /></div>) : null}{state ? (<>{/* THE MANAGE-ACCESS EDITOR (item 23): the list first, because thequestion people open this for is "who has this already" β with theone-line answer above it, since the fact that changes everything("Everyone can edit") is the one a list of rows buries. */}<p className="shell-share-summary">{shareSummary(entries)}</p>{/* ββ W42-T26 / C7 β THE RESULT: which fields actually travelled, and which could not,each with the reason the SERVER gave. Absent both keys this renders nothing at allso an older server remains compatible.β NO NEW CLASSES. `index.css` is another lane's file this wave and a lane sheetloses every equal-specificity fight with it [[a-lane-stylesheet-cannot-override-index-css]],so a refusal reuses the row/who/role anatomy the entries list already paints. */}{kind === "view" && sharedFields.length > 0 ? (<p className="shell-share-note">{SHARED_FIELDS_LEAD} {sharedFields.map((f) => f.key).join(", ")}</p>) : null}{kind === "view" && refusedFields.length > 0 ? (<><p className="shell-share-note">{REFUSED_FIELDS_LEAD}</p><div className="shell-share-list">{refusedFields.map((f) => (<div className="shell-share-row" key={f.key}><span className="shell-share-who">{f.key}</span>{f.reason ? <span className="shell-share-role">{f.reason}</span> : null}</div>))}</div></>) : null}<div className="shell-share-list">{/* W50-T23 / R7 -- THE OWNER ROW IS NEVER BLANK AND NEVER ABSENT. Under R7every editable field has an owner (its creator, else the tenantAdministrator) and a connector column reads "System (Odoo)", so there isalways something true to print. The old `: null` arm rendered NOTHING fora column whose owner the server could not name, which is how a memberended up being told to ask somebody the dialog never showed them.`ownerLabel` is preferred over `nameOf` only when `nameOf` could notresolve the username: a member gets `people: []`, so `nameOf` would printa raw login where the server already knows the real name. */}{state.owner || (kind === "field" && ownerLabel) ? (<div className="shell-share-row is-owner"><span className="shell-share-who">{state.owner? nameOf(state.owner) === state.owner? ownerLabel || state.owner: nameOf(state.owner): ownerLabel}</span><span className="shell-share-role">Owner</span></div>) : null}{entries.length === 0 ? (<div className="shell-share-empty">Not shared with anyone yet.</div>) : null}{entries.map((e) => (<div className="shell-share-row" key={e.user}><span className="shell-share-who">{nameOf(e.user)}</span><selectclassName="shell-share-select"value={e.role}disabled={!mayAdminister || busy}aria-label={`Role for ${nameOf(e.user)}`}onChange={(ev) => {const next = withEntry(entries, e.user, ev.target.value as ShareRole);setEntries(next);void save(next);}}>{/* β W51-T10 / R16 β THE LABEL IS PER KIND, exactly as `KIND_WORD` and`ROLE_BLURB` are. A workbook's read role is "View only" (the ruling's ownwords); the other four kinds keep "Can view" byte for byte, becausere-wording one label across a shared control is a repo-wide gate grep. */}{SHARE_ROLES.map((r) => (<option key={r} value={r}>{r === "edit"? "Can edit": kind === "workbook" ? "View only" : "Can view"}</option>))}</select><buttontype="button"className="shell-share-revoke"disabled={!mayAdminister || busy}onClick={() => {const next = withoutEntry(entries, e.user);setEntries(next);void save(next).then((ok) => {if (ok) onToast(`${nameOf(e.user)} no longer has this ${KIND_WORD[kind]}.`);});}}>Remove</button>{kind === "view" && mayAdminister && e.user !== "*" ? (<button type="button" className="shell-share-revoke" disabled={busy}onClick={() => void assign(e.user)}>Assign</button>) : null}</div>))}</div>{mayAdminister ? (<div className="shell-share-add"><selectclassName="shell-share-select"value={pick}disabled={busy}aria-label="Who to share with"onChange={(e) => setPick(e.target.value)}>{/* β An explicit placeholder OPTION, not a blank first row: a<select> whose value matches nothing renders its first optionwhile holding "", so the box would read as a chosen person andthe button beside it would grant somebody nobody picked([[cg-condition-builder-items]]). */}<option value="">Choose a personβ¦</option><option value="*">Everyone in this workspace</option>{options.map((p) => (<option key={p.user} value={p.user}>{p.name}</option>))}</select><selectclassName="shell-share-select"value={pickRole}disabled={busy}aria-label="Role for the person being added"onChange={(e) => setPickRole(e.target.value as ShareRole)}>{/* The add-person picker says the same words the row picker says. */}{SHARE_ROLES.map((r) => (<option key={r} value={r}>{r === "edit"? "Can edit": kind === "workbook" ? "View only" : "Can view"}</option>))}</select><buttontype="button"className="login-submit shell-share-grant"disabled={busy || !pick}onClick={() => {const next = withEntry(entries, pick, pickRole);setEntries(next);void save(next).then((ok) => {if (ok) {onToast(kind === "field"? `${nameOf(pick)} can now ${pickRole === "edit" ? "edit" : "view"} this field.`: `${nameOf(pick)} can now ${pickRole} this ${KIND_WORD[kind]}.`);setPick("");}});}}>Share</button><p className="shell-share-blurb">{ROLE_BLURB[kind][pickRole]}</p>{/* β W33-T30 / audit S-5 β `*` + `edit` IS A TENANT-WIDE WRITE GRANT AND LOOKEDLIKE ANY OTHER ROW. Two ordinary choices β a population and a role, eachunremarkable alone β combine into "anybody here may change this", and thedialog said nothing at the point where the two meet. The audit's fix is"make the population legible at the point of choice": one sentence, only onthe combination, in the words of the consequence rather than of the setting.β It is NOT a confirm step. The capability is real and deliberate; a personchoosing it on purpose should not be interrogated, only told what it means. */}{/* β `shell-share-note`, the class the refusal below already uses, rather than anew `shell-share-warn`: `index.css` is B's file this wave (contract C4), and anew class with no rule renders as unstyled body text β which for a sentencewhose whole job is to be NOTICED is worse than reusing a quiet one. */}{/* β STANDING RULE 2 (wave-36 QA) β the sentence below carried an em dash and`web_prose` scored this file 0 findings: the prose run WRAPS, and the gate'sJSX pass skips any run containing a newline [[web-prose-blind-to-wrapped-jsx]].REWRITTEN, not merely stripped β the comma keeps the contrast the sentenceexists to draw. */}{pick === "*" && pickRole === "edit" ? (<p className="shell-share-note">Everyone in this workspace will be able to change this {KIND_WORD[kind]},not just open it.</p>) : null}</div>) : (// β NOT A HIDDEN EDITOR β a stated refusal. A collaborator who can// change this object's CONTENT still cannot change who else reaches// it (the server's rule; this is the courtesy half). Saying why beats// greying three controls and letting the reader guess.// β STANDING RULE 2 (W39-T17) β TWO em dashes, live on screen, and `verify_prose`// green over both for the wrapped-JSX reason recorded above. NOT a pre-existing// violation this ticket may leave alone: adding `field` to `KIND_WORD` is what// brings this sentence to a NEW surface, so it ships the dash rather than merely// inheriting it. Rewritten with the owner in the subject, so no aside is needed.<p className="shell-share-note">Only this {KIND_WORD[kind]}'s owner and workspace administrators can change whoit is shared with. You can still use it as your role allows.</p>)}</>) : null}{/* ββ W33-T27 (item 8b, R5) β PUBLISH, below the grant editor and inside the samedialog, because this is where a person comes to ask "who can reach this?".β IT IS NOT A FOURTH ROLE IN THE LIST ABOVE, and the panel says so in its ownwords: a published link names nobody, creates no grant and is revoked by replacingthe link rather than by removing a person. Folding it into the entries list wouldhave made "the public" look like a grantee β which is precisely the conflation thesharing audit's S-4 row is about (two systems already answer "is this shared"; thisis a third thing).β ONLY FOR A VIEW, and only when the shell knew which database it belongs to. Thepanel then asks the SERVER whether this particular view may be published and rendersnothing if not β so "absent on non-interface views" is one evaluator, not two. */}{kind === "view" && topic ? <PublishPanel topic={topic} view={id} /> : null}{error ? <p className="shell-newdb-err">{error}</p> : null}</div></div>);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676// ---------------------------------------------------------------------------// shell/ShareDialog.tsx β WAVE 20 items 18 / 23 / 26 (R10, contract C-SHARE):// ONE dialog that shares a view, a folder or a database, and edits who already// has it.//// ONE dialog for three kinds is the ruling, not a convenience: R10 says folders// and databases share "with the SAME two-role vocabulary views use". Three// dialogs would drift into three vocabularies within a wave.//// It renders over the ALREADY-LOADED state and decides nothing itself β every// rule (what a junk entry means, who may administer, what the PUT carries) is in// `shareModel.ts`, where the access gate can run it.// ---------------------------------------------------------------------------import { useCallback, useEffect, useState } from "react";import { API_V1, CREDENTIALS } from "../apiContract";import PublishPanel from "../publish/PublishPanel";import {SHARE_ROLES,addablePeople,parseShare,sharePutBody,shareSummary,withEntry,withoutEntry,} from "./shareModel";import type { ShareEntry, ShareKind, ShareRole, ShareState } from "./shareModel";/*** ββ W39-T17 β THIS MAP DOES NOT DEGRADE, IT PRINTS THE WORD `undefined`. A kind with no entry* renders "Share undefined" in the heading AND "no longer has this undefined" in the revoke toast:* two live strings, not one. `Record<ShareKind, string>` is what stops that being a discovery β* add a member to `SHARE_KINDS` without one here and `tsc` names this line.*/const KIND_WORD: Record<ShareKind, string> = {view: "view",folder: "folder",database: "database",field: "field",workbook: "workbook",};// A newly-created field is posted through the standalone event queue. The// share dialog can open before that POST reaches the API, so give field lookups// a short, bounded chance to observe the definition before showing a 404.//// W50-T23 KEPT THIS DELIBERATELY, AND THE SERVER CHANGE IS WHAT SCOPED IT.// `GET /share/field/...` used to answer 404 for two different situations: a// column that does not exist yet (the create race above) and a column that// exists but is not this account's, which is far commoner. The route now// answers the second one with a 403 that names the column and its owner, so a// 404 on this kind means only "no definition in any stratum" -- which is the// race, and the one thing waiting can actually fix. Deleting the loop would// take the guard away from the race it was written for; the retry is now bounded// to that race by what the server can still answer, not by a client-side flag.const FIELD_SHARE_RETRY_MS = [150, 300, 600, 1000] as const;/** What each role MEANS on each kind, in the reader's own terms. A role picker* whose options are two nouns makes the reader guess; these sentences describe* the effective capability at the point where the role is chosen. */const ROLE_BLURB: Record<ShareKind, Record<ShareRole, string>> = {view: {view: "Can open this view. Cannot rename, refilter or delete it.",edit: "Can change this view's filters, sorts and columns.",},folder: {view: "Can open the folder and the views inside it.",edit: "Can rename the folder and move views in and out of it.",},database: {view: "Can open this database and read its records.",edit: "Can add, edit and delete its records.",},field: {view: "Can see this column. Cannot change its values or field settings.",edit: "Can change this column's values and field settings when the view is editable.",},/* R16, and the wording tracks the picker: a workbook's view role reads "View only", so thesentence under it says what "only" leaves out rather than restating the label. */workbook: {view: "View only: can open this workbook and read every sheet in it. Cannot change a cell, a formula or a binding.",edit: "Can change this workbook's cells, formulas and bindings.",},};/*** ββ W51-T10 / R16 β WHAT A WORKBOOK SHARE ACTUALLY HANDS OVER, AND THE HALF NOBODY EXPECTS.* A workbook's cells are not all values: a bound cell is a QUERY, and it is run again under* whoever is reading. So two people can open one shared workbook and honestly see two different* numbers, and the person doing the sharing has to be told that before they share.** β A `const`, NOT INLINE JSX, FOR THE REASON THIS FILE ALREADY RECORDS TWICE: `verify_prose`'s* JSX pass skips any run containing a newline, and a pinning regex cannot span a prettier line* wrap. `verify_wiring.py`'s W51-T10 section matches this literal.** β IT RENDERS ABOVE THE ROLE PICKER RATHER THAN INSIDE IT. The picker's blurb only paints once* the GET has answered, and the workbook share routes do not exist yet, so a sentence that lived* there alone would be absent in the only case that exists today.*/const WORKBOOK_BOUND_CELLS ="Bound cells show what each person may see: every bound cell is read again under the reader's own scope, so one workbook can honestly show two people different numbers.";/*** ββ THE DEGRADE, AND IT IS KEYED ON A RANGE RATHER THAN ON A LIST OF CODES. `GET* /share/workbook/{id}` sits under a `/{kind}/{oid}` path param, so an id this account cannot* reach answers 404 while a shape the server dislikes can surface as 400, 405 or 500. A code* list would miss the very answer the server actually gives, and the reader would get the* generic "The server answered 405." instead: a status number, which is not a sentence and* tells them nothing they can act on. 403 stays on the ordinary path, because "you may not" is* a real answer about a route that exists.** β THE SENTENCE CHANGED AT THE WAVE-51 GO-LIVE QA, AND THE OLD ONE WAS THE DEFECT.* It read *"Workbook sharing is still being built"*, which was true when W51-T10 shipped* against an unbuilt server half and FALSE the moment W51-T25 landed beside it in the combine.* The QA pass then found the real cause: `routes_shares.py::_owns_object` carried no* `workbook` branch, so the owner of an unshared workbook was answered `404 no_object` and this* copy explained a shipped feature away as unbuilt. The branch exists now; this string is the* ordinary degrade for a workbook that genuinely cannot be reached, and it no longer makes a* claim about the product's roadmap that only a code reader could falsify.* β NO EM DASH AND NO EN DASH: this reaches a screen (standing rule 2).*/const WORKBOOK_SHARE_UNREACHABLE ="This workbook's sharing list could not be loaded. Close and reopen the dialog; if it keeps failing, the workbook may have been deleted, or it may no longer be yours to share.";/*** ββ W42-T26 (owner instruction 8, R9, contract C7) β THE SHARER IS TOLD WHICH FIELDS TRAVEL.* Sharing a view grants every field the view NAMES, and until this landed the dialog said nothing* about fields at all. The trap the ticket names: T25 makes the behaviour correct and nothing on* screen changes, so the disclosure is the half that gets dropped.** β THESE ARE CONSTANTS, NOT INLINE JSX TEXT, FOR TWO REASONS. (1) `verify_prose`'s JSX pass skips* any run containing a newline [[web-prose-blind-to-wrapped-jsx]], and this file's own comments* record that blind spot twice; a `const` string literal is seen by the gate whatever prettier does* to the markup around it. (2) `wiring_rows/wave42_g.py` pins this copy by regex, and a regex* cannot span a JSX line wrap. Standing rule 2: no em dash and no en dash below.*/const VIEW_FIELD_TRAVEL ="Sharing a view also shares the fields it uses: the columns it shows, and the columns it groups by, colors by and sorts by.";/** β ITS OWN SENTENCE ON PURPOSE, and the non-obvious half of the disclosure. A sharer reasons* about the columns they can SEE; a condition may name one they never put on screen, and the* grant covers it all the same. The done-when calls this clause out separately, so it has to be* readable on its own rather than being a word inside a list.* β Do NOT restate the literal below in prose here: `wave42_g.py` pins it, and the WIRINGS loop* matches raw file text (comments included), so a paraphrase close enough to match would let the* row pass off its own explanation. */const VIEW_FILTER_FIELDS ="The filters count too. A filter can test a column that is not on screen, and sharing this view hands that column over as well.";/** β The grant is TOPIC-WIDE by construction (C7), so the dialog has to say so in the reader's* terms rather than let them assume it stops at this view. */const VIEW_FIELD_TOPIC_WIDE ="Each of those fields then shows on every view of this database, not only on this one.";const SHARED_FIELDS_LEAD = "Fields shared with this view:";const REFUSED_FIELDS_LEAD = "These fields could not be included:";/** One field the server named in its answer, with the reason it gave for refusing it. */type FieldNote = { key: string; reason: string };/*** `sharedFieldKeys` / `refusedFieldKeys` off the RAW PUT body, normalised.** β BOTH KEYS REMAIN OPTIONAL FOR BACKWARD COMPATIBILITY. Render nothing when either key is* missing or unusable and never throw. `shareModel.parseShare` cannot carry these (it builds a new* object with five fixed keys and drops the rest), so the raw response body remains the door.** β The shape is read defensively rather than assumed: `string[]`, `{key|colId|field, reason|why}[]`* and `Record<key, string | {reason}>` all normalise. The REASON TEXT IS THE SERVER'S, never* invented here, so a new refusal cause needs no client change.*/function fieldNotes(raw: unknown): FieldNote[] {const out: FieldNote[] = [];const push = (key: unknown, reason: unknown) => {const k = typeof key === "string" ? key.trim() : "";if (!k) return;out.push({ key: k, reason: typeof reason === "string" ? reason.trim() : "" });};if (Array.isArray(raw)) {for (const item of raw) {if (typeof item === "string") {push(item, "");} else if (item && typeof item === "object") {const rec = item as Record<string, unknown>;// The backend returns a stable reason code for machines and a complete message for the// person reading this dialog. Prefer that sentence; the code remains the safe fallback// for an older server or a future refusal shape that has not added copy yet.push(rec.key ?? rec.colId ?? rec.field, rec.message ?? rec.reason ?? rec.why);}}} else if (raw && typeof raw === "object") {for (const [k, v] of Object.entries(raw as Record<string, unknown>)) {if (v && typeof v === "object") {const rec = v as Record<string, unknown>;push(k, rec.message ?? rec.reason ?? rec.why);} else {push(k, typeof v === "string" ? v : "");}}}return out;}export default function ShareDialog({kind,id,label,topic,me,onClose,onToast,}: {kind: ShareKind;id: string;label: string;/*** β W33-T27 (item 8b, R5) β the DATABASE a shared VIEW belongs to, so the publish control can* address it as `(topic, view)`. Empty for a folder or a database share, and empty is honest:* the panel simply does not render, which is also what happens on a view the server refuses to* publish. β Supplied by `Shell` at the mount (`shareModel.ShareRequest.topic`), not by this* dialog β see that field's note for why it is optional and how the mount is asserted.*/topic?: string;/** The signed-in account's username, so the reader recognises themselves in the* list. `people` is deliberately the OTHER accounts (it is the add-picker's* source), so without this the owner row prints a raw login where every other* row prints a name. */me: string;onClose: () => void;onToast: (message: string) => void;}) {const [state, setState] = useState<ShareState | null>(null);const [entries, setEntries] = useState<ShareEntry[]>([]);const [error, setError] = useState("");const [busy, setBusy] = useState(false);const [pick, setPick] = useState("");const [pickRole, setPickRole] = useState<ShareRole>("view");// W42-T26 β the RESULT half: what the last successful save actually granted, and what it// refused. Empty until a save answers, and empty again whenever one answers without the keys.const [sharedFields, setSharedFields] = useState<FieldNote[]>([]);const [refusedFields, setRefusedFields] = useState<FieldNote[]>([]);// W50-T23 / R7 -- the owner in the words a person reads, resolved by the server// through the account registry, with "System (Odoo)" standing in for a column// the connector wrote. `parseShare` builds a fixed five-key object and drops// everything else, so this rides off the raw body exactly as `fieldNotes` does.const [ownerLabel, setOwnerLabel] = useState("");const path = `${API_V1}/share/${encodeURIComponent(kind)}/${encodeURIComponent(id)}`;useEffect(() => {let dead = false;setError("");void (async () => {try {let res: Response;for (let attempt = 0; ; attempt += 1) {res = await fetch(path, { credentials: CREDENTIALS });if (res.status !== 404 ||kind !== "field" ||attempt >= FIELD_SHARE_RETRY_MS.length) {break;}await new Promise<void>((resolve) => {window.setTimeout(resolve, FIELD_SHARE_RETRY_MS[attempt]);});if (dead) return;}if (!res.ok) {// W51-T10: a workbook the server will not answer for. A sentence, never a status// number, and never a blank dialog. See `WORKBOOK_SHARE_UNREACHABLE` for why the// test is a RANGE rather than a code list.if (kind === "workbook" && res.status >= 400 && res.status !== 403) {if (!dead) setError(WORKBOOK_SHARE_UNREACHABLE);return;}// 4xx text is policy the reader needs; a 5xx's internals are not theirs.if (!dead) setError(res.status >= 500? "Something went wrong on our side. Try again in a moment.": `The server answered ${res.status}.`);return;}const body = (await res.json().catch(() => null)) as unknown;if (dead) return;const parsed = parseShare(body);setState(parsed);setEntries(parsed.entries);setOwnerLabel(body && typeof body === "object"&& typeof (body as { ownerLabel?: unknown }).ownerLabel === "string"? ((body as { ownerLabel?: string }).ownerLabel ?? "").trim(): "");} catch {if (!dead) setError("Cannot reach the server.");}})();return () => {dead = true;};}, [path]);// β ESCAPE CLOSES A MODAL, or its scrim becomes a trap β the wave-18 lesson this// shell already carries at its other two dialogs.useEffect(() => {const onKey = (e: KeyboardEvent) => {if (e.key === "Escape" && !busy) onClose();};window.addEventListener("keydown", onKey);return () => window.removeEventListener("keydown", onKey);}, [busy, onClose]);const save = useCallback(async (next: ShareEntry[]) => {setBusy(true);setError("");// A new request invalidates the field report immediately. If it fails before receiving an// HTTP response, the dialog must not leave the previous save's result beside that failure.setSharedFields([]);setRefusedFields([]);try {const res = await fetch(path, {method: "PUT",credentials: CREDENTIALS,headers: { "Content-Type": "application/json" },// The WHOLE list, every time: the PUT replaces, so a body assembled from// a delta would revoke everyone it failed to mention.body: JSON.stringify(sharePutBody(next)),});if (!res.ok) {const body = (await res.json().catch(() => null)) as| { error?: { message?: string } }| null;setError(res.status >= 500? "Something went wrong on our side. Try again in a moment.": body?.error?.message || `The server answered ${res.status}.`);return false;}const body = (await res.json().catch(() => null)) as unknown;// Re-read the SERVER's copy rather than trusting the draft: `_clean_entries`// drops what it will not store, and an editor that kept showing a row the// store rejected would be the "shared, silently inert" failure this feature// exists to avoid.// β Only `.entries` is consumed here β the PUT answers with the stored record// (`{owner, entries}`) and says nothing about this session's standing, so the// literal below feeds the parser's required field and is never read back. The// editor's `mayAdminister` stays the one the GET established; a save cannot// promote anybody, and this line must never be the reason it looks like it can.const saved = parseShare({ ...(body as object), mayAdminister: true });setEntries(saved.entries);// β W42-T26 / C7 β read STRAIGHT OFF THE RAW BODY, because `parseShare` keeps five keys// and drops everything else, and `shareModel.ts` is another lane's file this wave.const answered = (body ?? null) as Record<string, unknown> | null;setSharedFields(fieldNotes(answered?.sharedFieldKeys));setRefusedFields(fieldNotes(answered?.refusedFieldKeys));return true;} catch {setError("Cannot reach the server.");return false;} finally {setBusy(false);}},[path]);const mayAdminister = !!state?.mayAdminister;const assign = useCallback(async (user: string) => {setBusy(true); setError("");try {const res = await fetch(`${path}/assign`, {method: "POST", credentials: CREDENTIALS,headers: { "Content-Type": "application/json" }, body: JSON.stringify({ user }),});if (!res.ok) { setError(`The server answered ${res.status}.`); return; }onToast(`${nameOf(user)} now has this assigned view.`);} catch { setError("Cannot reach the server."); }finally { setBusy(false); }}, [path, onToast]);const options = state ? addablePeople(state.people, entries) : [];const nameOf = (user: string) =>user === "*"? "Everyone": user && user === me.trim().toLowerCase()? "You": state?.people.find((p) => p.user === user)?.name ?? user;return (<div className="shell-newdb-scrim" onClick={() => (busy ? null : onClose())}><divclassName="shell-newdb shell-share"role="dialog"aria-label={`Share ${label}`}onClick={(e) => e.stopPropagation()}><h2>Share {KIND_WORD[kind]}</h2>{/* ββ W33-T30 / audit S-8 β THIS SENTENCE WAS FALSE FOR ONE OF THE THREE KINDS.It read, unconditionally, "Sharing never widens past this workspace: everyone herecan already open the surface it lives on." True for a VIEW or a FOLDER on a governedmodule, where the receiver's row scope and hidden-field closure run before anyforeign view is merged. FALSE for a `database` grant on a `ut_*` table: no row filterand no hidden field can even be DECLARED there (`_PERM_MODULES` is two keys and`_clean_perms` 400s the rest), so the grant registry IS the only wall and the grantis all-or-nothing. The audit's fix is "say so at BOTH doors"; `core/shares.py` and`routes_shares.py` are the other two, and this is the one a PERSON reads. */}{/* β STANDING RULE 2 (D-490, W39-T17) β THIS LINE CARRIED AN EM DASH TO THE SCREEN AND`verify_prose.py` SCORED THE FILE ZERO. The prose run WRAPS, and the gate's JSX passskips any run containing a newline [[web-prose-blind-to-wrapped-jsx]] β the same blindspot already recorded twenty lines below. REWRITTEN, not stripped: the question thedialog answers is now the sentence's subject, which needs no dash at all. */}<p className="shell-newdb-sub">Who can reach <strong>{label}</strong>, and what they can do with it.{" "}{kind === "workbook"? WORKBOOK_BOUND_CELLS: kind === "database"? "Sharing a database shares all of it: every record and every column. There is no per-row or per-column limit on a database grant.": kind === "field"? "A shared column starts out hidden from everybody else on this database. This is what lets the people you choose see it and its values.": "Sharing never widens past this workspace: everyone here can already open the surface it lives on."}</p>{kind === "view" ? (<><p className="shell-share-note">View access is the general rule. A field's own Share field access takes precedence, soa field shared as Can view stays read-only even inside an editable view.</p>{/* ββ W42-T26 / C7 β WHICH FIELDS TRAVEL, and how far. Two paragraphs, not one andnot four: the done-when reads for three statements (what travels, the FILTER'sfields by name, and the topic-wide reach), and a sharer must be able to point at asentence for each without reading an essay in a dialog subtitle. */}<p className="shell-share-note">{VIEW_FIELD_TRAVEL} {VIEW_FIELD_TOPIC_WIDE}</p><p className="shell-share-note">{VIEW_FILTER_FIELDS}</p></>) : kind === "field" ? (<p className="shell-share-note">Field access takes precedence over the view. Can view keeps values and field settingsread-only; Can edit allows changes when the view is editable.</p>) : null}{!state && !error ? (<div className="shell-share-wait"><span className="lp-spin" role="status" aria-label="Loading" /></div>) : null}{state ? (<>{/* THE MANAGE-ACCESS EDITOR (item 23): the list first, because thequestion people open this for is "who has this already" β with theone-line answer above it, since the fact that changes everything("Everyone can edit") is the one a list of rows buries. */}<p className="shell-share-summary">{shareSummary(entries)}</p>{/* ββ W42-T26 / C7 β THE RESULT: which fields actually travelled, and which could not,each with the reason the SERVER gave. Absent both keys this renders nothing at allso an older server remains compatible.β NO NEW CLASSES. `index.css` is another lane's file this wave and a lane sheetloses every equal-specificity fight with it [[a-lane-stylesheet-cannot-override-index-css]],so a refusal reuses the row/who/role anatomy the entries list already paints. */}{kind === "view" && sharedFields.length > 0 ? (<p className="shell-share-note">{SHARED_FIELDS_LEAD} {sharedFields.map((f) => f.key).join(", ")}</p>) : null}{kind === "view" && refusedFields.length > 0 ? (<><p className="shell-share-note">{REFUSED_FIELDS_LEAD}</p><div className="shell-share-list">{refusedFields.map((f) => (<div className="shell-share-row" key={f.key}><span className="shell-share-who">{f.key}</span>{f.reason ? <span className="shell-share-role">{f.reason}</span> : null}</div>))}</div></>) : null}<div className="shell-share-list">{/* W50-T23 / R7 -- THE OWNER ROW IS NEVER BLANK AND NEVER ABSENT. Under R7every editable field has an owner (its creator, else the tenantAdministrator) and a connector column reads "System (Odoo)", so there isalways something true to print. The old `: null` arm rendered NOTHING fora column whose owner the server could not name, which is how a memberended up being told to ask somebody the dialog never showed them.`ownerLabel` is preferred over `nameOf` only when `nameOf` could notresolve the username: a member gets `people: []`, so `nameOf` would printa raw login where the server already knows the real name. */}{state.owner || (kind === "field" && ownerLabel) ? (<div className="shell-share-row is-owner"><span className="shell-share-who">{state.owner? nameOf(state.owner) === state.owner? ownerLabel || state.owner: nameOf(state.owner): ownerLabel}</span><span className="shell-share-role">Owner</span></div>) : null}{entries.length === 0 ? (<div className="shell-share-empty">Not shared with anyone yet.</div>) : null}{entries.map((e) => (<div className="shell-share-row" key={e.user}><span className="shell-share-who">{nameOf(e.user)}</span><selectclassName="shell-share-select"value={e.role}disabled={!mayAdminister || busy}aria-label={`Role for ${nameOf(e.user)}`}onChange={(ev) => {const next = withEntry(entries, e.user, ev.target.value as ShareRole);setEntries(next);void save(next);}}>{/* β W51-T10 / R16 β THE LABEL IS PER KIND, exactly as `KIND_WORD` and`ROLE_BLURB` are. A workbook's read role is "View only" (the ruling's ownwords); the other four kinds keep "Can view" byte for byte, becausere-wording one label across a shared control is a repo-wide gate grep. */}{SHARE_ROLES.map((r) => (<option key={r} value={r}>{r === "edit"? "Can edit": kind === "workbook" ? "View only" : "Can view"}</option>))}</select><buttontype="button"className="shell-share-revoke"disabled={!mayAdminister || busy}onClick={() => {const next = withoutEntry(entries, e.user);setEntries(next);void save(next).then((ok) => {if (ok) onToast(`${nameOf(e.user)} no longer has this ${KIND_WORD[kind]}.`);});}}>Remove</button>{kind === "view" && mayAdminister && e.user !== "*" ? (<button type="button" className="shell-share-revoke" disabled={busy}onClick={() => void assign(e.user)}>Assign</button>) : null}</div>))}</div>{mayAdminister ? (<div className="shell-share-add"><selectclassName="shell-share-select"value={pick}disabled={busy}aria-label="Who to share with"onChange={(e) => setPick(e.target.value)}>{/* β An explicit placeholder OPTION, not a blank first row: a<select> whose value matches nothing renders its first optionwhile holding "", so the box would read as a chosen person andthe button beside it would grant somebody nobody picked([[cg-condition-builder-items]]). */}<option value="">Choose a personβ¦</option><option value="*">Everyone in this workspace</option>{options.map((p) => (<option key={p.user} value={p.user}>{p.name}</option>))}</select><selectclassName="shell-share-select"value={pickRole}disabled={busy}aria-label="Role for the person being added"onChange={(e) => setPickRole(e.target.value as ShareRole)}>{/* The add-person picker says the same words the row picker says. */}{SHARE_ROLES.map((r) => (<option key={r} value={r}>{r === "edit"? "Can edit": kind === "workbook" ? "View only" : "Can view"}</option>))}</select><buttontype="button"className="login-submit shell-share-grant"disabled={busy || !pick}onClick={() => {const next = withEntry(entries, pick, pickRole);setEntries(next);void save(next).then((ok) => {if (ok) {onToast(kind === "field"? `${nameOf(pick)} can now ${pickRole === "edit" ? "edit" : "view"} this field.`: `${nameOf(pick)} can now ${pickRole} this ${KIND_WORD[kind]}.`);setPick("");}});}}>Share</button><p className="shell-share-blurb">{ROLE_BLURB[kind][pickRole]}</p>{/* β W33-T30 / audit S-5 β `*` + `edit` IS A TENANT-WIDE WRITE GRANT AND LOOKEDLIKE ANY OTHER ROW. Two ordinary choices β a population and a role, eachunremarkable alone β combine into "anybody here may change this", and thedialog said nothing at the point where the two meet. The audit's fix is"make the population legible at the point of choice": one sentence, only onthe combination, in the words of the consequence rather than of the setting.β It is NOT a confirm step. The capability is real and deliberate; a personchoosing it on purpose should not be interrogated, only told what it means. */}{/* β `shell-share-note`, the class the refusal below already uses, rather than anew `shell-share-warn`: `index.css` is B's file this wave (contract C4), and anew class with no rule renders as unstyled body text β which for a sentencewhose whole job is to be NOTICED is worse than reusing a quiet one. */}{/* β STANDING RULE 2 (wave-36 QA) β the sentence below carried an em dash and`web_prose` scored this file 0 findings: the prose run WRAPS, and the gate'sJSX pass skips any run containing a newline [[web-prose-blind-to-wrapped-jsx]].REWRITTEN, not merely stripped β the comma keeps the contrast the sentenceexists to draw. */}{pick === "*" && pickRole === "edit" ? (<p className="shell-share-note">Everyone in this workspace will be able to change this {KIND_WORD[kind]},not just open it.</p>) : null}</div>) : (// β NOT A HIDDEN EDITOR β a stated refusal. A collaborator who can// change this object's CONTENT still cannot change who else reaches// it (the server's rule; this is the courtesy half). Saying why beats// greying three controls and letting the reader guess.// β STANDING RULE 2 (W39-T17) β TWO em dashes, live on screen, and `verify_prose`// green over both for the wrapped-JSX reason recorded above. NOT a pre-existing// violation this ticket may leave alone: adding `field` to `KIND_WORD` is what// brings this sentence to a NEW surface, so it ships the dash rather than merely// inheriting it. Rewritten with the owner in the subject, so no aside is needed.<p className="shell-share-note">Only this {KIND_WORD[kind]}'s owner and workspace administrators can change whoit is shared with. You can still use it as your role allows.</p>)}</>) : null}{/* ββ W33-T27 (item 8b, R5) β PUBLISH, below the grant editor and inside the samedialog, because this is where a person comes to ask "who can reach this?".β IT IS NOT A FOURTH ROLE IN THE LIST ABOVE, and the panel says so in its ownwords: a published link names nobody, creates no grant and is revoked by replacingthe link rather than by removing a person. Folding it into the entries list wouldhave made "the public" look like a grantee β which is precisely the conflation thesharing audit's S-4 row is about (two systems already answer "is this shared"; thisis a third thing).β ONLY FOR A VIEW, and only when the shell knew which database it belongs to. Thepanel then asks the SERVER whether this particular view may be published and rendersnothing if not β so "absent on non-interface views" is one evaluator, not two. */}{kind === "view" && topic ? <PublishPanel topic={topic} view={id} /> : null}{error ? <p className="shell-newdb-err">{error}</p> : null}</div></div>);}
RELEASES.json+7-1
VERSION+1-1
api/routes_connected_tables.py+76-76
api/routes_shares.py+24
platform/core/perm_migrate.py+13-6
platform/core/perm_scope.py+53-11
web/src/customer-grid/SwipeView.tsx+586-586
web/src/index.css
web/src/sheet/types.ts+750-750
web/src/shell/ShareDialog.tsx+676-666