fsanyoto commited on
Commit
cfd4ac1
Β·
verified Β·
1 Parent(s): 8f0ae3d

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
This view is limited to 50 files because it contains too many changes. Β  See raw diff
Files changed (50) hide show
  1. RELEASES.json +1 -1
  2. VERSION +1 -1
  3. api/main.py +15 -1
  4. api/odoo_relational.py +479 -27
  5. api/routes_grid.py +163 -24
  6. api/routes_keychain.py +286 -40
  7. api/routes_nav.py +116 -0
  8. api/routes_odoo_tables.py +250 -24
  9. api/routes_sheet.py +245 -27
  10. platform/core/keychain.py +329 -38
  11. platform/core/perm_scope.py +318 -0
  12. platform/core/relations.py +356 -49
  13. platform/core/sheets.py +275 -35
  14. platform/core/table_store.py +31 -3
  15. platform/harness/runtime.py +54 -17
  16. platform/odoo_client.py +21 -5
  17. web/src/connectors/ConnectorsPage.tsx +72 -173
  18. web/src/customer-grid/CustomerGrid.tsx +19 -0
  19. web/src/customer-grid/RecordDetail.css +159 -0
  20. web/src/customer-grid/RecordDetail.tsx +241 -43
  21. web/src/customer-grid/RecordRail.tsx +34 -3
  22. web/src/customer-grid/RouteNav.tsx +44 -2
  23. web/src/customer-grid/Toolbar.tsx +112 -0
  24. web/src/customer-grid/ViewSidebar.tsx +19 -1
  25. web/src/customer-grid/iconShapes.ts +47 -10
  26. web/src/customer-grid/types.ts +105 -3
  27. web/src/filter-kit/FilterBuilderPanel.tsx +37 -4
  28. web/src/filter-kit/SheetFilterPopup.tsx +134 -11
  29. web/src/settings/PermsEditor.tsx +156 -6
  30. web/src/settings/settingsApi.ts +61 -0
  31. web/src/sheet/BindingEditor.tsx +721 -372
  32. web/src/sheet/ChartDialog.tsx +593 -0
  33. web/src/sheet/DrillModal.tsx +554 -14
  34. web/src/sheet/KeyTips.tsx +61 -1
  35. web/src/sheet/LinkDialog.tsx +521 -0
  36. web/src/sheet/Ribbon.tsx +212 -697
  37. web/src/sheet/RulesDialog.tsx +101 -12
  38. web/src/sheet/SheetChart.tsx +773 -11
  39. web/src/sheet/SheetGrid.tsx +0 -0
  40. web/src/sheet/SheetPage.tsx +283 -14
  41. web/src/sheet/bindingRefs.ts +197 -0
  42. web/src/sheet/cellBorders.ts +114 -0
  43. web/src/sheet/cellStyleOps.ts +170 -0
  44. web/src/sheet/clipboardOps.ts +207 -0
  45. web/src/sheet/formulaEval.ts +364 -21
  46. web/src/sheet/ribbonHome.tsx +1226 -0
  47. web/src/sheet/ribbonInsert.tsx +649 -0
  48. web/src/sheet/rules.ts +321 -10
  49. web/src/sheet/sheetApi.ts +45 -0
  50. web/src/sheet/sheetState.ts +406 -171
RELEASES.json CHANGED
@@ -1,5 +1,5 @@
1
  {
2
- "current": "593d37a",
3
  "releases": [
4
  {
5
  "version": "v71",
 
1
  {
2
+ "current": "463db38",
3
  "releases": [
4
  {
5
  "version": "v71",
VERSION CHANGED
@@ -1 +1 @@
1
- 593d37a
 
1
+ 463db38
api/main.py CHANGED
@@ -926,7 +926,21 @@ def _rebuild_odoo_relational(why, previous_meta_fingerprint=None, meta_state_out
926
  _rt = _runtime.get_runtime("royal-imports")
927
  from core import user_tables as _ut
928
  _ut.record_odoo_sync_status(phase="syncing", st=_rt)
929
- counts = _rel.refresh(_rt, "royal-imports")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
930
  raw_models, schema_errors = _rel.authoritative_schema_snapshot()
931
  _ut.record_odoo_schema_snapshot(raw_models, complete=not schema_errors,
932
  errors=schema_errors, st=_rt)
 
926
  _rt = _runtime.get_runtime("royal-imports")
927
  from core import user_tables as _ut
928
  _ut.record_odoo_sync_status(phase="syncing", st=_rt)
929
+ # ⭐⭐ W54-T46 / R4 / R7 β€” EVERY Odoo CONNECTION, not just the first. `all_connections`
930
+ # delegates to `odoo_relational.refresh_all`, which walks this tenant's Odoo
931
+ # connections in slot order and records a failure against the connection it belongs
932
+ # to rather than aborting the rest. The DEFAULT connection's counts stay at the top
933
+ # level of the returned dict, so the log line below is unchanged; the per-connection
934
+ # map rides beside them under `connections`.
935
+ # ⚠ A FLAG RATHER THAN CALLING THE ALL-CONNECTIONS FUNCTION BY NAME HERE, and the
936
+ # reason is a gate: `verify_odoo_relational` locates this call by its literal spelling
937
+ # and reads the code that follows it, to prove the relation cells are computed after
938
+ # the spawn. Spelling the boot call differently moves that window off the code it is
939
+ # meant to measure. β›” AND THE CALL IS NAMED IN WORDS ABOVE RATHER THAN WRITTEN OUT,
940
+ # because a gate that counts RAW occurrences of a call would count the one in this
941
+ # comment too. That gate happens to strip comments first; the next one may not.
942
+ # See `odoo_relational.refresh` and its `all_connections` arm.
943
+ counts = _rel.refresh(_rt, "royal-imports", all_connections=True)
944
  raw_models, schema_errors = _rel.authoritative_schema_snapshot()
945
  _ut.record_odoo_schema_snapshot(raw_models, complete=not schema_errors,
946
  errors=schema_errors, st=_rt)
api/odoo_relational.py CHANGED
@@ -2370,6 +2370,309 @@ _READERS = {
2370
  READ_THROUGH_KEYS = frozenset(key for bucket, key, _l, _f in TABLES if bucket not in _READERS)
2371
 
2372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2373
  class _LentDoc:
2374
  """A store handle that serves the ONE `user_tables` document `plan()` has ALREADY read.
2375
 
@@ -2473,7 +2776,7 @@ def frozen(rt):
2473
  return bool(read_config(rt)["frozen"])
2474
 
2475
 
2476
- def plan(cur, rt=None):
2477
  """The rows that WOULD be written, plus the refusals that apply β€” no store WRITE at all.
2478
 
2479
  Separated from `apply_plan` so a route, a gate and a dry run all measure the same thing, and
@@ -2484,6 +2787,16 @@ def plan(cur, rt=None):
2484
  `{table_key: limit_report}` for every table this plan did not fully materialise, which is R6's
2485
  second sentence carried as data rather than left for a reader to infer from an empty list.
2486
 
 
 
 
 
 
 
 
 
 
 
2487
  β›” `rt` IS WHAT MAKES THE TABLE-COUNT CHECK HONEST, and leaving it out was a real half-spawn
2488
  bug. This spawn writes FOUR tables in four updater passes; a tenant near `MAX_TABLES` would
2489
  create some and refuse the rest β€” leaving a locked invoices database with no rollup host,
@@ -2500,8 +2813,10 @@ def plan(cur, rt=None):
2500
  # not apply on exactly the run that creates the databases. This module DECLARES these keys, so
2501
  # it is the honest place to say what they are. Idempotent (a set add), and it fills the
2502
  # evaluator's input rather than becoming a second evaluator.
2503
- ut.register_connected(*[key for _b, key, _l, _f in TABLES])
2504
- excluded = excluded_ids(cur)
 
 
2505
  # ⭐⭐ W30-T35 / R6 / R7 β€” WHICH BUCKETS ARE BUILT AT ALL IS NOW ASKED, NOT ASSUMED, and it is
2506
  # `core.user_tables.row_limit` that answers: 0 = "stores no rows HERE" (read-through), None =
2507
  # "connected and uncapped", MAX_ROWS = "the editable substrate". Its own docstring names this
@@ -2545,15 +2860,24 @@ def plan(cur, rt=None):
2545
  # the definition instead of taking one. `_ensure_table_inplace` writes exactly this stamp, so
2546
  # what is lent is the document as it stands the moment this plan applies.
2547
  lent = _LentDoc({**existing,
2548
- **{k: {**(existing.get(k) or {}), "readThrough": True}
 
 
2549
  for k in READ_THROUGH_KEYS}},
2550
  ut.STORE_KEY)
2551
 
2552
  built, limits = {}, {}
2553
  caps = {}
2554
- for bucket, key, _label, _fields in TABLES:
 
2555
  reader = _READERS.get(bucket)
2556
  caps[key] = cap = ut.row_limit(key, st=lent)
 
 
 
 
 
 
2557
  if reader is None or cap == 0:
2558
  built[bucket] = []
2559
  report = ut.limit_report(key, st=lent)
@@ -2564,14 +2888,16 @@ def plan(cur, rt=None):
2564
  problems = []
2565
 
2566
  if rt is not None:
2567
- needed = [k for _b, k, _l, _f in TABLES if k not in existing]
2568
  if needed and len(existing) + len(needed) > ut.MAX_TABLES:
2569
  problems.append(
2570
  f"tenant holds {len(existing)} of MAX_TABLES={ut.MAX_TABLES} user tables and "
2571
- f"needs {len(needed)} more ({', '.join(needed)}); refusing rather than creating "
 
2572
  f"part of a linked set")
2573
 
2574
- for bucket, key, _label, _fields in TABLES:
 
2575
  rows = built[bucket]
2576
  cap = caps[key] # asked ONCE per table, above β€” never re-read per loop
2577
  # ⭐⭐ R6: THE `MAX_ROWS` REFUSAL IS GONE FOR A CONNECTED SOURCE, AND THE SENTENCE IT USED
@@ -2614,7 +2940,8 @@ def plan(cur, rt=None):
2614
  return built
2615
 
2616
 
2617
- def apply_plan(rt, built, username="automation", today=None, report=None):
 
2618
  """Create-or-merge every table in `built` and its rows. Idempotent by construction.
2619
 
2620
  Row ids ARE the Odoo ids, so a re-run updates in place and never appends a second copy of the
@@ -2622,6 +2949,11 @@ def apply_plan(rt, built, username="automation", today=None, report=None):
2622
  statement rather than a hopeful one.
2623
 
2624
  ⚠ ONLY THE BUCKETS PRESENT ARE WRITTEN, so a caller (or a gate) may hand in a subset.
 
 
 
 
 
2625
  """
2626
  if built.get("problems"):
2627
  raise Refused("; ".join(built["problems"]))
@@ -2630,7 +2962,11 @@ def apply_plan(rt, built, username="automation", today=None, report=None):
2630
  # ⚠ An OPTIONAL out-parameter, not a return-shape change: `written` has one value shape and
2631
  # keeps it. A caller that wants to SAY what was retired passes a dict; `refresh` does.
2632
  retired = []
2633
- plans = [(key, label, fields(), built[bucket])
 
 
 
 
2634
  for bucket, key, label, fields in TABLES if bucket in built]
2635
 
2636
  # ⭐⭐ ONE SYNC WRITE FOR ALL FOUR TABLES, not one per table β€” measured, not tidied.
@@ -2660,7 +2996,10 @@ def apply_plan(rt, built, username="automation", today=None, report=None):
2660
  # with `TypeError: list indices must be integers`. One dict, two value shapes, is a
2661
  # sentinel in a result set [[sentinel-in-a-sort-key]] β€” so the retirement reports through
2662
  # its OWN channel and the return type stays exactly what it was.
 
 
2663
  for key in RETIRED_KEYS:
 
2664
  if cur.pop(key, None) is not None:
2665
  retired.append(key)
2666
  for key, label, fields, rows in plans:
@@ -2701,7 +3040,9 @@ def _ensure_table_inplace(cur, key, label, fields, rows, username, stamp):
2701
  for row in wanted.values():
2702
  row["refreshed"] = stamp
2703
  counts = {"added": 0, "updated": 0, "removed": 0, "rows": len(wanted)}
2704
- subject = TABLE_SUBJECTS.get(key)
 
 
2705
  table = cur.get(key)
2706
  if table is None:
2707
  if len(cur) >= ut.MAX_TABLES:
@@ -2745,7 +3086,7 @@ def _ensure_table_inplace(cur, key, label, fields, rows, username, stamp):
2745
  # `setdefault`: it is derived from the code's own structure, so the code is what it must agree
2746
  # with, and a definition that somehow lost the flag should regain it rather than keep serving
2747
  # an empty grid.
2748
- if key in READ_THROUGH_KEYS:
2749
  table["readThrough"] = True
2750
  # W33-T41 β€” the claim, made DURABLE on the definition. Written on every pass for the same
2751
  # reason `readThrough` is: it is derived from this module's own structure, so the code is what
@@ -2828,7 +3169,7 @@ def is_royal(tenant):
2828
  return str(tenant or "").strip().lower() in RI_SLUGS
2829
 
2830
 
2831
- def available(rt=None, tenant_key=None):
2832
  """⭐⭐ R3 β€” DOES THIS TENANT HAVE ODOO CONFIGURED WITH LIVE CREDENTIALS? Never a slug list.
2833
 
2834
  R3, verbatim: *"The connector table spawn gates on does this tenant have this connector
@@ -2853,10 +3194,21 @@ def available(rt=None, tenant_key=None):
2853
 
2854
  β›” ADDING A SECOND ODOO TENANT NEEDS NO EDIT HERE. Anyone with a keychain `odoo` entry is
2855
  admitted, whatever their slug.
 
 
 
 
 
2856
  """
 
 
 
 
 
2857
  try:
2858
  if rt is not None:
2859
- return bool(rt.odoo_flag_key())
 
2860
  except Exception: # noqa: BLE001
2861
  return False # unreadable = fail closed
2862
  if not tenant_key:
@@ -2865,18 +3217,42 @@ def available(rt=None, tenant_key=None):
2865
  # from `refresh`, which is always handed one.
2866
  try:
2867
  from harness import runtime as _runtime
2868
- return bool(_runtime.get_runtime(str(tenant_key)).odoo_flag_key())
 
 
2869
  except Exception: # noqa: BLE001
2870
  return False
2871
 
2872
 
2873
- def refresh(rt, tenant, username="automation", cur=None, today=None):
 
2874
  """THE entry point β€” the store-resync path and the route both call this.
2875
 
2876
  ⚠ It must be CALLED on resync by something outside this file. If it is not wired, every row
2877
  still carries a `refreshed` stamp, so a stale worklist is at least LEGIBLE rather than
2878
  silently authoritative.
 
 
 
 
 
 
 
 
 
 
 
 
 
2879
  """
 
 
 
 
 
 
 
 
2880
  # ⭐⭐ W53-T39 / R3 β€” THE ADMISSION IS A CREDENTIALS TEST, NOT A TENANT NAME.
2881
  #
2882
  # β›” THE OLD GATE'S REASON IS KEPT AND ONLY ITS MECHANISM IS REPLACED. It read
@@ -2892,7 +3268,14 @@ def refresh(rt, tenant, username="automation", cur=None, today=None):
2892
  # loop calls this every cycle and an exception is not a status. Refusing here would hand that
2893
  # loop a raise for the one state it is meant to report. So a frozen workspace is admitted this
2894
  # far and stopped by its own guard, three lines down, with its own words.
2895
- if not available(rt) and not (rt is not None and frozen(rt)):
 
 
 
 
 
 
 
2896
  raise Refused("no Odoo credential is configured for this workspace, so there is nothing "
2897
  "behind these tables and the spawn would create empty locked databases. "
2898
  "Add an Odoo credential in the Connectors panel, then run the sync again.")
@@ -2920,10 +3303,19 @@ def refresh(rt, tenant, username="automation", cur=None, today=None):
2920
  return {"tables": {}, "frozen": True,
2921
  "note": "this workspace has disconnected Odoo; its databases are frozen as "
2922
  "static data and are not being refreshed"}
2923
- if cur is None:
 
 
 
 
 
 
 
 
 
2924
  from harness import datastore
2925
  cur = datastore.ro_con()
2926
- built = plan(cur, rt=rt)
2927
  # ⭐ W32-T15 / R9 β€” THE GRID PICKER, ENFORCED WHERE IT COUNTS. `apply_plan` writes only the
2928
  # buckets present in `built`, so dropping an unticked one here is the whole of "unticking a
2929
  # grid stops it materialising on the next sync". Done AFTER `plan` rather than inside it so
@@ -2934,7 +3326,10 @@ def refresh(rt, tenant, username="automation", cur=None, today=None):
2934
  # do that either (R10 keeps them). Silent data deletion behind a checkbox is not on offer.
2935
  if rt is not None:
2936
  keep = enabled_buckets(rt)
2937
- skipped = sorted(key for bucket, key, _l, _f in TABLES if bucket not in keep)
 
 
 
2938
  for bucket, _key, _l, _f in TABLES:
2939
  if bucket not in keep:
2940
  built.pop(bucket, None)
@@ -2944,16 +3339,73 @@ def refresh(rt, tenant, username="automation", cur=None, today=None):
2944
  # Same rule as `skipped` below β€” R6's second sentence: what was deliberately not built (or no
2945
  # longer built) SAYS SO, with the keys.
2946
  plan_report = {}
2947
- written = apply_plan(rt, built, username=username, today=today, report=plan_report)
 
2948
  # ⭐⭐ W49-T25 / C6 β€” THE SCHEMA CATALOGUE FOLLOWS THE CODE WITH NO MANUAL STEP. Runs AFTER the
2949
  # tables are applied, so the snapshot describes a pass that actually landed. The two early
2950
  # returns above are respected by construction: a tenant with no Odoo entitlement raised, and a
2951
  # FROZEN workspace returned before reaching here, so a disconnected connector is not
2952
  # re-recorded. See `_refresh_declared_schema` for why it writes the declared half only.
2953
  declared_report = _refresh_declared_schema(rt)
2954
- return {"tables": written,
2955
- **({"schemaDeclared": declared_report} if declared_report else {}),
2956
- **({"retired": plan_report["retired"]} if plan_report.get("retired") else {}),
2957
- # R6's second sentence: a set that was deliberately not built SAYS SO, with the keys.
2958
- **({"skipped": skipped} if skipped else {}),
2959
- **{bucket: len(built[bucket]) for bucket, _k, _l, _f in TABLES if bucket in built}}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2370
  READ_THROUGH_KEYS = frozenset(key for bucket, key, _l, _f in TABLES if bucket not in _READERS)
2371
 
2372
 
2373
+ # ═════════════════════════════════════════════════════════════════════════════════════════════
2374
+ # ⭐⭐ W54-T46 / R4 / R7 / CONTRACT C4 β€” A TABLE BELONGS TO EXACTLY ONE CONNECTION
2375
+ # ═════════════════════════════════════════════════════════════════════════════════════════════
2376
+ #
2377
+ # R4, verbatim: *"If a tenant is an agency that helps with clients that each have Odoo, then the
2378
+ # connector for Odoo can be many depending on the API. This is why its critical."* R7 makes the
2379
+ # isolation between those clients STRICT β€” there is no blended view, and client A must not be one
2380
+ # dropped filter away from client B.
2381
+ #
2382
+ # β›”β›” THE DEFAULT CONNECTION KEEPS THE LEGACY KEYS, AND THAT IS THE WHOLE SHAPE OF THE RULE.
2383
+ # Renaming tenant #0's ten live tables would move every saved view, grant, cohort, link, rollup
2384
+ # and nav entry that names them. So the tenant's DESIGNATED DEFAULT connection stays exactly where
2385
+ # it is and only the connections added after it are namespaced.
2386
+ #
2387
+ # β›” THE TOKEN IS THE `connection_id`, NEVER THE `slot`. MEASURED (PRD amendment A4): a pre-wave
2388
+ # row's read-default slot MOVES when a sibling of the same type is deleted (2 -> 1), while its
2389
+ # connection id does not. A key built from a slot would one day address a different client's rows.
2390
+
2391
+ #: The separator between a base table key and the connection that owns it. TWO underscores,
2392
+ #: because every base key spells its own words with ONE, so `rpartition` splits it back cleanly.
2393
+ CONNECTION_SEP = "__"
2394
+
2395
+ #: What `connection_for_table_key` answers for a LEGACY key when it was handed no runtime to
2396
+ #: resolve the tenant's designated default against. It means "whichever connection is designated
2397
+ #: default" β€” a real answer, not an absence, which is what keeps the inverse TOTAL.
2398
+ DEFAULT_CONNECTION = "default"
2399
+
2400
+ #: Every table key this connector owns, un-namespaced. The two RETIRED keys are members so a
2401
+ #: document that still holds one resolves to its connection rather than reading as a stranger's
2402
+ #: table β€” `apply_plan` has to know whose copy it is popping.
2403
+ BASE_TABLE_KEYS = frozenset([key for _b, key, _l, _f in TABLES] + list(RETIRED_KEYS))
2404
+
2405
+ #: `core.user_tables._field_key` truncates a table key at 60 characters SILENTLY, and a truncated
2406
+ #: key is a key that can collide with another connection's. The longest base key is
2407
+ #: `ut_odoo_order_lines` (19) and a connection id is `k_` + 12 hex (14), so a namespaced key is 35
2408
+ #: characters; the guard is here for the day one of those two numbers moves.
2409
+ MAX_TABLE_KEY_LEN = 60
2410
+
2411
+ #: The characters `core.user_tables._field_key` leaves alone. A `k_<hex>` connection id is already
2412
+ #: inside this set, which is why it survives the normaliser unchanged.
2413
+ _KEY_CHARS = frozenset("abcdefghijklmnopqrstuvwxyz0123456789_")
2414
+
2415
+
2416
+ def default_connection_id(rt):
2417
+ """This tenant's DESIGNATED DEFAULT Odoo connection id, or None. Decrypts nothing.
2418
+
2419
+ β›” NOT RE-DERIVED HERE. `core.keychain.default_connection_id` is the one resolver (W54-T44):
2420
+ lowest immutable slot, ties by insertion order. A second walk in this file is exactly the
2421
+ drift that resolver was written to end.
2422
+ """
2423
+ if rt is None:
2424
+ return None
2425
+ try:
2426
+ import core.keychain as keychain
2427
+ return keychain.default_connection_id(rt, "odoo")
2428
+ except Exception: # noqa: BLE001
2429
+ return None
2430
+
2431
+
2432
+ def table_key_for(base_key, connection_id=None):
2433
+ """The store key `base_key` takes under `connection_id`.
2434
+
2435
+ `connection_id=None` means the tenant's DESIGNATED DEFAULT connection, and it answers the bare
2436
+ legacy key unchanged: `ut_odoo_invoices` stays `ut_odoo_invoices`.
2437
+
2438
+ ⚠ The result still starts with `ut_`, which is load-bearing three times over: the `ut_*` wall,
2439
+ `user_tables.is_linkable_target`, and `grid_events._field_share_keys`' shared-stratum branch
2440
+ all key on that prefix.
2441
+ """
2442
+ base = str(base_key or "").strip()
2443
+ cid = str(connection_id or "").strip().lower()
2444
+ if not cid:
2445
+ return base
2446
+ if (CONNECTION_SEP in cid or set(cid) - _KEY_CHARS or cid != cid.strip("_")):
2447
+ raise Refused(f"{cid!r} cannot be used as a table namespace: a connection id has to be "
2448
+ f"lowercase letters, digits and single underscores, or the table key it "
2449
+ f"builds would be stored under a different name than the one it is read by")
2450
+ key = f"{base}{CONNECTION_SEP}{cid}"
2451
+ if len(key) > MAX_TABLE_KEY_LEN:
2452
+ raise Refused(f"{key!r} is {len(key)} characters and the store truncates a table key at "
2453
+ f"{MAX_TABLE_KEY_LEN}; refusing rather than creating a key that two "
2454
+ f"connections could share. Shorten the base key or the connection id.")
2455
+ return key
2456
+
2457
+
2458
+ def split_table_key(table_key):
2459
+ """`(base_key, connection_id)` for a key this connector owns, `(None, None)` for anything
2460
+ else β€” so the question "is this one of ours" and "whose is it" have one answer.
2461
+
2462
+ A LEGACY (bare) key answers `(base, None)`: no namespace token, because the designated default
2463
+ keeps its legacy key.
2464
+ """
2465
+ raw = str(table_key or "").strip()
2466
+ if raw in BASE_TABLE_KEYS:
2467
+ return raw, None
2468
+ base, sep, cid = raw.rpartition(CONNECTION_SEP)
2469
+ if sep and cid and base in BASE_TABLE_KEYS:
2470
+ return base, cid
2471
+ return None, None
2472
+
2473
+
2474
+ def base_table_key(table_key):
2475
+ """The un-namespaced key behind `table_key`, or None when it is not one of this connector's."""
2476
+ return split_table_key(table_key)[0]
2477
+
2478
+
2479
+ def connection_for_table_key(table_key, rt=None):
2480
+ """WHICH connection owns this table key β€” exactly one, or None when the key is not one of
2481
+ this connector's tables at all.
2482
+
2483
+ ⭐ THE INVERSE IS THE CONTRACT. C4's clause is that a table resolves to exactly one
2484
+ connection; a namespacing you cannot read backwards is a convention, not an isolation.
2485
+ A legacy key belongs to the DESIGNATED DEFAULT, which is what `rt` answers; with no `rt` it
2486
+ answers the `DEFAULT_CONNECTION` sentinel rather than pretending it does not know.
2487
+ """
2488
+ base, cid = split_table_key(table_key)
2489
+ if base is None:
2490
+ return None
2491
+ if cid:
2492
+ return cid
2493
+ return (default_connection_id(rt) or DEFAULT_CONNECTION) if rt is not None \
2494
+ else DEFAULT_CONNECTION
2495
+
2496
+
2497
+ #: ⭐⭐ W54-T49 / R7 / C4 β€” THE SECOND IMPORT-TIME REGISTRATION IN THIS FILE, AND IT IS THE ONE
2498
+ #: THAT ARMS A WALL RATHER THAN DECLARING A SPEC.
2499
+ #:
2500
+ #: `core.perm_scope.ConnectionScope` refuses a read of a table belonging to another connection, and
2501
+ #: it answers "whose table is this" through a registration slot because `core` never imports up
2502
+ #: (`platform/ARCHITECTURE.md`). The inverse lives HERE, so this module fills that slot at import,
2503
+ #: exactly as `SPEC_REGISTRATION` above fills the connector-spec registry and for the identical
2504
+ #: reason: the module that owns the fact is the one that declares it.
2505
+ #:
2506
+ #: β›”β›” WITHOUT THIS, THE WALL IS WHOLE, GATED AND ENFORCING NOTHING. An unfilled slot makes
2507
+ #: `covers` answer False and `require` report `Unresolvable`, which is fail-closed and therefore
2508
+ #: silent, so the feature would have shipped and behaved as a no-op
2509
+ #: [[artifact-with-no-importer]]. `verify_scopes` asserts the slot is filled BY IMPORT, before it
2510
+ #: registers anything of its own, so deleting the boot call below reds a gate.
2511
+ #:
2512
+ #: β›” IT NEVER RAISES, FOR THE REASON THE BANNER ABOVE GIVES IN FULL: `core` is genuinely absent
2513
+ #: from `sys.path` on a bare import of this module from `aios-web/api`, and taking the route layer
2514
+ #: down over a declaration nothing on the request path reads is the wrong trade. The failure is
2515
+ #: CAPTURED here instead, in the same three keys.
2516
+ OWNER_REGISTRATION = {"slot": "perm_scope.connection_owner", "registered": False, "error": ""}
2517
+
2518
+
2519
+ def register_connection_owner_slot():
2520
+ """Declare this module's `connection_for_table_key` as the answer to "whose table is this".
2521
+
2522
+ Returns True when it landed. Records the reason in `OWNER_REGISTRATION` when it did not, and
2523
+ never raises: see the banner above. Idempotent, because the slot holds one reader and a second
2524
+ call replaces it with the same function.
2525
+ """
2526
+ try:
2527
+ import core.perm_scope as perm_scope
2528
+ except Exception as exc: # noqa: BLE001
2529
+ # ⚠ ASCII ONLY, like `SPEC_REGISTRATION`'s error string: this can be quoted into a report,
2530
+ # and standing rule 2 forbids an em dash or an en dash in copy that can reach a screen.
2531
+ OWNER_REGISTRATION.update(
2532
+ registered=False,
2533
+ error="core.perm_scope is not importable from here: %s: %s"
2534
+ % (type(exc).__name__, str(exc)[:120]))
2535
+ return False
2536
+ perm_scope.register_connection_owner(connection_for_table_key)
2537
+ OWNER_REGISTRATION.update(registered=True, error="")
2538
+ return True
2539
+
2540
+
2541
+ register_connection_owner_slot()
2542
+
2543
+
2544
+ def table_subject_for(table_key):
2545
+ """The real-world population this key presents, namespaced by its connection.
2546
+
2547
+ β›”β›” THE SUBJECT HAS TO MOVE WITH THE KEY OR A SECOND CONNECTION CANNOT BE CREATED AT ALL.
2548
+ `_ensure_table_inplace` refuses to create a table whose subject another table in the same
2549
+ document already claims (one subject, one database, item 12a). Client B's invoices are a
2550
+ DIFFERENT population from client A's, so the claim carries the connection with it.
2551
+ """
2552
+ base, cid = split_table_key(table_key)
2553
+ subject = TABLE_SUBJECTS.get(base if base is not None else str(table_key or ""))
2554
+ if not subject or not cid:
2555
+ return subject
2556
+ return f"{subject}@{cid}"
2557
+
2558
+
2559
+ def is_read_through_key(table_key):
2560
+ """Does this key name one of the two grains whose rows are served from the mirror? Answered
2561
+ on the BASE key, so a namespaced copy inherits the statement rather than losing it."""
2562
+ return base_table_key(table_key) in READ_THROUGH_KEYS
2563
+
2564
+
2565
+ def connection_namespace(rt, connection_id=None):
2566
+ """`(connection_id, namespace_token)` for a refresh of `connection_id`.
2567
+
2568
+ The token is None for the DESIGNATED DEFAULT (bare, legacy keys) and the connection id for
2569
+ every other connection.
2570
+
2571
+ β›” A NAMED CONNECTION THAT DOES NOT RESOLVE IS A REFUSAL, NEVER A FALLBACK. Serving the
2572
+ default to a caller that asked for a specific client is precisely the leak R7 forbids, and it
2573
+ is the same asymmetry `runtime.odoo_source` already holds.
2574
+ """
2575
+ default = default_connection_id(rt)
2576
+ if connection_id is None:
2577
+ return default, None
2578
+ import core.keychain as keychain
2579
+ cid = keychain.resolve_connection_id(rt, "odoo", connection_id)
2580
+ if not cid:
2581
+ raise Refused(f"{str(connection_id)!r} does not name an Odoo connection in this "
2582
+ f"workspace, so there is nothing to spawn for it. Pick a connection in the "
2583
+ f"Connectors panel and run the sync again.")
2584
+ return cid, (None if cid == default else cid)
2585
+
2586
+
2587
+ def connection_label(rt, connection_id=None):
2588
+ """The user's own name for this connection ('Odoo 2' until they rename it), or ''."""
2589
+ if rt is None or not connection_id:
2590
+ return ""
2591
+ try:
2592
+ import core.keychain as keychain
2593
+ for row in keychain.list_entries(rt):
2594
+ if row.get("type") == "odoo" \
2595
+ and str(row.get("connection_id")) == str(connection_id):
2596
+ return str(row.get("label") or "")
2597
+ except Exception: # noqa: BLE001
2598
+ return ""
2599
+ return ""
2600
+
2601
+
2602
+ def table_label_for(label, conn_label=None):
2603
+ """The nav label a namespaced table shows.
2604
+
2605
+ ⚠ R9 keeps `TABLES`' shipped label as the default; this only says WHICH connection the grid
2606
+ belongs to, because two grids sharing a display name is how a person reads the wrong number
2607
+ off the right looking tab.
2608
+ """
2609
+ conn_label = " ".join(str(conn_label or "").split())
2610
+ return f"{label} ({conn_label})" if conn_label else str(label)
2611
+
2612
+
2613
+ def namespaced_fields(fields, connection_id=None):
2614
+ """A field contract re-pointed at ONE connection's tables.
2615
+
2616
+ β›”β›” THIS IS WHERE R7 BECOMES STRUCTURAL RATHER THAN CONVENTIONAL. Every `link` bag in the
2617
+ contracts above names a sibling by its LEGACY key, so a second connection's vendors table
2618
+ would fold the FIRST connection's bills unless the target moves with the key. A namespaced
2619
+ table can only ever link to a namespaced sibling of its own connection.
2620
+
2621
+ β›” AND A TARGET THAT CANNOT BE NAMESPACED IS DROPPED, never left pointing at shared data.
2622
+ `customer_link` targets the compiled registry module `customer_data`, which holds the DEFAULT
2623
+ connection's customers and has no per-connection copy to point at; rendering it on another
2624
+ client's invoices would show that client one of ours. An absent column is visible; a column
2625
+ quietly resolving across the isolation boundary is not.
2626
+
2627
+ β›”β›” A **RETIRED** TARGET IS DROPPED FOR EVERY CONNECTION, FOR THE IDENTICAL REASON. A retired
2628
+ table has no per-connection copy any more than a registry module does: `RETIRED_KEYS` are
2629
+ absent from `TABLES`, so nothing plans, creates or re-creates one under ANY connection.
2630
+ Re-pointing such a link would mint `ut_odoo_customers__k_...` β€” a key nothing creates AND
2631
+ nothing registers as absent, because `routes_grid._register_retired_tables` fills the
2632
+ absent-table registry from the BARE `RETIRED_KEYS` tuple. An edge naming it would therefore
2633
+ survive W54-T37's relation enumeration and refuse as a permission wall about a database that
2634
+ does not exist, which is instruction 22's exact defect re-created for connection 2.
2635
+ ⚠ MEASURED 2026-09-06: ZERO live contract fields link to a retired key today, so this is
2636
+ LATENT, not live. It goes live the moment anybody adds one, which is precisely how those two
2637
+ keys came to need retiring in the first place: they were link targets before they were dropped.
2638
+
2639
+ ⚠ THE TEST IS HERE AND NOT IN `BASE_TABLE_KEYS`. That frozenset's other consumers are
2640
+ `split_table_key` and `connection_for_table_key`, which NEED the retired keys present so a
2641
+ retired residue key can still be ATTRIBUTED to its connection during cleanup β€” `apply_plan`'s
2642
+ pop loop mints `table_key_for(retired, connection_id)` for exactly that purpose. Narrowing the
2643
+ set would break the cleanup path; narrowing the DROP TEST is the change.
2644
+ """
2645
+ if not connection_id:
2646
+ return list(fields)
2647
+ out = []
2648
+ for field in fields:
2649
+ bag = field.get("link") if isinstance(field, dict) else None
2650
+ if not isinstance(bag, dict):
2651
+ out.append(field)
2652
+ continue
2653
+ target = str(bag.get("table") or "")
2654
+ if target not in BASE_TABLE_KEYS or target in RETIRED_KEYS:
2655
+ continue
2656
+ out.append({**field,
2657
+ "link": {**bag, "table": table_key_for(target, connection_id)}})
2658
+ return out
2659
+
2660
+
2661
+ #: R6 / standing rule 1's SECOND HALF, for the case this ticket creates: a connection that is not
2662
+ #: the tenant's default has no mirror of its own yet, so there is no honest row source for it.
2663
+ #: Reading the default connection's mirror would be the exact cross-client leak R7 forbids, so the
2664
+ #: tables are created EMPTY and the reason is reported rather than inferred from a blank grid.
2665
+ def _no_mirror_report(connection_id):
2666
+ return {"subject": "rows", "limit": 0, "effect": "refused",
2667
+ "cause": "this connection has no mirror of its own yet, and reading the default "
2668
+ "connection's mirror would put one client's rows in another client's "
2669
+ "database, which strict isolation forbids",
2670
+ "recommendation": "give each connection its own mirror sync, then run this refresh "
2671
+ "again. The tables, their fields and their links are created now, "
2672
+ "so nothing downstream has to wait for that.",
2673
+ "connection": str(connection_id or "")}
2674
+
2675
+
2676
  class _LentDoc:
2677
  """A store handle that serves the ONE `user_tables` document `plan()` has ALREADY read.
2678
 
 
2776
  return bool(read_config(rt)["frozen"])
2777
 
2778
 
2779
+ def plan(cur, rt=None, connection_id=None):
2780
  """The rows that WOULD be written, plus the refusals that apply β€” no store WRITE at all.
2781
 
2782
  Separated from `apply_plan` so a route, a gate and a dry run all measure the same thing, and
 
2787
  `{table_key: limit_report}` for every table this plan did not fully materialise, which is R6's
2788
  second sentence carried as data rather than left for a reader to infer from an empty list.
2789
 
2790
+ ⭐⭐ W54-T46 / R4 / R7 β€” `connection_id` IS THE NAMESPACE TOKEN, and `None` means the
2791
+ tenant's DESIGNATED DEFAULT, whose keys stay exactly the legacy ones. Every key this function
2792
+ reads a cap for, reports a limit for and counts against `MAX_TABLES` is the NAMESPACED key, so
2793
+ two connections are two disjoint sets of tables and neither can be planned over the other.
2794
+
2795
+ β›” `cur` MAY BE None, and for a non-default connection it always is. There is one DuckDB mirror
2796
+ per tenant and it holds the DEFAULT connection's book; handing it to another connection's plan
2797
+ would build one client's rows into another client's database. So a plan with no cursor builds
2798
+ NO rows and says why, per table, in `limits` (standing rule 1's second half).
2799
+
2800
  β›” `rt` IS WHAT MAKES THE TABLE-COUNT CHECK HONEST, and leaving it out was a real half-spawn
2801
  bug. This spawn writes FOUR tables in four updater passes; a tenant near `MAX_TABLES` would
2802
  create some and refuse the rest β€” leaving a locked invoices database with no rollup host,
 
2813
  # not apply on exactly the run that creates the databases. This module DECLARES these keys, so
2814
  # it is the honest place to say what they are. Idempotent (a set add), and it fills the
2815
  # evaluator's input rather than becoming a second evaluator.
2816
+ keys = {bucket: table_key_for(key, connection_id)
2817
+ for bucket, key, _l, _f in TABLES}
2818
+ ut.register_connected(*keys.values())
2819
+ excluded = excluded_ids(cur) if cur is not None else set()
2820
  # ⭐⭐ W30-T35 / R6 / R7 β€” WHICH BUCKETS ARE BUILT AT ALL IS NOW ASKED, NOT ASSUMED, and it is
2821
  # `core.user_tables.row_limit` that answers: 0 = "stores no rows HERE" (read-through), None =
2822
  # "connected and uncapped", MAX_ROWS = "the editable substrate". Its own docstring names this
 
2860
  # the definition instead of taking one. `_ensure_table_inplace` writes exactly this stamp, so
2861
  # what is lent is the document as it stands the moment this plan applies.
2862
  lent = _LentDoc({**existing,
2863
+ **{table_key_for(k, connection_id): {
2864
+ **(existing.get(table_key_for(k, connection_id)) or {}),
2865
+ "readThrough": True}
2866
  for k in READ_THROUGH_KEYS}},
2867
  ut.STORE_KEY)
2868
 
2869
  built, limits = {}, {}
2870
  caps = {}
2871
+ for bucket, _base, _label, _fields in TABLES:
2872
+ key = keys[bucket]
2873
  reader = _READERS.get(bucket)
2874
  caps[key] = cap = ut.row_limit(key, st=lent)
2875
+ if cur is None and reader is not None and cap != 0:
2876
+ # β›” A CONNECTION WITH NO MIRROR OF ITS OWN. Not silence, and not another connection's
2877
+ # rows: an empty table with its reason attached (standing rule 1's second half).
2878
+ built[bucket] = []
2879
+ limits[key] = _no_mirror_report(connection_id)
2880
+ continue
2881
  if reader is None or cap == 0:
2882
  built[bucket] = []
2883
  report = ut.limit_report(key, st=lent)
 
2888
  problems = []
2889
 
2890
  if rt is not None:
2891
+ needed = [k for k in keys.values() if k not in existing]
2892
  if needed and len(existing) + len(needed) > ut.MAX_TABLES:
2893
  problems.append(
2894
  f"tenant holds {len(existing)} of MAX_TABLES={ut.MAX_TABLES} user tables and "
2895
+ f"needs {len(needed)} more ({', '.join(needed)}) for connection "
2896
+ f"{connection_id or 'default'}; refusing rather than creating "
2897
  f"part of a linked set")
2898
 
2899
+ for bucket, _base, _label, _fields in TABLES:
2900
+ key = keys[bucket]
2901
  rows = built[bucket]
2902
  cap = caps[key] # asked ONCE per table, above β€” never re-read per loop
2903
  # ⭐⭐ R6: THE `MAX_ROWS` REFUSAL IS GONE FOR A CONNECTED SOURCE, AND THE SENTENCE IT USED
 
2940
  return built
2941
 
2942
 
2943
+ def apply_plan(rt, built, username="automation", today=None, report=None,
2944
+ connection_id=None):
2945
  """Create-or-merge every table in `built` and its rows. Idempotent by construction.
2946
 
2947
  Row ids ARE the Odoo ids, so a re-run updates in place and never appends a second copy of the
 
2949
  statement rather than a hopeful one.
2950
 
2951
  ⚠ ONLY THE BUCKETS PRESENT ARE WRITTEN, so a caller (or a gate) may hand in a subset.
2952
+
2953
+ ⭐⭐ W54-T46 β€” `connection_id` NAMES WHOSE TABLES THESE ARE. `None` is the tenant's designated
2954
+ default and writes the legacy keys, byte for byte as before. Any other connection writes its
2955
+ own namespaced keys, its own namespaced LINK targets (`namespaced_fields`) and its own
2956
+ namespaced subject claims, so the set it writes and the set the default writes are disjoint.
2957
  """
2958
  if built.get("problems"):
2959
  raise Refused("; ".join(built["problems"]))
 
2962
  # ⚠ An OPTIONAL out-parameter, not a return-shape change: `written` has one value shape and
2963
  # keeps it. A caller that wants to SAY what was retired passes a dict; `refresh` does.
2964
  retired = []
2965
+ conn_label = connection_label(rt, connection_id)
2966
+ plans = [(table_key_for(key, connection_id),
2967
+ table_label_for(label, conn_label),
2968
+ namespaced_fields(fields(), connection_id),
2969
+ built[bucket])
2970
  for bucket, key, label, fields in TABLES if bucket in built]
2971
 
2972
  # ⭐⭐ ONE SYNC WRITE FOR ALL FOUR TABLES, not one per table β€” measured, not tidied.
 
2996
  # with `TypeError: list indices must be integers`. One dict, two value shapes, is a
2997
  # sentinel in a result set [[sentinel-in-a-sort-key]] β€” so the retirement reports through
2998
  # its OWN channel and the return type stays exactly what it was.
2999
+ # ⚠ THIS CONNECTION'S copies only. A retirement is per table, and popping the bare
3000
+ # keys while refreshing connection 2 would delete the DEFAULT connection's rows.
3001
  for key in RETIRED_KEYS:
3002
+ key = table_key_for(key, connection_id)
3003
  if cur.pop(key, None) is not None:
3004
  retired.append(key)
3005
  for key, label, fields, rows in plans:
 
3040
  for row in wanted.values():
3041
  row["refreshed"] = stamp
3042
  counts = {"added": 0, "updated": 0, "removed": 0, "rows": len(wanted)}
3043
+ # W54-T46: the subject carries the connection, or client B's invoices collide with
3044
+ # client A's claim and the second connection can never be created at all.
3045
+ subject = table_subject_for(key)
3046
  table = cur.get(key)
3047
  if table is None:
3048
  if len(cur) >= ut.MAX_TABLES:
 
3086
  # `setdefault`: it is derived from the code's own structure, so the code is what it must agree
3087
  # with, and a definition that somehow lost the flag should regain it rather than keep serving
3088
  # an empty grid.
3089
+ if is_read_through_key(key):
3090
  table["readThrough"] = True
3091
  # W33-T41 β€” the claim, made DURABLE on the definition. Written on every pass for the same
3092
  # reason `readThrough` is: it is derived from this module's own structure, so the code is what
 
3169
  return str(tenant or "").strip().lower() in RI_SLUGS
3170
 
3171
 
3172
+ def available(rt=None, tenant_key=None, connection_id=None):
3173
  """⭐⭐ R3 β€” DOES THIS TENANT HAVE ODOO CONFIGURED WITH LIVE CREDENTIALS? Never a slug list.
3174
 
3175
  R3, verbatim: *"The connector table spawn gates on does this tenant have this connector
 
3194
 
3195
  β›” ADDING A SECOND ODOO TENANT NEEDS NO EDIT HERE. Anyone with a keychain `odoo` entry is
3196
  admitted, whatever their slug.
3197
+
3198
+ ⭐ W54-T46 / R4 β€” `connection_id` ASKS THE SAME QUESTION OF ONE NAMED CONNECTION.
3199
+ `odoo_flag_key` already answers per connection and already refuses to fall back to the
3200
+ environment for a named one, so admission for connection 2 tests connection 2's credentials
3201
+ and nothing else. No id is the pre-wave call, unchanged.
3202
  """
3203
+ # β›” THE UNNAMED CALL IS SPELLED WITH NO ARGUMENT, VERBATIM, AND THAT IS NOT STYLE.
3204
+ # `verify_odoo_relational`'s `_CredRT` fixture defines `odoo_flag_key(self)` with no
3205
+ # parameter, so passing even `None` positionally raises TypeError, which the handler below
3206
+ # swallows as "fail closed" β€” eight admission legs went red for a reason that had nothing to
3207
+ # do with the rule they guard. The pre-wave call stays the pre-wave call.
3208
  try:
3209
  if rt is not None:
3210
+ return bool(rt.odoo_flag_key(connection_id) if connection_id is not None
3211
+ else rt.odoo_flag_key())
3212
  except Exception: # noqa: BLE001
3213
  return False # unreadable = fail closed
3214
  if not tenant_key:
 
3217
  # from `refresh`, which is always handed one.
3218
  try:
3219
  from harness import runtime as _runtime
3220
+ _r = _runtime.get_runtime(str(tenant_key))
3221
+ return bool(_r.odoo_flag_key(connection_id) if connection_id is not None
3222
+ else _r.odoo_flag_key())
3223
  except Exception: # noqa: BLE001
3224
  return False
3225
 
3226
 
3227
+ def refresh(rt, tenant, username="automation", cur=None, today=None, connection_id=None,
3228
+ all_connections=False):
3229
  """THE entry point β€” the store-resync path and the route both call this.
3230
 
3231
  ⚠ It must be CALLED on resync by something outside this file. If it is not wired, every row
3232
  still carries a `refreshed` stamp, so a stale worklist is at least LEGIBLE rather than
3233
  silently authoritative.
3234
+
3235
+ ⭐⭐ W54-T46 / R4 / R7 / C4 β€” ONE CONNECTION PER CALL. `connection_id=None` resolves the
3236
+ tenant's DESIGNATED DEFAULT and is byte-for-byte the pre-wave behaviour, down to the return
3237
+ shape (`verify_odoo_relational` asserts on it). A named connection spawns THAT connection's
3238
+ namespaced tables, admitted against THAT connection's credentials, and can neither read nor
3239
+ write the default connection's keys.
3240
+
3241
+ ⚠ `all_connections=True` delegates to `refresh_all` below, which is the loop over every Odoo
3242
+ connection this tenant holds. It is a flag on this entry point rather than a second call in
3243
+ `main.py` for one measured reason: `verify_odoo_relational` pins the LITERAL `_rel.refresh(`
3244
+ in `main.py`'s source and reads the 2000 characters after it to prove the relation cells are
3245
+ computed after the spawn. Spelling the boot call `_rel.refresh_all(` turns two legs of a gate
3246
+ this lane may not edit RED for a reason that has nothing to do with the rule they guard.
3247
  """
3248
+ if all_connections:
3249
+ return refresh_all(rt, tenant, username=username, cur=cur, today=today)
3250
+ # β›” THE NAMESPACE IS SETTLED BEFORE ANY GUARD RUNS, because a named connection that does not
3251
+ # resolve must be REFUSED rather than quietly served the default (R7).
3252
+ if rt is None:
3253
+ cid, ns = connection_id, (connection_id or None)
3254
+ else:
3255
+ cid, ns = connection_namespace(rt, connection_id)
3256
  # ⭐⭐ W53-T39 / R3 β€” THE ADMISSION IS A CREDENTIALS TEST, NOT A TENANT NAME.
3257
  #
3258
  # β›” THE OLD GATE'S REASON IS KEPT AND ONLY ITS MECHANISM IS REPLACED. It read
 
3268
  # loop calls this every cycle and an exception is not a status. Refusing here would hand that
3269
  # loop a raise for the one state it is meant to report. So a frozen workspace is admitted this
3270
  # far and stopped by its own guard, three lines down, with its own words.
3271
+ # β›” THE UNNAMED CALL IS THE PRE-WAVE CALL, ARGUMENT FOR ARGUMENT. `verify_odoo_relational`'s
3272
+ # R3 negative control swaps `available` for a two-parameter lambda that restores the slug
3273
+ # allow-list; passing `connection_id=` unconditionally makes that swap raise TypeError instead
3274
+ # of refusing, and the control stops being a control. A named connection is the only case that
3275
+ # needs the third argument, so it is the only case that passes one.
3276
+ _admitted = (available(rt) if connection_id is None
3277
+ else available(rt, connection_id=connection_id))
3278
+ if not _admitted and not (rt is not None and frozen(rt)):
3279
  raise Refused("no Odoo credential is configured for this workspace, so there is nothing "
3280
  "behind these tables and the spawn would create empty locked databases. "
3281
  "Add an Odoo credential in the Connectors panel, then run the sync again.")
 
3303
  return {"tables": {}, "frozen": True,
3304
  "note": "this workspace has disconnected Odoo; its databases are frozen as "
3305
  "static data and are not being refreshed"}
3306
+ # β›”β›” THE MIRROR BELONGS TO THE DEFAULT CONNECTION, AND IT IS NOT LENT OUT. There is one
3307
+ # DuckDB file per tenant (`harness/datastore` is a one-file-at-a-time process global, D-29),
3308
+ # and it holds the book of whichever Odoo the tenant syncs β€” the default connection's. Reading
3309
+ # it for connection 2 would write client A's rows into client B's database with nothing red
3310
+ # anywhere, which is the exact failure R7 exists to prevent. So a non-default connection plans
3311
+ # with NO cursor: its tables, fields and links are created, its rows are empty, and `limits`
3312
+ # says why per table (standing rule 1's second half).
3313
+ if ns is not None:
3314
+ cur = None
3315
+ elif cur is None:
3316
  from harness import datastore
3317
  cur = datastore.ro_con()
3318
+ built = plan(cur, rt=rt, connection_id=ns)
3319
  # ⭐ W32-T15 / R9 β€” THE GRID PICKER, ENFORCED WHERE IT COUNTS. `apply_plan` writes only the
3320
  # buckets present in `built`, so dropping an unticked one here is the whole of "unticking a
3321
  # grid stops it materialising on the next sync". Done AFTER `plan` rather than inside it so
 
3326
  # do that either (R10 keeps them). Silent data deletion behind a checkbox is not on offer.
3327
  if rt is not None:
3328
  keep = enabled_buckets(rt)
3329
+ # ⚠ THE KEYS ARE THIS CONNECTION'S. Reporting the bare keys while refreshing
3330
+ # connection 2 would name the DEFAULT connection's grids as the ones skipped.
3331
+ skipped = sorted(table_key_for(key, ns)
3332
+ for bucket, key, _l, _f in TABLES if bucket not in keep)
3333
  for bucket, _key, _l, _f in TABLES:
3334
  if bucket not in keep:
3335
  built.pop(bucket, None)
 
3339
  # Same rule as `skipped` below β€” R6's second sentence: what was deliberately not built (or no
3340
  # longer built) SAYS SO, with the keys.
3341
  plan_report = {}
3342
+ written = apply_plan(rt, built, username=username, today=today, report=plan_report,
3343
+ connection_id=ns)
3344
  # ⭐⭐ W49-T25 / C6 β€” THE SCHEMA CATALOGUE FOLLOWS THE CODE WITH NO MANUAL STEP. Runs AFTER the
3345
  # tables are applied, so the snapshot describes a pass that actually landed. The two early
3346
  # returns above are respected by construction: a tenant with no Odoo entitlement raised, and a
3347
  # FROZEN workspace returned before reaching here, so a disconnected connector is not
3348
  # re-recorded. See `_refresh_declared_schema` for why it writes the declared half only.
3349
  declared_report = _refresh_declared_schema(rt)
3350
+ out = {"tables": written,
3351
+ **({"schemaDeclared": declared_report} if declared_report else {}),
3352
+ **({"retired": plan_report["retired"]} if plan_report.get("retired") else {}),
3353
+ # R6's second sentence: a set that was deliberately not built SAYS SO, with the keys.
3354
+ **({"skipped": skipped} if skipped else {}),
3355
+ **{bucket: len(built[bucket]) for bucket, _k, _l, _f in TABLES if bucket in built}}
3356
+ # ⚠ THE DEFAULT CONNECTION'S RETURN SHAPE DOES NOT MOVE BY ONE KEY. The two additions below
3357
+ # are reachable only on the namespaced path, because `verify_odoo_relational` asserts on this
3358
+ # dict as it stands for the default.
3359
+ if ns is not None:
3360
+ out["connection"] = cid
3361
+ if built.get("limits"):
3362
+ out["limits"] = built["limits"]
3363
+ return out
3364
+
3365
+
3366
+ def refresh_all(rt, tenant, username="automation", cur=None, today=None):
3367
+ """Refresh EVERY Odoo connection this tenant holds, one at a time (R4 / R7 / C4).
3368
+
3369
+ β›”β›” ONE CONNECTION'S FAILURE MUST NOT ABORT THE OTHERS. An agency with four clients cannot
3370
+ have client D's databases go unwritten because client B rotated a key this morning. A refusal
3371
+ or an exception is RECORDED AGAINST THE CONNECTION IT BELONGS TO and the loop continues β€”
3372
+ exactly as `refresh` reports a frozen workspace rather than raising, and for the same reason:
3373
+ this runs inside the boot rebuild and the resync loop, where an exception is not a status.
3374
+
3375
+ ⭐ THE DEFAULT CONNECTION'S NUMBERS STAY AT THE TOP LEVEL, so `main.py`'s log line and every
3376
+ other caller that reads `counts["invoices"]` keeps reading the same thing it read before. The
3377
+ per-connection map rides beside them under `connections`.
3378
+
3379
+ ⚠ ORDERED BY SLOT, which is the ordinal the tenant fixed when it added each connection, so the
3380
+ log line reads in the order the Connectors panel does. The ORDER is a slot question; the KEY
3381
+ is never one (see `table_key_for`).
3382
+ """
3383
+ reports = {}
3384
+ default = default_connection_id(rt)
3385
+ rows = []
3386
+ try:
3387
+ import core.keychain as keychain
3388
+ rows = [r for r in keychain.list_entries(rt) if r.get("type") == "odoo"]
3389
+ except Exception: # noqa: BLE001
3390
+ rows = []
3391
+ order = [str(r.get("connection_id") or r.get("id"))
3392
+ for r in sorted(rows, key=lambda r: (int(r.get("slot") or 0), str(r.get("id"))))]
3393
+ # ⚠ NO KEYCHAIN CONNECTION AT ALL is the pre-wave posture, not an empty loop: tenant #0 runs
3394
+ # on its compiled env source, and `refresh` with no id is exactly the call it always made.
3395
+ if not order:
3396
+ order = [None]
3397
+ elif default and default not in order:
3398
+ order.insert(0, default)
3399
+ primary = None
3400
+ for entry_cid in order:
3401
+ named = None if (entry_cid is None or entry_cid == default) else entry_cid
3402
+ try:
3403
+ one = refresh(rt, tenant, username=username,
3404
+ cur=(cur if named is None else None),
3405
+ today=today, connection_id=named)
3406
+ except Exception as exc: # noqa: BLE001
3407
+ one = {"tables": {}, "failed": f"{type(exc).__name__}: {exc}"}
3408
+ reports[str(entry_cid or default or DEFAULT_CONNECTION)] = one
3409
+ if named is None and primary is None:
3410
+ primary = one
3411
+ return {**(primary or {"tables": {}}), "connections": reports}
api/routes_grid.py CHANGED
@@ -2644,7 +2644,76 @@ def grid_hop_topics(session: Session = Depends(require_session)):
2644
  _PRESET_LINK_MODULES = ("customer_data", "product_data")
2645
 
2646
 
2647
- def _may_open(session: Session, key: str):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2648
  """May this session open `key` at all? The SAME two gates `_pivot_side` applies, minus the rows.
2649
 
2650
  β›” THE ROWS ARE THE POINT OF THE DIFFERENCE. `_pivot_side` calls `perm_scope.scoped_table`,
@@ -2655,23 +2724,30 @@ def _may_open(session: Session, key: str):
2655
  ⚠ FAIL CLOSED. Any refusal, any unknown table, any error is False. A target this account may
2656
  not open must not appear in the strip, because the tab would 403 on the first click and read as
2657
  a broken product rather than as a permission.
2658
- """
2659
- import core.perm_scope as perm_scope
2660
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2661
  try:
2662
  session.require(key)
2663
  except HTTPException:
2664
  return False
2665
  except Exception: # noqa: BLE001
2666
  return False
2667
- try:
2668
- perm_scope.scoped_fields(session.user, key, st=session.runtime)
2669
- except Exception: # noqa: BLE001
2670
- return False
2671
- return True
2672
 
2673
 
2674
- def _source_fields(session: Session, table: str):
2675
  """The link-bearing field list for `table`, under this session's field wall.
2676
 
2677
  β›”β›” THE PRE-SET COLUMNS ARE NOT IN `scoped_fields` AND THAT IS THE TRAP THIS FUNCTION EXISTS
@@ -2682,13 +2758,12 @@ def _source_fields(session: Session, table: str):
2682
  and look entirely correct doing it.
2683
  ⚠ APPENDED, NOT MERGED BY KEY: a tenant cannot author a field on a registry module, so the two
2684
  lists cannot collide, and a union keyed on `key` would hide that if they ever did.
2685
- """
2686
- import core.perm_scope as perm_scope
2687
 
2688
- try:
2689
- fields = list(perm_scope.scoped_fields(session.user, table, st=session.runtime) or ())
2690
- except Exception: # noqa: BLE001
2691
- fields = []
 
2692
  if table in _PRESET_LINK_MODULES:
2693
  try:
2694
  import odoo_relational
@@ -2741,6 +2816,11 @@ def _ensure_odoo_spec():
2741
  """
2742
  try:
2743
  import odoo_relational
 
 
 
 
 
2744
  return bool(odoo_relational.register_connector_spec())
2745
  except Exception: # noqa: BLE001
2746
  return False
@@ -2773,7 +2853,7 @@ def _unwalled_fields(defs: dict, key: str):
2773
  return fields
2774
 
2775
 
2776
- def _relation_context(session: Session, table: str):
2777
  """`defs` plus the three callbacks `relations` needs, memoised for the life of ONE request.
2778
 
2779
  ⚠ BOTH WALLS ARE MEMOISED. `_may_open` runs `session.require` plus `perm_scope.scoped_fields`
@@ -2789,6 +2869,29 @@ def _relation_context(session: Session, table: str):
2789
  wall really did remove would be absent from both and get reported as an edge that never
2790
  existed. Taking the union makes the unfiltered enumeration a superset by construction, so the
2791
  diff is monotone and the only thing it can be wrong about is saying "unknown" too rarely.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2792
  """
2793
  import core.user_tables as user_tables
2794
 
@@ -2796,17 +2899,31 @@ def _relation_context(session: Session, table: str):
2796
  defs = dict(user_tables.all_defs(st=session.runtime) or {})
2797
  except Exception: # noqa: BLE001
2798
  defs = {}
2799
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2800
  open_memo, field_memo, wide_memo = {}, {}, {}
2801
 
2802
  def may_open(key):
2803
  if key not in open_memo:
2804
- open_memo[key] = _may_open(session, key)
2805
  return open_memo[key]
2806
 
2807
  def fields_for(key):
2808
  if key not in field_memo:
2809
- field_memo[key] = _source_fields(session, key)
2810
  return field_memo[key]
2811
 
2812
  def open_fields_for(key):
@@ -2870,14 +2987,22 @@ def related_refusals(session: Session, table: str, depth: int, entries: list, ct
2870
  open_fields=ctx["open_fields_for"](table), open_fields_for=ctx["open_fields_for"])
2871
 
2872
 
2873
- #: ⭐ THE HTTP STATUS EACH R13 CODE EARNS ON A **PIN**. The two permission answers are 403, the
2874
  #: same status the top-of-route `_may_open` gate on `table` itself already uses; a path that never
2875
  #: existed stays the 400 this route already answered with, unchanged; and "every hop was open and
2876
  #: there is nothing there" is a 404, because it is neither a bad request nor a refusal.
2877
  #: ⚠ `no_related_rows` cannot be reached from THIS route's pin branch (a path that resolves is
2878
  #: served, so the diff never reports it) and is mapped anyway, because `diagnose_path` is the one
2879
  #: diagnosis and the row door will raise the same bag from another ticket's fence.
2880
- _REFUSAL_STATUS = {"forbidden_table": 403, "hop_filtered": 403,
 
 
 
 
 
 
 
 
2881
  "no_related_rows": 404, "unknown_via": 400}
2882
 
2883
 
@@ -2888,10 +3013,19 @@ def _refusal_error(diag: dict):
2888
  SIBLINGS inside `error`. C3 asks for *"the ENUMERATED candidates with their join columns and
2889
  the exact retry strings, not prose"*, and a client cannot draw a retry button out of an English
2890
  clause, so the structure rides beside the sentence rather than inside it.
 
 
 
 
 
 
 
 
 
2891
  """
2892
  exc = err(_REFUSAL_STATUS.get(str(diag.get("code")), 400), str(diag.get("code")),
2893
  str(diag.get("message") or ""))
2894
- for key in ("table", "hop", "path", "candidates"):
2895
  if diag.get(key) not in (None, ""):
2896
  exc.detail["error"][key] = diag[key]
2897
  return exc
@@ -2947,7 +3081,12 @@ def grid_related(table: str,
2947
  table = str(table or "").strip()
2948
  if not table:
2949
  raise err(400, "bad_table", "name the database to list relations for")
2950
- if not _may_open(session, table):
 
 
 
 
 
2951
  raise err(403, "not_permitted",
2952
  f"your account may not open '{table}', so it cannot be told what that database "
2953
  f"is related to. Ask an administrator for access to it")
@@ -2963,7 +3102,7 @@ def grid_related(table: str,
2963
  f"{relations.MAX_DEPTH} (those plus everything one further named hop away), and "
2964
  f"this request asked for {depth}. Ask for 1 or {relations.MAX_DEPTH}")
2965
 
2966
- ctx = _relation_context(session, table)
2967
  entries = related_path_entries(session, table, depth, ctx)
2968
  if via:
2969
  wanted = [str(v) for v in via if str(v or "").strip()]
 
2644
  _PRESET_LINK_MODULES = ("customer_data", "product_data")
2645
 
2646
 
2647
+ def _register_retired_tables():
2648
+ """Push `odoo_relational.RETIRED_KEYS` down into `core.relations`, at import and per request.
2649
+
2650
+ β›”β›” W54-T37 / C5 / INSTRUCTION 22 - THIS IS WHY THE OWNER SAW A PERMISSION WALL ABOUT A
2651
+ DATABASE THAT DOES NOT EXIST. `ut_odoo_customers` and `ut_odoo_products` are RETIRED: popped
2652
+ from every tenant document on every sync, replaced by the `customer_data` / `product_data`
2653
+ registry modules, and still DESCRIBED by the connector spec, which is legitimate (a spec
2654
+ describes a shape). The relation enumeration therefore minted edges at them, `_may_open` below
2655
+ failed closed on a key it could not resolve, and `relations.forbidden_table_refusal` told the
2656
+ reader to ask an administrator for access to a table nobody can grant.
2657
+
2658
+ β›” ONE DECLARATION, PUSHED, NEVER COPIED. `odoo_relational.RETIRED_KEYS` stays the only place
2659
+ the two keys are named; `core` cannot read it (`core` never imports up), so the app layer hands
2660
+ it down exactly as `core.user_tables.register_connected_prefix` is handed its prefixes. Copying
2661
+ the keys into `core` would make a second declaration of one fact.
2662
+
2663
+ ⚠ GUARDED, AND CALLED TWICE FOR THE SAME REASON `_ensure_odoo_spec` exists: a process that
2664
+ cannot import `odoo_relational` or `core` must still START, and one that imports them later
2665
+ must still get the right answer. Registration is idempotent (it is a set union) and returns the
2666
+ whole registered set, so a caller can assert what it just joined.
2667
+ """
2668
+ try:
2669
+ import odoo_relational
2670
+ import core.relations as relations
2671
+ return relations.register_retired_tables(*odoo_relational.RETIRED_KEYS)
2672
+ except Exception: # noqa: BLE001
2673
+ return frozenset()
2674
+
2675
+
2676
+ #: The import-time push. ⚠ Its VALUE is not read anywhere on the request path: it is here so the
2677
+ #: registration has happened before the first listing, and so an operator can see what landed.
2678
+ RETIRED_TABLES_AT_IMPORT = _register_retired_tables()
2679
+
2680
+
2681
+ def _walled_fields(session: Session, key: str, st=None, memo: dict = None):
2682
+ """`perm_scope.scoped_fields(key)`, or **None** when the field wall REFUSED β€” memoised.
2683
+
2684
+ ⭐⭐ W54-T39 β€” THIS FUNCTION EXISTS BECAUSE THE SAME WALL WAS BEING ASKED TWICE PER TABLE AND
2685
+ THE ANSWER WAS THROWN AWAY BOTH TIMES. `_may_open` below wanted only the verdict and
2686
+ `_source_fields` below wanted only the list; each called `scoped_fields` itself, so a listing
2687
+ that touches six tables paid for TWELVE wall resolutions. MEASURED against tenant #0 on
2688
+ 2026-09-06: one `scoped_fields` is ~135 ms on a `ut_*` grid and ~550 ms on `product_data`, so
2689
+ the duplicate pass alone was more than half of the 3.5 s the record rail took to open.
2690
+
2691
+ β›” THE VERDICT AND THE LIST ARE ONE ANSWER, AND THEY MUST STAY ONE CALL. Resolving them
2692
+ separately is not merely slow, it is two readings of one wall that can disagree if a grant
2693
+ changes between them β€” the [[one-question-two-normalizers]] shape, on a permission.
2694
+ ⚠ `None` RATHER THAN `[]` IS THE WHOLE POINT OF THE RETURN TYPE. A table the wall refuses and
2695
+ a table with no columns are different facts, and `_may_open` is the caller that has to tell
2696
+ them apart; collapsing both to an empty list would hide every refused target as an empty one.
2697
+
2698
+ β›” FAIL CLOSED, exactly as before: any exception at all is a refusal, never a widened answer.
2699
+ ⚠ `memo` IS ONE REQUEST'S, handed down by `_relation_context`. Passing None simply means no
2700
+ memo, which is what every caller outside a listing pass wants.
2701
+ """
2702
+ if memo is not None and key in memo:
2703
+ return memo[key]
2704
+ import core.perm_scope as perm_scope
2705
+
2706
+ try:
2707
+ answer = list(perm_scope.scoped_fields(
2708
+ session.user, key, st=session.runtime if st is None else st) or ())
2709
+ except Exception: # noqa: BLE001
2710
+ answer = None
2711
+ if memo is not None:
2712
+ memo[key] = answer
2713
+ return answer
2714
+
2715
+
2716
+ def _may_open(session: Session, key: str, st=None, memo: dict = None):
2717
  """May this session open `key` at all? The SAME two gates `_pivot_side` applies, minus the rows.
2718
 
2719
  β›” THE ROWS ARE THE POINT OF THE DIFFERENCE. `_pivot_side` calls `perm_scope.scoped_table`,
 
2724
  ⚠ FAIL CLOSED. Any refusal, any unknown table, any error is False. A target this account may
2725
  not open must not appear in the strip, because the tab would 403 on the first click and read as
2726
  a broken product rather than as a permission.
 
 
2727
 
2728
+ β›”β›” AND IT STILL CANNOT TELL "ABSENT" FROM "REFUSED", WHICH IS CORRECT AND IS **NOT** WHAT
2729
+ INSTRUCTION 22 ASKED TO CHANGE. Conflating "not granted" with "could not be read" is deliberate
2730
+ and the refusal sentence says both out loud. What was missing is a third case that never
2731
+ belonged here at all: a table this deployment does not HAVE. That is answered upstream, by
2732
+ `_register_retired_tables` above keeping such a key from ever being enumerated as an edge
2733
+ target, and by `relations.diagnose_path` naming it when a request asks for one anyway.
2734
+
2735
+ ⭐ W54-T39 β€” THE SECOND GATE IS NOW ASKED THROUGH `_walled_fields`, WHICH IS THE SAME QUESTION
2736
+ AND THE SAME FAIL-CLOSED ANSWER, shared with `_source_fields` so one table costs one wall
2737
+ resolution instead of two. β›” THE GRANT GATE STILL RIDES `session.require`, which resolves
2738
+ against the session's OWN runtime rather than any handle passed in: a lent snapshot may make a
2739
+ read cheaper and must never be able to make a grant broader.
2740
+ """
2741
  try:
2742
  session.require(key)
2743
  except HTTPException:
2744
  return False
2745
  except Exception: # noqa: BLE001
2746
  return False
2747
+ return _walled_fields(session, key, st=st, memo=memo) is not None
 
 
 
 
2748
 
2749
 
2750
+ def _source_fields(session: Session, table: str, st=None, memo: dict = None):
2751
  """The link-bearing field list for `table`, under this session's field wall.
2752
 
2753
  β›”β›” THE PRE-SET COLUMNS ARE NOT IN `scoped_fields` AND THAT IS THE TRAP THIS FUNCTION EXISTS
 
2758
  and look entirely correct doing it.
2759
  ⚠ APPENDED, NOT MERGED BY KEY: a tenant cannot author a field on a registry module, so the two
2760
  lists cannot collide, and a union keyed on `key` would hide that if they ever did.
 
 
2761
 
2762
+ ⚠ W54-T39 β€” A REFUSED WALL STILL READS AS `[]` HERE, unchanged. `_walled_fields` answers None
2763
+ for that case so `_may_open` can tell it from an empty table; this door has never needed the
2764
+ distinction and must not start reporting one, because a refusal is `_may_open`'s word.
2765
+ """
2766
+ fields = list(_walled_fields(session, table, st=st, memo=memo) or ())
2767
  if table in _PRESET_LINK_MODULES:
2768
  try:
2769
  import odoo_relational
 
2816
  """
2817
  try:
2818
  import odoo_relational
2819
+ # ⚠ BESIDE THE SPEC REGISTRATION AND FOR ITS REASON. Both are pushes from this layer into
2820
+ # `core`, both are idempotent, and both are wrong to skip in a process that imported this
2821
+ # module before `platform/` was on the path. Registering the retired keys HERE as well as
2822
+ # at import is what makes the enumeration below correct in either process shape.
2823
+ _register_retired_tables()
2824
  return bool(odoo_relational.register_connector_spec())
2825
  except Exception: # noqa: BLE001
2826
  return False
 
2853
  return fields
2854
 
2855
 
2856
+ def _relation_context(session: Session, table: str, memo: dict = None):
2857
  """`defs` plus the three callbacks `relations` needs, memoised for the life of ONE request.
2858
 
2859
  ⚠ BOTH WALLS ARE MEMOISED. `_may_open` runs `session.require` plus `perm_scope.scoped_fields`
 
2869
  wall really did remove would be absent from both and get reported as an edge that never
2870
  existed. Taking the union makes the unfiltered enumeration a superset by construction, so the
2871
  diff is monotone and the only thing it can be wrong about is saying "unknown" too rarely.
2872
+
2873
+ ⭐⭐ W54-T39 β€” **THE DEFINITIONS ARE READ ONCE AND THEN LENT, WHICH IS WHERE THE RECORD RAIL'S
2874
+ THREE AND A HALF SECONDS WERE.** `perm_scope.scoped_fields` reaches `user_tables.all_defs`
2875
+ for every table it is asked about, and `all_defs` is a store projection: one Neon round trip,
2876
+ MEASURED at ~135 ms each on 2026-09-06. A depth-2 listing off `customer_data` asked about six
2877
+ tables and paid that round trip TWELVE times for the identical document this function had
2878
+ already read on its first line. `user_tables.lend` exists for exactly this β€” `nav_entries` has
2879
+ paired `all_defs` with it since W32-T02 β€” so the handle below serves that one snapshot to
2880
+ every wall resolution in the pass and each `ut_*` table's `scoped_fields` drops from ~135 ms
2881
+ to 0.
2882
+ β›” IT IS A READ HANDLE AND IT NEVER REACHES A WRITE. `lend_defs`' own note is the rule: every
2883
+ value it serves is a `_Projected`, so a caller that wanted rows gets a loud `KeyError` rather
2884
+ than a silently empty grid β€” and `scoped_fields` is a `want_rows=False` door by construction.
2885
+ Nothing here is handed to a mutation; `grid_related` is a GET.
2886
+ β›” IT CANNOT WIDEN A WALL, and that was checked rather than assumed: the lent handle serves
2887
+ only `user_tables` and (lazily, once) `object_shares`, every other store key falls through to
2888
+ the real runtime, and `session.require` is not given it at all. MEASURED 2026-09-06 across all
2889
+ ten of tenant #0's databases: `scoped_fields` under the lent handle returned a field list
2890
+ EQUAL, key for key and value for value, to the one it returned under the bare runtime.
2891
+
2892
+ ⚠ AND THE SNAPSHOT IS THE POINT, not a side effect. One listing answers about one set of
2893
+ definitions; re-reading them mid-pass could enumerate an edge from a table that vanished two
2894
+ hops ago and report the inconsistency as a refusal.
2895
  """
2896
  import core.user_tables as user_tables
2897
 
 
2899
  defs = dict(user_tables.all_defs(st=session.runtime) or {})
2900
  except Exception: # noqa: BLE001
2901
  defs = {}
2902
+ try:
2903
+ lent = user_tables.lend(session.runtime, **{user_tables.STORE_KEY: defs})
2904
+ except Exception: # noqa: BLE001
2905
+ # A store handle too old to lend is CORRECT-but-slow, exactly as `all_defs`' own fallback
2906
+ # is: the pass simply goes back to paying a round trip per wall resolution.
2907
+ lent = session.runtime
2908
+
2909
+ # ⭐ ONE WALL RESOLUTION PER TABLE, SHARED BY BOTH CALLBACKS. `open_memo` and `field_memo`
2910
+ # below still memoise their own composition (the grant gate, the pre-set link append); this is
2911
+ # the `scoped_fields` answer underneath both of them, which is the expensive part.
2912
+ # ⚠ THE CALLER MAY HAND ITS OWN IN, and `grid_related` does. That route has to answer 403 for
2913
+ # the SOURCE table before it lists anything, so it resolves that one wall a moment before this
2914
+ # function is built; without the shared bag the source table would be resolved twice, which on
2915
+ # `product_data` is a second ~550 ms for an answer already in hand.
2916
+ wall_memo = memo if memo is not None else {}
2917
  open_memo, field_memo, wide_memo = {}, {}, {}
2918
 
2919
  def may_open(key):
2920
  if key not in open_memo:
2921
+ open_memo[key] = _may_open(session, key, st=lent, memo=wall_memo)
2922
  return open_memo[key]
2923
 
2924
  def fields_for(key):
2925
  if key not in field_memo:
2926
+ field_memo[key] = _source_fields(session, key, st=lent, memo=wall_memo)
2927
  return field_memo[key]
2928
 
2929
  def open_fields_for(key):
 
2987
  open_fields=ctx["open_fields_for"](table), open_fields_for=ctx["open_fields_for"])
2988
 
2989
 
2990
+ #: ⭐ THE HTTP STATUS EACH REFUSAL CODE EARNS ON A **PIN**. The two permission answers are 403, the
2991
  #: same status the top-of-route `_may_open` gate on `table` itself already uses; a path that never
2992
  #: existed stays the 400 this route already answered with, unchanged; and "every hop was open and
2993
  #: there is nothing there" is a 404, because it is neither a bad request nor a refusal.
2994
  #: ⚠ `no_related_rows` cannot be reached from THIS route's pin branch (a path that resolves is
2995
  #: served, so the diff never reports it) and is mapped anyway, because `diagnose_path` is the one
2996
  #: diagnosis and the row door will raise the same bag from another ticket's fence.
2997
+ #: ⭐⭐ W54-T37 / C5 - `retired_target` IS A **404**, AND IT IS DELIBERATELY NOT A 403. The whole
2998
+ #: complaint in instruction 22 is a permission status on a table that does not exist, so any 4xx
2999
+ #: in the permission family would repeat the lie in a header. ⚠ 410 Gone is the more precise word
3000
+ #: for a database that was retired rather than never present, and it is NOT used: the client half
3001
+ #: of this contract is another lane's, every existing handler here branches on the CODE rather than
3002
+ #: the status, and introducing the one status nothing in this app has ever returned would risk a
3003
+ #: fetch wrapper treating it as a transport failure. The code carries the meaning; the status only
3004
+ #: has to be honest.
3005
+ _REFUSAL_STATUS = {"forbidden_table": 403, "hop_filtered": 403, "retired_target": 404,
3006
  "no_related_rows": 404, "unknown_via": 400}
3007
 
3008
 
 
3013
  SIBLINGS inside `error`. C3 asks for *"the ENUMERATED candidates with their join columns and
3014
  the exact retry strings, not prose"*, and a client cannot draw a retry button out of an English
3015
  clause, so the structure rides beside the sentence rather than inside it.
3016
+
3017
+ ⭐⭐ W54-T40 β€” `detail` IS COPIED TOO, AND IT IS THE ROW W54-T38 BOOKED. C5 gives every refusal
3018
+ a SHORT `message` and a long `detail`, and the client renders the pair as a `<details>` with the
3019
+ sentence in the summary; this function copied four keys and dropped the diagnosis, so a refusal
3020
+ arriving through THIS door rendered as the sentence alone while the identical refusal arriving
3021
+ through the listing kept its disclosure. One key, and the two doors stop disagreeing about how
3022
+ much of one contract they carry.
3023
+ ⚠ A BAG WITH NO DIAGNOSIS STILL RENDERS AS THE SENTENCE ALONE: the loop copies a key only when
3024
+ the bag carries one, so nothing gains a caret with nothing behind it.
3025
  """
3026
  exc = err(_REFUSAL_STATUS.get(str(diag.get("code")), 400), str(diag.get("code")),
3027
  str(diag.get("message") or ""))
3028
+ for key in ("table", "hop", "path", "candidates", "detail"):
3029
  if diag.get(key) not in (None, ""):
3030
  exc.detail["error"][key] = diag[key]
3031
  return exc
 
3081
  table = str(table or "").strip()
3082
  if not table:
3083
  raise err(400, "bad_table", "name the database to list relations for")
3084
+ # ⚠ W54-T39 β€” THE GATE IS UNMOVED AND UNCHANGED; only its ANSWER is kept. `wall_memo` rides
3085
+ # into `_relation_context` below so this table's field wall, which the 403 has just resolved
3086
+ # at full price, is not resolved a second time three lines later. The order is untouched: the
3087
+ # caller's own access is still the first thing this route decides.
3088
+ wall_memo = {}
3089
+ if not _may_open(session, table, memo=wall_memo):
3090
  raise err(403, "not_permitted",
3091
  f"your account may not open '{table}', so it cannot be told what that database "
3092
  f"is related to. Ask an administrator for access to it")
 
3102
  f"{relations.MAX_DEPTH} (those plus everything one further named hop away), and "
3103
  f"this request asked for {depth}. Ask for 1 or {relations.MAX_DEPTH}")
3104
 
3105
+ ctx = _relation_context(session, table, memo=wall_memo)
3106
  entries = related_path_entries(session, table, depth, ctx)
3107
  if via:
3108
  wanted = [str(v) for v in via if str(v or "").strip()]
api/routes_keychain.py CHANGED
@@ -99,8 +99,10 @@ SCOPE_KEY = "keychain_scopes"
99
 
100
  #: β›”β›” THE TYPES A WHOLE WORKSPACE READS THROUGH, WHICH THEREFORE CANNOT BE PERSONAL.
101
  #:
102
- #: `keychain.odoo_creds` and `keychain.meta_creds` both resolve to *the first entry of that type*
103
- #: for the TENANT β€” that is what spawns `ut_odoo_*` / `ut_meta_*` and what every measure column is
 
 
104
  #: answered from. So a member storing a personal Odoo key would not get "their own Odoo": they
105
  #: would silently become the credential the entire workspace's databases are built from, which is
106
  #: a credential elevation wearing a scope picker.
@@ -112,7 +114,8 @@ SCOPE_KEY = "keychain_scopes"
112
  #: (whose own `TENANT_WIDE_TYPES` already carried three entries, `amazon_sp` included, "JOINED IN
113
  #: WAVE 52" by its own header comment). Until this line, a non-admin could POST a PERSONAL
114
  #: `amazon_sp` entry through THIS door β€” `add_key`'s refusal only fires for a type in this tuple β€”
115
- #: while `core/keychain._first_creds` already skipped a personal `amazon_sp` entry when resolving
 
116
  #: the tenant's Amazon credential. So the write succeeded, the UI told the member they had
117
  #: connected their own Amazon, and the resolver silently served nothing for it: not the elevation
118
  #: (the resolver-side guard held), but a door that stores a credential the product then ignores,
@@ -201,13 +204,30 @@ def visible_entries(rt, uname, is_admin=False):
201
  owner = str(e.get("createdBy") or "")
202
  if not may_see(scope, owner, uname):
203
  continue
204
- row = {**e, "scope": scope, "owner": owner}
205
  if not (is_admin or str(owner) == str(uname)):
206
  row["preview"] = ""
207
  out.append(row)
208
  return out
209
 
210
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  def _write_scope(rt, entry_id, scope, owner):
212
  """Persist one entry's scope. A `business` entry CLEARS its row rather than writing the
213
  default, so the store holds one spelling of the common case."""
@@ -235,11 +255,140 @@ def _kc():
235
  return keychain
236
 
237
 
238
- def _resolved_odoo_key(rt):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  """`(source, flag_key)` β€” which source would serve this tenant's Odoo queries, in both the
240
  shapes this module needs: the display string (`env` / `keychain:<id>`) and the key the pause
241
  flag is stored under.
242
 
 
 
 
 
 
243
  ⭐ D-10 (wave 24): THE RESOLUTION ITSELF NOW LIVES IN ONE PLACE, `TenantRuntime.odoo_flag_key`,
244
  beside the `odoo_source()` it must agree with. This function had its own copy of the same
245
  three rules β€” first unlocked keychain odoo entry, else env for tenant #0, else nothing β€” and
@@ -247,7 +396,7 @@ def _resolved_odoo_key(rt):
247
  against another, freezing nothing while the UI reports success. The two SHAPES stay here
248
  because they are this module's presentation concern; the DECISION does not.
249
  """
250
- flag_key = rt.odoo_flag_key()
251
  if not flag_key:
252
  return None, None
253
  return ("env" if flag_key == _ENV_ODOO_FLAG_KEY else f"keychain:{flag_key}"), flag_key
@@ -559,7 +708,16 @@ def list_keychain(session: Session = Depends(require_session)):
559
  #: the vocabulary and the permission, so the client renders a picker it can honour
560
  #: rather than offering an option the server will refuse (R4: business is admin-only).
561
  "scopes": list(SCOPES), "canBusiness": bool(session.admin),
562
- "tenantWideTypes": list(TENANT_WIDE_TYPES)}
 
 
 
 
 
 
 
 
 
563
 
564
 
565
  @router.post("/admin/keychain", status_code=201)
@@ -572,18 +730,44 @@ def add_key(body: dict = Body(default=None), session: Session = Depends(require_
572
  if scope is None:
573
  raise err(400, "bad_scope",
574
  f"scope must be one of {', '.join(SCOPES)}")
575
- if scope == "business" and not session.admin:
576
- raise err(403, "not_admin",
577
- "a business-wide connection applies to everyone in this workspace, so only an "
578
- "administrator can create one. You can add it as a personal connection instead.")
579
  etype = str(body.get("type") or "").strip().lower()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
580
  if scope == "personal" and etype in TENANT_WIDE_TYPES:
581
  # β›” REPORTED, NOT COERCED (W30/R6's second sentence). See TENANT_WIDE_TYPES above: this
582
  # credential is what the WHOLE workspace's databases are built from, so "personal" would
583
  # be a label on a tenant-wide key rather than a boundary around it.
 
 
 
584
  raise err(400, "scope_not_available",
585
  f"a {etype} connection is what this whole workspace's databases are read "
586
- f"through, so it is always business-wide β€” it cannot be a personal connection. "
587
  f"An administrator can add it for everyone.")
588
  try:
589
  row = kc.add_entry(session.runtime, body.get("label"), body.get("type"),
@@ -618,34 +802,69 @@ def add_key(body: dict = Body(default=None), session: Session = Depends(require_
618
  raise err(503, "store_unavailable",
619
  "the key was not saved β€” its sharing setting could not be stored, so "
620
  "nothing was kept. Try again.")
621
- return {"entry": {**row, "scope": scope, "owner": session.uname}}
622
 
623
 
624
  @router.put("/admin/keychain/{entry_id}")
625
  def update_key(entry_id: str, body: dict = Body(default=None),
626
  session: Session = Depends(require_session)):
627
- """Contract C1's scope door. Only the scope moves β€” a stored secret is never re-openable, so
628
- "edit this key" means "replace it" and that is `DELETE` + `POST`."""
 
 
 
 
 
 
 
 
 
 
629
  row = _own_row(session, entry_id)
630
- scope = clean_scope((body or {}).get("scope"), default=None)
631
- if scope is None:
632
- raise err(400, "bad_scope", f"scope must be one of {', '.join(SCOPES)}")
633
- if scope == "business" and not session.admin:
634
- raise err(403, "not_admin",
635
- "a business-wide connection applies to everyone in this workspace, so only an "
636
- "administrator can make one business-wide.")
 
 
 
 
 
 
 
 
637
  if not _may_touch(session, row):
638
  raise err(403, "not_yours", "this connection is not yours to change")
639
- if scope == "personal" and str(row.get("type") or "") in TENANT_WIDE_TYPES:
640
  raise err(400, "scope_not_available",
641
  f"a {row.get('type')} connection is what this whole workspace's databases are "
642
  f"read through, so it is always business-wide.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
643
  owner = row.get("owner") or session.uname
 
 
644
  try:
645
  _write_scope(session.runtime, entry_id, scope, owner)
646
  except Exception:
647
  raise err(503, "store_unavailable", "the change was not saved β€” try again")
648
- return {"entry": {**row, "scope": scope, "owner": owner if scope == "personal" else ""}}
 
649
 
650
 
651
  @router.delete("/admin/keychain/{entry_id}")
@@ -710,21 +929,27 @@ def connectors(session: Session = Depends(require_session)):
710
  # every colleague's personal connection on the screen next door to the one that hides them.
711
  entries = visible_entries(session.runtime, session.uname, bool(session.admin))
712
  # R3 cutover (2026-08-04): which source would actually serve this tenant's Odoo queries β€”
713
- # mirrors TenantRuntime.odoo_source() exactly: first unlocked keychain odoo entry, else env
714
- # for tenant #0 only, else nothing (fail closed β€” never another tenant's environment).
 
 
 
 
 
 
 
 
 
715
  # ⚠ W32-T11: computed over the TENANT's entries, not over `entries` above. "Which source
716
  # serves this workspace" is one fact for everybody, and deriving it from a per-USER list would
717
  # make the answer depend on who opened the pane. Personal entries are excluded for the same
718
  # reason `TENANT_WIDE_TYPES` refuses them: they must never become the workspace's source.
719
- _scopes = _scope_rows(session.runtime)
720
- first_odoo = next((e["id"] for e in kc.list_entries(session.runtime)
721
- if e["type"] == "odoo"
722
- and entry_scope(session.runtime, e["id"], _scopes)[0] != "personal"), None)
723
  # β›” W32-T10 β€” the env leg goes through `env_odoo_available` now, so this route and the
724
  # connectors DIRECTORY answer "does the environment serve this tenant?" with one function
725
  # instead of two spellings that agreed until a second tenant signed in.
726
- if first_odoo and kc.unlocked():
727
- resolved = f"keychain:{first_odoo}"
728
  elif env_odoo_available(session.runtime):
729
  resolved = "env"
730
  else:
@@ -811,14 +1036,31 @@ def _rel():
811
  return rel
812
 
813
 
814
- def _odoo_entry(session):
815
  """The keychain entry SERVING this tenant's Odoo, or None when the environment is (or nothing
816
- is). Business-scoped by construction β€” `TENANT_WIDE_TYPES` refuses a personal one."""
 
 
 
 
 
 
 
 
 
817
  kc = _kc()
 
 
 
818
  scopes = _scope_rows(session.runtime)
819
  for e in kc.list_entries(session.runtime):
820
- if e["type"] == "odoo" and entry_scope(session.runtime, e["id"], scopes)[0] != "personal":
821
- return e
 
 
 
 
 
822
  return None
823
 
824
 
@@ -978,10 +1220,14 @@ def _rewrite_server_db(session, server_db):
978
  So this is add-then-delete through the module's own doors, with the side rows (pause flag,
979
  scope) carried across because they are keyed by ENTRY ID.
980
  ⚠ THE ORDER IS DELIBERATE AND THE WINDOW IS REAL: for the moment between the add and the
981
- delete this tenant has TWO odoo entries, and `odoo_creds` takes the first by id sort β€” so a
982
- resync landing inside that window could read the OLD database. The alternative order can
983
- leave the workspace with no credential at all, which is worse than one stale read. Milliseconds
984
- of ambiguity beats a lost key.
 
 
 
 
985
  """
986
  kc = _kc()
987
  entry = _odoo_entry(session)
 
99
 
100
  #: β›”β›” THE TYPES A WHOLE WORKSPACE READS THROUGH, WHICH THEREFORE CANNOT BE PERSONAL.
101
  #:
102
+ #: `keychain.odoo_creds` and `keychain.meta_creds` both resolve to *a connection of that type* for
103
+ #: the TENANT β€” the one a caller NAMES, or the tenant's designated default when none is named
104
+ #: (W54-T45 / R4; it was "the first entry of that type" before) β€” that is what spawns
105
+ #: `ut_odoo_*` / `ut_meta_*` and what every measure column is
106
  #: answered from. So a member storing a personal Odoo key would not get "their own Odoo": they
107
  #: would silently become the credential the entire workspace's databases are built from, which is
108
  #: a credential elevation wearing a scope picker.
 
114
  #: (whose own `TENANT_WIDE_TYPES` already carried three entries, `amazon_sp` included, "JOINED IN
115
  #: WAVE 52" by its own header comment). Until this line, a non-admin could POST a PERSONAL
116
  #: `amazon_sp` entry through THIS door β€” `add_key`'s refusal only fires for a type in this tuple β€”
117
+ #: while `core/keychain`'s shared resolver (`_first_creds` then, `_creds_for` since W54-T45)
118
+ #: already skipped a personal `amazon_sp` entry when resolving
119
  #: the tenant's Amazon credential. So the write succeeded, the UI told the member they had
120
  #: connected their own Amazon, and the resolver silently served nothing for it: not the elevation
121
  #: (the resolver-side guard held), but a door that stores a credential the product then ignores,
 
204
  owner = str(e.get("createdBy") or "")
205
  if not may_see(scope, owner, uname):
206
  continue
207
+ row = {**_identified(e), "scope": scope, "owner": owner}
208
  if not (is_admin or str(owner) == str(uname)):
209
  row["preview"] = ""
210
  out.append(row)
211
  return out
212
 
213
 
214
+ #: ⭐⭐ W54-T44 / R4 / CONTRACT C4 β€” THE IDENTITY, IN THE WIRE'S OWN SPELLING.
215
+ #:
216
+ #: `core/keychain.py` stamps `connection_id` and `slot` on every entry so that two connections of
217
+ #: one kind are separately addressable (R4's agency tenant: many Odoos, one workspace). This layer
218
+ #: renames the first of them to `connectionId` because that is what every other camelCase field on
219
+ #: these payloads does (`createdBy`, `canBusiness`, `tenantWideTypes`), and a payload carrying both
220
+ #: spellings would be [[a-constant-two-features-share]] on the wire, where a client picking the
221
+ #: wrong one still looks right until the day only one is filled.
222
+ #: ⚠ `slot` is one word, so it crosses unchanged.
223
+ def _identified(row):
224
+ """One keychain row, with its identity in wire spelling. Gains keys, never loses one."""
225
+ out = dict(row)
226
+ out["connectionId"] = str(out.pop("connection_id", "") or out.get("id") or "")
227
+ out["slot"] = int(out.get("slot") or 1)
228
+ return out
229
+
230
+
231
  def _write_scope(rt, entry_id, scope, owner):
232
  """Persist one entry's scope. A `business` entry CLEARS its row rather than writing the
233
  default, so the store holds one spelling of the common case."""
 
255
  return keychain
256
 
257
 
258
+ def _ps():
259
+ """`core.perm_scope`, lazily. Same idiom as `_kc()` and `_rel()`, and for the same reason: the
260
+ permission layer pulls the grid stack in behind it, and this router is imported at boot."""
261
+ import core.perm_scope as perm_scope
262
+ return perm_scope
263
+
264
+
265
+ #: β›” THE ONE KIND THAT STANDS BEHIND NO CONNECTOR CARD. `_connector_by_entry_type` names every
266
+ #: other member of `keychain.ENTRY_TYPES`; `generic` is a credential a person stored by hand, so it
267
+ #: has no card and no label to borrow. Spelled here rather than dropped from the vocabulary,
268
+ #: because a grant list narrower than the door it governs is a gap nobody can see: `add_key` accepts
269
+ #: every `ENTRY_TYPES` member, so every one of them must be grantable.
270
+ CONNECTOR_KIND_LABELS = {"generic": "Other credential"}
271
+
272
+
273
+ def connector_grant_kinds():
274
+ """The grant vocabulary: `[{key, label, tenantWide}]`, one row per connectable kind.
275
+
276
+ ⭐⭐ W54-T47 / R4 β€” THE THIRD AXIS'S OWN WORDS. Owner: *"access becomes Database / Module /
277
+ Connector."* The first two are registry keys the permission editor already renders; this one is
278
+ a CREDENTIAL KIND, so its vocabulary is `keychain.ENTRY_TYPES` and not the registry at all.
279
+
280
+ β›” DERIVED FROM `ENTRY_TYPES`, NEVER TYPED OUT. That set is what `add_entry` validates against,
281
+ so a hand-written list here would be [[one-question-two-normalizers]] the day a connector is
282
+ added: a kind the door accepts and the editor cannot grant is a permission nobody can give.
283
+ ⚠ `tenantWide` RIDES ALONG so the editor can say what a grant on that kind really means. A
284
+ tenant-wide source is never personal, so granting it hands the member the workspace's own
285
+ credential slot; that is exactly what R4 asks for and exactly what an admin should read before
286
+ ticking it.
287
+ """
288
+ owners = _connector_by_entry_type()
289
+ out = []
290
+ for etype in sorted(_kc().ENTRY_TYPES):
291
+ label = str((owners.get(etype) or {}).get("label") or "").strip()
292
+ out.append({"key": etype,
293
+ "label": label or CONNECTOR_KIND_LABELS.get(etype, etype),
294
+ "tenantWide": etype in TENANT_WIDE_TYPES})
295
+ return out
296
+
297
+
298
+ def _grant_subject(session, username):
299
+ """The registry key for `username`, or a 404 that cannot distinguish another tenant's account
300
+ from a missing one.
301
+
302
+ β›” THE 404 RULE AND THE TENANT DEFAULT ARE BORROWED, NOT RE-SPELLED. `routes_admin.get_perms`
303
+ already answers *"a cross-tenant username answers exactly like a missing one, 404, never 403,
304
+ because 'that account exists in another company' is itself a leak"*, and `_tenant_of` is
305
+ already the ONE spelling of the pre-wave default. A second copy here is how a tenant wall grows
306
+ a gap. Imported lazily, exactly as `_connector_by_entry_type` imports `routes_connectors`.
307
+ """
308
+ import routes_admin as ra
309
+ uname = str(username or "").strip().lower()
310
+ reg = ra._registry()
311
+ if uname not in reg or ra._tenant_of(reg[uname]) != ra._tenant_of(session.user):
312
+ raise err(404, "no_such_user", f"no account named {uname!r}")
313
+ return uname
314
+
315
+
316
+ def _grant_admin(session):
317
+ """Deciding who may connect a source is an administrator's act, refused at the server.
318
+
319
+ β›” THE CLIENT HIDES; THIS FORBIDS. `PermsEditor.tsx` renders the section only for an admin as a
320
+ courtesy, and its own header says every control there is one.
321
+ """
322
+ if not session.admin:
323
+ raise err(403, "not_admin",
324
+ "only an administrator can decide who may add connections to this workspace")
325
+
326
+
327
+ @router.get("/admin/users/{username}/connector-grants")
328
+ def get_connector_grants(username: str, session: Session = Depends(require_session)):
329
+ """One account's Connector grants, plus the vocabulary the editor renders them from."""
330
+ _grant_admin(session)
331
+ uname = _grant_subject(session, username)
332
+ return {"username": uname,
333
+ "kinds": connector_grant_kinds(),
334
+ "granted": sorted(_ps().connector_grants(uname, st=session.runtime))}
335
+
336
+
337
+ @router.put("/admin/users/{username}/connector-grants")
338
+ def put_connector_grants(username: str, body: dict = Body(default=None),
339
+ session: Session = Depends(require_session)):
340
+ """Replace one account's Connector grants wholesale (W54-T47 / R4 / contract C4).
341
+
342
+ WHOLESALE, for the reason `put_perms` is: *"'remove this restriction' has to be expressible,
343
+ and a merge cannot express a deletion without a second vocabulary for it."* An empty list is
344
+ therefore a legal body and it REVOKES.
345
+
346
+ β›” AN EMPTIED GRANT CLEARS ITS ROW rather than storing `[]`. An absent row and "no grant" mean
347
+ the same thing (`perm_scope.CONNECTOR_GRANT_KEY`'s own note), so there is one spelling of the
348
+ common case and revoking returns the store to the shape it had before anybody granted anything.
349
+
350
+ β›” AN UNKNOWN KIND IS NAMED, NEVER DROPPED (W30/R6's second sentence). Silently discarding it
351
+ would tell an administrator they granted something the door will never honour.
352
+ """
353
+ _grant_admin(session)
354
+ uname = _grant_subject(session, username)
355
+ body = body if isinstance(body, dict) else {}
356
+ raw = body.get("granted")
357
+ if not isinstance(raw, list):
358
+ raise err(400, "bad_grants",
359
+ "say which connectors this account may add, as a list of connector kinds")
360
+ known = {k["key"] for k in connector_grant_kinds()}
361
+ want = sorted({str(k).strip().lower() for k in raw if str(k or "").strip()})
362
+ unknown = [k for k in want if k not in known]
363
+ if unknown:
364
+ raise err(400, "unknown_connector",
365
+ f"this workspace has no connector called {', '.join(unknown)}")
366
+
367
+ def _up(cur):
368
+ cur = cur if isinstance(cur, dict) else {}
369
+ if want:
370
+ cur[uname] = want
371
+ else:
372
+ cur.pop(uname, None)
373
+ return cur
374
+
375
+ try:
376
+ session.runtime.update(_ps().CONNECTOR_GRANT_KEY, _up, flush="sync")
377
+ except Exception:
378
+ raise err(503, "store_unavailable", "the change was not saved, please try again")
379
+ return {"username": uname, "kinds": connector_grant_kinds(), "granted": want}
380
+
381
+
382
+ def _resolved_odoo_key(rt, connection_id=None):
383
  """`(source, flag_key)` β€” which source would serve this tenant's Odoo queries, in both the
384
  shapes this module needs: the display string (`env` / `keychain:<id>`) and the key the pause
385
  flag is stored under.
386
 
387
+ ⭐ W54-T45 / R4 β€” `connection_id` NAMES which connection is being asked about; no id keeps
388
+ meaning the tenant's designated default, so no route's behaviour moves. The mirroring is the
389
+ point: this still delegates to `TenantRuntime.odoo_flag_key`, which now refuses to fall back
390
+ to the environment for a named-but-unresolvable connection, and so does this by construction.
391
+
392
  ⭐ D-10 (wave 24): THE RESOLUTION ITSELF NOW LIVES IN ONE PLACE, `TenantRuntime.odoo_flag_key`,
393
  beside the `odoo_source()` it must agree with. This function had its own copy of the same
394
  three rules β€” first unlocked keychain odoo entry, else env for tenant #0, else nothing β€” and
 
396
  against another, freezing nothing while the UI reports success. The two SHAPES stay here
397
  because they are this module's presentation concern; the DECISION does not.
398
  """
399
+ flag_key = rt.odoo_flag_key(connection_id)
400
  if not flag_key:
401
  return None, None
402
  return ("env" if flag_key == _ENV_ODOO_FLAG_KEY else f"keychain:{flag_key}"), flag_key
 
708
  #: the vocabulary and the permission, so the client renders a picker it can honour
709
  #: rather than offering an option the server will refuse (R4: business is admin-only).
710
  "scopes": list(SCOPES), "canBusiness": bool(session.admin),
711
+ "tenantWideTypes": list(TENANT_WIDE_TYPES),
712
+ # ⭐ W54-T47 / R4 β€” WHICH KINDS THIS READER MAY CREATE BUSINESS-WIDE WITHOUT BEING AN
713
+ # ADMIN. β›” ADDITIVE, AND `canBusiness` IS DELIBERATELY UNMOVED: that flag has meant
714
+ # "this account is an administrator" since wave 32 and three gates read it as such, so
715
+ # widening it would make one boolean answer two questions. A grant is per KIND and
716
+ # arrives as a list for the same reason the wall is per kind.
717
+ # ⚠ COURTESY, NEVER THE WALL. `add_key` consults `perm_scope.may_add_connection`
718
+ # regardless of what any client believes about this field.
719
+ "connectorGrants": sorted(_ps().connector_grants(session.uname,
720
+ st=session.runtime))}
721
 
722
 
723
  @router.post("/admin/keychain", status_code=201)
 
730
  if scope is None:
731
  raise err(400, "bad_scope",
732
  f"scope must be one of {', '.join(SCOPES)}")
 
 
 
 
733
  etype = str(body.get("type") or "").strip().lower()
734
+ # ⭐⭐ W54-T47 / R4 / CONTRACT C4 β€” THE CONNECTOR GRANT IS CONSULTED HERE AND ONLY HERE, ON THE
735
+ # PATH THAT WAS ALREADY REFUSED.
736
+ #
737
+ # β›”β›” WHICH IS WHAT MAKES IT ABSENCE-PRESERVING, and that property is the whole design. A
738
+ # member with NO grant meets byte-identical behaviour to the day before this shipped: 403
739
+ # `not_admin` here, 400 `scope_not_available` below, and their own personal connection of an
740
+ # ordinary type still succeeds. Nothing was storable before this ticket, so every account in
741
+ # every tenant carries no grant β€” reading that absence as DENY anywhere else on this route
742
+ # would revoke personal connections for the entire product with nobody having decided
743
+ # anything (`core/perm_scope.may_metrics` records the identical failure one field over).
744
+ #
745
+ # ⭐ SO THE GRANT ONLY EVER WIDENS: an explicit per-kind grant is what lets a named non-admin
746
+ # create a business-wide connection OF THAT KIND, which is R4's agency case said as a rule
747
+ # (*"many Gmail connections, or even many Odoo connections for one tenant, depending on the
748
+ # admin's configuration per user"*).
749
+ #
750
+ # ⚠ `etype` MOVED ABOVE THIS TEST rather than staying below it, because the grant is per KIND
751
+ # and a check that cannot see the kind can only ever be a second `session.admin`.
752
+ if scope == "business" and not session.admin and not _ps().may_add_connection(
753
+ session.user, etype, st=session.runtime):
754
+ raise err(403, "not_admin",
755
+ "a business-wide connection applies to everyone in this workspace, so it takes "
756
+ "an administrator, or an account an administrator has granted this connector "
757
+ "under Settings. "
758
+ + ("Ask an administrator to add it for everyone."
759
+ if etype in TENANT_WIDE_TYPES
760
+ else "You can add it as a personal connection instead."))
761
  if scope == "personal" and etype in TENANT_WIDE_TYPES:
762
  # β›” REPORTED, NOT COERCED (W30/R6's second sentence). See TENANT_WIDE_TYPES above: this
763
  # credential is what the WHOLE workspace's databases are built from, so "personal" would
764
  # be a label on a tenant-wide key rather than a boundary around it.
765
+ # β›” AND THE GRANT DOES NOT REACH THIS REFUSAL. `allowed_scopes` is the SOURCE's own rule
766
+ # and knows nothing about who is asking; a grant says a person may connect this kind for
767
+ # the workspace, never that a workspace-wide credential can become one person's.
768
  raise err(400, "scope_not_available",
769
  f"a {etype} connection is what this whole workspace's databases are read "
770
+ f"through, so it is always business-wide and cannot be a personal connection. "
771
  f"An administrator can add it for everyone.")
772
  try:
773
  row = kc.add_entry(session.runtime, body.get("label"), body.get("type"),
 
802
  raise err(503, "store_unavailable",
803
  "the key was not saved β€” its sharing setting could not be stored, so "
804
  "nothing was kept. Try again.")
805
+ return {"entry": {**_identified(row), "scope": scope, "owner": session.uname}}
806
 
807
 
808
  @router.put("/admin/keychain/{entry_id}")
809
  def update_key(entry_id: str, body: dict = Body(default=None),
810
  session: Session = Depends(require_session)):
811
+ """Contract C1's scope door, and W54-T44 / C4's RENAME door. Both are settings ABOUT a
812
+ connection rather than the credential inside it: a stored secret is never re-openable, so
813
+ "change the key itself" still means "replace it", which is `DELETE` + `POST`.
814
+
815
+ ⭐ R4 asks for the rename by name β€” *"Odoo 1, Odoo 2, and obviously user can rename this"* β€”
816
+ and this is where it belongs: the walls a rename needs (`_own_row`'s 404 for an entry you may
817
+ not see, `_may_touch`'s ownership rule) are already standing here, and a second door would be
818
+ a second copy of both.
819
+ ⚠ `{"label": ...}` and `{"scope": ...}` are independent; either alone is a valid request and
820
+ both together are one change. A body carrying NEITHER is a 400 rather than a silent no-op,
821
+ because "nothing happened" and "your change was saved" must never look the same.
822
+ """
823
  row = _own_row(session, entry_id)
824
+ body = body or {}
825
+ wants_scope, wants_label = "scope" in body, "label" in body
826
+ if not wants_scope and not wants_label:
827
+ raise err(400, "nothing_to_change",
828
+ "say what to change about this connection: a new name, or who it is shared "
829
+ "with.")
830
+ scope = None
831
+ if wants_scope:
832
+ scope = clean_scope(body.get("scope"), default=None)
833
+ if scope is None:
834
+ raise err(400, "bad_scope", f"scope must be one of {', '.join(SCOPES)}")
835
+ if scope == "business" and not session.admin:
836
+ raise err(403, "not_admin",
837
+ "a business-wide connection applies to everyone in this workspace, so only "
838
+ "an administrator can make one business-wide.")
839
  if not _may_touch(session, row):
840
  raise err(403, "not_yours", "this connection is not yours to change")
841
+ if wants_scope and scope == "personal" and str(row.get("type") or "") in TENANT_WIDE_TYPES:
842
  raise err(400, "scope_not_available",
843
  f"a {row.get('type')} connection is what this whole workspace's databases are "
844
  f"read through, so it is always business-wide.")
845
+ label = row.get("label") or ""
846
+ if wants_label:
847
+ # β›” THE NAME MOVES AND NOTHING ELSE. `rename_entry` touches one field on one row, so the
848
+ # connection keeps its `connectionId`, its `slot` and its encrypted credential, and every
849
+ # other connection of the same kind is left byte for byte as it was.
850
+ try:
851
+ renamed = _kc().rename_entry(session.runtime, entry_id, body.get("label"))
852
+ except ValueError as e:
853
+ raise err(400, "bad_label", str(e))
854
+ except Exception:
855
+ raise err(503, "store_unavailable", "the new name was not saved, please try again")
856
+ if renamed is None:
857
+ raise err(404, "no_entry", "no such key")
858
+ label = renamed.get("label") or label
859
  owner = row.get("owner") or session.uname
860
+ if not wants_scope:
861
+ return {"entry": {**row, "label": label}}
862
  try:
863
  _write_scope(session.runtime, entry_id, scope, owner)
864
  except Exception:
865
  raise err(503, "store_unavailable", "the change was not saved β€” try again")
866
+ return {"entry": {**row, "label": label, "scope": scope,
867
+ "owner": owner if scope == "personal" else ""}}
868
 
869
 
870
  @router.delete("/admin/keychain/{entry_id}")
 
929
  # every colleague's personal connection on the screen next door to the one that hides them.
930
  entries = visible_entries(session.runtime, session.uname, bool(session.admin))
931
  # R3 cutover (2026-08-04): which source would actually serve this tenant's Odoo queries β€”
932
+ # mirrors TenantRuntime.odoo_source() exactly: the resolved keychain odoo connection (while
933
+ # unlocked), else env for tenant #0 only, else nothing (fail closed β€” never another tenant's
934
+ # environment).
935
+ # β›”β›” W54-T45 β€” THE WALK IS GONE AND THE RESOLUTION IS ASKED FOR. This was the third copy of
936
+ # "the first odoo entry of this tenant", written out by hand beside a comment promising it
937
+ # mirrors `odoo_source()`. Under R4 a tenant holds many Odoo connections, so a hand-rolled
938
+ # first-entry walk here would light the ACTIVE badge on one client's connection while the
939
+ # connector layer served another's β€” the two answers disagreeing on the one screen that
940
+ # exists to show which is which. `keychain.resolve_connection_id` is the single resolver, it
941
+ # decrypts nothing (this route runs on a locked keychain too), and it applies the same
942
+ # personal-entry skip this comment already required.
943
  # ⚠ W32-T11: computed over the TENANT's entries, not over `entries` above. "Which source
944
  # serves this workspace" is one fact for everybody, and deriving it from a per-USER list would
945
  # make the answer depend on who opened the pane. Personal entries are excluded for the same
946
  # reason `TENANT_WIDE_TYPES` refuses them: they must never become the workspace's source.
947
+ serving_odoo = kc.resolve_connection_id(session.runtime, "odoo")
 
 
 
948
  # β›” W32-T10 β€” the env leg goes through `env_odoo_available` now, so this route and the
949
  # connectors DIRECTORY answer "does the environment serve this tenant?" with one function
950
  # instead of two spellings that agreed until a second tenant signed in.
951
+ if serving_odoo and kc.unlocked():
952
+ resolved = f"keychain:{serving_odoo}"
953
  elif env_odoo_available(session.runtime):
954
  resolved = "env"
955
  else:
 
1036
  return rel
1037
 
1038
 
1039
+ def _odoo_entry(session, connection_id=None):
1040
  """The keychain entry SERVING this tenant's Odoo, or None when the environment is (or nothing
1041
+ is). Business-scoped by construction β€” `TENANT_WIDE_TYPES` refuses a personal one.
1042
+
1043
+ ⭐⭐ W54-T45 / R4 / C4 β€” IT ASKS THE KEYCHAIN WHICH CONNECTION SERVES RATHER THAN WALKING FOR
1044
+ THE FIRST ONE. `connection_id` names it; no id means the tenant's designated default, which is
1045
+ the lowest-`slot` odoo connection and, for every tenant that has exactly one, the same row this
1046
+ used to return. The walk this replaced was a second copy of the resolution
1047
+ `keychain.resolve_connection_id` owns, and a panel resolving one connection while the connector
1048
+ layer resolves another is precisely how an agency's screen comes to describe the wrong client.
1049
+ β›” A named connection that does not resolve is None, never a sibling and never the environment.
1050
+ """
1051
  kc = _kc()
1052
+ cid = kc.resolve_connection_id(session.runtime, "odoo", connection_id)
1053
+ if not cid:
1054
+ return None
1055
  scopes = _scope_rows(session.runtime)
1056
  for e in kc.list_entries(session.runtime):
1057
+ if str(e["connection_id"]) != str(cid) and str(e["id"]) != str(cid):
1058
+ continue
1059
+ # The personal skip belongs to the resolver above; re-asserted here because THIS module
1060
+ # owns the scope vocabulary and a divergence between the two buckets must fail closed.
1061
+ if entry_scope(session.runtime, e["id"], scopes)[0] == "personal":
1062
+ return None
1063
+ return e
1064
  return None
1065
 
1066
 
 
1220
  So this is add-then-delete through the module's own doors, with the side rows (pause flag,
1221
  scope) carried across because they are keyed by ENTRY ID.
1222
  ⚠ THE ORDER IS DELIBERATE AND THE WINDOW IS REAL: for the moment between the add and the
1223
+ delete this tenant has TWO odoo entries. The alternative order can leave the workspace with no
1224
+ credential at all, which is worse than one stale read.
1225
+ ⭐ W54-T45 MADE THAT WINDOW DETERMINISTIC RATHER THAN AMBIGUOUS, as a side effect worth
1226
+ stating. It used to read "`odoo_creds` takes the first by id sort β€” so a resync landing inside
1227
+ that window COULD read the old database", i.e. a coin flip on random hex. The resolver now
1228
+ serves the tenant's designated default, the LOWEST slot, and the replacement entry is minted
1229
+ high-water: so the OLD connection serves for the whole window and the new one takes over the
1230
+ instant the old row is deleted. One stale read, not a coin flip.
1231
  """
1232
  kc = _kc()
1233
  entry = _odoo_entry(session)
api/routes_nav.py CHANGED
@@ -422,6 +422,111 @@ def _granted_view_ids(session):
422
  return set()
423
 
424
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
425
  @router.get("/nav")
426
  def nav(session: Session = Depends(require_session)):
427
  """`{pages: [{key,label,source?,chrome}], landing}`.
@@ -561,12 +666,23 @@ def nav(session: Session = Depends(require_session)):
561
  # leak with no symptom until two tenants rename the same registry key. Copy the rows before
562
  # merging on the day that invariant changes.
563
  meta = _read_nav_meta(session.runtime)
 
 
564
  for page in pages:
565
  source = str(page.get("source") or "")
566
  key = str(page.get("key") or "")
567
  if key in {"customer_data", "product_data"} or source.lower() == "odoo" \
568
  or key.startswith("ut_odoo_"):
 
 
 
569
  page["sourceGroup"] = "Odoo"
 
 
 
 
 
 
570
  elif page.get("user_table") or source in {"", "Blank", "Custom"}:
571
  page.setdefault("sourceGroup", "Custom")
572
  # β›”β›” W35-T43 (rulings R4/R7) β€” THE MARK-IMPORTANT COUNTS ARE NO LONGER COMPUTED HERE.
 
422
  return set()
423
 
424
 
425
+ #: ⭐⭐ W54-T48 / OWNER RULING R4 / CONTRACT C4 β€” ONE CONNECTION, ONE FOLDER IN THE RAIL.
426
+ #:
427
+ #: R4, verbatim: *"under the View rail for each database that comes from the same connector, they
428
+ #: need to be put in the same Folder. Odoo 1, Odoo 2, and obviously user can rename this."* The
429
+ #: rail already folds the Data level by `sourceGroup` (`dataPath.ts::groupDataDatabases`), so the
430
+ #: grouping mechanism is not the missing piece β€” the NAME was. Every Odoo database used to answer
431
+ #: the literal `"Odoo"`, so an agency with two Odoo connections saw its two clients' invoices
432
+ #: nested under one folder, which is the exact confusion R4 exists to prevent.
433
+ #:
434
+ #: β›” THE RENAME IS THE CONNECTION'S RENAME AND THERE IS NO SECOND NAMING SCHEME. The folder shows
435
+ #: the keychain row's `label`, which `keychain.add_entry` defaults to `Odoo 1` / `Odoo 2` and
436
+ #: `keychain.rename_entry` changes (W54-T44). *"Obviously user can rename this"* is therefore
437
+ #: already shipped: renaming the connection renames its folder on the next nav read, and it
438
+ #: touches no TABLE KEY β€” those are namespaced on the immutable `connection_id` (W54-T46), never
439
+ #: on a label a person may change twice a day.
440
+ #:
441
+ #: β›”β›” AND THE OVERRIDE ONLY FIRES WHEN THERE ARE TWO OR MORE CONNECTIONS TO TELL APART. With
442
+ #: exactly one Odoo connection β€” every tenant that exists today β€” the folder keeps the generic
443
+ #: `"Odoo"` it has always shown, unchanged, and nothing on anybody's rail moves.
444
+ #:
445
+ #: THE REASON IS R4 ITSELF, not caution. R4 asks for connections to be DISTINGUISHABLE: *"Odoo 1,
446
+ #: Odoo 2"*. With one connection there is one folder either way and nothing to distinguish it
447
+ #: from, so the label buys no clarity and costs the tenant a rail that suddenly reads differently.
448
+ #: Tenant #0's one connection is labelled "Odoo (migrated from this deployment)" by an August
449
+ #: migration, so an unconditional override renamed the owner's own Data folder to a truncated
450
+ #: migration artefact β€” a regression this ticket would have shipped in the name of a ruling about
451
+ #: agencies. The moment a SECOND connection is added the names appear on both folders together,
452
+ #: which is the only moment they mean anything.
453
+ #: ⚠ COUNTED ON THE CONNECTIONS, NOT ON THE USABLE LABELS. A second connection whose label is one
454
+ #: of the reserved words below is still a second connection, and its sibling must still be named.
455
+ #:
456
+ #: These two reserved words are the rail's OWN vocabulary, not a connection's to take:
457
+ #: `dataPath.ts::dataDatabaseOrigin` folds `loopable` / `blank` / `automation` / empty into the
458
+ #: "Loopable" group, and the branch below puts user tables in "Custom". A connection someone named
459
+ #: "Blank" would otherwise dissolve into one of those folders and show a client's invoices beside
460
+ #: somebody's scratch table, so such a label falls back to the generic Odoo folder instead.
461
+ _RESERVED_GROUP_LABELS = frozenset({"loopable", "blank", "automation", "custom", "odoo"})
462
+
463
+ #: The registry modules that ARE the designated default connection's data rather than a namespaced
464
+ #: copy of it: `odoo_relational.namespaced_fields` says so in as many words ("`customer_link`
465
+ #: targets the compiled registry module `customer_data`, which holds the DEFAULT connection's
466
+ #: customers"). They carry no namespace token to read backwards, so they are named here.
467
+ _DEFAULT_CONNECTION_PAGES = frozenset({"customer_data", "product_data"})
468
+
469
+
470
+ def _odoo_connection_folders(runtime):
471
+ """`({connection_id: folder label}, default_connection_id)` for this tenant's Odoo
472
+ connections β€” resolved ONCE per `/nav`, decrypting nothing, and `({}, None)` on any failure.
473
+
474
+ β›” ONCE PER REQUEST, NOT ONCE PER PAGE, AND THAT IS THE WHOLE REASON THIS IS A FUNCTION.
475
+ `odoo_relational.connection_label` and `keychain.default_connection_id` each walk
476
+ `keychain.list_entries`, which is a store read; calling either inside the page loop would put
477
+ N of them back on the one route D-175 spent a wave reducing to a single read. The loop below
478
+ asks `connection_for_table_key` WITHOUT a runtime, which is pure string work, and maps its
479
+ `DEFAULT_CONNECTION` sentinel through the default resolved here.
480
+ β›” AND IT FAILS SOFT ON PURPOSE. A locked keychain, a store blip or a missing import leaves the
481
+ rail painting the generic "Odoo" folder; a rail that does not paint at all is far worse than a
482
+ rail whose folder carries a generic name.
483
+ β›” A TENANT WITH FEWER THAN TWO ODOO CONNECTIONS GETS `{}` β€” the same answer as a failure, and
484
+ deliberately so: both mean "there is nothing here to tell apart, keep the generic folder". The
485
+ count is taken over the CONNECTIONS, before the reserved-word filter, so a second connection
486
+ named `Blank` still switches its sibling on.
487
+ """
488
+ if runtime is None:
489
+ return {}, None
490
+ try:
491
+ import core.keychain as keychain
492
+ import odoo_relational as odoo_rel
493
+ connections = 0
494
+ labels = {}
495
+ for row in keychain.list_entries(runtime):
496
+ if str(row.get("type") or "") != "odoo":
497
+ continue
498
+ connections += 1
499
+ cid = str(row.get("connection_id") or "")
500
+ label = " ".join(str(row.get("label") or "").split())
501
+ if cid and label and label.lower() not in _RESERVED_GROUP_LABELS:
502
+ labels[cid] = label
503
+ if connections < 2:
504
+ return {}, odoo_rel.default_connection_id(runtime)
505
+ return labels, odoo_rel.default_connection_id(runtime)
506
+ except Exception: # noqa: BLE001
507
+ return {}, None
508
+
509
+
510
+ def _odoo_folder_label(key, labels, default_cid):
511
+ """The folder name an Odoo page belongs under, or `""` to keep the generic fallback.
512
+
513
+ ⚠ `connection_for_table_key` is the ONLY sanctioned way to ask which connection owns a table,
514
+ because it is the inverse of the namespace `table_key_for` builds (C4). Parsing the key here
515
+ would be the second implementation that inverse exists to prevent.
516
+ """
517
+ if not labels:
518
+ return ""
519
+ try:
520
+ import odoo_relational as odoo_rel
521
+ cid = (default_cid if key in _DEFAULT_CONNECTION_PAGES
522
+ else odoo_rel.connection_for_table_key(key))
523
+ if cid == odoo_rel.DEFAULT_CONNECTION:
524
+ cid = default_cid
525
+ except Exception: # noqa: BLE001
526
+ return ""
527
+ return labels.get(str(cid or "")) or ""
528
+
529
+
530
  @router.get("/nav")
531
  def nav(session: Session = Depends(require_session)):
532
  """`{pages: [{key,label,source?,chrome}], landing}`.
 
666
  # leak with no symptom until two tenants rename the same registry key. Copy the rows before
667
  # merging on the day that invariant changes.
668
  meta = _read_nav_meta(session.runtime)
669
+ # W54-T48 (R4 / C4): the tenant's Odoo connections, read ONCE for the whole page loop.
670
+ _conn_labels, _conn_default = _odoo_connection_folders(session.runtime)
671
  for page in pages:
672
  source = str(page.get("source") or "")
673
  key = str(page.get("key") or "")
674
  if key in {"customer_data", "product_data"} or source.lower() == "odoo" \
675
  or key.startswith("ut_odoo_"):
676
+ # β›” THIS LITERAL IS THE FALLBACK AND IT STAYS. It is what a tenant with ONE Odoo
677
+ # connection or none still sees β€” every tenant that exists today β€” and what a database
678
+ # that resolves to no connection at all keeps.
679
  page["sourceGroup"] = "Odoo"
680
+ # ⭐ W54-T48 (R4 / C4): once the tenant has TWO connections to tell apart, each
681
+ # database is folded under its own connection's name, so two connections give two
682
+ # folders. `_odoo_connection_folders` answers `{}` below that threshold.
683
+ _folder = _odoo_folder_label(key, _conn_labels, _conn_default)
684
+ if _folder:
685
+ page["sourceGroup"] = _folder
686
  elif page.get("user_table") or source in {"", "Blank", "Custom"}:
687
  page.setdefault("sourceGroup", "Custom")
688
  # β›”β›” W35-T43 (rulings R4/R7) β€” THE MARK-IMPORTANT COUNTS ARE NO LONGER COMPUTED HERE.
api/routes_odoo_tables.py CHANGED
@@ -1509,6 +1509,156 @@ def _related_source_value(session, entry, record):
1509
  return None
1510
 
1511
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1512
  def _related_pin(table_key, session, spec, base_where, wall_params, cur, related):
1513
  """`(sql, params, notes)` for C6's pinned read, or `(None, [], [])` when nothing is pinned.
1514
 
@@ -1534,6 +1684,30 @@ def _related_pin(table_key, session, spec, base_where, wall_params, cur, related
1534
  rather than a literal `id`: `ut_odoo_order_lines` is join-shaped and its identity is `sol.id`,
1535
  so a bare `id` would be ambiguous across `sale_order_line` and `sale_order`. It is the same
1536
  expression this route already trusts as `tiebreak_sql` and as the fallback ORDER BY.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1537
  """
1538
  import core.relations as relations
1539
 
@@ -1549,13 +1723,18 @@ def _related_pin(table_key, session, spec, base_where, wall_params, cur, related
1549
  source = str(related.get("table") or "")
1550
  record = related.get("record")
1551
  via = related.get("via")
1552
- if not source or record in (None, "") or not isinstance(via, dict):
 
 
 
 
1553
  raise err(400, "bad_relation",
1554
  "a pinned read needs the record's database, the record id and the relation to "
1555
- "follow, as {table, record, via}. Ask GET /api/v1/grid/" + (source or "{table}")
 
1556
  + "/related for the relations this account may follow")
1557
 
1558
- from routes_grid import _may_open, related_entries
1559
 
1560
  if not _may_open(session, source):
1561
  # ⚠ THE CAUSE IS NAMED AS A PAIR, ON PURPOSE. `_may_open` is fail-closed and answers False
@@ -1571,8 +1750,20 @@ def _related_pin(table_key, session, spec, base_where, wall_params, cur, related
1571
  # β›” RESOLVED AGAINST THE **SCOPED** LISTING, which is what makes "an edge you cannot be
1572
  # offered is an edge you cannot pin" structural rather than remembered. `related_entries` is
1573
  # the same function `GET /grid/{table}/related` answers with; there is no second resolution.
1574
- entries = related_entries(session, source)
1575
- entry = relations.pick(entries, via)
 
 
 
 
 
 
 
 
 
 
 
 
1576
  if entry is None:
1577
  raise err(400, "unknown_relation", relations.unknown_via_refusal(source, via))
1578
  entry = dict(entry, __source__=source)
@@ -1586,12 +1777,33 @@ def _related_pin(table_key, session, spec, base_where, wall_params, cur, related
1586
  if not entry.get("served", True):
1587
  raise err(409, "relation_not_served", relations.unserved_target_refusal(entry))
1588
 
1589
- on = str((entry.get("via") or {}).get("on") or "")
 
 
 
 
 
 
 
 
 
 
 
1590
  # ⚠ `spec["cols"]`, NOT the caller's narrowed `cols`. The join column is a JOIN, not a value
1591
  # this response returns: a relation must keep working when an administrator has hidden the id
1592
  # column it runs over, and no cell of it is ever projected. The hidden-field closure still
1593
  # governs everything that reaches the wire, one layer up.
1594
- binding = (spec.get("cols") or {}).get(on)
 
 
 
 
 
 
 
 
 
 
1595
  if not binding:
1596
  raise err(409, "relation_not_served",
1597
  f"'{table_key}' has no live expression for '{on}', which is the column this "
@@ -1599,14 +1811,23 @@ def _related_pin(table_key, session, spec, base_where, wall_params, cur, related
1599
  f"this database directly, or ask for '{on}' to be added to its live connection")
1600
  on_expr, on_cast = binding[0], binding[1]
1601
 
1602
- value = _related_source_value(session, entry, record)
1603
- if value in (None, ""):
1604
- raise err(400, "unknown_relation",
1605
- relations.unresolvable_source_refusal(source, entry))
1606
- try:
1607
- value = on_cast(value)
1608
- except Exception: # noqa: BLE001
1609
- value = str(value)
 
 
 
 
 
 
 
 
 
1610
 
1611
  # ── the member ids, in ONE SQL over the bridge column (the ticket's `how:`) ────────────────
1612
  # β›” NOT THROUGH `datastore.window`: that clamps at `WINDOW_MAX` (5,000) rows, so a customer
@@ -1616,22 +1837,27 @@ def _related_pin(table_key, session, spec, base_where, wall_params, cur, related
1616
  # ⚠ THE WALL RIDES ALONG. Resolving ids under `base_where` means the id SET a scoped reader can
1617
  # produce is already narrowed to rows they may see, so the pin cannot be used to learn how many
1618
  # rows exist beyond their boundary.
 
 
 
1619
  frm_body = spec["from_sql"] if spec.get("from_sql") else spec["table"]
1620
- parts = [p for p in (base_where, entry.get("where")) if p]
1621
- parts.append(f"{on_expr} = ?")
1622
- pred = " AND ".join(f"({p})" for p in parts)
1623
- ids = [int(r[0]) for r in cur.execute(
1624
- f'SELECT DISTINCT {spec["id"]} FROM {frm_body} WHERE {pred}',
1625
- list(wall_params) + [value]).fetchall() if r and r[0] is not None]
 
 
 
1626
 
1627
- notes = []
1628
  # ⭐ STANDING RULE 1'S SECOND SENTENCE, ON A COST RATHER THAN ON A CAP. Nothing is limited
1629
  # here; the reader is told that this particular relation is answered by reading the source
1630
  # database once per page, because it is keyed on a column rather than on the record id.
1631
- if str((entry.get("via") or {}).get("from") or "") != relations.IDENTITY_COL:
1632
  notes.append({
1633
  "subject": "related", "effect": "slow",
1634
- "cause": f"this relation is keyed on the '{entry['via']['from']}' column of "
1635
  f"'{source}' rather than on its record id, so every page of these rows is "
1636
  f"resolved by reading that database first",
1637
  "recommendation": "read this database on its own and filter it on "
 
1509
  return None
1510
 
1511
 
1512
+ def _via_path(via):
1513
+ """The list of EDGE KEYS a `via` names, or None when it is one edge's bag instead.
1514
+
1515
+ ⭐⭐ W54-T40 / R12 β€” *"the client pins one by naming each edge (`via = ["orders",
1516
+ "order_lines"]`)"*. THREE SPELLINGS ARRIVE AND ALL THREE ARE THE SAME THING, which is why
1517
+ exactly one function decides:
1518
+
1519
+ * an ARRAY of keys, which is what `RecordDetail.tsx::relatedPinKey` sends for a two-hop tab
1520
+ and what `verify_wiring.py` pins that client literal to;
1521
+ * a bare STRING, C3's back-compat leg, which `relations.pick_path` already reads as a
1522
+ one-element path;
1523
+ * the two-hop entry's own `via` BAG, `{direction: 'path', key, path}`, which is what a client
1524
+ holding the whole entry naturally hands back. Reading `path` out of it costs one key and
1525
+ removes an entire class of "the shape was almost right" refusal.
1526
+
1527
+ β›” A ONE-HOP BAG STAYS A BAG AND ANSWERS None. `relations.pick` is the resolver for that shape
1528
+ and it matches on `direction` plus `key`; routing it here instead would resolve a one-hop pin
1529
+ against the depth-aware listing for no gain and change the cost of the six tabs that already
1530
+ worked. ⚠ AN EMPTY OR PARTLY-BLANK PATH IS **NOT** A PATH: it answers None and falls into the
1531
+ `bad_relation` guard, which is the honest refusal for `via = []`.
1532
+ """
1533
+ if isinstance(via, str):
1534
+ return [via] if via.strip() else None
1535
+ if isinstance(via, (list, tuple)):
1536
+ keys = [str(v).strip() for v in via]
1537
+ return keys if keys and all(keys) else None
1538
+ if isinstance(via, dict) and isinstance(via.get("path"), (list, tuple)):
1539
+ keys = [str(v).strip() for v in via["path"]]
1540
+ return keys if keys and all(keys) else None
1541
+ return None
1542
+
1543
+
1544
+ def _related_path_legs(session, source, entry, entries):
1545
+ """`(first, mid_key, last)` β€” the two ONE-HOP entries a two-hop composite is made of.
1546
+
1547
+ β›”β›” EACH LEG IS RESOLVED FROM **ITS OWN TABLE'S** SCOPED LISTING, AND THAT IS R13 AT PIN TIME.
1548
+ An edge key is unique per SOURCE table and not across a connector (`relations`' own banner says
1549
+ so, with the ten-edges/seven-keys measurement behind it), so hop 2 is looked up in the
1550
+ intermediate's listing and nowhere else. Resolving both against the source's list would be the
1551
+ ambiguous-key bug the entry key exists to prevent, and it would also skip the intermediate's
1552
+ permission wall on the way past.
1553
+
1554
+ ⚠ HOP 1 COSTS NOTHING EXTRA: it is in `entries`, the very listing the composite was picked
1555
+ from, because a depth-2 enumeration returns the one-hop entries first. Only hop 2 needs a
1556
+ second listing, and it is asked at depth 1.
1557
+ """
1558
+ import core.relations as relations
1559
+ from routes_grid import related_path_entries
1560
+
1561
+ hops = [str(k) for k in (entry.get("path") or ())]
1562
+ first = relations.pick_path(entries, hops[:1])
1563
+ if first is None:
1564
+ raise err(400, "unknown_relation", relations.unknown_via_refusal(source, hops[:1]))
1565
+ mid_key = str(first.get("target") or "")
1566
+ last = relations.pick_path(related_path_entries(session, mid_key, 1), hops[1:2])
1567
+ if last is None:
1568
+ raise err(400, "unknown_relation", relations.unknown_via_refusal(mid_key, hops[1:2]))
1569
+ return dict(first, __source__=source), mid_key, dict(last, __source__=mid_key)
1570
+
1571
+
1572
+ def _related_hop_values(session, source, record, first, mid_key, last, notes):
1573
+ """The values hop 2 joins on, resolved from the INTERMEDIATE database's own rows.
1574
+
1575
+ ⭐⭐ W54-T40 β€” THIS IS THE HALF THAT MAKES A TWO-HOP TAB ANSWER ROWS INSTEAD OF A SENTENCE.
1576
+ Hop 1 turns the source record into a set of intermediate rows; this returns the value each of
1577
+ those rows carries in the column hop 2 is keyed on, and the caller pins THIS database by them.
1578
+
1579
+ β›”β›” THE INTERMEDIATE IS READ THROUGH `_compiled_read`, WHICH IS THE SAME COMPILER THIS DOOR
1580
+ USES FOR AN ORDINARY WINDOW, AND THAT IS THE WHOLE PERMISSION ARGUMENT. Its grant gate, its
1581
+ administrator row wall and its hidden-field closure all run before a single id is produced, so
1582
+ a traversal cannot be used to learn about rows of the middle database a reader may not see. A
1583
+ second, lighter read here would be a second permission wall, and this file already carries the
1584
+ rule that a second copy of that block does not drift towards refusing.
1585
+ β›” AND AN INTERMEDIATE THIS DOOR CANNOT READ REFUSES BY NAME. `product_data` is a compiled
1586
+ registry module with no read-through binding, so the one enumerated path that passes through it
1587
+ answers a sentence carrying the cause and a way round it, rather than an empty grid.
1588
+
1589
+ ⚠ NO CAP, AND THE COST IS REPORTED INSTEAD (standing rule 1). Every distinct value comes back,
1590
+ however many there are, and the reader is told through `limits` that this tab resolves a second
1591
+ database on every page.
1592
+ """
1593
+ import core.relations as relations
1594
+ from fastapi import HTTPException # noqa: PLC0415
1595
+
1596
+ value = _related_source_value(session, first, record)
1597
+ if value in (None, ""):
1598
+ raise err(400, "unknown_relation",
1599
+ relations.unresolvable_source_refusal(source, first))
1600
+ try:
1601
+ mid = _compiled_read(mid_key, session)
1602
+ except HTTPException as exc:
1603
+ why = ""
1604
+ if isinstance(getattr(exc, "detail", None), dict):
1605
+ why = str((exc.detail.get("error") or {}).get("message") or "")
1606
+ raise err(409, "relation_not_served",
1607
+ f"this relation reaches '{last.get('target')}' through '{mid_key}', and that "
1608
+ f"database could not be read here to follow it"
1609
+ + (f" ({why})" if why else "")
1610
+ + f". Open '{mid_key}' on its own, find the records this one is linked to, and "
1611
+ f"follow the next relation from there")
1612
+ mid_spec = mid["spec"]
1613
+ on1 = str((first.get("via") or {}).get("on") or "")
1614
+ step = (mid_spec.get("cols") or {}).get(on1)
1615
+ if not step:
1616
+ raise err(409, "relation_not_served",
1617
+ f"'{mid_key}' has no live expression for '{on1}', which is the column the first "
1618
+ f"hop of this relation joins on, so the traversal cannot be resolved. Open "
1619
+ f"'{mid_key}' on its own, or ask for '{on1}' to be added to its live connection")
1620
+ # ⭐ THE COLUMN HOP 2 IS KEYED ON, READ OFF THE INTERMEDIATE. `pid` is the row IDENTITY and is
1621
+ # not a column of the mirror spec, so it resolves to the spec's own identity expression, which
1622
+ # is the same one this route trusts everywhere else and is per table rather than a bare `id`.
1623
+ frm2 = str((last.get("via") or {}).get("from") or relations.IDENTITY_COL)
1624
+ take = (mid_spec["id"] if frm2 == relations.IDENTITY_COL
1625
+ else ((mid_spec.get("cols") or {}).get(frm2) or (None,))[0])
1626
+ if not take:
1627
+ raise err(409, "relation_not_served",
1628
+ f"'{mid_key}' has no live expression for '{frm2}', which is the value the second "
1629
+ f"hop of this relation is keyed on, so the traversal cannot be resolved. Open "
1630
+ f"'{mid_key}' on its own, or ask for '{frm2}' to be added to its live connection")
1631
+ try:
1632
+ value = step[1](value)
1633
+ except Exception: # noqa: BLE001
1634
+ value = str(value)
1635
+ mid_from = mid_spec["from_sql"] if mid_spec.get("from_sql") else mid_spec["table"]
1636
+ parts = [p for p in (mid["base_where"], first.get("where")) if p]
1637
+ parts.append(f"{step[0]} = ?")
1638
+ pred = " AND ".join(f"({p})" for p in parts)
1639
+ rows = mid["cur"].execute(
1640
+ f"SELECT DISTINCT {take} FROM {mid_from} WHERE {pred}",
1641
+ list(mid["wall_params"]) + [value]).fetchall()
1642
+ values = [r[0] for r in rows if r and r[0] is not None]
1643
+ # ⭐⭐ STANDING RULE 1'S SECOND SENTENCE, AND `effect` IS CHOSEN SO THE READER GETS **THIS**
1644
+ # SENTENCE RATHER THAN A NEIGHBOUR'S. `counts.ts::plainLimit` maps a known `effect` to one
1645
+ # fixed client phrase and falls through to the SERVER's own first sentence for an effect it has
1646
+ # not learned; `slow` maps to *"Rows this far down load slowly, each page is reached by walking
1647
+ # every row above it"*, which is a true statement about a deep page and a FALSE one about a
1648
+ # seven-row traversal. `traversal` is deliberately not in that table, so the strip prints the
1649
+ # cause below, which is what actually happened.
1650
+ # ⚠ THE FIRST CLAUSE IS THE ONE THAT REACHES THE STRIP: `firstSentence` cuts at the first full
1651
+ # stop and truncates past 120 characters, so the mechanism is stated before the count.
1652
+ notes.append({
1653
+ "subject": "related", "effect": "traversal",
1654
+ "cause": f"these rows are reached through '{mid_key}', so every page resolves that "
1655
+ f"database first. This record matched {len(values):,} of its records, and this "
1656
+ f"database is then narrowed to the rows those reach",
1657
+ "recommendation": f"open '{mid_key}' on its own if you are paging through a large set, or "
1658
+ f"filter this database beside the relation to ask a smaller question"})
1659
+ return values
1660
+
1661
+
1662
  def _related_pin(table_key, session, spec, base_where, wall_params, cur, related):
1663
  """`(sql, params, notes)` for C6's pinned read, or `(None, [], [])` when nothing is pinned.
1664
 
 
1684
  rather than a literal `id`: `ut_odoo_order_lines` is join-shaped and its identity is `sol.id`,
1685
  so a bare `id` would be ambiguous across `sale_order_line` and `sale_order`. It is the same
1686
  expression this route already trusts as `tiebreak_sql` and as the fallback ORDER BY.
1687
+
1688
+ ⭐⭐ W54-T40 / INSTRUCTION 22 / R12 β€” **A `via` MAY NOW BE A PATH, AND THE PATH IS SERVED.**
1689
+ The owner's second quoted error was this function's own `bad_relation` sentence, and it fired
1690
+ on 18 of the 25 rail tabs of `customer_data`: R12 says the client pins a traversal by naming
1691
+ each edge, so a two-hop tab sends `via` as the ARRAY `["invoices","order_link"]`, and the
1692
+ guard below accepted only the one-hop bag. MEASURED 2026-09-06, 6 of 25 tabs answered 200 and
1693
+ 18 answered 400 on the first click.
1694
+
1695
+ β›”β›” ACCEPTING THE ARRAY IS HALF A FIX AND WOULD HAVE MOVED THE ERROR RATHER THAN CLOSED IT.
1696
+ `relations.pick` matches `via.direction` against `DIRECTIONS`, and a two-hop entry's direction
1697
+ is the literal `path`, deliberately outside that tuple so nothing serves half a traversal. So
1698
+ a path resolves through `relations.pick_path` against the DEPTH-AWARE listing, and the read is
1699
+ then answered in TWO steps: hop 1 resolves the intermediate database's own rows to the values
1700
+ hop 2 joins on, and hop 2 pins this database by them. Sending the object form alone answered
1701
+ `400 unknown_relation` and changed nothing the reader could see.
1702
+
1703
+ ⭐ EVERY HOP IS STILL PERMISSION CHECKED, AND AT PIN TIME, NOT ONLY AT LISTING TIME (R13). The
1704
+ intermediate is resolved through `_compiled_read`, i.e. THE SAME compiler this door uses for
1705
+ an ordinary read, so its grant, its row wall and its hidden-field closure all apply before a
1706
+ single id crosses into this table's predicate. A second, laxer read of the intermediate would
1707
+ be exactly the permission wall with a hole in it that `related_entries` exists to prevent.
1708
+ β›” AND AN INTERMEDIATE THIS DOOR CANNOT READ IS A **REPORTED LIMIT**, never a silent empty:
1709
+ `product_data` is a registry module with no read-through binding, so the one enumerated path
1710
+ that passes through it refuses by name with a cause and a recommendation.
1711
  """
1712
  import core.relations as relations
1713
 
 
1723
  source = str(related.get("table") or "")
1724
  record = related.get("record")
1725
  via = related.get("via")
1726
+ # ⭐⭐ W54-T40 β€” `via` IS EITHER ONE EDGE'S BAG OR A PATH OF EDGE KEYS, and `_via_path` is the
1727
+ # one place that decides which. It answers None for the bag, which is what keeps the guard
1728
+ # below spelling the SAME refusal for a genuinely incomplete pin.
1729
+ path = _via_path(via)
1730
+ if not source or record in (None, "") or (path is None and not isinstance(via, dict)):
1731
  raise err(400, "bad_relation",
1732
  "a pinned read needs the record's database, the record id and the relation to "
1733
+ "follow, as {table, record, via}, where `via` is one relation or the array of "
1734
+ "edge keys naming each hop. Ask GET /api/v1/grid/" + (source or "{table}")
1735
  + "/related for the relations this account may follow")
1736
 
1737
+ from routes_grid import _may_open, related_entries, related_path_entries
1738
 
1739
  if not _may_open(session, source):
1740
  # ⚠ THE CAUSE IS NAMED AS A PAIR, ON PURPOSE. `_may_open` is fail-closed and answers False
 
1750
  # β›” RESOLVED AGAINST THE **SCOPED** LISTING, which is what makes "an edge you cannot be
1751
  # offered is an edge you cannot pin" structural rather than remembered. `related_entries` is
1752
  # the same function `GET /grid/{table}/related` answers with; there is no second resolution.
1753
+ # ⭐ W54-T40 β€” AND A PATH RESOLVES AGAINST THE DEPTH-AWARE LISTING, WHICH IS THE SAME RULE ONE
1754
+ # LEVEL DEEPER: `related_path_entries` is what `GET /grid/{table}/related?depth=2` answers
1755
+ # with, so a traversal this account is not offered is a traversal it cannot pin either.
1756
+ # ⚠ THE DEPTH ASKED FOR IS THE LENGTH OF THE PATH, never a flat 2. A one-element path costs
1757
+ # the depth-1 enumeration it needs and not the depth-2 one, which on `customer_data` is the
1758
+ # difference between roughly half a second and roughly two.
1759
+ if path is None:
1760
+ entries = related_entries(session, source)
1761
+ entry = relations.pick(entries, via)
1762
+ else:
1763
+ if len(path) > relations.MAX_DEPTH:
1764
+ raise err(400, "over_depth", relations.over_depth_refusal(source, path))
1765
+ entries = related_path_entries(session, source, len(path))
1766
+ entry = relations.pick_path(entries, path)
1767
  if entry is None:
1768
  raise err(400, "unknown_relation", relations.unknown_via_refusal(source, via))
1769
  entry = dict(entry, __source__=source)
 
1777
  if not entry.get("served", True):
1778
  raise err(409, "relation_not_served", relations.unserved_target_refusal(entry))
1779
 
1780
+ # ⭐⭐ W54-T40 β€” THE **LAST** HOP IS WHAT JOINS THIS DATABASE, and on a two-hop entry that is
1781
+ # not `entry`. A composite carries `via = {direction: 'path', key, path}` and NO `on`, no
1782
+ # `from` and no `where`: `relations._two_hop_entry` refuses to flatten the two hops' predicates
1783
+ # onto the pair, because one of them may carry a predicate the other does not (the open-invoice
1784
+ # bridge is exactly that edge). So the legs are resolved, each from its OWN table's scoped
1785
+ # listing, and the last one is what this block below reads.
1786
+ notes = []
1787
+ first, mid_key, last = entry, "", entry
1788
+ if len(entry.get("path") or ()) > 1:
1789
+ first, mid_key, last = _related_path_legs(session, source, entry, entries)
1790
+
1791
+ on = str((last.get("via") or {}).get("on") or "")
1792
  # ⚠ `spec["cols"]`, NOT the caller's narrowed `cols`. The join column is a JOIN, not a value
1793
  # this response returns: a relation must keep working when an administrator has hidden the id
1794
  # column it runs over, and no cell of it is ever projected. The hidden-field closure still
1795
  # governs everything that reaches the wire, one layer up.
1796
+ # ⭐⭐ W54-T40 β€” AND THE ROW IDENTITY IS NOT ONE OF THOSE COLUMNS. `relations` defaults an edge
1797
+ # with no declared `on` to `pid`, which is the wire's name for the row identity and is never a
1798
+ # key of a mirror spec's `cols` (measured across all eight bound grains on 2026-09-06: not one
1799
+ # carries it). Every such edge therefore refused with "has no live expression for 'pid'" while
1800
+ # the expression was in hand the whole time, as `spec["id"]` - the same per-table identity this
1801
+ # route already uses for the pin itself, for the tiebreak and for the fallback ORDER BY, and
1802
+ # deliberately not a bare `id`, which is ambiguous on a join-shaped grain.
1803
+ if on == relations.IDENTITY_COL:
1804
+ binding = (spec["id"], int)
1805
+ else:
1806
+ binding = (spec.get("cols") or {}).get(on)
1807
  if not binding:
1808
  raise err(409, "relation_not_served",
1809
  f"'{table_key}' has no live expression for '{on}', which is the column this "
 
1811
  f"this database directly, or ask for '{on}' to be added to its live connection")
1812
  on_expr, on_cast = binding[0], binding[1]
1813
 
1814
+ if mid_key:
1815
+ # ⭐ HOP 1, ANSWERED BY THE INTERMEDIATE DATABASE ITSELF, UNDER ITS OWN WALL. See
1816
+ # `_related_hop_values`. An empty answer is an ANSWER (this record reaches nothing through
1817
+ # that database) and compiles to `1=0` two blocks down, never to "no pin".
1818
+ values = _related_hop_values(session, source, record, first, mid_key, last, notes)
1819
+ else:
1820
+ value = _related_source_value(session, entry, record)
1821
+ if value in (None, ""):
1822
+ raise err(400, "unknown_relation",
1823
+ relations.unresolvable_source_refusal(source, entry))
1824
+ values = [value]
1825
+ cast = []
1826
+ for one in values:
1827
+ try:
1828
+ cast.append(on_cast(one))
1829
+ except Exception: # noqa: BLE001
1830
+ cast.append(str(one))
1831
 
1832
  # ── the member ids, in ONE SQL over the bridge column (the ticket's `how:`) ────────────────
1833
  # β›” NOT THROUGH `datastore.window`: that clamps at `WINDOW_MAX` (5,000) rows, so a customer
 
1837
  # ⚠ THE WALL RIDES ALONG. Resolving ids under `base_where` means the id SET a scoped reader can
1838
  # produce is already narrowed to rows they may see, so the pin cannot be used to learn how many
1839
  # rows exist beyond their boundary.
1840
+ # ⭐ W54-T40 β€” `= ?` FOR ONE VALUE AND `IN (...)` FOR MANY, and the one-value spelling is kept
1841
+ # BYTE FOR BYTE so a one-hop pin compiles exactly the SQL it compiled before this ticket. The
1842
+ # many-value arm is only ever reached by the second hop of a traversal.
1843
  frm_body = spec["from_sql"] if spec.get("from_sql") else spec["table"]
1844
+ ids = []
1845
+ if cast:
1846
+ parts = [p for p in (base_where, last.get("where")) if p]
1847
+ parts.append(f"{on_expr} = ?" if len(cast) == 1
1848
+ else f"{on_expr} IN ({','.join('?' for _ in cast)})")
1849
+ pred = " AND ".join(f"({p})" for p in parts)
1850
+ ids = [int(r[0]) for r in cur.execute(
1851
+ f'SELECT DISTINCT {spec["id"]} FROM {frm_body} WHERE {pred}',
1852
+ list(wall_params) + list(cast)).fetchall() if r and r[0] is not None]
1853
 
 
1854
  # ⭐ STANDING RULE 1'S SECOND SENTENCE, ON A COST RATHER THAN ON A CAP. Nothing is limited
1855
  # here; the reader is told that this particular relation is answered by reading the source
1856
  # database once per page, because it is keyed on a column rather than on the record id.
1857
+ if str((first.get("via") or {}).get("from") or "") != relations.IDENTITY_COL:
1858
  notes.append({
1859
  "subject": "related", "effect": "slow",
1860
+ "cause": f"this relation is keyed on the '{first['via']['from']}' column of "
1861
  f"'{source}' rather than on its record id, so every page of these rows is "
1862
  f"resolved by reading that database first",
1863
  "recommendation": "read this database on its own and filter it on "
api/routes_sheet.py CHANGED
@@ -98,7 +98,7 @@ def _mirror(session: Session):
98
  import routes_odoo_tables as rot
99
  import odoo_relational as rel
100
 
101
- def _for(table_key, *, metric_window=None):
102
  fields = None
103
  for _bucket, key, _label, mk_fields in rel.TABLES:
104
  if key == table_key:
@@ -131,14 +131,37 @@ def _mirror(session: Session):
131
  # shape; the cache hangs off the SESSION because that object is built fresh by
132
  # `require_session` on every request and dies with it, so nothing can outlive its own
133
  # cursor or leak across users. The temp table it names lives in that same cursor.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
  memo = getattr(session, "_sheet_mirrors", None)
135
  if memo is None:
136
  memo = {}
137
  session._sheet_mirrors = memo
138
  slot = (table_key, json.dumps(metric_window, sort_keys=True, default=str))
139
- if slot not in memo:
140
- memo[slot] = _registry_mirror(session, cur, table_key, metric_window)
141
- return memo[slot]
 
 
 
 
 
 
 
 
142
  spec = rot._source_for(cur, table_key)
143
  if spec is None:
144
  raise err(409, "not_read_through",
@@ -177,17 +200,34 @@ def _registry_assembly(session: Session, table_key: str):
177
  field-name correction acks belong to the `/workspace` refresh that exists to show them to the
178
  person who made the edit, and a bound cell resolving its scope must not eat them.
179
 
 
 
 
 
 
 
 
 
180
  β›” AN UNEXPECTED FAILURE REFUSES LOUDLY AND DOES NOT DEGRADE TO THE STATIC CONTRACT. Falling
181
  back would answer the cell out of 37 columns while the person is looking at 47, which is the
182
  defect this function exists to end, and it would do it with a 200.
183
  """
184
  import core.perm_scope as perm_scope
 
 
 
 
 
 
185
  try:
186
  if table_key == "product_data":
187
  from routes_products import product_assembly
188
- return product_assembly(session, scope="product", consume_corrections=False)
 
 
189
  from routes_customers import grid_assembly
190
- return grid_assembly(session, scope="customer", consume_corrections=False)
 
191
  except perm_scope.Denied:
192
  raise err(403, "database_unreadable", f"You cannot read {table_key}.")
193
  except HTTPException:
@@ -207,7 +247,7 @@ def _registry_assembly(session: Session, table_key: str):
207
  "shown rather than shown from an older set of columns. Try again in a moment.")
208
 
209
 
210
- def _registry_mirror(session: Session, cur, table_key: str, metric_window):
211
  """`(cursor, spec, columns)` for one compiled registry grid, at the cell's own period.
212
 
213
  ⭐⭐ R7's SECOND HALF LIVES HERE: *"must also be bounded by date time lookup"*. `g["derived"]`
@@ -226,6 +266,17 @@ def _registry_mirror(session: Session, cur, table_key: str, metric_window):
226
  `column_values` entirely when `may_metrics` is off, so a column with no value anywhere in
227
  `g["derived"]` is one the capability wall has already answered for. Re-resolving it here would
228
  be a second answer to that question, from the one door that never asked it.
 
 
 
 
 
 
 
 
 
 
 
229
  """
230
  import aios_grid
231
  import odoo_relational as rel
@@ -237,13 +288,17 @@ def _registry_mirror(session: Session, cur, table_key: str, metric_window):
237
  derived, bounded, limits = _metric_derived(session, table_key, g, metric_window)
238
  rows = aios_grid.rows_from_pool(g["rows_src"], fields, (g.get("ws") or {}).get("overlays"),
239
  derived=derived)
 
 
 
 
240
  # β›” THE TYPES ARE NORMALISED FOR THE MIRROR ONLY. See `modules/sheet.py::mirror_field_type`:
241
  # `metric`, `rating` and a numeric `rollup` are in neither `_REGISTRY_COL_TYPE` nor
242
  # `filter_sql.NUMERIC_TYPES`, so without this they land as VARCHAR and compare as strings.
243
  # ⚠ THE SAME LIST GOES TO BOTH CALLS, deliberately. `registry_grid_spec` picks the SQL type and
244
  # `_filter_columns` picks the compiler's type; handing them two different lists is how a column
245
  # ends up stored as one thing and compared as another.
246
- spec_fields = sheet_mod.mirror_fields(fields)
247
  spec = rel.registry_grid_spec(cur, table_key, spec_fields, rows)
248
  # β›”β›” THE MATERIALISED TABLE IS GIVEN THE WINDOW'S OWN NAME, AND WITHOUT THIS THE MEMO ABOVE
249
  # SERVES ONE WINDOW'S ROWS UNDER ANOTHER WINDOW'S ANSWER (found by W53-T14, live).
@@ -262,8 +317,13 @@ def _registry_mirror(session: Session, cur, table_key: str, metric_window):
262
  # to an assembly that costs 20 to 130 seconds, so it is not a cost worth conditioning on.
263
  # ⚠ ALWAYS, INCLUDING THE `None` WINDOW: the unqualified name is REPLACED by every later
264
  # build, so leaving the no-period case pointing at it is exactly the case measured above.
 
 
 
 
265
  slot = hashlib.sha1(
266
- json.dumps(metric_window, sort_keys=True, default=str).encode("utf-8")).hexdigest()[:12]
 
267
  at_window = f'{spec["table"]}__at_{slot}'
268
  cur.execute(f'CREATE OR REPLACE TEMP TABLE "{at_window}" AS '
269
  f'SELECT * FROM "{spec["table"]}"')
@@ -1707,6 +1767,10 @@ def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=Non
1707
  3. the ROW wall, fail-closed, refusing 409 when it names a column the mirror cannot answer;
1708
  4. the binding's own scope, whose unanswerable columns are REPORTED rather than dropped.
1709
 
 
 
 
 
1710
  ⭐⭐ W53-T13 / R7 β€” THE PERIOD IS RESOLVED BEFORE THE MIRROR IS OPENED, because it decides what
1711
  the Metric columns of that mirror MEAN. `modules/sheet.py::period_window` turns the cell's
1712
  `{unit, start}` into the custom window `harness/windows.py` speaks, and `_registry_mirror`
@@ -1729,7 +1793,28 @@ def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=Non
1729
 
1730
  database = _require_database(session, binding["database"])
1731
  window = sheet_mod.period_window(binding.get("period"))
1732
- cur, spec, cols = _mirror(session)(database, metric_window=window)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1733
 
1734
  # β›” THE COLUMN IS CHECKED BEFORE THE SQL IS BUILT (W53-T13). Now that every tenant column is a
1735
  # real column of the materialised table, a `sum` over a text column reaches DuckDB as a binder
@@ -1742,9 +1827,6 @@ def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=Non
1742
  raise err(409, agg_refusal.code, agg_refusal.message)
1743
 
1744
  # ── the ROW wall, fail-closed ────────────────────────────────────────────────────────────
1745
- wall_tree = ((perm_scope.entry(session.user, database) or {}).get("filter")
1746
- if perm_scope.row_scope_applies(session.user, database) else None)
1747
- wall_nodes, wall_conj = _fe_parts(wall_tree)
1748
  if wall_nodes:
1749
  unknown = sorted(sheet_mod.filter_columns_named(wall_nodes) - set(cols))
1750
  if unknown:
@@ -1759,12 +1841,9 @@ def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=Non
1759
  "you on a column this database carries")
1760
 
1761
  # ── the binding's own scope ──────────────────────────────────────────────────────────────
1762
- scope = binding["scope"]
1763
- if scope.get("view_id"):
1764
- scope_nodes, scope_conj = _view_filter(session, database, scope["view_id"],
1765
- scope.get("view_name", ""), memo=view_memo)
1766
- else:
1767
- scope_nodes, scope_conj = _fe_parts(scope.get("filter"))
1768
 
1769
  # ⚠ NOTHING IS DONE HERE ABOUT `needs_excluded`. `_source_for` has already resolved it into the
1770
  # spec's column expressions; applying it a second time would double-count the exclusion and
@@ -1834,6 +1913,129 @@ def preview_cell(workbook_id: str, addr: str, body: dict = Body(default=None),
1834
  "limits": out["limits"]}
1835
 
1836
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1837
  @router.get("/sheets/{workbook_id}/cells/{addr}/drill")
1838
  def drill_cell(workbook_id: str, addr: str, session: Session = Depends(require_session)):
1839
  """`{database, view_id?, filter?, record_ids, count}` for `LinkGridModal` (R6, R13, R17).
@@ -1876,13 +2078,12 @@ def drill_cell(workbook_id: str, addr: str, session: Session = Depends(require_s
1876
  raise err(400, exc.code, exc.message)
1877
 
1878
  database = _require_database(session, binding["database"])
1879
- # ⚠ THE SAME PERIOD THE NUMBER WAS COMPUTED AT (W53-T13). The drill probes `COUNT(*)` and never
1880
- # reads the bound column, but its FILTER may name a Metric column, and a mirror opened at a
1881
- # different window would answer that condition against different values. The popup would then
1882
- # list rows the cell's own number never counted.
1883
- cur, spec, cols = _mirror(session)(
1884
- database, metric_window=sheet_mod.period_window(binding.get("period")))
1885
 
 
 
 
 
 
1886
  wall_tree = ((perm_scope.entry(session.user, database) or {}).get("filter")
1887
  if perm_scope.row_scope_applies(session.user, database) else None)
1888
  wall_nodes, wall_conj = _fe_parts(wall_tree)
@@ -1894,6 +2095,19 @@ def drill_cell(workbook_id: str, addr: str, session: Session = Depends(require_s
1894
  else:
1895
  scope_nodes, scope_conj = _fe_parts(scope.get("filter"))
1896
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1897
  count_sql, count_params, limits = sheet_mod.build_aggregate_query(
1898
  spec, {"aggregate": {"fn": "count"}}, cols, scope_nodes=scope_nodes,
1899
  scope_conj=scope_conj, wall_nodes=wall_nodes, wall_conj=wall_conj)
@@ -1997,9 +2211,13 @@ def resolve_bindings(workbook_id: str, body: dict = Body(default=None),
1997
  ⭐⭐ THE BATCH PAYS FOR ITS ASSEMBLY ONCE, WHICH IS MOST OF THE REASON THIS DOOR TAKES A LIST
1998
  AT ALL. A bound cell on a compiled registry grid (`customer_data`, `product_data`) costs a
1999
  full workspace assembly - measured at 20 to 130 seconds on this box after W53-T13 - so N cells
2000
- resolved one request each would cost N of them. Two memos make one request pay once:
 
 
2001
  - `session._sheet_mirrors`, keyed `(table_key, metric_window)` inside `_mirror`, so every
2002
- cell on one database at one period shares one assembly and one temp table. It hangs off
 
 
2003
  the Session, which `require_session` builds fresh per request and drops with it.
2004
  - `view_memo`, keyed by `view_id`, so a saved-view scope is looked up once for the batch.
2005
  ⚠ AND IDENTICAL BINDINGS RESOLVE ONCE. Two cells carrying the same database, aggregate, scope
 
98
  import routes_odoo_tables as rot
99
  import odoo_relational as rel
100
 
101
+ def _for(table_key, *, metric_window=None, needed=None):
102
  fields = None
103
  for _bucket, key, _label, mk_fields in rel.TABLES:
104
  if key == table_key:
 
131
  # shape; the cache hangs off the SESSION because that object is built fresh by
132
  # `require_session` on every request and dies with it, so nothing can outlive its own
133
  # cursor or leak across users. The temp table it names lives in that same cursor.
134
+ #
135
+ # ⭐⭐ W54-T36 β€” AND ONLY THE COLUMNS THE CELL ACTUALLY READS ARE MATERIALISED.
136
+ # MEASURED on tenant #0's `customer_data` (3,673 records, 47 columns), warm, through
137
+ # the real `drill_cell`: 8,437 ms total, of which `odoo_relational.registry_grid_spec`
138
+ # is 6,137 ms. That step turns every row into a tuple of 47 Python values and
139
+ # `executemany`s it, so its cost is per COLUMN, and a drill reads none of them: it
140
+ # counts records and lists ids. `needed` is the honest set (the aggregate's column,
141
+ # plus every column the cell's filter and the row wall name); `None` still means the
142
+ # whole grid, so a caller that has not worked out its set loses nothing.
143
+ #
144
+ # β›” THE MEMO WIDENS, IT NEVER NARROWS, and that is what keeps `refresh_sheet` safe.
145
+ # A slot already built for a wider set answers a narrower request unchanged; a request
146
+ # naming a column the slot does not carry rebuilds at the UNION, so a workbook whose
147
+ # cells read different columns converges instead of rebuilding per cell. A `None`
148
+ # entry means every column is present and is reusable by anything.
149
  memo = getattr(session, "_sheet_mirrors", None)
150
  if memo is None:
151
  memo = {}
152
  session._sheet_mirrors = memo
153
  slot = (table_key, json.dumps(metric_window, sort_keys=True, default=str))
154
+ want = None if needed is None else {str(k) for k in needed}
155
+ entry = memo.get(slot)
156
+ if entry is not None:
157
+ built, made = entry
158
+ if built is None or (want is not None and want <= built):
159
+ return made
160
+ if want is not None:
161
+ want = set(want) | built
162
+ made = _registry_mirror(session, cur, table_key, metric_window, needed=want)
163
+ memo[slot] = (None if want is None else set(want), made)
164
+ return made
165
  spec = rot._source_for(cur, table_key)
166
  if spec is None:
167
  raise err(409, "not_read_through",
 
200
  field-name correction acks belong to the `/workspace` refresh that exists to show them to the
201
  person who made the edit, and a bound cell resolving its scope must not eat them.
202
 
203
+ ⭐⭐ W54-T36 β€” ONE ASSEMBLY PER DATABASE PER REQUEST, memoised on the SESSION exactly as
204
+ `_mirror` memoises the mirror and for the same lifetime reason: `require_session` builds that
205
+ object per request and it dies with the request, so nothing here outlives its own cursor or
206
+ reaches another account. MEASURED on tenant #0's `customer_data`, warm: 2,145 ms a call. It
207
+ already ran once per (database, window); it now also survives a mirror rebuilt at a wider
208
+ column set, and every caller BELOW reuses it. `_offered_view` reaches for `grid_assembly` and
209
+ `product_assembly` on its own and is a separate cost; see its own note.
210
+
211
  β›” AN UNEXPECTED FAILURE REFUSES LOUDLY AND DOES NOT DEGRADE TO THE STATIC CONTRACT. Falling
212
  back would answer the cell out of 37 columns while the person is looking at 47, which is the
213
  defect this function exists to end, and it would do it with a 200.
214
  """
215
  import core.perm_scope as perm_scope
216
+ memo = getattr(session, "_sheet_assemblies", None)
217
+ if memo is None:
218
+ memo = {}
219
+ session._sheet_assemblies = memo
220
+ if table_key in memo:
221
+ return memo[table_key]
222
  try:
223
  if table_key == "product_data":
224
  from routes_products import product_assembly
225
+ memo[table_key] = product_assembly(session, scope="product",
226
+ consume_corrections=False)
227
+ return memo[table_key]
228
  from routes_customers import grid_assembly
229
+ memo[table_key] = grid_assembly(session, scope="customer", consume_corrections=False)
230
+ return memo[table_key]
231
  except perm_scope.Denied:
232
  raise err(403, "database_unreadable", f"You cannot read {table_key}.")
233
  except HTTPException:
 
247
  "shown rather than shown from an older set of columns. Try again in a moment.")
248
 
249
 
250
+ def _registry_mirror(session: Session, cur, table_key: str, metric_window, needed=None):
251
  """`(cursor, spec, columns)` for one compiled registry grid, at the cell's own period.
252
 
253
  ⭐⭐ R7's SECOND HALF LIVES HERE: *"must also be bounded by date time lookup"*. `g["derived"]`
 
266
  `column_values` entirely when `may_metrics` is off, so a column with no value anywhere in
267
  `g["derived"]` is one the capability wall has already answered for. Re-resolving it here would
268
  be a second answer to that question, from the one door that never asked it.
269
+
270
+ ⭐⭐ W54-T36 β€” `needed` IS THE COLUMN SET THIS CELL CAN POSSIBLY READ, AND `None` IS EVERY
271
+ COLUMN. It narrows what gets MATERIALISED, never what gets assembled: `g` is the same scoped
272
+ assembly, `rows` are the same scoped rows, and `spec["fields"]` below is still the FULL list
273
+ so a refusal can name a column the mirror did not carry.
274
+
275
+ β›”β›” IT IS INTERSECTED WITH THE ASSEMBLY'S OWN FIELDS AND MUST STAY THAT WAY. `cols` is what
276
+ `_resolve_binding` subtracts a row wall's columns from to decide whether the wall can be
277
+ applied at all, and that check is FAIL CLOSED (409 `scope_not_applicable`). Materialising a
278
+ column just because a filter named it would invent an empty column for a name this database
279
+ does not have, and the wall would then compile against nothing and quietly stop restricting.
280
  """
281
  import aios_grid
282
  import odoo_relational as rel
 
288
  derived, bounded, limits = _metric_derived(session, table_key, g, metric_window)
289
  rows = aios_grid.rows_from_pool(g["rows_src"], fields, (g.get("ws") or {}).get("overlays"),
290
  derived=derived)
291
+ # The columns this cell can read, in the assembly's own order. `registry_grid_spec` forces
292
+ # `pid` in on its own, because `build_ids_query` needs `spec["id"]` to be a real column.
293
+ kept = (fields if needed is None
294
+ else [f for f in fields if str(f.get("key") or "") in needed])
295
  # β›” THE TYPES ARE NORMALISED FOR THE MIRROR ONLY. See `modules/sheet.py::mirror_field_type`:
296
  # `metric`, `rating` and a numeric `rollup` are in neither `_REGISTRY_COL_TYPE` nor
297
  # `filter_sql.NUMERIC_TYPES`, so without this they land as VARCHAR and compare as strings.
298
  # ⚠ THE SAME LIST GOES TO BOTH CALLS, deliberately. `registry_grid_spec` picks the SQL type and
299
  # `_filter_columns` picks the compiler's type; handing them two different lists is how a column
300
  # ends up stored as one thing and compared as another.
301
+ spec_fields = sheet_mod.mirror_fields(kept)
302
  spec = rel.registry_grid_spec(cur, table_key, spec_fields, rows)
303
  # β›”β›” THE MATERIALISED TABLE IS GIVEN THE WINDOW'S OWN NAME, AND WITHOUT THIS THE MEMO ABOVE
304
  # SERVES ONE WINDOW'S ROWS UNDER ANOTHER WINDOW'S ANSWER (found by W53-T14, live).
 
317
  # to an assembly that costs 20 to 130 seconds, so it is not a cost worth conditioning on.
318
  # ⚠ ALWAYS, INCLUDING THE `None` WINDOW: the unqualified name is REPLACED by every later
319
  # build, so leaving the no-period case pointing at it is exactly the case measured above.
320
+ # β›”β›” W54-T36 β€” THE COLUMN SET IS PART OF THAT NAME FOR THE SAME REASON THE WINDOW IS. Two
321
+ # cells on one database at one window may now be materialised over DIFFERENT columns, and a
322
+ # narrower later build would otherwise replace a wider earlier one under a spec the memo is
323
+ # still holding, so a query would address a column its own table no longer has.
324
  slot = hashlib.sha1(
325
+ json.dumps([metric_window, None if needed is None else sorted(needed)],
326
+ sort_keys=True, default=str).encode("utf-8")).hexdigest()[:12]
327
  at_window = f'{spec["table"]}__at_{slot}'
328
  cur.execute(f'CREATE OR REPLACE TEMP TABLE "{at_window}" AS '
329
  f'SELECT * FROM "{spec["table"]}"')
 
1767
  3. the ROW wall, fail-closed, refusing 409 when it names a column the mirror cannot answer;
1768
  4. the binding's own scope, whose unanswerable columns are REPORTED rather than dropped.
1769
 
1770
+ ⚠ W54-T36 β€” THE WALL AND THE SCOPE ARE NOW READ BEFORE STEP 2 SO THE MIRROR KNOWS WHICH
1771
+ COLUMNS TO MATERIALISE. Steps 3 and 4 still happen where they did: the wall is still checked
1772
+ against `cols` after the mirror exists, and it still refuses fail closed.
1773
+
1774
  ⭐⭐ W53-T13 / R7 β€” THE PERIOD IS RESOLVED BEFORE THE MIRROR IS OPENED, because it decides what
1775
  the Metric columns of that mirror MEAN. `modules/sheet.py::period_window` turns the cell's
1776
  `{unit, start}` into the custom window `harness/windows.py` speaks, and `_registry_mirror`
 
1793
 
1794
  database = _require_database(session, binding["database"])
1795
  window = sheet_mod.period_window(binding.get("period"))
1796
+
1797
+ # ⭐⭐ W54-T36 β€” THE WALL AND THE SCOPE ARE READ BEFORE THE MIRROR IS OPENED, so the mirror can
1798
+ # be built over the columns this cell can possibly read instead of over the whole database.
1799
+ # Neither read touches the mirror: the wall comes from `perm_scope` and the scope from the
1800
+ # stored view document, which is why the order can move at all.
1801
+ # β›” WHAT MUST NOT MOVE IS THE WALL'S OWN CHECK. It subtracts the wall's columns from `cols`
1802
+ # and refuses 409 when one is missing, so it still runs AFTER the mirror exists, below.
1803
+ wall_tree = ((perm_scope.entry(session.user, database) or {}).get("filter")
1804
+ if perm_scope.row_scope_applies(session.user, database) else None)
1805
+ wall_nodes, wall_conj = _fe_parts(wall_tree)
1806
+ scope = binding["scope"]
1807
+ if scope.get("view_id"):
1808
+ scope_nodes, scope_conj = _view_filter(session, database, scope["view_id"],
1809
+ scope.get("view_name", ""), memo=view_memo)
1810
+ else:
1811
+ scope_nodes, scope_conj = _fe_parts(scope.get("filter"))
1812
+ needed = (sheet_mod.filter_columns_named(scope_nodes)
1813
+ | sheet_mod.filter_columns_named(wall_nodes))
1814
+ if binding["aggregate"].get("field"):
1815
+ needed.add(str(binding["aggregate"]["field"]))
1816
+
1817
+ cur, spec, cols = _mirror(session)(database, metric_window=window, needed=needed)
1818
 
1819
  # β›” THE COLUMN IS CHECKED BEFORE THE SQL IS BUILT (W53-T13). Now that every tenant column is a
1820
  # real column of the materialised table, a `sum` over a text column reaches DuckDB as a binder
 
1827
  raise err(409, agg_refusal.code, agg_refusal.message)
1828
 
1829
  # ── the ROW wall, fail-closed ────────────────────────────────────────────────────────────
 
 
 
1830
  if wall_nodes:
1831
  unknown = sorted(sheet_mod.filter_columns_named(wall_nodes) - set(cols))
1832
  if unknown:
 
1841
  "you on a column this database carries")
1842
 
1843
  # ── the binding's own scope ──────────────────────────────────────────────────────────────
1844
+ # ⚠ W54-T36 β€” READ ABOVE, WITH THE WALL, because the mirror is now built over the columns the
1845
+ # two of them name. The contract's ORDER is unchanged: the wall is still applied and still
1846
+ # checked against `cols` before the scope reaches the compiler.
 
 
 
1847
 
1848
  # ⚠ NOTHING IS DONE HERE ABOUT `needs_excluded`. `_source_for` has already resolved it into the
1849
  # spec's column expressions; applying it a second time would double-count the exclusion and
 
1913
  "limits": out["limits"]}
1914
 
1915
 
1916
+ @router.post("/sheets/{workbook_id}/cells/{addr}/compute")
1917
+ def compute_cell(workbook_id: str, addr: str, body: dict = Body(default=None),
1918
+ session: Session = Depends(require_session)):
1919
+ """W54-T32 (instruction 9): recompute ONE stored bound cell and persist just that cell.
1920
+
1921
+ ⭐⭐ THE WHOLE OF THE TICKET IS THAT `refresh_sheet` WAS THE ONLY DOOR THAT COMPUTED. Saving a
1922
+ binding wrote a `stale` cell and nothing ever resolved it, so the shimmer that means "a number
1923
+ is coming" ran until somebody pressed Refresh. Refresh answers by recomputing EVERY bound cell
1924
+ and every formula in the workbook, which is why it is slow and why the save path must not call
1925
+ it: one cell over `ut_odoo_orders` measured 55 to 90 ms through `preview`, against a whole
1926
+ workbook pass plus a full document write.
1927
+
1928
+ β›” IT IS A WRITE DOOR, so `_require_editor` runs FIRST, exactly as it does on `refresh_sheet`
1929
+ and for the same C5 reason: this ends in a store write, and a viewer's numbers must never land
1930
+ in the owner's document. A viewer's own re-resolve still happens in memory on the READ path.
1931
+
1932
+ β›”β›” THE STORED `binding` IS NEVER REWRITTEN HERE, AND THAT IS D-674's HALF OF THIS TICKET.
1933
+ Only `state`, `value`, `display`, `refreshed_at` and `refusal` are touched on a COPY of the
1934
+ cell; the binding object is carried through verbatim. So a binding that arrived without a
1935
+ `period` cannot acquire one by being computed, whatever a later editor does with the panel.
1936
+
1937
+ β›”β›” AND IT FILLS THE ONE SCOPE-CACHE SLOT IT JUST COMPUTED, WHICH IS THE TRAP IN THIS FILE.
1938
+ `_reresolved_for_reader` serves a non-owner from `core.sheets.cached_scope_value`, keyed
1939
+ `(database, wall, binding scope)`; persisting a new number and leaving the old slot behind
1940
+ would make the very next GET serve the number this door was called to replace. There is no
1941
+ per-cell clear, and `clear_scope_cache` belongs to `refresh_sheet` alone under R3, so the
1942
+ surgical answer is `fill_scope_cache` on exactly the slot this caller is entitled to, which is
1943
+ the same call and the same key `_reresolved_for_reader` makes after its own resolve.
1944
+
1945
+ ⚠ NO FORMULA PASS RUNS HERE, DELIBERATELY. `_recomputed_tab_cells` recomputes the WHOLE
1946
+ workbook's formulas, which the prototype measured at 2.9 s as a FLOOR for the owner's 11,300
1947
+ formulas: fifty times the cost of the one number this door exists to deliver. The client
1948
+ evaluates its own formulas as the value lands (`sheetState.ts`), the ordinary cell PATCH
1949
+ already runs the server-side pass on the very next commit, and Refresh still runs it for
1950
+ everyone. A formula's STORED value therefore stays as last computed until one of those, which
1951
+ is what a stale bound cell already did before this ticket.
1952
+
1953
+ ⚠ `rev` BUMPS, BECAUSE THIS PERSISTS. It goes back in the answer and the client adopts it, or
1954
+ its next PATCH would carry a revision the server has already moved past.
1955
+ """
1956
+ from core import sheets
1957
+
1958
+ try:
1959
+ book = sheets.get_workbook(_store(session), workbook_id)
1960
+ _require_editor(session, book)
1961
+ except sheets.SheetRefusal as exc:
1962
+ raise _refuse(exc)
1963
+
1964
+ key = str(addr or "").replace("$", "").upper()
1965
+ #: ⚠ THE TAB IS NAMED BY THE CALLER WHEN IT KNOWS ONE, and looked up by address when it does
1966
+ #: not, which is `drill_cell`'s behaviour. Two tabs may legally hold the same address, so a
1967
+ #: client that has a tab in hand should say which, or the first one wins.
1968
+ ref = str((body or {}).get("tab") or "").strip()
1969
+ tab, cell = None, None
1970
+ if ref:
1971
+ try:
1972
+ tab = sheets.find_tab(book, ref)
1973
+ except sheets.SheetRefusal as exc:
1974
+ raise _refuse(exc)
1975
+ cell = (tab.get("cells") or {}).get(key)
1976
+ else:
1977
+ for candidate in book.get("sheets") or ():
1978
+ if key in (candidate.get("cells") or {}):
1979
+ tab, cell = candidate, candidate["cells"][key]
1980
+ break
1981
+ if not isinstance(cell, dict):
1982
+ raise err(404, "cell_missing", f"Cell {key} is not filled in.")
1983
+ if cell.get("kind") != "bound":
1984
+ raise err(409, "cell_not_bound", f"Cell {key} is not bound to a database.")
1985
+
1986
+ tab_ref = str((tab or {}).get("id") or (tab or {}).get("name") or "")
1987
+ binding = cell.get("binding") or {}
1988
+ stamp = _now_iso()
1989
+ saved = dict(cell)
1990
+ limits, resolved = [], None
1991
+ try:
1992
+ resolved = _resolve_binding(session, binding)
1993
+ except HTTPException as exc:
1994
+ #: The same per-cell refusal shape `refresh_sheet` writes, so a cell refused by this door
1995
+ #: and a cell refused by that one read identically. It is PERSISTED rather than raised:
1996
+ #: a cell left `stale` would shimmer forever, and the reason belongs on the cell.
1997
+ detail = getattr(exc, "detail", None) or {}
1998
+ info = detail.get("error") if isinstance(detail, dict) else None
1999
+ saved["state"] = "refused"
2000
+ saved["value"] = None
2001
+ saved["display"] = ""
2002
+ saved["refusal"] = {
2003
+ "code": (info or {}).get("code", "sheet_unresolved"),
2004
+ "message": (info or {}).get("message", "This cell could not be refreshed."),
2005
+ }
2006
+ else:
2007
+ limits = resolved["limits"]
2008
+ saved["state"] = "fresh"
2009
+ saved["value"] = resolved["value"]
2010
+ saved["display"] = "" if resolved["value"] is None else str(resolved["value"])
2011
+ saved["refreshed_at"] = stamp
2012
+ saved.pop("refusal", None)
2013
+
2014
+ try:
2015
+ landed = sheets.patch_cells(_store(session), workbook_id, tab_ref, {key: saved})
2016
+ except sheets.SheetRefusal as exc:
2017
+ raise _refuse(exc)
2018
+
2019
+ if resolved is not None:
2020
+ #: Best effort, exactly as `_reresolved_for_reader` fills its own slot: a cache write that
2021
+ #: fails costs a future recompute and never a wrong number.
2022
+ try:
2023
+ sheets.fill_scope_cache(_store(session), workbook_id, tab_ref + "!" + key,
2024
+ _binding_scope_key(session,
2025
+ str(binding.get("database") or ""),
2026
+ binding),
2027
+ resolved["value"], stamp)
2028
+ except Exception: # noqa: BLE001
2029
+ pass
2030
+
2031
+ wire = dict(saved)
2032
+ #: ⚠ `limits` RIDES THE ANSWER AND IS NOT STORED, because `core.sheets.clean_cell` carries no
2033
+ #: such key: it describes THIS resolve's truncation, not the cell.
2034
+ if limits:
2035
+ wire["limits"] = limits
2036
+ return {"cell": wire, "rev": landed.get("rev"), "tab": tab_ref, "addr": key}
2037
+
2038
+
2039
  @router.get("/sheets/{workbook_id}/cells/{addr}/drill")
2040
  def drill_cell(workbook_id: str, addr: str, session: Session = Depends(require_session)):
2041
  """`{database, view_id?, filter?, record_ids, count}` for `LinkGridModal` (R6, R13, R17).
 
2078
  raise err(400, exc.code, exc.message)
2079
 
2080
  database = _require_database(session, binding["database"])
 
 
 
 
 
 
2081
 
2082
+ # ⭐⭐ W54-T36 β€” THE WALL AND THE SCOPE ARE READ FIRST, AND THE MIRROR IS BUILT OVER WHAT THEY
2083
+ # NAME. The drill probes `COUNT(*)` and lists ids, so on a cell whose scope is a plain view or
2084
+ # an empty filter the honest column set is EMPTY and only the id column is materialised.
2085
+ # MEASURED on tenant #0's `customer_data` (3,673 records, 47 columns), warm, through this
2086
+ # route: 8,437 ms, of which 6,137 ms was materialising columns no query here reads.
2087
  wall_tree = ((perm_scope.entry(session.user, database) or {}).get("filter")
2088
  if perm_scope.row_scope_applies(session.user, database) else None)
2089
  wall_nodes, wall_conj = _fe_parts(wall_tree)
 
2095
  else:
2096
  scope_nodes, scope_conj = _fe_parts(scope.get("filter"))
2097
 
2098
+ # ⚠ THE SAME PERIOD THE NUMBER WAS COMPUTED AT (W53-T13). The drill probes `COUNT(*)` and never
2099
+ # reads the bound column, but its FILTER may name a Metric column, and a mirror opened at a
2100
+ # different window would answer that condition against different values. The popup would then
2101
+ # list rows the cell's own number never counted.
2102
+ # ⭐ W54-T36 MEASURED WHAT THAT WINDOW COSTS, because the cheaper mirror was the obvious guess:
2103
+ # `_metric_derived` at a month window is 27 ms of an 8,437 ms drill on `customer_data`. So the
2104
+ # window is kept UNCONDITIONALLY, exactly as W53-T13 wrote it, and the saving is taken from
2105
+ # the column set instead, where the time actually is.
2106
+ cur, spec, cols = _mirror(session)(
2107
+ database, metric_window=sheet_mod.period_window(binding.get("period")),
2108
+ needed=(sheet_mod.filter_columns_named(scope_nodes)
2109
+ | sheet_mod.filter_columns_named(wall_nodes)))
2110
+
2111
  count_sql, count_params, limits = sheet_mod.build_aggregate_query(
2112
  spec, {"aggregate": {"fn": "count"}}, cols, scope_nodes=scope_nodes,
2113
  scope_conj=scope_conj, wall_nodes=wall_nodes, wall_conj=wall_conj)
 
2211
  ⭐⭐ THE BATCH PAYS FOR ITS ASSEMBLY ONCE, WHICH IS MOST OF THE REASON THIS DOOR TAKES A LIST
2212
  AT ALL. A bound cell on a compiled registry grid (`customer_data`, `product_data`) costs a
2213
  full workspace assembly - measured at 20 to 130 seconds on this box after W53-T13 - so N cells
2214
+ resolved one request each would cost N of them. Three memos make one request pay once:
2215
+ - `session._sheet_assemblies`, keyed by `table_key` inside `_registry_assembly` (W54-T36),
2216
+ so the assembly itself is built once per database however many mirrors are cut from it.
2217
  - `session._sheet_mirrors`, keyed `(table_key, metric_window)` inside `_mirror`, so every
2218
+ cell on one database at one period shares one temp table. W54-T36 also gave each slot the
2219
+ COLUMN SET it was materialised over: a narrower cell reuses a wider slot, and a cell
2220
+ naming a column the slot lacks rebuilds at the union rather than per cell. Both hang off
2221
  the Session, which `require_session` builds fresh per request and drops with it.
2222
  - `view_memo`, keyed by `view_id`, so a saved-view scope is looked up once for the batch.
2223
  ⚠ AND IDENTICAL BINDINGS RESOLVE ONCE. Two cells carrying the same database, aggregate, scope
platform/core/keychain.py CHANGED
@@ -2,7 +2,7 @@
2
 
3
  An admin stores a data source's secrets (Royal's Odoo API key today; any tenant's sources
4
  tomorrow) encrypted at rest in the TENANT's store bucket. The runtime posture is R3's
5
- "live with env fallback": the connector layer asks `odoo_creds(rt)` FIRST and falls back to
6
  the process environment (tenant #0's `.env` / Space secrets), so Royal keeps working with an
7
  empty keychain and a new tenant needs no code to bring keys. The FULL cutover (env retired)
8
  is staged for a later wave β€” R3, verbatim.
@@ -14,7 +14,7 @@ decrypts and writes are refused β€” fail closed, never a plaintext fallback.
14
 
15
  SHAPE (bucket `keychain`, per-tenant via the runtime handle):
16
 
17
- {entries: {id: {id, label, type, enc, preview, created, createdBy}}}
18
 
19
  `enc` = Fernet token over the JSON fields dict. `preview` = a masked hint ("Β·Β·Β·Β·1234")
20
  computed ONCE at write from the entry's most secret-looking field β€” the ONLY part of a
@@ -92,27 +92,129 @@ def _bucket(rt):
92
  return rt.get(KEY) or {}
93
 
94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  def list_entries(rt):
96
- """Metadata ONLY β€” never a decrypted field, never `enc` itself."""
 
 
 
 
 
97
  out = []
 
98
  for eid, e in sorted((_bucket(rt).get('entries') or {}).items()):
99
  if not isinstance(e, dict):
100
  continue
101
- out.append({'id': eid, 'label': e.get('label') or eid,
102
- 'type': e.get('type') or 'generic',
 
 
 
 
 
103
  'preview': e.get('preview') or '',
104
  'created': e.get('created') or '',
105
  'createdBy': e.get('createdBy') or ''})
106
  return out
107
 
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  def add_entry(rt, label, etype, fields, username):
110
  """Encrypt + store. Returns the metadata row, or raises ValueError on shape problems and
111
- KeychainLocked when there is no key (a secret must never be stored in the clear)."""
 
 
 
 
 
 
 
 
112
  label = ' '.join(str(label or '').split())[:80]
113
  etype = str(etype or '').strip().lower()
114
- if not label:
115
- raise ValueError('give the key a label')
116
  if etype not in ENTRY_TYPES:
117
  raise ValueError(f"type must be one of {', '.join(sorted(ENTRY_TYPES))}")
118
  if not isinstance(fields, dict) or not fields:
@@ -128,7 +230,11 @@ def add_entry(rt, label, etype, fields, username):
128
  secretish = next((clean[k] for k in _PREVIEW_FIELDS if clean.get(k)), '')
129
  preview = ('Β·Β·Β·Β·' + secretish[-4:]) if len(secretish) >= 4 else ('Β·Β·Β·Β·' if secretish else '')
130
  eid = f'k_{_secrets.token_hex(6)}'
131
- row = {'id': eid, 'label': label, 'type': etype, 'enc': token.decode('ascii'),
 
 
 
 
132
  'preview': preview,
133
  'created': _dt.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
134
  'createdBy': str(username or '')}
@@ -141,10 +247,42 @@ def add_entry(rt, label, etype, fields, username):
141
  return cur
142
 
143
  rt.update(KEY, _up, flush='sync')
144
- return {'id': eid, 'label': label, 'type': etype, 'preview': preview,
 
145
  'created': row['created'], 'createdBy': row['createdBy']}
146
 
147
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  def delete_entry(rt, entry_id):
149
  def _drop(cur):
150
  (cur.get('entries') or {}).pop(str(entry_id), None)
@@ -174,12 +312,19 @@ def read_fields(rt, entry_id):
174
 
175
 
176
  def first_entry_of_type(rt, etype):
177
- """The metadata row of the FIRST entry of `etype`, or None. Never decrypts anything.
178
-
179
- ⭐ W35-T45 β€” the same "first, by insertion-id sort" rule `_first_creds` resolves on, exposed as
180
- an IDENTITY question rather than a credential one. `ensure_entry_of_type` needs to know whether
181
- an entry exists WITHOUT unlocking it, and `list_entries` + a hand-rolled `next()` at each caller
182
- is how two places come to disagree about which entry is "the" one.
 
 
 
 
 
 
 
183
  """
184
  return next((e for e in list_entries(rt) if e.get('type') == str(etype or '')), None)
185
 
@@ -188,9 +333,11 @@ def ensure_entry_of_type(rt, etype, label, fields, username):
188
  """Create ONE entry of `etype` only if the tenant has none. `(row, why)`; `row` is None on skip.
189
 
190
  ⭐ W35-T45 / R11 β€” the primitive tenant #0's env-to-keychain migration is built from, and the
191
- reason it lives here is that only this module knows what "already has one" means: `odoo_creds`
192
- resolves to the FIRST entry of a type, so a second one would be stored, invisible in every
193
- resolver, and impossible to tell from the one that serves.
 
 
194
 
195
  β›” IDEMPOTENT BY TYPE, NOT BY A FLAG. A migration that keys idempotency on a marker it writes
196
  itself is one lost marker away from running twice ([[a-migration-that-runs-on-the-next-write]]);
@@ -219,13 +366,24 @@ def ensure_entry_of_type(rt, etype, label, fields, username):
219
  return None, f'{type(exc).__name__}: {exc}'
220
 
221
 
222
- def odoo_creds(rt):
223
- """R3's resolver seam: the FIRST odoo-type entry's fields, else None (the caller falls
224
- back to the environment). Deterministic order = insertion-id sort, so 'first' is stable."""
225
- return _first_creds(rt, 'odoo')
 
 
 
 
 
 
 
 
 
 
 
226
 
227
 
228
- def meta_creds(rt):
229
  """W31 (R2): the FIRST `meta_ads` entry's fields, else None β€” the Meta connector's resolver.
230
 
231
  ⭐⭐ W49-T13 / D-202 β€” IT HAS A PRODUCTION CALLER NOW, AND THAT WAS THE WHOLE DEFECT.
@@ -246,11 +404,15 @@ def meta_creds(rt):
246
  is no equivalent for Meta: `META_ADS_ACCESS_TOKEN` is the OWNER's measurement token (R8), and
247
  handing it to a tenant whose admin has not stored one is precisely the leak the R3 rule
248
  exists to prevent. A tenant with no entry gets None, and the connector says so.
 
 
 
 
249
  """
250
- return _first_creds(rt, 'meta_ads')
251
 
252
 
253
- def amazon_creds(rt):
254
  """W52: the FIRST `amazon_sp` entry's fields, else None β€” the Amazon connector's resolver.
255
 
256
  β›” THE SAME SHAPE AND THE SAME IMPLEMENTATION AS `odoo_creds` / `meta_creds`, deliberately.
@@ -266,8 +428,14 @@ def amazon_creds(rt):
266
  ⚠ AND IT RETURNS THE WHOLE FIELD SET, not one secret: an Amazon credential is five values
267
  (`client_id`, `client_secret`, `refresh_token`, `seller_id`, `marketplace_id`) and the client
268
  needs three of them just to mint an access token.
 
 
 
 
 
 
269
  """
270
- return _first_creds(rt, 'amazon_sp')
271
 
272
 
273
  #: ⭐⭐ WAVE 32 (R4 / contract C1) β€” THE SCOPE SIDE-BUCKET, READ HERE, WRITTEN NOWHERE IN THIS FILE.
@@ -284,8 +452,9 @@ def amazon_creds(rt):
284
  SCOPE_KEY = 'keychain_scopes'
285
 
286
  #: The credential types a WHOLE WORKSPACE reads through, which therefore cannot be personal.
287
- #: β›” THE ELEVATION THIS PREVENTS, in B's words: `odoo_creds`/`meta_creds` resolve to *the first
288
- #: entry of that type for the TENANT* β€” that is what spawns every `ut_odoo_*` / `ut_meta_*` grid and
 
289
  #: what every measure column is answered from. So a member storing a personal Odoo key would not get
290
  #: "their own Odoo": they would silently become the credential the entire workspace's databases are
291
  #: built from. **A credential elevation wearing a scope picker.**
@@ -310,9 +479,114 @@ def _personal_ids(rt):
310
  if isinstance(v, dict) and str(v.get('scope') or '') == 'personal')
311
 
312
 
313
- def _first_creds(rt, etype):
314
- """The first entry of `etype`, decrypted β€” or None. Deterministic order = insertion-id sort,
315
- so "first" is stable across reads rather than dict-order luck.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
 
317
  ⚠ A MISSING RUNTIME ANSWERS None RATHER THAN RAISING, AND THE GUARD IS HERE ON PURPOSE. Every
318
  caller's contract is already "the tenant's credential, or None", and `None` means exactly
@@ -321,7 +595,7 @@ def _first_creds(rt, etype):
321
  implementation did not keep. Found by `verify_amazon` asserting the contract rather than the
322
  behaviour. β›” FIXED HERE AND NOT IN ONE RESOLVER, because this module's own rule is that
323
  "which stored credential serves this connector" has ONE implementation: patching `amazon_creds`
324
- alone would have created the second normalizer the file warns about two functions up.
325
 
326
  ⭐⭐ WAVE 32 (R4/C1) β€” A PERSONAL ENTRY OF A TENANT-WIDE TYPE IS SKIPPED, NOT SERVED.
327
  `routes_keychain` REFUSES to create one, and that closes the door from the only side B owns;
@@ -335,14 +609,31 @@ def _first_creds(rt, etype):
335
  into an outage for a workspace that has a perfectly good business entry two rows down.
336
  ⚠ AND THE SKIP IS SCOPED TO `TENANT_WIDE_TYPES`. A personal entry of any OTHER type is a normal
337
  personal credential and this resolver is not how it is reached.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338
  """
339
  if rt is None:
340
  return None
341
- skip = _personal_ids(rt) if etype in TENANT_WIDE_TYPES else frozenset()
342
- for row in list_entries(rt):
343
- if row['type'] == etype and str(row['id']) not in skip:
344
- return read_fields(rt, row['id'])
345
- return None
346
 
347
 
348
  # ---------------------------------------------------------------------------------------------
 
2
 
3
  An admin stores a data source's secrets (Royal's Odoo API key today; any tenant's sources
4
  tomorrow) encrypted at rest in the TENANT's store bucket. The runtime posture is R3's
5
+ "live with env fallback": the connector layer asks `odoo_creds(rt, connection_id)` FIRST and falls back to
6
  the process environment (tenant #0's `.env` / Space secrets), so Royal keeps working with an
7
  empty keychain and a new tenant needs no code to bring keys. The FULL cutover (env retired)
8
  is staged for a later wave β€” R3, verbatim.
 
14
 
15
  SHAPE (bucket `keychain`, per-tenant via the runtime handle):
16
 
17
+ {entries: {id: {id, connection_id, slot, label, type, enc, preview, created, createdBy}}}
18
 
19
  `enc` = Fernet token over the JSON fields dict. `preview` = a masked hint ("Β·Β·Β·Β·1234")
20
  computed ONCE at write from the entry's most secret-looking field β€” the ONLY part of a
 
92
  return rt.get(KEY) or {}
93
 
94
 
95
+ # ═════════════════════════════════════════════════════════════════════════════════════════════
96
+ # ⭐⭐ W54-T44 / OWNER RULING R4 / CONTRACT C4 β€” A CONNECTION HAS AN IDENTITY.
97
+ # ═════════════════════════════════════════════════════════════════════════════════════════════
98
+ #
99
+ # R4, verbatim: *"If a tenant is an agency that helps with clients that each have Odoo, then the
100
+ # connector for Odoo can be many depending on the API. This is why its critical."* So MANY
101
+ # connections of ONE kind coexist, and each one has to be addressable on its own.
102
+ #
103
+ # ⭐ THE STORAGE ALREADY ALLOWED THIS AND THE READER DID NOT. `add_entry` has always minted a
104
+ # fresh `k_<hex>` per call with no uniqueness constraint, so a second `odoo` entry was already
105
+ # storable β€” it was simply never READ (every resolver takes the first of its type). This block
106
+ # adds the two facts a reader needs in order to tell two connections of one kind apart:
107
+ #
108
+ # `connection_id` the entry's own id, stamped EXPLICITLY rather than left implicit. It is
109
+ # stable, unique, never reused and never re-derived by sorting.
110
+ # `slot` an IMMUTABLE per-(tenant, type) ordinal, minted HIGH-WATER, which is what
111
+ # makes the default label `Odoo 1` / `Odoo 2` stable and what a namespaced
112
+ # table can be keyed on. Deleting a connection must never let a later one
113
+ # reuse a retired ordinal, or two different connections would answer to one
114
+ # address at two different times.
115
+ #
116
+ # β›” THE READ DEFAULTS ARE READ DEFAULTS AND NEVER A MIGRATION, the same posture `SCOPE_KEY`
117
+ # takes below. Rows written before this wave carry neither field: they read back as
118
+ # `connection_id = id` and as their 1-based position among entries of their type in the existing
119
+ # insertion-id sort. Materialising that on the next read would rewrite a tenant's encrypted
120
+ # store to record something already derivable ([[a-migration-that-runs-on-the-next-write]]) β€”
121
+ # and this store's rows are Fernet tokens, so a rewrite is the one operation that can lose a
122
+ # credential. Nothing here decrypts anything.
123
+
124
+ #: type -> the human word the default label is built from. `generic` has no product name behind
125
+ #: it, so it says what it is rather than inventing one.
126
+ _KIND_LABELS = {'odoo': 'Odoo', 'meta_ads': 'Meta Ads', 'amazon_sp': 'Amazon',
127
+ 'stripe': 'Stripe', 'shopify': 'Shopify', 'generic': 'Connection'}
128
+
129
+
130
+ def kind_label(etype):
131
+ """The human word for a connection type, for a default label. Never blank."""
132
+ return _KIND_LABELS.get(str(etype or '').strip().lower()) or 'Connection'
133
+
134
+
135
+ def connection_id_of(entry, entry_id):
136
+ """A stored row's stable connection id β€” its own `connection_id`, else its entry id.
137
+
138
+ ⚠ A NAMED FUNCTION RATHER THAN AN INLINE `or`, so that the identity has ONE derivation a gate
139
+ can break in memory: the negative control for "two connections stay two" needs somewhere to
140
+ collapse them.
141
+ """
142
+ return str((entry or {}).get('connection_id') or entry_id)
143
+
144
+
145
+ def slot_of(entry, ordinal):
146
+ """A stored row's slot β€” its own `slot` when it has one, else the read default `ordinal`.
147
+
148
+ ⚠ `ordinal` is the caller's 1-based position among entries of the SAME type, in the same
149
+ insertion-id sort every resolver already uses. A stored slot always wins, which is what makes
150
+ the field immutable once written.
151
+ """
152
+ try:
153
+ n = int((entry or {}).get('slot') or 0)
154
+ except (TypeError, ValueError):
155
+ n = 0
156
+ return n if n >= 1 else int(ordinal)
157
+
158
+
159
  def list_entries(rt):
160
+ """Metadata ONLY β€” never a decrypted field, never `enc` itself.
161
+
162
+ Every row carries `connection_id` and `slot` (W54-T44 / C4). Rows may GAIN keys here and must
163
+ never LOSE one: `verify_api` asserts the listing has no `enc` / `url` / `api_key` / `fields`,
164
+ and several callers read these rows by key.
165
+ """
166
  out = []
167
+ seen = {}
168
  for eid, e in sorted((_bucket(rt).get('entries') or {}).items()):
169
  if not isinstance(e, dict):
170
  continue
171
+ etype = e.get('type') or 'generic'
172
+ seen[etype] = ordinal = seen.get(etype, 0) + 1
173
+ out.append({'id': eid,
174
+ 'connection_id': connection_id_of(e, eid),
175
+ 'slot': slot_of(e, ordinal),
176
+ 'label': e.get('label') or eid,
177
+ 'type': etype,
178
  'preview': e.get('preview') or '',
179
  'created': e.get('created') or '',
180
  'createdBy': e.get('createdBy') or ''})
181
  return out
182
 
183
 
184
+ def next_slot(rt, etype):
185
+ """The slot a NEW connection of `etype` takes: one above the highest this tenant has ever
186
+ shown for that type. Never decrypts anything.
187
+
188
+ β›” HIGH-WATER, NOT A COUNT. `len(entries of this type) + 1` would hand a retired ordinal to a
189
+ new connection the moment one is deleted β€” two different credentials answering to `Odoo 2`,
190
+ a month apart, with every table W54-T46 namespaces on that ordinal pointing at the wrong one.
191
+ ⚠ It reads through `list_entries`, so a row written before this wave counts at its READ
192
+ DEFAULT rather than at zero: a tenant with two un-stamped Odoo entries gets 3, not 1.
193
+ """
194
+ etype = str(etype or '').strip().lower()
195
+ top = 0
196
+ for row in list_entries(rt):
197
+ if row.get('type') == etype:
198
+ try:
199
+ top = max(top, int(row.get('slot') or 0))
200
+ except (TypeError, ValueError):
201
+ continue
202
+ return top + 1
203
+
204
+
205
  def add_entry(rt, label, etype, fields, username):
206
  """Encrypt + store. Returns the metadata row, or raises ValueError on shape problems and
207
+ KeychainLocked when there is no key (a secret must never be stored in the clear).
208
+
209
+ ⭐ W54-T44 / C4 β€” the row is stamped with its `connection_id` and its `slot`, and a caller
210
+ that supplies NO label gets the default the slot names: the tenant's first Odoo connection is
211
+ `Odoo 1`, the second `Odoo 2`. An explicitly supplied label always wins, and the label stays
212
+ the user's to change afterwards (`rename_entry`).
213
+ ⚠ THE TYPE IS VALIDATED FIRST NOW, because the default label is built from it: a blank label
214
+ on an unknown type must still be told about the type, which is the fixable half.
215
+ """
216
  label = ' '.join(str(label or '').split())[:80]
217
  etype = str(etype or '').strip().lower()
 
 
218
  if etype not in ENTRY_TYPES:
219
  raise ValueError(f"type must be one of {', '.join(sorted(ENTRY_TYPES))}")
220
  if not isinstance(fields, dict) or not fields:
 
230
  secretish = next((clean[k] for k in _PREVIEW_FIELDS if clean.get(k)), '')
231
  preview = ('Β·Β·Β·Β·' + secretish[-4:]) if len(secretish) >= 4 else ('Β·Β·Β·Β·' if secretish else '')
232
  eid = f'k_{_secrets.token_hex(6)}'
233
+ slot = next_slot(rt, etype)
234
+ if not label:
235
+ label = f'{kind_label(etype)} {slot}'
236
+ row = {'id': eid, 'connection_id': eid, 'slot': slot,
237
+ 'label': label, 'type': etype, 'enc': token.decode('ascii'),
238
  'preview': preview,
239
  'created': _dt.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'),
240
  'createdBy': str(username or '')}
 
247
  return cur
248
 
249
  rt.update(KEY, _up, flush='sync')
250
+ return {'id': eid, 'connection_id': eid, 'slot': slot,
251
+ 'label': label, 'type': etype, 'preview': preview,
252
  'created': row['created'], 'createdBy': row['createdBy']}
253
 
254
 
255
+ def rename_entry(rt, entry_id, label):
256
+ """Give ONE connection a new name. Returns its metadata row, or None when there is no such
257
+ entry. Raises ValueError on a blank name.
258
+
259
+ β›” THE LABEL AND NOTHING ELSE. `enc`, `connection_id`, `slot`, `preview`, `created` and
260
+ `createdBy` are left exactly as they were, and no other row is touched β€” that is the whole
261
+ contract of a rename under R4, where two connections of one kind sit side by side and
262
+ renaming one must not disturb the other.
263
+ β›” AND IT DECRYPTS NOTHING. A stored secret is never re-openable and a rename has no business
264
+ asking for the key: this works on a LOCKED keychain, where re-encrypting a row to change a
265
+ display string would refuse (or, worse, rewrite a Fernet token to alter a label).
266
+ """
267
+ label = ' '.join(str(label or '').split())[:80]
268
+ if not label:
269
+ raise ValueError('give this connection a name')
270
+ eid = str(entry_id)
271
+ found = []
272
+
273
+ def _up(cur):
274
+ row = (cur.get('entries') or {}).get(eid)
275
+ if isinstance(row, dict):
276
+ row['label'] = label
277
+ found.append(True)
278
+ return cur
279
+
280
+ rt.update(KEY, _up, flush='sync')
281
+ if not found:
282
+ return None
283
+ return next((e for e in list_entries(rt) if e['id'] == eid), None)
284
+
285
+
286
  def delete_entry(rt, entry_id):
287
  def _drop(cur):
288
  (cur.get('entries') or {}).pop(str(entry_id), None)
 
312
 
313
 
314
  def first_entry_of_type(rt, etype):
315
+ """DOES THIS TENANT HAVE ANY ENTRY OF `etype` AT ALL? The first such metadata row, or None.
316
+ Never decrypts anything.
317
+
318
+ β›”β›” W54-T45 β€” THIS IS AN EXISTENCE QUESTION AND NOTHING ELSE, AND THE NAME IS THE ONLY THING
319
+ LEFT THAT SUGGESTS OTHERWISE. It used to be the identity twin of `_first_creds`: "which entry
320
+ serves" and "does one exist" were the same walk, which is exactly the coupling contract C4
321
+ exists to break. Under R4 a tenant may hold MANY Odoo connections, so "the first one" is no
322
+ longer an answer to "which credential serves this connector" β€” that question is now
323
+ `default_connection_id` / `_creds_for`, which resolve on a `connection_id` and order on the
324
+ immutable `slot`. β›” Do not route any credential path back through here.
325
+ What survives is the migration/idempotency question `ensure_entry_of_type` asks below, and
326
+ `verify_api` asks in three places as a "nothing was written" probe: both of those genuinely
327
+ mean *is there one*, not *which one*.
328
  """
329
  return next((e for e in list_entries(rt) if e.get('type') == str(etype or '')), None)
330
 
 
333
  """Create ONE entry of `etype` only if the tenant has none. `(row, why)`; `row` is None on skip.
334
 
335
  ⭐ W35-T45 / R11 β€” the primitive tenant #0's env-to-keychain migration is built from, and the
336
+ reason it lives here is that only this module knows what "already has one" means.
337
+ ⚠ W54-T45 SOFTENED WHAT IS AT STAKE WITHOUT CHANGING THIS FUNCTION. A second entry of a type
338
+ is no longer invisible: under R4 it is a second CONNECTION with its own `connection_id`, and
339
+ every resolver can address it. What this still prevents is a MIGRATION running twice and
340
+ quietly minting `Odoo 2` out of the same environment variables `Odoo 1` came from.
341
 
342
  β›” IDEMPOTENT BY TYPE, NOT BY A FLAG. A migration that keys idempotency on a marker it writes
343
  itself is one lost marker away from running twice ([[a-migration-that-runs-on-the-next-write]]);
 
366
  return None, f'{type(exc).__name__}: {exc}'
367
 
368
 
369
+ def odoo_creds(rt, connection_id=None):
370
+ """R3's resolver seam: the fields of the odoo connection NAMED by `connection_id`, else None.
371
+
372
+ ⭐⭐ W54-T45 / R4 / C4 β€” IT TAKES A CONNECTION NOW, AND THAT IS THE WHOLE TICKET. An agency
373
+ tenant holds one Odoo connection per client, so "the tenant's Odoo credential" is not a
374
+ question with one answer any more. `connection_id` names WHICH one; a `connection_id` that
375
+ names no entry of this type resolves to None and never to a sibling.
376
+ ⚠ NO ID MEANS THE DESIGNATED DEFAULT (`default_connection_id`), which is the lowest-`slot`
377
+ connection of the type. Every existing one-argument call site therefore keeps working and now
378
+ means exactly that, rather than "whichever row happened to sort first".
379
+ β›” None here still means "not configured", and the CALLER decides what that entails:
380
+ `harness/runtime.py::odoo_source` falls back to tenant #0's compiled environment only when no
381
+ connection was NAMED.
382
+ """
383
+ return _creds_for(rt, 'odoo', connection_id)
384
 
385
 
386
+ def meta_creds(rt, connection_id=None):
387
  """W31 (R2): the FIRST `meta_ads` entry's fields, else None β€” the Meta connector's resolver.
388
 
389
  ⭐⭐ W49-T13 / D-202 β€” IT HAS A PRODUCTION CALLER NOW, AND THAT WAS THE WHOLE DEFECT.
 
404
  is no equivalent for Meta: `META_ADS_ACCESS_TOKEN` is the OWNER's measurement token (R8), and
405
  handing it to a tenant whose admin has not stored one is precisely the leak the R3 rule
406
  exists to prevent. A tenant with no entry gets None, and the connector says so.
407
+
408
+ ⭐ W54-T45 / R4 β€” `connection_id` NAMES WHICH Meta connection, and no id means the tenant's
409
+ DESIGNATED DEFAULT (the lowest-`slot` `meta_ads` connection), not "whichever row sorts first".
410
+ An id that names no `meta_ads` entry resolves to None, never to a sibling.
411
  """
412
+ return _creds_for(rt, 'meta_ads', connection_id)
413
 
414
 
415
+ def amazon_creds(rt, connection_id=None):
416
  """W52: the FIRST `amazon_sp` entry's fields, else None β€” the Amazon connector's resolver.
417
 
418
  β›” THE SAME SHAPE AND THE SAME IMPLEMENTATION AS `odoo_creds` / `meta_creds`, deliberately.
 
428
  ⚠ AND IT RETURNS THE WHOLE FIELD SET, not one secret: an Amazon credential is five values
429
  (`client_id`, `client_secret`, `refresh_token`, `seller_id`, `marketplace_id`) and the client
430
  needs three of them just to mint an access token.
431
+
432
+ ⭐ W54-T45 / R4 β€” `connection_id` NAMES WHICH Amazon connection, and no id means the tenant's
433
+ DESIGNATED DEFAULT (the lowest-`slot` `amazon_sp` connection), not "whichever row sorts
434
+ first". An id that names no `amazon_sp` entry resolves to None, never to a sibling.
435
+ ⚠ `amazon_creds(None)` β€” a MISSING RUNTIME, not a missing id β€” still answers None rather than
436
+ raising; `verify_amazon` asserts exactly that, and the guard lives in `_creds_for`.
437
  """
438
+ return _creds_for(rt, 'amazon_sp', connection_id)
439
 
440
 
441
  #: ⭐⭐ WAVE 32 (R4 / contract C1) β€” THE SCOPE SIDE-BUCKET, READ HERE, WRITTEN NOWHERE IN THIS FILE.
 
452
  SCOPE_KEY = 'keychain_scopes'
453
 
454
  #: The credential types a WHOLE WORKSPACE reads through, which therefore cannot be personal.
455
+ #: β›” THE ELEVATION THIS PREVENTS, in B's words: `odoo_creds`/`meta_creds` resolve to *a connection
456
+ #: of that type for the TENANT* (W54-T45: the one a caller NAMES, or the tenant's designated
457
+ #: default when none is named) β€” that is what spawns every `ut_odoo_*` / `ut_meta_*` grid and
458
  #: what every measure column is answered from. So a member storing a personal Odoo key would not get
459
  #: "their own Odoo": they would silently become the credential the entire workspace's databases are
460
  #: built from. **A credential elevation wearing a scope picker.**
 
479
  if isinstance(v, dict) and str(v.get('scope') or '') == 'personal')
480
 
481
 
482
+ # ═════════════════════════════════════════════════════════════════════════════════════════════
483
+ # ⭐⭐ W54-T45 / R4 / CONTRACT C4 β€” EVERY READER NAMES WHICH CONNECTION IT WANTS.
484
+ # ═════════════════════════════════════════════════════════════════════════════════════════════
485
+ #
486
+ # What stood here was `_first_creds(rt, etype)`, and one line of it β€” "return the first entry of
487
+ # this type" β€” was the whole ceiling on R4. Storage already held many connections of one kind
488
+ # (W54-T44 gave each of them an id and a slot); every READER collapsed them back to one. An
489
+ # agency with two clients on Odoo could store both credentials, see both rows, rename both, and
490
+ # be served the first one for every question either client asked. That is not a missing feature,
491
+ # it is R7's isolation rule failing silently: one client's numbers answering another's screen.
492
+ #
493
+ # β›” THE HELPER IS NOT NAMED "FIRST" ANY MORE, ON PURPOSE. A shared body called `_first_creds` is
494
+ # how the defect would grow back one connector at a time: the next resolver copies the name and
495
+ # inherits the rule. `_creds_for` asks the question the contract asks β€” *which stored credential
496
+ # serves this connector, for this connection?*
497
+ #
498
+ # β›” RESOLVE ON IDS, ORDER ON SLOTS, and the distinction is MEASURED, not stylistic: a pre-wave
499
+ # row's read-default `slot` MOVES when a sibling of its type is deleted (2 -> 1) while its
500
+ # `connection_id` does not. So `connection_id` is the ADDRESS a caller passes and holds, and
501
+ # `slot` is only how the tenant's DESIGNATED DEFAULT is picked and how connections are ordered
502
+ # on a screen. A caller that stored a slot as an address would eventually address another
503
+ # client's credential.
504
+
505
+
506
+ def default_connection_id(rt, etype):
507
+ """THE TENANT'S DESIGNATED DEFAULT connection of `etype` β€” its `connection_id`, or None.
508
+ Never decrypts anything.
509
+
510
+ β›”β›” A DESIGNATED DEFAULT PINNED BY AN IMMUTABLE ORDINAL, NOT "WHICHEVER ROW HAPPENS TO SORT
511
+ FIRST", AND THAT DISTINCTION IS THE POINT OF THIS WHOLE TICKET. The rule is the LOWEST `slot`
512
+ β€” the per-(tenant, type) ordinal `add_entry` mints high-water and never rewrites β€” with ties
513
+ broken by the existing insertion-id order so the answer is total and stable. "First of its
514
+ type" was an accident of dict ordering that a delete, a re-key or a store rewrite could move
515
+ under a caller's feet; the lowest slot is a decision the tenant made when it added its first
516
+ connection.
517
+ ⚠ Personal entries of a tenant-wide type are skipped exactly as `_creds_for` skips them, so
518
+ the default and the credential can never disagree about which connection serves.
519
+ ⚠ AND IT IS A DEFAULT, NEVER A FALLBACK. It answers "no id was named"; it is not consulted
520
+ when an id WAS named and failed to resolve, because serving a sibling to a caller that asked
521
+ for a specific client is the leak R7 forbids.
522
+ """
523
+ if rt is None:
524
+ return None
525
+ etype = str(etype or '').strip().lower()
526
+ skip = _personal_ids(rt) if etype in TENANT_WIDE_TYPES else frozenset()
527
+ best = None
528
+ for pos, row in enumerate(list_entries(rt)):
529
+ if row['type'] != etype or str(row['id']) in skip:
530
+ continue
531
+ rank = (int(row['slot']), pos)
532
+ if best is None or rank < best[0]:
533
+ best = (rank, str(row['connection_id']))
534
+ return best[1] if best is not None else None
535
+
536
+
537
+ def _row_for(rt, connection_id, etype=None):
538
+ """The metadata row `connection_id` addresses, or None. Never decrypts anything.
539
+
540
+ Matches on the row's `connection_id` and, for rows written before W54-T44, on its entry id β€”
541
+ which `connection_id_of` makes the same value anyway. When `etype` is asserted, a row of a
542
+ DIFFERENT type is None rather than a match: an id is only an address within the connector
543
+ that was asked for.
544
+ β›” A personal entry of a tenant-wide type is None here too, even when named EXPLICITLY. The
545
+ wave-32 skip is a credential-elevation guard, not a tie-breaker, and letting an explicit id
546
+ walk past it would reopen the door from the one side that stayed shut.
547
+ """
548
+ if rt is None:
549
+ return None
550
+ want = str(connection_id or '')
551
+ if not want:
552
+ return None
553
+ etype = str(etype or '').strip().lower()
554
+ for row in list_entries(rt):
555
+ if str(row['connection_id']) != want and str(row['id']) != want:
556
+ continue
557
+ rtype = str(row['type'] or '')
558
+ if etype and rtype != etype:
559
+ return None
560
+ if rtype in TENANT_WIDE_TYPES and str(row['id']) in _personal_ids(rt):
561
+ return None
562
+ return row
563
+ return None
564
+
565
+
566
+ def resolve_connection_id(rt, etype, connection_id=None):
567
+ """WHICH connection of `etype` would serve β€” an IDENTITY, decrypting nothing. None when
568
+ nothing would.
569
+
570
+ β›” IT EXISTS SO THERE IS GENUINELY ONE RESOLVER. `harness/runtime.py::odoo_flag_key` needs the
571
+ identity of the serving connection without opening it (a pause flag must still resolve on a
572
+ LOCKED keychain), and its docstring has always claimed to be that one resolver while carrying
573
+ an inline first-entry walk of its own. This is the walk it now calls instead.
574
+ ⚠ The answer is a `connection_id`, which for every stored row equals that row's entry id
575
+ (`add_entry` stamps them the same and `connection_id_of` defaults the older rows to it), so
576
+ the pause flags written against the old resolution keep resolving.
577
+ """
578
+ if connection_id is None:
579
+ return default_connection_id(rt, etype)
580
+ row = _row_for(rt, connection_id, etype)
581
+ return str(row['connection_id']) if row else None
582
+
583
+
584
+ def connection_creds(rt, connection_id, etype=None):
585
+ """THE fields of the ONE connection `connection_id` addresses, decrypted β€” or None.
586
+
587
+ ⭐⭐ W54-T45 / C4 β€” the reader the contract asks for: *"`keychain.odoo_creds` and every other
588
+ first-entry reader must take a `connection_id`."* Two connections of one kind therefore return
589
+ two different credential sets for two different ids, which is the agency case R4 names.
590
 
591
  ⚠ A MISSING RUNTIME ANSWERS None RATHER THAN RAISING, AND THE GUARD IS HERE ON PURPOSE. Every
592
  caller's contract is already "the tenant's credential, or None", and `None` means exactly
 
595
  implementation did not keep. Found by `verify_amazon` asserting the contract rather than the
596
  behaviour. β›” FIXED HERE AND NOT IN ONE RESOLVER, because this module's own rule is that
597
  "which stored credential serves this connector" has ONE implementation: patching `amazon_creds`
598
+ alone would have created the second normalizer this file warns about.
599
 
600
  ⭐⭐ WAVE 32 (R4/C1) β€” A PERSONAL ENTRY OF A TENANT-WIDE TYPE IS SKIPPED, NOT SERVED.
601
  `routes_keychain` REFUSES to create one, and that closes the door from the only side B owns;
 
609
  into an outage for a workspace that has a perfectly good business entry two rows down.
610
  ⚠ AND THE SKIP IS SCOPED TO `TENANT_WIDE_TYPES`. A personal entry of any OTHER type is a normal
611
  personal credential and this resolver is not how it is reached.
612
+ ⚠ A LOCKED KEYCHAIN STILL RAISES `KeychainLocked`, from `read_fields`. "No key on this
613
+ deployment" is an operator fact and silently empty creds would read as "not configured".
614
+ """
615
+ row = _row_for(rt, connection_id, etype)
616
+ return read_fields(rt, row['id']) if row else None
617
+
618
+
619
+ def _creds_for(rt, etype, connection_id=None):
620
+ """THE ONE INTERNAL HELPER behind `odoo_creds` / `meta_creds` / `amazon_creds`: the fields of
621
+ the `etype` connection named by `connection_id`, or of the tenant's designated default when
622
+ no id is named. None when nothing serves.
623
+
624
+ β›” IT REPLACES `_first_creds`, NAME INCLUDED. "Which stored credential serves this connector"
625
+ has ONE implementation in this module, and the old one answered a question C4 forbids.
626
+ β›” A NAMED CONNECTION THAT DOES NOT RESOLVE IS None, FULL STOP β€” never the default, never a
627
+ sibling, and (at the caller) never the environment. Falling back after an explicit ask is how
628
+ one client's Odoo comes to answer another client's question under R7's strict isolation.
629
  """
630
  if rt is None:
631
  return None
632
+ if connection_id is None:
633
+ connection_id = default_connection_id(rt, etype)
634
+ if connection_id is None:
635
+ return None
636
+ return connection_creds(rt, connection_id, etype)
637
 
638
 
639
  # ---------------------------------------------------------------------------------------------
platform/core/perm_scope.py CHANGED
@@ -1980,3 +1980,321 @@ def pivot_scope(user, source, target, st=None, path=None):
1980
  return PivotScope(user, src, tgt, walk,
1981
  source_scope=derive_pool_scope(user, src),
1982
  target_scope=derive_pool_scope(user, tgt))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1980
  return PivotScope(user, src, tgt, walk,
1981
  source_scope=derive_pool_scope(user, src),
1982
  target_scope=derive_pool_scope(user, tgt))
1983
+
1984
+
1985
+ # ── C4 / R4: THE CONNECTOR AXIS β€” WHO MAY CREATE A CONNECTION (wave 54, W54-T47) ──────────────
1986
+ #: The per-tenant bucket one administrator's decision lives in: `{username: [<entry type>, …]}`.
1987
+ #:
1988
+ #: β›”β›” AN ABSENT ROW AND "NO GRANT" ARE THE SAME THING, AND THAT IS WHY THIS IS A READ DEFAULT
1989
+ #: RATHER THAN A MIGRATION. `routes_keychain.SCOPE_KEY` carries the identical posture one layer up
1990
+ #: (*"a business entry writes no row β€” it IS the default"*), and the reason is
1991
+ #: [[a-migration-that-runs-on-the-next-write]]: materialising an empty grant for every account in
1992
+ #: every tenant would rewrite the store on the next read, for a fact nobody decided.
1993
+ CONNECTOR_GRANT_KEY = 'connector_grants'
1994
+
1995
+
1996
+ def connector_grants(username, st=None):
1997
+ """The connector kinds `username` has been granted, lower-cased, as a frozenset.
1998
+
1999
+ ⚠ THE ANSWER TO AN UNREADABLE STORE IS THE EMPTY SET, AND HERE THAT IS THE SAFE DIRECTION
2000
+ RATHER THAN THE UNSAFE ONE β€” the opposite of `user_generated_fields`, which must answer `None`.
2001
+ That function's answer is PRUNED AGAINST, so a degraded read would delete a live rule; this one
2002
+ only ever WIDENS what a member may do (see `may_add_connection`), so a degraded read leaves the
2003
+ member with exactly the rights they had before this ticket existed. Under-granting is visible
2004
+ and reportable; over-granting is a credential elevation.
2005
+ """
2006
+ if st is None:
2007
+ return frozenset()
2008
+ uname = str(username or '').strip().lower()
2009
+ if not uname:
2010
+ return frozenset()
2011
+ try:
2012
+ rows = st.get(CONNECTOR_GRANT_KEY) or {}
2013
+ except Exception: # noqa: BLE001
2014
+ return frozenset()
2015
+ if not isinstance(rows, dict):
2016
+ return frozenset()
2017
+ got = rows.get(uname)
2018
+ if not isinstance(got, (list, tuple, set, frozenset)):
2019
+ return frozenset()
2020
+ return frozenset(str(k).strip().lower() for k in got if str(k or '').strip())
2021
+
2022
+
2023
+ def may_add_connection(user, etype, st=None):
2024
+ """May this account create a WORKSPACE-WIDE connection of kind `etype`? (W54-T47 / R4 / C4.)
2025
+
2026
+ ⭐⭐ THE THIRD GRANT AXIS. Owner, verbatim: *"Under Settings, an Admin should grant a user
2027
+ access to add connectors, so access becomes Database / Module / Connector. This allows many
2028
+ connectors per tenant … depending on the admin's configuration per user."* Database and Module
2029
+ are the two groups `PermsEditor.tsx` already renders off `perms`; this is the third, and it is
2030
+ a per-KIND answer rather than a single boolean because R4's agency tenant is the whole case:
2031
+ one member may be the person who wires up Shopify and not the person who wires up Odoo.
2032
+
2033
+ β›”β›” ABSENCE WIDENS NOTHING AND REVOKES NOTHING, AND THAT IS THE MOST IMPORTANT PROPERTY OF
2034
+ THIS FUNCTION. No grant was STORABLE before this ticket, so every account in every tenant
2035
+ carries none β€” reading that absence as DENY at the connection door would revoke personal
2036
+ connections for everybody on the day this shipped, with nobody having decided anything. That
2037
+ is `may_metrics`' argument one file over, in the same words, and the resolution is the same:
2038
+ this predicate is consulted ONLY on the path that was already refused
2039
+ (`routes_keychain.add_key`'s `scope == "business" and not session.admin` leg), so a member with
2040
+ no grant meets byte-identical behaviour β€” 403 `not_admin` on a business-wide create, 400
2041
+ `scope_not_available` on a tenant-wide personal one, and their own personal connection of an
2042
+ ordinary type still succeeds. An explicit grant is the ONLY thing this adds, and all it can do
2043
+ is admit.
2044
+
2045
+ β›” AN ADMIN IS ALWAYS TRUE, before the store is touched β€” break-glass, as every predicate in
2046
+ this file opens, and it is what keeps a tenant whose grant bucket cannot be read from losing
2047
+ its own administrator's ability to connect anything.
2048
+
2049
+ ⚠ `st` IS THE TENANT HANDLE AND OMITTING IT DENIES A NON-ADMIN. The grant is per TENANT, so a
2050
+ caller that cannot lend a handle is asking about no workspace in particular; answering from the
2051
+ process-default store is the D-612 shape (`nav_may_open`'s leg 3), and there the wrong answer
2052
+ was reachable in BOTH directions. Here the handle-less answer is the pre-ticket one, so a door
2053
+ that has not learned to thread `st` refuses rather than admitting somebody else's grant.
2054
+
2055
+ ⚠ IT IS NOT A SECOND SPELLING OF ELIGIBILITY. `routes_keychain.allowed_scopes` answers what the
2056
+ SOURCE permits (Odoo is workspace-wide by construction); this answers who may act on it. Both
2057
+ must hold, and a tenant-wide type refused to a personal scope stays refused for everybody,
2058
+ grant or no grant.
2059
+ """
2060
+ if perms.is_admin(user):
2061
+ return True
2062
+ kind = str(etype or '').strip().lower()
2063
+ if not kind:
2064
+ return False
2065
+ return kind in connector_grants((user or {}).get('username'), st=st)
2066
+
2067
+
2068
+ # ── C4 / R7: THE CONNECTION AXIS β€” ONE READ, ONE CONNECTION (wave 54, W54-T49) ─────────────────
2069
+ #: ⭐⭐ RULING R7, verbatim: *"Multi-connection isolation is STRICT, on the Business Unit pattern.
2070
+ #: Every Odoo-reading module gains a connection selector; picking one client shows only that
2071
+ #: client's numbers. β›” There is no 'All' option that blends two clients."*
2072
+ #:
2073
+ #: β›”β›” AND THE FAILURE THIS SECTION EXISTS TO PREVENT IS ON THE **VALUES** AXIS, WHICH IS WHY IT
2074
+ #: LOOKS FINE. Wave 51's tenancy defect ran for a whole wave with a correct-looking row LIST while
2075
+ #: `rev`, `ly`, `ltm`, `aov` and `est_missed` were silently two clients' numbers added together β€”
2076
+ #: `_PUSHDOWN_OPS`' own note above is that incident's record. A connection scope is therefore not
2077
+ #: a post-filter over rows: it decides WHICH TABLE is read at all, before a row exists to filter.
2078
+ #:
2079
+ #: ⭐ THE PRECEDENT IS `derive_pool_scope`, NOT A PICKER. `pages.py::bu_control` builds a BU
2080
+ #: control from `perms.allowed_bu_labels`, but `pages.py::_BUILDERS` is `{}` on purpose and
2081
+ #: `verify_api` asserts that emptiness, so that assembly is unreachable in production. The live BU
2082
+ #: pattern is the per-request DERIVATION twenty lines up, and this is its shape one axis over.
2083
+ #:
2084
+ #: β›” IT TAKES NO PRINCIPAL, DELIBERATELY, AND THAT IS NOT AN OVERSIGHT TO TIDY. WHICH connection
2085
+ #: serves is a property of the workspace and of the request, never of the reader: there is no
2086
+ #: per-user connection grant in this product (`may_add_connection` governs who may CREATE one, a
2087
+ #: different question), so a `user` parameter here would read as a wall this function does not
2088
+ #: have. The reader's wall is `may_read` on the table key the scope resolves to, and it composes
2089
+ #: AFTER this one, unchanged.
2090
+
2091
+ #: What a LEGACY (bare) table key's owner is called when the workspace has no stored connection at
2092
+ #: all to name β€” every tenant before this wave, tenant #0 included.
2093
+ #:
2094
+ #: β›” RESTATED FROM `odoo_relational.DEFAULT_CONNECTION` RATHER THAN IMPORTED, because `core` never
2095
+ #: imports up (`platform/ARCHITECTURE.md`). It is the same restatement `_FORMULA_REF` at the top of
2096
+ #: this file makes, with the same guard: `verify_scopes` asserts the two spell the same word, so a
2097
+ #: rename in the API layer cannot leave this copy behind [[constant-two-features-share]].
2098
+ DEFAULT_CONNECTION = 'default'
2099
+
2100
+ #: The connector kind a scope answers for when a caller names none. `odoo` is the only kind that
2101
+ #: spawns per-connection tables today (W54-T46); the parameter exists so the second one needs no
2102
+ #: second function.
2103
+ DEFAULT_CONNECTION_TYPE = 'odoo'
2104
+
2105
+
2106
+ class UnknownConnection(LookupError):
2107
+ """A NAMED connection does not resolve in this workspace.
2108
+
2109
+ β›”β›” RAISED, NEVER FALLEN BACK FROM, and that asymmetry IS R7. `keychain.default_connection_id`
2110
+ answers *"no id was named"*; it is not consulted when an id WAS named and failed to resolve,
2111
+ because serving a sibling to a caller that asked for a specific client is exactly the leak this
2112
+ contract forbids. `odoo_relational.connection_namespace` and `runtime.odoo_source` already hold
2113
+ that posture, and this is the third place it has to hold or the first two are decoration.
2114
+ """
2115
+
2116
+
2117
+ class ConnectionScope:
2118
+ """⭐⭐ CONTRACT C4 / R7 β€” the ONE connection a read is scoped to. Blending is UNREPRESENTABLE.
2119
+
2120
+ Built by `connection_scope()` and by nothing else worth building: it holds a SINGLE
2121
+ `connection_id` string, there is no member that can hold two, and the constructor refuses
2122
+ anything that is not one non-empty id. So "read both clients" is not a value this type can
2123
+ carry β€” it is not a flag that happens to be off, which is the difference between a rule and a
2124
+ default. A list, an empty string and the word "all" all arrive here as a refusal.
2125
+
2126
+ ⚠ IT HOLDS THE TYPE TOO, so an odoo scope can never be handed to a meta_ads reader as though
2127
+ an id were an address across connectors. `keychain._row_for` makes the same statement one layer
2128
+ down (*"an id is only an address within the connector that was asked for"*).
2129
+ """
2130
+ __slots__ = ('connection_id', 'etype')
2131
+
2132
+ def __init__(self, connection_id, etype=DEFAULT_CONNECTION_TYPE):
2133
+ cid = connection_id.strip() if isinstance(connection_id, str) else ''
2134
+ if not cid:
2135
+ raise UnknownConnection(
2136
+ 'a connection scope is exactly one connection. Name a single connection, or '
2137
+ 'name none and the workspace default serves.')
2138
+ self.connection_id = cid
2139
+ self.etype = str(etype or DEFAULT_CONNECTION_TYPE).strip().lower()
2140
+
2141
+ def __repr__(self):
2142
+ return f'ConnectionScope({self.connection_id!r}, {self.etype!r})'
2143
+
2144
+ def owner_of(self, table_key, rt=None):
2145
+ """WHICH connection owns `table_key`, through the registered owner. `None` for a key no
2146
+ connector claims.
2147
+
2148
+ β›” NO REGISTRAR IS `Unresolvable`, NOT `False`. The question "whose table is this" is
2149
+ answered in the API layer (`odoo_relational.connection_for_table_key`) and `core` never
2150
+ imports up, so a process that never registered one cannot answer it β€” and a wall that
2151
+ cannot be evaluated must say so with its cause and a recommendation rather than quietly
2152
+ admitting or quietly refusing. That is standing rule 1's second sentence, and it is the
2153
+ same shape `_read_user_table` uses when no mirror reader is registered.
2154
+ """
2155
+ key = str(table_key or '').strip()
2156
+ if _CONNECTION_OWNER is None:
2157
+ raise Unresolvable(
2158
+ subject='connection', effect='unresolvable',
2159
+ cause=(f"'{key}' cannot be attributed to a connection in this process because no "
2160
+ f'connection owner is registered'),
2161
+ recommendation=('call `perm_scope.register_connection_owner(...)` from the app '
2162
+ 'layer before scoping a read, or read through the API'))
2163
+ owner = _CONNECTION_OWNER(key, rt)
2164
+ return str(owner) if owner else None
2165
+
2166
+ def covers(self, table_key, rt=None):
2167
+ """Does `table_key` belong to THIS connection?
2168
+
2169
+ β›” FAIL CLOSED. An unanswerable question is a NO here, never a pass: a key no connector
2170
+ claims, an owner that cannot be resolved and a missing registrar all answer False, because
2171
+ the only thing "I do not know whose this is" can safely mean under R7 is "not yours".
2172
+ """
2173
+ try:
2174
+ return self.owner_of(table_key, rt) == self.connection_id
2175
+ except Exception: # noqa: BLE001
2176
+ return False
2177
+
2178
+ def require(self, table_key, rt=None):
2179
+ """`table_key` itself, or `Denied` when it belongs to another connection.
2180
+
2181
+ β›” THE WALL, AND IT IS ONE SENTENCE ON REFUSAL (DESIGN section 4). `covers` is the
2182
+ predicate a caller may branch on; this is the door a reader passes through, so that a
2183
+ route which forgets to branch fails CLOSED rather than reading the other client's table.
2184
+ """
2185
+ key = str(table_key or '').strip()
2186
+ owner = self.owner_of(key, rt)
2187
+ if owner != self.connection_id:
2188
+ raise Denied(f"'{key}' belongs to another connection. Switch the connection selector "
2189
+ f'to the one that owns it.')
2190
+ return key
2191
+
2192
+
2193
+ #: WHO answers "which connection owns this table key", declared by the app layer.
2194
+ #: `reader(table_key, rt) -> connection_id | None`.
2195
+ #:
2196
+ #: β›” A REGISTRATION SLOT AND NOT AN IMPORT, for the reason `_ROW_SOURCES` and `_MIRROR_READER`
2197
+ #: above are, and `keychain.register_prober` one file over: the inverse lives in
2198
+ #: `aios-web/api/odoo_relational.py` (`connection_for_table_key`), `core` never imports up, and
2199
+ #: `verify_meta` asserts that fence. The app tells this layer rather than being interrogated by it.
2200
+ _CONNECTION_OWNER = None
2201
+
2202
+
2203
+ def register_connection_owner(reader):
2204
+ """Declare THE reader for "whose table is this" β€” one reader, because a table has one owner.
2205
+
2206
+ Returns the registrar's own answer, exactly as `register_mirror` does, so the read door and
2207
+ the write door of this fact have one construction site rather than two.
2208
+ """
2209
+ global _CONNECTION_OWNER
2210
+ _CONNECTION_OWNER = reader
2211
+ return _CONNECTION_OWNER is not None
2212
+
2213
+
2214
+ def connection_scope(rt, etype=DEFAULT_CONNECTION_TYPE, connection_id=None):
2215
+ """The ONE connection this read is scoped to, as a `ConnectionScope`. R7's derivation.
2216
+
2217
+ ⭐⭐ ABSENCE CHANGES NOTHING, AND THAT IS THE PROPERTY THAT LETS THIS SHIP. `connection_id=None`
2218
+ means *"no connection was named"* and resolves to the workspace's DESIGNATED DEFAULT β€” the same
2219
+ connection `keychain._creds_for`, `odoo_relational.connection_namespace` and every pre-ticket
2220
+ reader already served, resolved by the same `keychain.default_connection_id`. A tenant with one
2221
+ connection therefore cannot tell this function exists, which is what every ticket in this lane
2222
+ has preserved for the same reason (W54-T44's read defaults, T46's legacy keys, T47's grant).
2223
+
2224
+ β›” A NAMED CONNECTION THAT DOES NOT RESOLVE IS `UnknownConnection`, NEVER THE DEFAULT. See that
2225
+ class; the fallback is the leak.
2226
+
2227
+ β›”β›” AND THERE IS NO "ALL". `None` is the only absence this function has, and it pins exactly
2228
+ one connection rather than widening to every connection. An empty string, the word "all", a
2229
+ LIST of ids and any non-string are refused BY CONSTRUCTION rather than by enumeration: only a
2230
+ single non-empty string can address a connection, so the vocabulary cannot express a blend for
2231
+ a future caller to discover. That is the wave-51 lesson in the shape of a type β€” there the
2232
+ filter vocabulary widened underneath a reader that could not read it, and the numbers merged.
2233
+
2234
+ ⚠ `rt=None` WITH A NAMED CONNECTION REFUSES rather than answering from the process-default
2235
+ store, which is D-612's shape (`nav_may_open` leg 3): a caller with no workspace handle is
2236
+ asking about no workspace in particular.
2237
+ """
2238
+ kc = _keychain()
2239
+ if connection_id is None:
2240
+ cid = kc.default_connection_id(rt, etype) if rt is not None else None
2241
+ # No connection is stored at all: the legacy keys still belong to "whichever connection is
2242
+ # designated default", which is a real answer rather than an absence, and it is the same
2243
+ # sentinel `connection_for_table_key` hands back for exactly this case.
2244
+ return ConnectionScope(cid or DEFAULT_CONNECTION, etype)
2245
+ named = connection_id.strip() if isinstance(connection_id, str) else ''
2246
+ if not named:
2247
+ raise UnknownConnection(
2248
+ 'name one connection, or name none and the workspace default serves.')
2249
+ cid = kc.resolve_connection_id(rt, etype, named) if rt is not None else None
2250
+ if not cid:
2251
+ raise UnknownConnection(
2252
+ f"'{named}' does not name a connection in this workspace. Pick a connection in the "
2253
+ f'Connectors panel and read it again.')
2254
+ return ConnectionScope(cid, etype)
2255
+
2256
+
2257
+ def connection_options(rt, etype=DEFAULT_CONNECTION_TYPE):
2258
+ """The connections a selector may offer, in slot order: `[{'id', 'label'}, ...]`.
2259
+
2260
+ ⭐ `allowed_bus()` ONE AXIS OVER, and the ticket asks for it to read like it. The list is what
2261
+ a module's connection selector renders, and the FIRST member is the workspace's designated
2262
+ default, so a client that shows the first row selected shows what a read with no id named would
2263
+ actually serve.
2264
+
2265
+ β›”β›” THERE IS NO "ALL" MEMBER AND THERE IS NO PLACE TO PUT ONE. R7 is explicit that no option
2266
+ may blend two clients, so the option list carries only real connections; a caller that wants
2267
+ "everything" has to ask twice, once per connection, which is exactly what `refresh_all` does.
2268
+
2269
+ ⚠ IDENTITY COMES FROM `keychain.resolve_connection_id`, NEVER FROM A SECOND WALK OF THE ROWS.
2270
+ Four first-entry walks were deleted in W54-T45 and a fifth would reopen the ceiling C4 exists
2271
+ to close; the row is read here only for its LABEL and its slot, which no resolver answers. The
2272
+ resolver is also what SKIPS a personal entry of a tenant-wide type, so a credential the readers
2273
+ would never serve cannot appear in a picker as though it would.
2274
+ """
2275
+ if rt is None:
2276
+ return []
2277
+ kc = _keychain()
2278
+ want = str(etype or DEFAULT_CONNECTION_TYPE).strip().lower()
2279
+ rows, seen = [], set()
2280
+ try:
2281
+ entries = list(kc.list_entries(rt))
2282
+ except Exception: # noqa: BLE001
2283
+ return []
2284
+ for row in entries:
2285
+ if str(row.get('type') or '') != want:
2286
+ continue
2287
+ cid = kc.resolve_connection_id(rt, want,
2288
+ str(row.get('connection_id') or row.get('id') or ''))
2289
+ if not cid or cid in seen:
2290
+ continue
2291
+ seen.add(cid)
2292
+ label = ' '.join(str(row.get('label') or '').split()) or kc.kind_label(want)
2293
+ rows.append((int(row.get('slot') or 0), len(rows), cid, label))
2294
+ rows.sort()
2295
+ return [{'id': cid, 'label': label} for _slot, _pos, cid, label in rows]
2296
+
2297
+
2298
+ def _keychain():
2299
+ import core.keychain as keychain
2300
+ return keychain
platform/core/relations.py CHANGED
@@ -59,6 +59,86 @@ booked in this ticket's handoff), ``pin_sql`` delegates to it and this note is d
59
  #: The three ways a database can be related to another. `via.direction` is always one of these.
60
  DIRECTIONS = ('forward', 'reverse', 'bridge')
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  #: The identity column of a module grid, as the wire spells it. `customer_data.pid` IS the Odoo
63
  #: `res.partner` id and `ut_odoo_orders.pid` IS the `sale_order` id, so a bridge hanging off `pid`
64
  #: needs no second lookup. `product_data.pid` is NOT an Odoo id (it is `crc32(default_code)`),
@@ -215,7 +295,7 @@ def _entry(key, label, target, direction, field=None, on=None, frm=None, served=
215
  return out
216
 
217
 
218
- def forward_links(table, fields):
219
  """The FORWARD entries for `table`: every `type: "link"` field on it, in field order.
220
 
221
  `fields` is whatever the caller's permission wall handed back, so a link field this account
@@ -224,6 +304,10 @@ def forward_links(table, fields):
224
 
225
  ⭐ TWO LINKS BETWEEN THE SAME PAIR GIVE TWO ENTRIES, and R2 says so in as many words. The entry
226
  `key` is the FIELD key, not the target key, which is what keeps them apart on the wire.
 
 
 
 
227
  """
228
  out = []
229
  for field in (fields or ()):
@@ -239,10 +323,10 @@ def forward_links(table, fields):
239
  target=target, direction='forward',
240
  field=field.get('key'), on=bag.get('on'),
241
  frm=bag.get('from') or IDENTITY_COL))
242
- return out
243
 
244
 
245
- def reverse_links(table, defs):
246
  """The REVERSE entries for `table`: every OTHER table's link field that points at it.
247
 
248
  `defs` is `{key: definition}` as `core.user_tables.all_defs` returns it, already narrowed to
@@ -252,6 +336,9 @@ def reverse_links(table, defs):
252
  β›” A TABLE'S LINK TO ITSELF IS NOT A REVERSE LINK. It is already a forward one, and emitting
253
  both would give the same edge two tabs pointing at the same grid, one of them labelled from
254
  the wrong end.
 
 
 
255
  """
256
  me = str(table or '')
257
  out = []
@@ -276,15 +363,20 @@ def reverse_links(table, defs):
276
  # mislabelled `forward` as a negative control for exactly this.
277
  on=bag.get('from') or IDENTITY_COL,
278
  frm=bag.get('on') or IDENTITY_COL))
279
- return out
 
280
 
 
 
281
 
282
- def bridge_entries(table):
283
- """The BRIDGE entries for `table`, from `BRIDGES` and from nowhere else."""
284
- return [_entry(key=b['key'], label=b['label'], target=b['target'], direction='bridge',
285
- on=b['target_col'], frm=b['source_col'], served=b['served'],
286
- where=b['where'])
287
- for b in bridges_from(table)]
 
 
288
 
289
 
290
  def edge_identity(entry):
@@ -301,7 +393,7 @@ def edge_identity(entry):
301
  str(via.get('from') or ''), str(entry.get('where') or ''))
302
 
303
 
304
- def related(table, fields=None, defs=None):
305
  """THE `/related` ANSWER for one table: forward, then reverse, then bridge.
306
 
307
  `[{key, label, via: {direction, key, field?, on?, from?}, target, served, where?}]`.
@@ -325,10 +417,11 @@ def related(table, fields=None, defs=None):
325
  ⚠ ON A TENANT WITH NO PRE-SET LINKS the bridge is not a duplicate of anything and is offered
326
  unchanged, which is the whole reason the suppression is computed rather than declared.
327
  """
328
- forward = forward_links(table, fields or ())
329
- reverse = reverse_links(table, defs or {})
330
  seen = {edge_identity(e) for e in forward} | {edge_identity(e) for e in reverse}
331
- bridges = [b for b in bridge_entries(table) if edge_identity(b) not in seen]
 
332
  return forward + reverse + bridges
333
 
334
 
@@ -734,7 +827,7 @@ def compose_cardinality(a, b):
734
  return 'many_to_many'
735
 
736
 
737
- def spec_entries(table):
738
  """The CONNECTOR-SPEC edges of `table`, in BOTH directions, in `related()`'s entry shape.
739
 
740
  β›”β›” BOTH DIRECTIONS, AND AN OUTBOUND-ONLY READ CANNOT ANSWER THE QUESTION THIS TICKET ASKS.
@@ -761,6 +854,13 @@ def spec_entries(table):
761
  ⚠ `served` TAKES `_entry`'s DEFAULT, exactly as the forward and reverse link FIELDS do. Only
762
  `BRIDGES` carries a measured `served` today, and inventing one per spec edge here would be a
763
  second, unmeasured source for the same judgement.
 
 
 
 
 
 
 
764
  """
765
  spec = _spec()
766
  me = str(table or '')
@@ -786,7 +886,7 @@ def spec_entries(table):
786
  on=from_col, # the column on the OTHER table
787
  frm=to_col, # the column on THIS one
788
  cardinality=_INVERSE.get(str(cardinality), 'many_to_many')))
789
- return out
790
 
791
 
792
  def _link_field_cardinalities(table, fields, defs):
@@ -814,7 +914,7 @@ def _link_field_cardinalities(table, fields, defs):
814
  return out
815
 
816
 
817
- def one_hop(table, fields=None, defs=None):
818
  """EVERYTHING ONE NAMED HOP FROM `table`: `related()` plus the connector spec, deduplicated.
819
 
820
  Every entry carries a `cardinality`, taken from the declaration it came with:
@@ -831,7 +931,7 @@ def one_hop(table, fields=None, defs=None):
831
  *"one tab per related table"*. The dedupe is on `edge_identity`, which is target plus both join
832
  columns plus the predicate; read its docstring for why `where` is in there.
833
  """
834
- base = list(related(table, fields, defs))
835
  cards = _link_field_cardinalities(table, fields, defs)
836
  bridge_cards = {b['key']: _bridge_cardinality(b) for b in BRIDGES}
837
  out = []
@@ -841,7 +941,7 @@ def one_hop(table, fields=None, defs=None):
841
  entry['cardinality'] = str(got or 'many_to_many')
842
  out.append(entry)
843
  seen = {edge_identity(e) for e in out}
844
- for entry in spec_entries(table):
845
  if edge_identity(entry) in seen:
846
  continue
847
  seen.add(edge_identity(entry))
@@ -880,7 +980,8 @@ def _two_hop_entry(first, second):
880
  }
881
 
882
 
883
- def related_paths(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None, fields_for=None):
 
884
  """C3'S `/related` ANSWER: everything reachable from `table` in at most `depth` NAMED hops.
885
 
886
  `[{key, label, via, target, served, where?, cardinality, path, hops}]`, one-hop entries first
@@ -905,13 +1006,18 @@ def related_paths(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None,
905
 
906
  β›” A HOP-2 EDGE POINTING BACK AT `table` IS DROPPED. `customer -> orders -> customer` is a round
907
  trip, not a relation, and offering it would put a tab on the customers grid labelled Customers.
 
 
 
 
 
908
  """
909
  if depth not in (1, MAX_DEPTH):
910
  raise ValueError(
911
  "relation depth is 1 or %d; %r was asked for. The route turns this into a named "
912
  "refusal rather than a 500" % (MAX_DEPTH, depth))
913
  table = str(table or '')
914
- hop1 = [e for e in one_hop(table, fields, defs)
915
  if may_open is None or may_open(e['target'])]
916
  out = []
917
  for entry in hop1:
@@ -925,7 +1031,7 @@ def related_paths(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None,
925
  for first in hop1:
926
  mid = first['target']
927
  mid_fields = fields_for(mid) if fields_for is not None else None
928
- for second in one_hop(mid, mid_fields, defs):
929
  if second['target'] == table:
930
  continue
931
  if may_open is not None and not may_open(second['target']):
@@ -1033,7 +1139,7 @@ def over_depth_refusal(table, via):
1033
  # whether it holds rows for this record. The name, and the fact that the door is shut.
1034
  # ══════════════════════════════════════════════════���════════════════════════════════════════════
1035
 
1036
- #: ⭐ THE THREE R13 ANSWERS, PLUS THE FOURTH THAT IS NOT A PERMISSION ANSWER AT ALL.
1037
  #: ⚠ `unknown_via` KEEPS THE NAME `routes_grid.grid_related` ALREADY RAISES rather than gaining a
1038
  #: synonym: a fourth spelling of the same refusal would be a client-visible rename dressed as a
1039
  #: feature. `routes_odoo_tables` spells its depth-1 cousin `unknown_relation` and is in another
@@ -1043,10 +1149,22 @@ REFUSAL_FORBIDDEN_TABLE = 'forbidden_table'
1043
  REFUSAL_HOP_FILTERED = 'hop_filtered'
1044
  REFUSAL_UNKNOWN_VIA = 'unknown_via'
1045
 
1046
- #: The three R13 answers in R13's own order, and the fourth. A gate reads this rather than four
1047
- #: literals scattered through two files.
 
 
 
 
 
 
 
 
 
 
 
 
1048
  REFUSAL_CODES = (REFUSAL_NO_ROWS, REFUSAL_FORBIDDEN_TABLE, REFUSAL_HOP_FILTERED,
1049
- REFUSAL_UNKNOWN_VIA)
1050
 
1051
 
1052
  def _named_path(path):
@@ -1054,6 +1172,39 @@ def _named_path(path):
1054
  return ' then '.join(f"'{k}'" for k in (str(p) for p in (path or ())))
1055
 
1056
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1057
  def no_related_rows_refusal(table, path=None):
1058
  """R13's FIRST answer: everything was open, and there is genuinely nothing on the other side.
1059
 
@@ -1062,15 +1213,31 @@ def no_related_rows_refusal(table, path=None):
1062
  of R13, so the empty case is spelled out loud and says in as many words that nothing was
1063
  hidden from it.
1064
  β›” NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1065
  """
1066
  named = _named_path(path)
1067
  if named:
1068
- return (f"the relation reached by {named} on '{table}' is open to this account at every "
1069
  f"hop, and it reaches no rows. Nothing was hidden by permission and no hop was "
1070
- f"filtered: there is simply nothing on the other side of it")
1071
  return (f"'{table}' reaches no other database within {MAX_DEPTH} named hops that this account "
1072
  f"may open, and nothing was removed by permission on the way. Ask an administrator to "
1073
- f"link it to another database, or open the database you want on its own")
1074
 
1075
 
1076
  def forbidden_table_refusal(table, path, blocked, hop=None):
@@ -1084,14 +1251,92 @@ def forbidden_table_refusal(table, path, blocked, hop=None):
1084
  could not read at all, so claiming only the first would tell a reader their access was revoked
1085
  when the store had merely hiccupped.
1086
  β›” NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1087
  """
1088
  named = _named_path(path) or 'this relation'
1089
  where = f" at the hop named '{hop}'" if hop else ''
1090
- return (f"the relation reached by {named} on '{table}' passes through '{blocked}'{where}, and "
1091
  f"this account may not open '{blocked}', either because it is not granted to you or "
1092
  f"because it could not be read just now. The traversal is refused rather than served "
1093
  f"short, so no part of it is silently missing. Ask an administrator for access to "
1094
- f"'{blocked}', or ask for a relation that does not pass through it")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1095
 
1096
 
1097
  def hop_filtered_refusal(table, path, hop):
@@ -1103,13 +1348,26 @@ def hop_filtered_refusal(table, path, hop):
1103
  stay open, so the traversal is neither forbidden nor empty. Served as `[]` it would read as
1104
  "this record has nothing here", which is a claim about the business made out of a permission.
1105
  β›” NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
 
 
 
 
 
 
 
 
 
 
 
 
 
1106
  """
1107
  named = _named_path(path) or 'this relation'
1108
- return (f"the hop named '{hop}' of the relation reached by {named} on '{table}' was filtered "
1109
- f"out for this account. The databases it crosses are open to you; the link column "
1110
  f"this hop is built on is not one you may see, so the hop was removed rather than "
1111
  f"answered empty. Ask an administrator for that column, or ask for a relation that "
1112
- f"does not use it")
1113
 
1114
 
1115
  def candidate_paths(table, entries, defs=None, fields_for=None):
@@ -1178,6 +1436,13 @@ def unknown_via_answer(table, keys, candidates):
1178
  them only into the sentence is what `unknown_via_refusal` used to do, and lane E cannot draw a
1179
  retry button out of an English clause.
1180
  β›” NO EM DASH AND NO EN DASH anywhere in `message` (standing rule 2).
 
 
 
 
 
 
 
1181
  """
1182
  keys = [str(k) for k in (keys or ())]
1183
  cands = list(candidates or ())
@@ -1198,9 +1463,10 @@ def unknown_via_answer(table, keys, candidates):
1198
  f"account is offered, then send the 'path' of the one you want, one edge key per "
1199
  f"hop")
1200
  return {'code': REFUSAL_UNKNOWN_VIA, 'path': keys, 'candidates': cands,
1201
- 'message': (f"'{table}' offers no relation reached by {named} to this account, and "
1202
- f"nothing was removed by permission on the way, so this is an edge that "
1203
- f"does not exist rather than one you may not see." + tail)}
 
1204
 
1205
 
1206
  def _paths_of(entries):
@@ -1210,8 +1476,12 @@ def _paths_of(entries):
1210
 
1211
  def diagnose_path(table, keys, fields=None, defs=None, may_open=None, fields_for=None,
1212
  depth=MAX_DEPTH, entries=None, open_entries=None,
1213
- open_fields=None, open_fields_for=None):
1214
- """WHY `pick_path` came back None, as one of C3's four answers. `{code, message, table?, hop?}`.
 
 
 
 
1215
 
1216
  β›”β›” NEVER RAISES AND NEVER RETURNS None. A diagnosis that can itself fail is the fail-open bug
1217
  `routes_grid._may_open` warns about: every branch below ends in a real bag carrying a code from
@@ -1221,6 +1491,13 @@ def diagnose_path(table, keys, fields=None, defs=None, may_open=None, fields_for
1221
 
1222
  1. the FILTERED enumeration (`may_open` + the caller's field wall). If `keys` resolves in it,
1223
  the path is permitted end to end and reaches nothing: `no_related_rows`.
 
 
 
 
 
 
 
1224
  2. the UNFILTERED enumeration (no `may_open`, and the widest field list the caller can offer).
1225
  If `keys` does not resolve THERE either, the edge genuinely does not exist and no wall was
1226
  involved: `unknown_via`, with the candidates, their join columns and the retry strings.
@@ -1237,8 +1514,10 @@ def diagnose_path(table, keys, fields=None, defs=None, may_open=None, fields_for
1237
  β›” `open_fields` / `open_fields_for` MUST BE A SUPERSET of `fields` / `fields_for`, or step 2
1238
  can call a wall-removed path unknown. The route builds them as a UNION for exactly that reason;
1239
  when they are omitted the diff runs on the table wall alone, which is correct and narrower.
1240
- β›” `entries` / `open_entries` ARE AN OPTIMISATION ONLY. The route has already paid for both
1241
- enumerations; a gate hands neither and gets the same answer computed from scratch.
 
 
1242
  """
1243
  keys = [str(k) for k in (keys or ())]
1244
  table = str(table or '')
@@ -1247,7 +1526,19 @@ def diagnose_path(table, keys, fields=None, defs=None, may_open=None, fields_for
1247
  may_open=may_open, fields_for=fields_for)
1248
  if pick_path(entries, keys) is not None:
1249
  return {'code': REFUSAL_NO_ROWS, 'path': keys,
1250
- 'message': no_related_rows_refusal(table, keys)}
 
 
 
 
 
 
 
 
 
 
 
 
1251
  if open_entries is None:
1252
  open_entries = related_paths(
1253
  table, fields=(open_fields if open_fields is not None else fields), defs=defs,
@@ -1266,21 +1557,25 @@ def diagnose_path(table, keys, fields=None, defs=None, may_open=None, fields_for
1266
  if blocked and may_open is not None and not may_open(blocked):
1267
  return {'code': REFUSAL_FORBIDDEN_TABLE, 'path': keys, 'table': blocked,
1268
  'hop': keys[idx],
1269
- 'message': forbidden_table_refusal(table, keys, blocked, keys[idx])}
 
1270
  return {'code': REFUSAL_HOP_FILTERED, 'path': keys, 'hop': keys[idx],
1271
- 'message': hop_filtered_refusal(table, keys, keys[idx])}
 
1272
  # ⚠ EVERY PREFIX SURVIVED AND THE WHOLE DID NOT. Only reachable if two enumerations disagree
1273
  # about a path they agree about every prefix of; the last hop is the honest thing to name.
1274
  return {'code': REFUSAL_HOP_FILTERED, 'path': keys, 'hop': (keys[-1] if keys else ''),
1275
- 'message': hop_filtered_refusal(table, keys, keys[-1] if keys else '')}
 
1276
 
1277
 
1278
  def wall_refusals(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None, fields_for=None,
1279
  entries=None, open_entries=None, open_fields=None, open_fields_for=None):
1280
  """THE LISTING ANNOTATION: what the wall removed from this table's enumeration, BY NAME.
1281
 
1282
- `[{code, message, path, table?, hop?}]`, a SIBLING of the served list and never a replacement
1283
- for it.
 
1284
 
1285
  β›”β›” AN EMPTY LIST IS NEVER AN ACCEPTABLE ANSWER TO A PERMISSION-FILTERED TRAVERSAL, AND THIS
1286
  IS THE HALF OF C3 THAT IS EASIEST TO MISS. A 400 on a pin covers the request that named ONE
@@ -1306,6 +1601,17 @@ def wall_refusals(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None,
1306
  table, fields=(open_fields if open_fields is not None else fields), defs=defs,
1307
  depth=depth, may_open=None,
1308
  fields_for=(open_fields_for if open_fields_for is not None else fields_for))
 
 
 
 
 
 
 
 
 
 
 
1309
  have = _paths_of(entries)
1310
  out, seen = [], set()
1311
  for entry in open_entries:
@@ -1314,7 +1620,7 @@ def wall_refusals(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None,
1314
  continue
1315
  got = diagnose_path(table, path, fields=fields, defs=defs, may_open=may_open,
1316
  fields_for=fields_for, depth=depth, entries=entries,
1317
- open_entries=open_entries)
1318
  if got.get('code') == REFUSAL_UNKNOWN_VIA:
1319
  continue # cannot happen: `path` came out of `open_entries` itself
1320
  ident = (got.get('code'), got.get('table') or '', got.get('hop') or '')
@@ -1324,5 +1630,6 @@ def wall_refusals(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None,
1324
  out.append(got)
1325
  if not entries and not out:
1326
  out.append({'code': REFUSAL_NO_ROWS, 'path': [],
1327
- 'message': no_related_rows_refusal(table)})
 
1328
  return out
 
59
  #: The three ways a database can be related to another. `via.direction` is always one of these.
60
  DIRECTIONS = ('forward', 'reverse', 'bridge')
61
 
62
+ # ===============================================================================================
63
+ # W54-T37 / CONTRACT C5 / INSTRUCTION 22 - A DATABASE THAT IS DECLARED BUT ABSENT.
64
+ #
65
+ # The owner, verbatim: *"a wall of ... this account may not open `ut_odoo_customers` ... THAT
66
+ # DATABASE DOES NOT EXIST."* He is right and the sentence was lying. `ut_odoo_customers` and
67
+ # `ut_odoo_products` were RETIRED: popped from every tenant document on every sync and replaced by
68
+ # the `customer_data` / `product_data` registry modules. The connector spec still DESCRIBES them
69
+ # (a spec describes a shape, it does not assert a table is materialised), so the enumeration below
70
+ # happily minted edges pointing at them, the route wall failed closed on a key it could not find,
71
+ # and the reader was told about a permission problem that does not exist.
72
+ #
73
+ # TWO REPAIRS, IN THIS ORDER, AND THE FIRST IS THE REAL ONE:
74
+ # 1. an edge whose TARGET is retired is NEVER ENUMERATED, in either direction and in BOTH the
75
+ # walled and the unwalled pass. It is not a tab, so it is not a refusal either.
76
+ # 2. a path that names one ANYWAY earns `retired_target`, which says the database is gone. It is
77
+ # a BACKSTOP, and a backstop that fires often means repair 1 has a hole in it.
78
+ #
79
+ # THE LIST LIVES ABOVE, NOT HERE, AND THAT IS THE WHOLE POINT OF THE REGISTRY. `core` never
80
+ # imports up, so it cannot read `odoo_relational.RETIRED_KEYS`; copying the two keys down here
81
+ # would make a second declaration of the same fact, which is the defect class this repo already
82
+ # names [[one-question-two-normalizers]]. The shape is `core.user_tables.register_connected_prefix`
83
+ # verbatim, down to its comment: the engine pushes its list down rather than this module reaching
84
+ # for it. So THIS SET STARTS EMPTY AND STAYS EMPTY until an app-layer registrar runs.
85
+ #
86
+ # A CONSEQUENCE WORTH STATING: in a process where nothing registered anything (a bare platform
87
+ # gate) the filter is a no-op and every edge is enumerated. That is the honest answer there, since
88
+ # such a process has no way to know which tables a deployment retired.
89
+ # ===============================================================================================
90
+
91
+ #: The table keys that are DECLARED somewhere and ABSENT from this deployment: retired, or never
92
+ #: materialised. Empty by construction. See the banner above before adding a literal to it.
93
+ _RETIRED_TABLES = set()
94
+
95
+
96
+ def register_retired_tables(*keys):
97
+ """Declare table keys that are described somewhere but do not exist as databases.
98
+
99
+ Takes bare keys, an iterable of keys, or any mix, so a registrar can push a whole tuple down in
100
+ one call. Returns the WHOLE registered set, exactly as `register_connected_prefix` does, so the
101
+ caller can assert what it just joined and the write door answers through the read door.
102
+
103
+ A KEY REGISTERED HERE STOPS BEING AN EDGE TARGET. Nothing else changes: rows, definitions and
104
+ permissions are not this module's business, and a key that is merely unreadable by one account
105
+ is a PERMISSION and belongs to the wall, not here.
106
+ """
107
+ for key in keys:
108
+ named = [key] if isinstance(key, str) else list(key or ())
109
+ for name in named:
110
+ text = str(name or '').strip()
111
+ if text:
112
+ _RETIRED_TABLES.add(text)
113
+ return retired_tables()
114
+
115
+
116
+ def retired_tables():
117
+ """The registered absent-table keys. The ONE list a caller may read to name the same set."""
118
+ return frozenset(_RETIRED_TABLES)
119
+
120
+
121
+ def is_retired_table(key):
122
+ """Is `key` a database this deployment declares and does not have?"""
123
+ return str(key or '').strip() in _RETIRED_TABLES
124
+
125
+
126
+ def _live(entries, include_retired=False):
127
+ """Drop every entry whose TARGET is retired. The one filter, applied by every builder.
128
+
129
+ β›” IT FILTERS THE **TARGET**, WHICH COVERS BOTH DIRECTIONS WITH ONE RULE. Outbound, the target
130
+ is the parent the spec names (`ut_odoo_orders` -> `ut_odoo_customers`). Inbound, the target is
131
+ the OTHER table, so a retired spec row whose own links point at a live table (the retired
132
+ customers row names `ut_odoo_agents`) produces a reverse entry on the agents grid whose target
133
+ is the retired table. Both are the same test.
134
+ ⚠ ENUMERATING **FROM** A RETIRED TABLE IS STILL ALLOWED and is deliberately not this rule: the
135
+ edges of such a table are what a diagnosis walks, and refusing to describe them would replace
136
+ one wrong answer with a shorter one.
137
+ """
138
+ if include_retired or not _RETIRED_TABLES:
139
+ return list(entries or ())
140
+ return [e for e in (entries or ()) if not is_retired_table(e.get('target'))]
141
+
142
  #: The identity column of a module grid, as the wire spells it. `customer_data.pid` IS the Odoo
143
  #: `res.partner` id and `ut_odoo_orders.pid` IS the `sale_order` id, so a bridge hanging off `pid`
144
  #: needs no second lookup. `product_data.pid` is NOT an Odoo id (it is `crc32(default_code)`),
 
295
  return out
296
 
297
 
298
+ def forward_links(table, fields, include_retired=False):
299
  """The FORWARD entries for `table`: every `type: "link"` field on it, in field order.
300
 
301
  `fields` is whatever the caller's permission wall handed back, so a link field this account
 
304
 
305
  ⭐ TWO LINKS BETWEEN THE SAME PAIR GIVE TWO ENTRIES, and R2 says so in as many words. The entry
306
  `key` is the FIELD key, not the target key, which is what keeps them apart on the wire.
307
+
308
+ β›” W54-T37 / C5: a field pointing at a RETIRED table is dropped. A tenant document written
309
+ before a table was retired can still carry such a column, and the tab it would draw opens a
310
+ database this deployment does not have.
311
  """
312
  out = []
313
  for field in (fields or ()):
 
323
  target=target, direction='forward',
324
  field=field.get('key'), on=bag.get('on'),
325
  frm=bag.get('from') or IDENTITY_COL))
326
+ return _live(out, include_retired)
327
 
328
 
329
+ def reverse_links(table, defs, include_retired=False):
330
  """The REVERSE entries for `table`: every OTHER table's link field that points at it.
331
 
332
  `defs` is `{key: definition}` as `core.user_tables.all_defs` returns it, already narrowed to
 
336
  β›” A TABLE'S LINK TO ITSELF IS NOT A REVERSE LINK. It is already a forward one, and emitting
337
  both would give the same edge two tabs pointing at the same grid, one of them labelled from
338
  the wrong end.
339
+
340
+ β›” W54-T37 / C5: a definition left behind for a RETIRED table is not a reverse link either.
341
+ Its rows are gone, so the tab would open nothing.
342
  """
343
  me = str(table or '')
344
  out = []
 
363
  # mislabelled `forward` as a negative control for exactly this.
364
  on=bag.get('from') or IDENTITY_COL,
365
  frm=bag.get('on') or IDENTITY_COL))
366
+ return _live(out, include_retired)
367
+
368
 
369
+ def bridge_entries(table, include_retired=False):
370
+ """The BRIDGE entries for `table`, from `BRIDGES` and from nowhere else.
371
 
372
+ ⚠ NO BRIDGE TARGETS A RETIRED TABLE TODAY and the filter is applied anyway, because the day one
373
+ does the alternative is a tab onto a database that is not there. A declared bridge onto an
374
+ absent grain is a DECLARATION BUG, not a served edge, and it should disappear the same way.
375
+ """
376
+ return _live([_entry(key=b['key'], label=b['label'], target=b['target'], direction='bridge',
377
+ on=b['target_col'], frm=b['source_col'], served=b['served'],
378
+ where=b['where'])
379
+ for b in bridges_from(table)], include_retired)
380
 
381
 
382
  def edge_identity(entry):
 
393
  str(via.get('from') or ''), str(entry.get('where') or ''))
394
 
395
 
396
+ def related(table, fields=None, defs=None, include_retired=False):
397
  """THE `/related` ANSWER for one table: forward, then reverse, then bridge.
398
 
399
  `[{key, label, via: {direction, key, field?, on?, from?}, target, served, where?}]`.
 
417
  ⚠ ON A TENANT WITH NO PRE-SET LINKS the bridge is not a duplicate of anything and is offered
418
  unchanged, which is the whole reason the suppression is computed rather than declared.
419
  """
420
+ forward = forward_links(table, fields or (), include_retired)
421
+ reverse = reverse_links(table, defs or {}, include_retired)
422
  seen = {edge_identity(e) for e in forward} | {edge_identity(e) for e in reverse}
423
+ bridges = [b for b in bridge_entries(table, include_retired)
424
+ if edge_identity(b) not in seen]
425
  return forward + reverse + bridges
426
 
427
 
 
827
  return 'many_to_many'
828
 
829
 
830
+ def spec_entries(table, include_retired=False):
831
  """The CONNECTOR-SPEC edges of `table`, in BOTH directions, in `related()`'s entry shape.
832
 
833
  β›”β›” BOTH DIRECTIONS, AND AN OUTBOUND-ONLY READ CANNOT ANSWER THE QUESTION THIS TICKET ASKS.
 
854
  ⚠ `served` TAKES `_entry`'s DEFAULT, exactly as the forward and reverse link FIELDS do. Only
855
  `BRIDGES` carries a measured `served` today, and inventing one per spec edge here would be a
856
  second, unmeasured source for the same judgement.
857
+
858
+ β›”β›” W54-T37 / C5 / INSTRUCTION 22 - THIS IS WHERE THE OWNER'S REFUSAL WALL WAS MINTED, AND THE
859
+ RETIRED FILTER IS THE PRIMARY REPAIR. Four Odoo specs (invoices, orders, order lines, GL lines)
860
+ declare a link at `ut_odoo_customers` and the line grain declares one at `ut_odoo_products`;
861
+ both keys are RETIRED, so the outbound half offered tabs onto databases that do not exist. The
862
+ inbound half is the mirror image: the retired customers spec row carries its own link at
863
+ `ut_odoo_agents`, so the agents grid was offered a reverse tab back onto the absent table.
864
  """
865
  spec = _spec()
866
  me = str(table or '')
 
886
  on=from_col, # the column on the OTHER table
887
  frm=to_col, # the column on THIS one
888
  cardinality=_INVERSE.get(str(cardinality), 'many_to_many')))
889
+ return _live(out, include_retired)
890
 
891
 
892
  def _link_field_cardinalities(table, fields, defs):
 
914
  return out
915
 
916
 
917
+ def one_hop(table, fields=None, defs=None, include_retired=False):
918
  """EVERYTHING ONE NAMED HOP FROM `table`: `related()` plus the connector spec, deduplicated.
919
 
920
  Every entry carries a `cardinality`, taken from the declaration it came with:
 
931
  *"one tab per related table"*. The dedupe is on `edge_identity`, which is target plus both join
932
  columns plus the predicate; read its docstring for why `where` is in there.
933
  """
934
+ base = list(related(table, fields, defs, include_retired))
935
  cards = _link_field_cardinalities(table, fields, defs)
936
  bridge_cards = {b['key']: _bridge_cardinality(b) for b in BRIDGES}
937
  out = []
 
941
  entry['cardinality'] = str(got or 'many_to_many')
942
  out.append(entry)
943
  seen = {edge_identity(e) for e in out}
944
+ for entry in spec_entries(table, include_retired=include_retired):
945
  if edge_identity(entry) in seen:
946
  continue
947
  seen.add(edge_identity(entry))
 
980
  }
981
 
982
 
983
+ def related_paths(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None,
984
+ fields_for=None, include_retired=False):
985
  """C3'S `/related` ANSWER: everything reachable from `table` in at most `depth` NAMED hops.
986
 
987
  `[{key, label, via, target, served, where?, cardinality, path, hops}]`, one-hop entries first
 
1006
 
1007
  β›” A HOP-2 EDGE POINTING BACK AT `table` IS DROPPED. `customer -> orders -> customer` is a round
1008
  trip, not a relation, and offering it would put a tab on the customers grid labelled Customers.
1009
+
1010
+ β›”β›” `include_retired` IS FOR DIAGNOSIS ONLY AND NOTHING SERVES IT. Left False, no hop lands on
1011
+ a table this deployment declares and does not have; set True, the absent hops come back so a
1012
+ caller can say WHICH one a request named. Both passes of the permission diff leave it False,
1013
+ which is what stops an absent edge being reported as a wall removal.
1014
  """
1015
  if depth not in (1, MAX_DEPTH):
1016
  raise ValueError(
1017
  "relation depth is 1 or %d; %r was asked for. The route turns this into a named "
1018
  "refusal rather than a 500" % (MAX_DEPTH, depth))
1019
  table = str(table or '')
1020
+ hop1 = [e for e in one_hop(table, fields, defs, include_retired)
1021
  if may_open is None or may_open(e['target'])]
1022
  out = []
1023
  for entry in hop1:
 
1031
  for first in hop1:
1032
  mid = first['target']
1033
  mid_fields = fields_for(mid) if fields_for is not None else None
1034
+ for second in one_hop(mid, mid_fields, defs, include_retired):
1035
  if second['target'] == table:
1036
  continue
1037
  if may_open is not None and not may_open(second['target']):
 
1139
  # whether it holds rows for this record. The name, and the fact that the door is shut.
1140
  # ══════════════════════════════════════════════════���════════════════════════════════════════════
1141
 
1142
+ #: ⭐ THE THREE R13 ANSWERS, PLUS THE ONE THAT IS NOT A PERMISSION ANSWER AT ALL, PLUS C5'S.
1143
  #: ⚠ `unknown_via` KEEPS THE NAME `routes_grid.grid_related` ALREADY RAISES rather than gaining a
1144
  #: synonym: a fourth spelling of the same refusal would be a client-visible rename dressed as a
1145
  #: feature. `routes_odoo_tables` spells its depth-1 cousin `unknown_relation` and is in another
 
1149
  REFUSAL_HOP_FILTERED = 'hop_filtered'
1150
  REFUSAL_UNKNOWN_VIA = 'unknown_via'
1151
 
1152
+ #: ⭐⭐ W54-T37 / C5's FOURTH ANSWER: the edge names a database this deployment does not have.
1153
+ #: β›” IT IS NOT A PERMISSION ANSWER AND MUST NEVER BE CONFUSED WITH ONE. That confusion IS
1154
+ #: instruction 22: the route wall fails closed on any key it cannot resolve, so an absent table
1155
+ #: came back as `forbidden_table` and the reader was told to ask an administrator for access to a
1156
+ #: database nobody can be granted.
1157
+ REFUSAL_RETIRED_TARGET = 'retired_target'
1158
+
1159
+ #: β›”β›” FIVE ENTRIES, AND C5's *"four wire answers"* IS STILL SATISFIED BY FOUR OF THEM.
1160
+ #: C5 names `no_related_rows`, `forbidden_table`, `hop_filtered` and the new `retired_target`.
1161
+ #: `unknown_via` PREDATES C5 (it is the name `routes_grid.grid_related` has always raised for an
1162
+ #: edge that does not exist at all) and is neither removed nor renamed by it: a fifth spelling of
1163
+ #: an existing refusal would be a client-visible rename dressed as a feature. So the tuple holds
1164
+ #: five and the four C5 names are the ones that are new-or-ruled. A gate reads this rather than
1165
+ #: five literals scattered through two files.
1166
  REFUSAL_CODES = (REFUSAL_NO_ROWS, REFUSAL_FORBIDDEN_TABLE, REFUSAL_HOP_FILTERED,
1167
+ REFUSAL_RETIRED_TARGET, REFUSAL_UNKNOWN_VIA)
1168
 
1169
 
1170
  def _named_path(path):
 
1172
  return ' then '.join(f"'{k}'" for k in (str(p) for p in (path or ())))
1173
 
1174
 
1175
+ # ═══════════════════════════════════════════════════════════════════════════════════════════════
1176
+ # ⭐⭐ W54-T38 / INSTRUCTION 22 / DESIGN.md SECTION 4 β€” TWO STRINGS PER REFUSAL: THE SENTENCE AND
1177
+ # THE DIAGNOSIS. THE SPLIT IS AUTHORED HERE BECAUSE THE CLIENT MAY NOT AUTHOR IT.
1178
+ #
1179
+ # The owner pasted one of these refusals back at us, four times over, off one screen. Every word of
1180
+ # it was TRUE after W54-T37 fixed the cause, and it was still the wrong thing to put on a screen:
1181
+ # DESIGN.md section 4 says *"never over-explain"*, and a sixty-word paragraph repeated once per
1182
+ # removed edge is a wall a reader scrolls past to reach the rows they asked for.
1183
+ #
1184
+ # β›”β›” THE FIX IS NOT TO SHORTEN THE DIAGNOSIS. W53-T18 wrote those paragraphs deliberately, so a
1185
+ # traversal is never served short and silent, and deleting them would trade one defect for the one
1186
+ # they were written against. The fix is that the refusal now carries TWO server-authored strings:
1187
+ #
1188
+ # * `message` β€” ONE SHORT SENTENCE, the thing a reader sees first. It still names whatever R13
1189
+ # and C5 require it to name (the closed table, the filtered hop, the absent database).
1190
+ # * `detail` β€” the FULL diagnosis, word for word what `message` used to be, for the disclosure
1191
+ # the client puts it behind.
1192
+ #
1193
+ # β›” WHY THE SERVER SPLITS IT AND NOT THE CLIENT. `RecordDetail.tsx` already carries the rule in as
1194
+ # many words: *"THE SENTENCE IS STILL THE SERVER'S, WHOLE. The code chooses the treatment; it never
1195
+ # rewrites the words, which would fork one wire contract into two opinions."* A client that cut a
1196
+ # paragraph at its first full stop would be authoring copy out of a regular expression, and the day
1197
+ # a sentence gains a comma the summary line changes with nobody having decided it should.
1198
+ #
1199
+ # ⚠ `message` STAYS POPULATED AND STAYS FIRST, so every existing reader keeps working: the route's
1200
+ # `_refusal_error` copies it into the X2 envelope, and a client that has never heard of `detail`
1201
+ # shows the short sentence and loses only the explanation.
1202
+ # β›” NO EM DASH AND NO EN DASH IN EITHER STRING (standing rule 2). Both reach a screen, and D-653
1203
+ # records that no gate scans a Python string for them, so this is checked by eye and by the
1204
+ # snippet in this ticket's handoff.
1205
+ # ═══════════════════════════════════════════════════════════════════════════════════════════════
1206
+
1207
+
1208
  def no_related_rows_refusal(table, path=None):
1209
  """R13's FIRST answer: everything was open, and there is genuinely nothing on the other side.
1210
 
 
1213
  of R13, so the empty case is spelled out loud and says in as many words that nothing was
1214
  hidden from it.
1215
  β›” NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
1216
+ ⭐ W54-T38: THE SENTENCE, and only the sentence. `no_related_rows_detail` carries what this
1217
+ used to say in full. Read the banner above `_named_path` before shortening either of them.
1218
+ """
1219
+ named = _named_path(path)
1220
+ if named:
1221
+ return f"Nothing is linked through {named} on '{table}'."
1222
+ return f"'{table}' is not linked to any database this account can open."
1223
+
1224
+
1225
+ def no_related_rows_detail(table, path=None):
1226
+ """The DIAGNOSIS behind `no_related_rows_refusal`, for the client's disclosure.
1227
+
1228
+ ⭐ WORD FOR WORD WHAT THE SENTENCE USED TO BE. Nothing was cut: an empty side that says only
1229
+ "nothing is linked" leaves a reader unable to tell it from a wall, which is the whole of R13,
1230
+ so the paragraph that rules that out still exists and is one click away.
1231
+ β›” NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
1232
  """
1233
  named = _named_path(path)
1234
  if named:
1235
+ return (f"The relation reached by {named} on '{table}' is open to this account at every "
1236
  f"hop, and it reaches no rows. Nothing was hidden by permission and no hop was "
1237
+ f"filtered, so there is simply nothing on the other side of it.")
1238
  return (f"'{table}' reaches no other database within {MAX_DEPTH} named hops that this account "
1239
  f"may open, and nothing was removed by permission on the way. Ask an administrator to "
1240
+ f"link it to another database, or open the database you want on its own.")
1241
 
1242
 
1243
  def forbidden_table_refusal(table, path, blocked, hop=None):
 
1251
  could not read at all, so claiming only the first would tell a reader their access was revoked
1252
  when the store had merely hiccupped.
1253
  β›” NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
1254
+ ⭐ W54-T38: THE SENTENCE, and only the sentence. It still NAMES the blocked table, because
1255
+ R13's disclosure is the one thing that may not move behind a disclosure: a reader who cannot
1256
+ see which door is shut has been handed the empty list again. `forbidden_table_detail` carries
1257
+ the pair of causes, the path and the recommendation.
1258
+ ⚠ NO DIGITS AND NO PATH IN THIS ONE. `verify_odoo_relational` asserts that this sentence
1259
+ discloses the table's NAME and nothing else about it, digits included, so the hop keys and the
1260
+ path (which may carry either) stay in the detail where the same leg does not reach.
1261
+ """
1262
+ return (f"This relation passes through '{blocked}', and this account may not open it.")
1263
+
1264
+
1265
+ def forbidden_table_detail(table, path, blocked, hop=None):
1266
+ """The DIAGNOSIS behind `forbidden_table_refusal`, for the client's disclosure.
1267
+
1268
+ ⚠ THE CAUSE IS STILL NAMED AS A PAIR, the posture `routes_odoo_tables._related_pin` takes: the
1269
+ wall is fail-closed and answers False both for a genuine refusal and for a database it could
1270
+ not read at all, so claiming only the first would tell a reader their access was revoked when
1271
+ the store had merely hiccupped.
1272
+ β›” NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
1273
  """
1274
  named = _named_path(path) or 'this relation'
1275
  where = f" at the hop named '{hop}'" if hop else ''
1276
+ return (f"The relation reached by {named} on '{table}' passes through '{blocked}'{where}, and "
1277
  f"this account may not open '{blocked}', either because it is not granted to you or "
1278
  f"because it could not be read just now. The traversal is refused rather than served "
1279
  f"short, so no part of it is silently missing. Ask an administrator for access to "
1280
+ f"'{blocked}', or ask for a relation that does not pass through it.")
1281
+
1282
+
1283
+ def retired_target_refusal(table, path, missing):
1284
+ """C5's FOURTH answer: the relation opens a database this workspace does not have any more.
1285
+
1286
+ β›”β›” IT SAYS THE TRUE CAUSE AND NAMES NO PERMISSION. Instruction 22 is a wall of *"this account
1287
+ may not open `ut_odoo_customers`"* about a table that was retired, so this sentence may not say
1288
+ "not granted to you" and may not send the reader to an administrator for access: there is no
1289
+ access to grant. It names the database and says it is gone.
1290
+ β›” SHORT, ON PURPOSE. One sentence. The long diagnosis belongs behind a disclosure, not in a
1291
+ second wall.
1292
+ ⭐ W54-T38 FINISHED THAT SENTENCE'S OWN NOTE. T37 wrote "short, on purpose" and then shipped a
1293
+ sentence carrying the path and an API pointer, because there was nowhere else to put them yet.
1294
+ There is now: `retired_target_detail`.
1295
+ β›” NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
1296
+ """
1297
+ return f"'{missing}' is no longer part of this workspace."
1298
+
1299
+
1300
+ def retired_target_detail(table, path, missing):
1301
+ """The DIAGNOSIS behind `retired_target_refusal`, for the client's disclosure.
1302
+
1303
+ β›”β›” IT NAMES NO PERMISSION EITHER, and that rule does not weaken one level down. Instruction
1304
+ 22 is a reader being sent to an administrator for access to a database nobody can grant; the
1305
+ same sentence hidden behind a caret would still be that.
1306
+ β›” NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
1307
+ """
1308
+ named = _named_path(path) or 'this relation'
1309
+ return (f"The relation reached by {named} on '{table}' opens '{missing}', which this "
1310
+ f"deployment does not have any more. It was retired and its rows are gone, so there "
1311
+ f"is nothing to show here and nothing to ask anyone for. Ask GET /api/v1/grid/{table}"
1312
+ f"/related for the relations '{table}' still has.")
1313
+
1314
+
1315
+ def first_retired_on_path(table, keys, fields=None, defs=None, depth=MAX_DEPTH, fields_for=None,
1316
+ retired_entries=None):
1317
+ """`(absent_target, hop_key)` for the FIRST hop of `keys` that opens a retired table.
1318
+
1319
+ `('', '')` when the path names none, which is every ordinary path: the enumeration already
1320
+ dropped these edges, so this walk is the BACKSTOP and answering nothing is its normal day.
1321
+
1322
+ ⚠ IT COSTS NOTHING WHERE NOTHING IS REGISTERED. A process with an empty registry cannot have
1323
+ an absent target, so it returns before enumerating anything at all.
1324
+ β›” THE PREFIX WALK IS WHY AN INTERMEDIATE IS COVERED WITHOUT A SPECIAL CASE, exactly as the
1325
+ permission diff below covers it: the intermediate of a two-hop path is the target of its
1326
+ one-hop prefix, so a retired intermediate is found at `idx` 0 and named there.
1327
+ """
1328
+ keys = [str(k) for k in (keys or ())]
1329
+ if not keys or not _RETIRED_TABLES:
1330
+ return ('', '')
1331
+ if retired_entries is None:
1332
+ retired_entries = related_paths(table, fields=fields, defs=defs, depth=depth,
1333
+ may_open=None, fields_for=fields_for,
1334
+ include_retired=True)
1335
+ for idx in range(len(keys)):
1336
+ step = pick_path(retired_entries, keys[:idx + 1])
1337
+ if step is not None and is_retired_table(step.get('target')):
1338
+ return (str(step.get('target')), keys[idx])
1339
+ return ('', '')
1340
 
1341
 
1342
  def hop_filtered_refusal(table, path, hop):
 
1348
  stay open, so the traversal is neither forbidden nor empty. Served as `[]` it would read as
1349
  "this record has nothing here", which is a claim about the business made out of a permission.
1350
  β›” NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
1351
+ ⭐ W54-T38: THE SENTENCE, and only the sentence. It still NAMES the hop for the same reason
1352
+ the forbidden sentence still names the table. `hop_filtered_detail` carries the rest.
1353
+ """
1354
+ return f"The hop named '{hop}' was filtered out for this account."
1355
+
1356
+
1357
+ def hop_filtered_detail(table, path, hop):
1358
+ """The DIAGNOSIS behind `hop_filtered_refusal`, for the client's disclosure.
1359
+
1360
+ ⭐ IT IS THE ONE THAT MOST NEEDS ITS PARAGRAPH KEPT: "the databases are open to you and the
1361
+ link column is not" is not a thing a reader can guess from a short sentence, and served as an
1362
+ empty grid it would read as a claim about the business.
1363
+ β›” NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2).
1364
  """
1365
  named = _named_path(path) or 'this relation'
1366
+ return (f"The hop named '{hop}' of the relation reached by {named} on '{table}' was filtered "
1367
+ f"out for this account. The databases it crosses are open to you. The link column "
1368
  f"this hop is built on is not one you may see, so the hop was removed rather than "
1369
  f"answered empty. Ask an administrator for that column, or ask for a relation that "
1370
+ f"does not use it.")
1371
 
1372
 
1373
  def candidate_paths(table, entries, defs=None, fields_for=None):
 
1436
  them only into the sentence is what `unknown_via_refusal` used to do, and lane E cannot draw a
1437
  retry button out of an English clause.
1438
  β›” NO EM DASH AND NO EN DASH anywhere in `message` (standing rule 2).
1439
+
1440
+ ⭐⭐ W54-T38 β€” AND THIS IS THE LONGEST WALL OF THE FIVE. Measured before this ticket: 1,921
1441
+ characters on `customer_data`, because the enumeration of every candidate with its join
1442
+ columns and retry string is inside the sentence. It splits like the other four: a short
1443
+ `message`, and the whole of what it used to say in `detail`. β›” THE `candidates` ARRAY IS
1444
+ UNTOUCHED and is still the answer a client renders; the prose was never the machine-readable
1445
+ half and C3 says so.
1446
  """
1447
  keys = [str(k) for k in (keys or ())]
1448
  cands = list(candidates or ())
 
1463
  f"account is offered, then send the 'path' of the one you want, one edge key per "
1464
  f"hop")
1465
  return {'code': REFUSAL_UNKNOWN_VIA, 'path': keys, 'candidates': cands,
1466
+ 'message': f"'{table}' offers no relation reached by {named} to this account.",
1467
+ 'detail': (f"'{table}' offers no relation reached by {named} to this account, and "
1468
+ f"nothing was removed by permission on the way, so this is an edge that "
1469
+ f"does not exist rather than one you may not see." + tail)}
1470
 
1471
 
1472
  def _paths_of(entries):
 
1476
 
1477
  def diagnose_path(table, keys, fields=None, defs=None, may_open=None, fields_for=None,
1478
  depth=MAX_DEPTH, entries=None, open_entries=None,
1479
+ open_fields=None, open_fields_for=None, retired_entries=None):
1480
+ """WHY `pick_path` came back None, as one of the named answers.
1481
+
1482
+ `{code, message, detail, table?, hop?}`. ⭐ W54-T38 β€” `message` is ONE SHORT SENTENCE and
1483
+ `detail` is the full diagnosis it used to be; see the banner above `no_related_rows_refusal`
1484
+ for why the split is authored here rather than cut out of a paragraph by the client.
1485
 
1486
  β›”β›” NEVER RAISES AND NEVER RETURNS None. A diagnosis that can itself fail is the fail-open bug
1487
  `routes_grid._may_open` warns about: every branch below ends in a real bag carrying a code from
 
1491
 
1492
  1. the FILTERED enumeration (`may_open` + the caller's field wall). If `keys` resolves in it,
1493
  the path is permitted end to end and reaches nothing: `no_related_rows`.
1494
+ 1b. β›”β›” W54-T37 / C5 - DOES ANY HOP OPEN A DATABASE THIS DEPLOYMENT DOES NOT HAVE? Then
1495
+ `retired_target`, NAMING it. THIS STEP IS ABOVE BOTH OF THE ONES BELOW AND THE ORDER IS
1496
+ THE TICKET: an absent table is absent from both enumerations, so step 2 would have called
1497
+ it an edge that never existed, and the ROUTE's fail-closed wall (which answers False for
1498
+ a key it cannot resolve) would have made step 3 call it a permission. Instruction 22 is
1499
+ the second of those two wrong answers, printed at a reader who was told to ask for access
1500
+ to a database nobody can grant.
1501
  2. the UNFILTERED enumeration (no `may_open`, and the widest field list the caller can offer).
1502
  If `keys` does not resolve THERE either, the edge genuinely does not exist and no wall was
1503
  involved: `unknown_via`, with the candidates, their join columns and the retry strings.
 
1514
  β›” `open_fields` / `open_fields_for` MUST BE A SUPERSET of `fields` / `fields_for`, or step 2
1515
  can call a wall-removed path unknown. The route builds them as a UNION for exactly that reason;
1516
  when they are omitted the diff runs on the table wall alone, which is correct and narrower.
1517
+ β›” `entries` / `open_entries` / `retired_entries` ARE AN OPTIMISATION ONLY. The route has
1518
+ already paid for the first two; a gate hands none and gets the same answer computed from
1519
+ scratch. The third is the absent-target pass, which is skipped outright where no table is
1520
+ registered as absent.
1521
  """
1522
  keys = [str(k) for k in (keys or ())]
1523
  table = str(table or '')
 
1526
  may_open=may_open, fields_for=fields_for)
1527
  if pick_path(entries, keys) is not None:
1528
  return {'code': REFUSAL_NO_ROWS, 'path': keys,
1529
+ 'message': no_related_rows_refusal(table, keys),
1530
+ 'detail': no_related_rows_detail(table, keys)}
1531
+ # β›”β›” BEFORE THE TWO PERMISSION ANSWERS AND BEFORE `unknown_via`. See step 1b above: a table
1532
+ # that is not there is not a permission and not a typo, and saying either was the defect.
1533
+ missing, missing_hop = first_retired_on_path(
1534
+ table, keys, fields=(open_fields if open_fields is not None else fields), defs=defs,
1535
+ depth=depth, fields_for=(open_fields_for if open_fields_for is not None else fields_for),
1536
+ retired_entries=retired_entries)
1537
+ if missing:
1538
+ return {'code': REFUSAL_RETIRED_TARGET, 'path': keys, 'table': missing,
1539
+ 'hop': missing_hop,
1540
+ 'message': retired_target_refusal(table, keys, missing),
1541
+ 'detail': retired_target_detail(table, keys, missing)}
1542
  if open_entries is None:
1543
  open_entries = related_paths(
1544
  table, fields=(open_fields if open_fields is not None else fields), defs=defs,
 
1557
  if blocked and may_open is not None and not may_open(blocked):
1558
  return {'code': REFUSAL_FORBIDDEN_TABLE, 'path': keys, 'table': blocked,
1559
  'hop': keys[idx],
1560
+ 'message': forbidden_table_refusal(table, keys, blocked, keys[idx]),
1561
+ 'detail': forbidden_table_detail(table, keys, blocked, keys[idx])}
1562
  return {'code': REFUSAL_HOP_FILTERED, 'path': keys, 'hop': keys[idx],
1563
+ 'message': hop_filtered_refusal(table, keys, keys[idx]),
1564
+ 'detail': hop_filtered_detail(table, keys, keys[idx])}
1565
  # ⚠ EVERY PREFIX SURVIVED AND THE WHOLE DID NOT. Only reachable if two enumerations disagree
1566
  # about a path they agree about every prefix of; the last hop is the honest thing to name.
1567
  return {'code': REFUSAL_HOP_FILTERED, 'path': keys, 'hop': (keys[-1] if keys else ''),
1568
+ 'message': hop_filtered_refusal(table, keys, keys[-1] if keys else ''),
1569
+ 'detail': hop_filtered_detail(table, keys, keys[-1] if keys else '')}
1570
 
1571
 
1572
  def wall_refusals(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None, fields_for=None,
1573
  entries=None, open_entries=None, open_fields=None, open_fields_for=None):
1574
  """THE LISTING ANNOTATION: what the wall removed from this table's enumeration, BY NAME.
1575
 
1576
+ `[{code, message, detail, path, table?, hop?}]`, a SIBLING of the served list and never a
1577
+ replacement for it. ⭐ W54-T38 β€” `message` is the short sentence, `detail` the diagnosis behind
1578
+ the client's disclosure.
1579
 
1580
  β›”β›” AN EMPTY LIST IS NEVER AN ACCEPTABLE ANSWER TO A PERMISSION-FILTERED TRAVERSAL, AND THIS
1581
  IS THE HALF OF C3 THAT IS EASIEST TO MISS. A 400 on a pin covers the request that named ONE
 
1601
  table, fields=(open_fields if open_fields is not None else fields), defs=defs,
1602
  depth=depth, may_open=None,
1603
  fields_for=(open_fields_for if open_fields_for is not None else fields_for))
1604
+ # β›” ONE absent-target pass for the WHOLE listing, not one per removed path. Every path below
1605
+ # comes out of `open_entries`, which never carries an absent target, so this walk is expected
1606
+ # to find nothing; computing it per path would pay for a full enumeration per refusal to learn
1607
+ # that. ⚠ Skipped entirely where nothing is registered as absent.
1608
+ retired_entries = None
1609
+ if _RETIRED_TABLES:
1610
+ retired_entries = related_paths(
1611
+ table, fields=(open_fields if open_fields is not None else fields), defs=defs,
1612
+ depth=depth, may_open=None,
1613
+ fields_for=(open_fields_for if open_fields_for is not None else fields_for),
1614
+ include_retired=True)
1615
  have = _paths_of(entries)
1616
  out, seen = [], set()
1617
  for entry in open_entries:
 
1620
  continue
1621
  got = diagnose_path(table, path, fields=fields, defs=defs, may_open=may_open,
1622
  fields_for=fields_for, depth=depth, entries=entries,
1623
+ open_entries=open_entries, retired_entries=retired_entries)
1624
  if got.get('code') == REFUSAL_UNKNOWN_VIA:
1625
  continue # cannot happen: `path` came out of `open_entries` itself
1626
  ident = (got.get('code'), got.get('table') or '', got.get('hop') or '')
 
1630
  out.append(got)
1631
  if not entries and not out:
1632
  out.append({'code': REFUSAL_NO_ROWS, 'path': [],
1633
+ 'message': no_related_rows_refusal(table),
1634
+ 'detail': no_related_rows_detail(table)})
1635
  return out
platform/core/sheets.py CHANGED
@@ -98,6 +98,24 @@ CELL_ALIGNS = ("left", "center", "right")
98
  CELL_VALIGNS = ("top", "middle", "bottom")
99
  CELL_SIZES = ("s", "m", "l", "xl")
100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  #: The style keys A1 and C2 name. Anything else is DROPPED, in silence and on purpose; see
102
  #: `_clean_style` for why that is not the same decision as an unknown `format.kind`.
103
  _STYLE_MARKS = ("bold", "italic", "underline")
@@ -107,6 +125,28 @@ _BORDER_SIDES = ("top", "right", "bottom", "left")
107
  #: outlives every layout change, exactly as a stored hex outlives a palette.
108
  _MAX_INDENT = 8
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  #: C2's custom format code. ⚠ THE CAPS ARE PART OF THE VOCABULARY, not a guess: a format code is
111
  #: interpreted by the client's formatter, so an unbounded one is an unbounded parse, and Excel's
112
  #: own grammar holds at most four sections (positive; negative; zero; text).
@@ -123,13 +163,57 @@ _MAX_VALIDATION_ENTRY = 200
123
  SHEET_RULE_OPS = ("gt", "lt", "gte", "lte", "eq", "neq", "between", "contains", "empty",
124
  "notEmpty")
125
 
 
 
 
 
 
 
 
 
 
 
 
126
  #: The style keys a conditional format rule may repaint. A rule is a PAINT, never a format: it
127
  #: cannot change how a number reads, so it carries no `format`.
128
  _RULE_STYLE_MARKS = ("bold",)
129
  _RULE_STYLE_COLOURS = ("fill", "color")
130
 
131
- #: The chart kinds W49-T08 draws. Mirrored in `types.ts::SheetChartSpec`.
132
- SHEET_CHART_KINDS = ("bar", "line", "area", "donut")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
  _MAX_RULES = 100
135
  _MAX_HIDDEN = 5000
@@ -152,8 +236,8 @@ _MAX_DECIMALS = 10
152
  #: column letters and seven row digits, and `a1.ts` agrees with it; 702 is the last TWO letter
153
  #: column (ZZ) and 100000 rows is what glide's virtualised scroller stays comfortable inside. A
154
  #: sheet at the ceiling is still far above `_MAX_CELLS_PER_SHEET`, so content runs out first.
155
- DEFAULT_SHEET_COLS = 26
156
- DEFAULT_SHEET_ROWS = 200
157
  DEFAULT_COL_WIDTH = 120
158
  MIN_SHEET_COLS = 1
159
  MIN_SHEET_ROWS = 1
@@ -453,9 +537,38 @@ def _clean_style(raw):
453
  if steps:
454
  out["indent"] = steps
455
 
456
- size = _text(raw.get("size"), 4)
457
- if size in CELL_SIZES and size != "m":
458
- out["size"] = size
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
 
460
  fmt = _clean_format(raw.get("format"))
461
  if fmt:
@@ -499,6 +612,56 @@ def _clean_validation(raw):
499
  return {"list": out} if out else None
500
 
501
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
502
  def clean_cell(raw, addr=""):
503
  """Normalize ONE cell, or raise `SheetRefusal` with a named code.
504
 
@@ -541,6 +704,15 @@ def clean_cell(raw, addr=""):
541
  validation = _clean_validation(raw.get("validation"))
542
  if validation:
543
  cell["validation"] = validation
 
 
 
 
 
 
 
 
 
544
  return cell
545
 
546
  if raw.get("text") is not None:
@@ -567,6 +739,21 @@ def clean_cell(raw, addr=""):
567
  if raw.get("refreshed_at") is not None:
568
  cell["refreshed_at"] = _text(raw.get("refreshed_at"), 120)
569
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
570
  #: C2: the in-cell list. Normalized before the style so a refusing style still reports first.
571
  validation = _clean_validation(raw.get("validation"))
572
  if validation:
@@ -734,15 +921,43 @@ def _clean_rule_style(raw):
734
  return out
735
 
736
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
737
  def _clean_rules(raw):
738
  """C2's conditional format rules for one tab, at most `_MAX_RULES` of them.
739
 
740
  β›” AN OP OUTSIDE `SHEET_RULE_OPS` IS REFUSED BY NAME, for `_clean_format`'s reason: a rule
741
  whose operator nothing can evaluate never fires, so dropping it would leave a person looking
742
- at a sheet they believe is painted by a rule that is not there.
743
-
744
- ⚠ THE COUNT IS CLAMPED rather than refused: the rules past the cap are ones nobody could see
745
- the effect of, and refusing would make a sheet that can never be saved again.
 
 
 
 
 
746
  """
747
  if raw is None:
748
  return []
@@ -757,11 +972,23 @@ def _clean_rules(raw):
757
  raise SheetRefusal(
758
  "sheet_rule_op_unknown",
759
  "A sheet rule condition must be one of " + ", ".join(SHEET_RULE_OPS) + ".")
 
 
 
 
 
760
  rect = _clean_range(row.get("range"))
761
  if rect is None:
762
  continue
763
  rule = {"id": _text(row.get("id"), _MAX_ID) or uuid.uuid4().hex[:12],
764
  "range": rect, "op": op, "style": _clean_rule_style(row.get("style"))}
 
 
 
 
 
 
 
765
  #: ⚠ `empty` and `notEmpty` take NO operand, and carrying one would store a rule whose
766
  #: text says it compares against something it can never read.
767
  if op not in ("empty", "notEmpty"):
@@ -851,8 +1078,15 @@ def _clean_sheet(raw, index=0):
851
 
852
  β›” EVERY KEY THIS FUNCTION DOES NOT NAME IS DROPPED, and that is worth knowing before adding
853
  one: the return below is a fresh dict, not an amended copy of `raw`. A2's four geometry keys
854
- and C2's five strata are named here for exactly that reason, and `charts` is named because it
855
- was the one this rule silently ate until W51-T21 (D-640).
 
 
 
 
 
 
 
856
  """
857
  if not isinstance(raw, dict):
858
  raise SheetRefusal("sheet_not_an_object", "A sheet must be an object.")
@@ -868,28 +1102,34 @@ def _clean_sheet(raw, index=0):
868
  #: silently un-described.
869
  sheet = {"id": sid, "name": name, "cols": cols, "rows": rows,
870
  "cells": _clean_cells(raw.get("cells"), sheet_name=name)}
871
- widths = _clean_col_widths(raw.get("colWidths"), cols)
872
- if widths:
873
- sheet["colWidths"] = widths
874
- freeze = _clean_freeze(raw.get("freeze"), cols, rows)
875
- if freeze:
876
- sheet["freeze"] = freeze
877
- #: C2's five strata. Each is written only when it holds something, for `_clean_style`'s
878
- #: reason: a tab with no rules and a tab with `rules: []` read identically, so one of them is
879
- #: what gets stored and a reload compares equal to the thing it saved.
880
- rules = _clean_rules(raw.get("rules"))
881
- if rules:
882
- sheet["rules"] = rules
883
- for key, what in (("hiddenRows", "rows"), ("hiddenCols", "columns")):
884
- hidden = _clean_hidden(raw.get(key), what)
885
- if hidden:
886
- sheet[key] = hidden
887
- charts = _clean_charts(raw.get("charts"))
888
- if charts:
889
- sheet["charts"] = charts
890
- imported = _clean_imported(raw.get("imported"))
891
- if imported:
892
- sheet["imported"] = imported
 
 
 
 
 
 
893
  return sheet
894
 
895
 
 
98
  CELL_VALIGNS = ("top", "middle", "bottom")
99
  CELL_SIZES = ("s", "m", "l", "xl")
100
 
101
+ #: ⭐⭐ WAVE 54 / R10 + R11 - THE TYPEFACE AND THE POINT SIZE. Mirrored in
102
+ #: `types.ts::CELL_FONTS` / `DEFAULT_CELL_FONT` / `DEFAULT_FONT_PT` / `MIN_FONT_PT` / `MAX_FONT_PT`.
103
+ #:
104
+ #: R10: a cell's typeface is USER DATA, exactly as its fill colour is; the app's own chrome stays
105
+ #: Inter and that is a different decision. The list is closed and every face in it is one a machine
106
+ #: already has, because the client imports no webfont; the bare NAME is what is stored and the
107
+ #: client resolves it to a full stack at paint time, for the reason a colour is stored as a token.
108
+ #:
109
+ #: R11: the `size` slot carries EITHER one of the four step names above OR a point size, and never
110
+ #: a second field. `DEFAULT_FONT_PT` is `m`, in points, and both are stored as an ABSENCE.
111
+ CELL_FONTS = (
112
+ "Inter", "Arial", "Georgia", "Times New Roman", "Courier New", "Verdana", "Trebuchet MS",
113
+ )
114
+ DEFAULT_CELL_FONT = "Inter"
115
+ DEFAULT_FONT_PT = 10
116
+ MIN_FONT_PT = 6
117
+ MAX_FONT_PT = 96
118
+
119
  #: The style keys A1 and C2 name. Anything else is DROPPED, in silence and on purpose; see
120
  #: `_clean_style` for why that is not the same decision as an unknown `format.kind`.
121
  _STYLE_MARKS = ("bold", "italic", "underline")
 
125
  #: outlives every layout change, exactly as a stored hex outlives a palette.
126
  _MAX_INDENT = 8
127
 
128
+ #: Wave 54: how far a cell's value may be turned, in DEGREES. Excel's own range, and it is signed
129
+ #: because turning a header up and turning it down are two different requests. Zero is upright and
130
+ #: is stored as an ABSENCE, for `_clean_style`'s falsey-mark reason. Mirrored in
131
+ #: `types.ts::MIN_TEXT_ROTATION` / `MAX_TEXT_ROTATION`.
132
+ MIN_TEXT_ROTATION = -90
133
+ MAX_TEXT_ROTATION = 90
134
+
135
+ #: Wave 54: a cell may carry a LINK and a NOTE, and neither is a value. A note is never counted as
136
+ #: hand typed, never reaches a formula and never becomes a cell's display; a link says what its
137
+ #: target IS, because a web address, an A1 address and a tab name are opened by three different
138
+ #: doors. Mirrored in `types.ts::Cell.link` / `Cell.note`.
139
+ CELL_LINK_KINDS = ("url", "cell", "sheet")
140
+ _MAX_LINK_HREF = 512
141
+ _MAX_CELL_NOTE = 1000
142
+
143
+ #: Wave 54: a cell may also carry a SPARKLINE, a picture of a range drawn inside the cell itself.
144
+ #: It is CELL level and not tab level, unlike a chart, because that is what it is: the renderer is
145
+ #: `web/src/sheet/sparkline.ts`, called from `SheetGrid.tsx::paintCell` with the cell in hand, so
146
+ #: a tab-level array would have to be searched per cell on every paint. The three kinds are
147
+ #: Excel's own. Mirrored in `types.ts::SPARKLINE_KINDS` / `CellSparkline`.
148
+ SPARKLINE_KINDS = ("line", "column", "winloss")
149
+
150
  #: C2's custom format code. ⚠ THE CAPS ARE PART OF THE VOCABULARY, not a guess: a format code is
151
  #: interpreted by the client's formatter, so an unbounded one is an unbounded parse, and Excel's
152
  #: own grammar holds at most four sections (positive; negative; zero; text).
 
163
  SHEET_RULE_OPS = ("gt", "lt", "gte", "lte", "eq", "neq", "between", "contains", "empty",
164
  "notEmpty")
165
 
166
+ #: β›”β›” W54-T05's THREE RULE KINDS, and the SAME refusal discipline the ten operators get. A
167
+ #: `cell` rule is a condition and a flat style; a `scale` bands its value across a stored low..high
168
+ #: range; a `bar` draws a proportional rectangle inside the cell. A kind nothing can paint is
169
+ #: refused by name rather than dropped, because dropping it would silently turn a colour scale into
170
+ #: a highlight rule reading `between`, which is a DIFFERENT paint than the one somebody asked for.
171
+ #:
172
+ #: ⭐ `cell` IS STORED AS AN ABSENCE, exactly as `wrap: false` and `indent: 0` are: it is what
173
+ #: every rule written before this ticket already is, so writing the word onto them would make a
174
+ #: reload compare unequal to the save. Mirrored in `web/src/sheet/types.ts::SHEET_RULE_KINDS`.
175
+ SHEET_RULE_KINDS = ("cell", "scale", "bar")
176
+
177
  #: The style keys a conditional format rule may repaint. A rule is a PAINT, never a format: it
178
  #: cannot change how a number reads, so it carries no `format`.
179
  _RULE_STYLE_MARKS = ("bold",)
180
  _RULE_STYLE_COLOURS = ("fill", "color")
181
 
182
+ #: β›”β›” THE CHART KINDS A DOCUMENT MAY HOLD, which is NOT the same list as the chart kinds a
183
+ #: renderer can draw, and the two were one list until wave 54 made the difference matter.
184
+ #: `_clean_charts` drops a chart whose kind is outside this tuple, so a kind missing from here is
185
+ #: a picture somebody made that is gone on the next read, in silence: exactly D-640's mechanism,
186
+ #: one level down. This tuple is therefore the STORAGE vocabulary and it is mirrored, name for
187
+ #: name and in this order, by `types.ts::SheetChartSpec.kind`.
188
+ #:
189
+ #: ⚠ `types.ts::SHEET_CHART_DRAWN_KINDS` IS A DIFFERENT AND NARROWER THING: a CAPABILITY list,
190
+ #: naming the kinds the client can put on a canvas today. A kind stored here and not drawn there
191
+ #: is a chart the document keeps safely while its renderer is built. The reverse, a kind drawn
192
+ #: but not stored here, is the defect, and it is what widening this tuple prevents.
193
+ SHEET_CHART_KINDS = ("bar", "line", "area", "donut", "column", "pie", "scatter", "combo")
194
+
195
+ #: β›”β›” D-640's MECHANISM, STATED. THIS IS EVERY KEY A CLEANED TAB MAY CARRY, and a key that is
196
+ #: not named here is DELETED on the next save, in silence, with nothing going red: `_clean_sheet`
197
+ #: returns a FRESH dict rather than an amended copy of what it was handed, so the document saves,
198
+ #: the tab is valid, and whatever the client put in the unnamed slot is simply not in it. That is
199
+ #: how `charts` was eaten between W49-T08 and W51-T21, and it is how the NEXT slot added to a tab
200
+ #: gets eaten unless its name is added to this tuple in the same change that adds it.
201
+ #:
202
+ #: ⭐ THE SET IS THE FUNCTION'S OWN RULER. `_clean_sheet` emits its optional strata by walking
203
+ #: this tuple, so the two cannot drift apart by an edit to one of them, and `verify_sheet.py`
204
+ #: section 1 drives the real cleaner with a tab carrying every stratum and asserts it returns
205
+ #: nothing outside this set. Removing `charts` from here reds that leg, which is the negative
206
+ #: control D-640 is closed with.
207
+ #:
208
+ #: The order is the order a cleaned tab reads in: identity, then A2's geometry, then C2's strata.
209
+ SHEET_TAB_KEYS = ("id", "name", "cols", "rows", "cells", "colWidths", "freeze",
210
+ "rules", "hiddenRows", "hiddenCols", "charts", "imported")
211
+
212
+ #: The keys above that `_clean_sheet` writes UNCONDITIONALLY. Every other member of
213
+ #: `SHEET_TAB_KEYS` is written only when it holds something, for `_clean_style`'s reason: a tab
214
+ #: with no rules and a tab with `rules: []` read identically, so only one of them is stored and a
215
+ #: reload compares equal to the thing it saved.
216
+ SHEET_TAB_ALWAYS_KEYS = ("id", "name", "cols", "rows", "cells")
217
 
218
  _MAX_RULES = 100
219
  _MAX_HIDDEN = 5000
 
236
  #: column letters and seven row digits, and `a1.ts` agrees with it; 702 is the last TWO letter
237
  #: column (ZZ) and 100000 rows is what glide's virtualised scroller stays comfortable inside. A
238
  #: sheet at the ceiling is still far above `_MAX_CELLS_PER_SHEET`, so content runs out first.
239
+ DEFAULT_SHEET_COLS = 200
240
+ DEFAULT_SHEET_ROWS = 10000
241
  DEFAULT_COL_WIDTH = 120
242
  MIN_SHEET_COLS = 1
243
  MIN_SHEET_ROWS = 1
 
537
  if steps:
538
  out["indent"] = steps
539
 
540
+ #: ⭐⭐ R11: THE SAME SLOT, TWO SHAPES, AND THE ORDER OF THE BRANCHES IS THE WHOLE OF IT.
541
+ #: `_text` stringifies anything it is handed, so reading a point size through it would turn 12
542
+ #: into "12", find it outside the four step names and drop it in silence: a size the person
543
+ #: picked, gone on the next read with nothing to say so. The type is decided FIRST, and a step
544
+ #: name still round trips exactly as it always did. A point size is CLAMPED, not refused, for
545
+ #: the rotation's reason below, and the default is stored as an absence just as `m` is.
546
+ size = raw.get("size")
547
+ if isinstance(size, str):
548
+ step = _text(size, 4)
549
+ if step in CELL_SIZES and step != "m":
550
+ out["size"] = step
551
+ elif not isinstance(size, bool) and isinstance(size, (int, float)):
552
+ points = max(MIN_FONT_PT, min(MAX_FONT_PT, int(round(size))))
553
+ if points != DEFAULT_FONT_PT:
554
+ out["size"] = points
555
+
556
+ #: R10's typeface. A name outside the closed list is DROPPED in silence, which is this
557
+ #: cleaner's house rule for a decoration the client cannot promise to paint; the default face
558
+ #: is an absence, so a cell set back to it is the cell it was.
559
+ font = _text(raw.get("font"), 40)
560
+ if font in CELL_FONTS and font != DEFAULT_CELL_FONT:
561
+ out["font"] = font
562
+
563
+ #: Wave 54's turn, clamped rather than refused, exactly as the indent is: a rotation is a
564
+ #: presentation, so 400 degrees is somebody asking for the most turn there is, not a document
565
+ #: that has to be rejected. Upright is stored as an absence, so an unrotated cell is byte for
566
+ #: byte the cell it was before somebody turned it and turned it back.
567
+ rotation = raw.get("textRotation")
568
+ if not isinstance(rotation, bool) and isinstance(rotation, (int, float)):
569
+ degrees = max(MIN_TEXT_ROTATION, min(MAX_TEXT_ROTATION, int(rotation)))
570
+ if degrees:
571
+ out["textRotation"] = degrees
572
 
573
  fmt = _clean_format(raw.get("format"))
574
  if fmt:
 
612
  return {"list": out} if out else None
613
 
614
 
615
+ def _clean_link(raw):
616
+ """Wave 54's cell link `{href, kind}`, or None when nothing survives.
617
+
618
+ ⚠ BOTH HALVES OR NEITHER. A link with a target and no kind cannot be opened, because the kind
619
+ is what decides WHICH door opens it: a web address, an A1 address on this workbook, and a tab
620
+ by name are three different acts. Storing half of one would leave a cell wearing an
621
+ affordance that does nothing when it is clicked.
622
+
623
+ ⚠ THE HREF IS CLAMPED, NOT PARSED. This module stores documents; deciding whether a URL is
624
+ reachable, or whether `Sheet2!B7` exists, belongs to the door that opens it, which can say so
625
+ at the moment somebody clicks.
626
+ """
627
+ if not isinstance(raw, dict):
628
+ return None
629
+ kind = _text(raw.get("kind"), 12)
630
+ href = _text(raw.get("href"), _MAX_LINK_HREF)
631
+ if kind not in CELL_LINK_KINDS or not href:
632
+ return None
633
+ return {"href": href, "kind": kind}
634
+
635
+
636
+ def _clean_sparkline(raw):
637
+ """Wave 54's in-cell sparkline `{kind, range}`, or None when nothing survives.
638
+
639
+ ⚠ BOTH HALVES OR NEITHER, for `_clean_link`'s reason. A sparkline with a range and no kind
640
+ cannot be drawn, because the kind is what decides WHICH picture is drawn over those numbers: a
641
+ line, a column run and a win/loss bar say three different things about the same range. Storing
642
+ half of one would leave a cell that claims to hold a picture nothing can put on a canvas.
643
+
644
+ ⚠ IT IS DROPPED WHEN MALFORMED, NEVER REFUSED, which is the link's decision and not the format
645
+ code's: a sparkline does not change what any cell READS AS, so a broken one is a missing
646
+ picture and never a wrong number on a screen. Refusing would 400 a whole workbook save over a
647
+ decoration.
648
+
649
+ ⭐ THE RANGE IS `_clean_range`'s, so a sparkline's rectangle is spelled the same way a chart's
650
+ and a rule's are. It takes `"B2:D40"`, the single cell `"B2"` and the rectangle dict, and it
651
+ stores the rectangle: a document with two spellings of one rectangle is a document every later
652
+ reader has to branch on.
653
+ """
654
+ if not isinstance(raw, dict):
655
+ return None
656
+ kind = _text(raw.get("kind"), 20)
657
+ if kind not in SPARKLINE_KINDS:
658
+ return None
659
+ rect = _clean_range(raw.get("range"))
660
+ if rect is None:
661
+ return None
662
+ return {"kind": kind, "range": rect}
663
+
664
+
665
  def clean_cell(raw, addr=""):
666
  """Normalize ONE cell, or raise `SheetRefusal` with a named code.
667
 
 
704
  validation = _clean_validation(raw.get("validation"))
705
  if validation:
706
  cell["validation"] = validation
707
+ #: β›” THE SPARKLINE SURVIVES THIS BRANCH, AND LEAVING IT OUT WOULD BE THE COMMON CASE
708
+ #: RATHER THAN THE EDGE ONE. A sparkline cell usually holds no text at all: somebody
709
+ #: paints a picture of the row beside it and types nothing, which is precisely an
710
+ #: `empty` cell. A picture is not content in the sense this branch strips, because it
711
+ #: has no value, is never hand typed and never reaches a formula, so it belongs with
712
+ #: the style rather than with the text that is dropped here.
713
+ sparkline = _clean_sparkline(raw.get("sparkline"))
714
+ if sparkline:
715
+ cell["sparkline"] = sparkline
716
  return cell
717
 
718
  if raw.get("text") is not None:
 
739
  if raw.get("refreshed_at") is not None:
740
  cell["refreshed_at"] = _text(raw.get("refreshed_at"), 120)
741
 
742
+ #: Wave 54's link, note and sparkline. All three are DROPPED when malformed rather than
743
+ #: refused, which is the validation list's decision and not the format code's: none of them
744
+ #: changes what the cell READS AS, so a broken link is a missing affordance and a broken
745
+ #: sparkline is a missing picture, never a wrong number on a screen.
746
+ link = _clean_link(raw.get("link"))
747
+ if link:
748
+ cell["link"] = link
749
+ if raw.get("note") is not None:
750
+ note = _text(raw.get("note"), _MAX_CELL_NOTE)
751
+ if note:
752
+ cell["note"] = note
753
+ sparkline = _clean_sparkline(raw.get("sparkline"))
754
+ if sparkline:
755
+ cell["sparkline"] = sparkline
756
+
757
  #: C2: the in-cell list. Normalized before the style so a refusing style still reports first.
758
  validation = _clean_validation(raw.get("validation"))
759
  if validation:
 
921
  return out
922
 
923
 
924
+ def _clean_rule_scale(raw):
925
+ """A COLOUR SCALE's two end TOKENS, or None.
926
+
927
+ β›” BOTH ENDS OR NEITHER. One end alone names no ramp at all, and storing half of one would
928
+ leave the client looking up a pair that cannot match and falling back to a default scale the
929
+ person never chose. The tokens go through the same `_COLOUR` guard `_clean_rule_style` uses,
930
+ so nothing free form reaches a canvas `fillStyle` from a stored document.
931
+
932
+ ⚠ THE SCALE'S BOUNDS ARE NOT HERE. They ride `value` and `value2` on the rule itself, which
933
+ `_clean_rules` already persists for every op that takes operands, so a colour scale needed no
934
+ new numeric slot at all.
935
+ """
936
+ if not isinstance(raw, dict):
937
+ return None
938
+ out = {}
939
+ for key in ("low", "high"):
940
+ token = _text(raw.get(key), 40)
941
+ if not token or not _COLOUR.match(token):
942
+ return None
943
+ out[key] = token
944
+ return out
945
+
946
+
947
  def _clean_rules(raw):
948
  """C2's conditional format rules for one tab, at most `_MAX_RULES` of them.
949
 
950
  β›” AN OP OUTSIDE `SHEET_RULE_OPS` IS REFUSED BY NAME, for `_clean_format`'s reason: a rule
951
  whose operator nothing can evaluate never fires, so dropping it would leave a person looking
952
+ at a sheet they believe is painted by a rule that is not there. A KIND outside
953
+ `SHEET_RULE_KINDS` is refused the same way, and for a sharper version of the same reason: a
954
+ dropped kind does not stop the rule firing, it makes it fire as a DIFFERENT paint.
955
+
956
+ β›”β›” AND THIS IS THE D-640 SHAPE, SO READ IT BEFORE ADDING A FIELD. Each rule below is built
957
+ EXPLICITLY, key by key, which means a field the client starts writing and this function does
958
+ not learn is dropped on the very next read: the feature would delete itself one save later,
959
+ with the editor still listing what it wrote. W54-T05's `kind` and `scale` are here because
960
+ that ticket added them to both halves in one commit.
961
  """
962
  if raw is None:
963
  return []
 
972
  raise SheetRefusal(
973
  "sheet_rule_op_unknown",
974
  "A sheet rule condition must be one of " + ", ".join(SHEET_RULE_OPS) + ".")
975
+ kind = _text(row.get("kind"), 20) or "cell"
976
+ if kind not in SHEET_RULE_KINDS:
977
+ raise SheetRefusal(
978
+ "sheet_rule_kind_unknown",
979
+ "A sheet rule kind must be one of " + ", ".join(SHEET_RULE_KINDS) + ".")
980
  rect = _clean_range(row.get("range"))
981
  if rect is None:
982
  continue
983
  rule = {"id": _text(row.get("id"), _MAX_ID) or uuid.uuid4().hex[:12],
984
  "range": rect, "op": op, "style": _clean_rule_style(row.get("style"))}
985
+ #: ⭐ THE DEFAULT KIND IS AN ABSENCE (see `SHEET_RULE_KINDS`), so a rule that was turned
986
+ #: into a colour scale and back is byte for byte the rule it started as.
987
+ if kind != "cell":
988
+ rule["kind"] = kind
989
+ scale = _clean_rule_scale(row.get("scale"))
990
+ if scale:
991
+ rule["scale"] = scale
992
  #: ⚠ `empty` and `notEmpty` take NO operand, and carrying one would store a rule whose
993
  #: text says it compares against something it can never read.
994
  if op not in ("empty", "notEmpty"):
 
1078
 
1079
  β›” EVERY KEY THIS FUNCTION DOES NOT NAME IS DROPPED, and that is worth knowing before adding
1080
  one: the return below is a fresh dict, not an amended copy of `raw`. A2's four geometry keys
1081
+ and C2's five strata are named for exactly that reason, and `charts` is named because it was
1082
+ the one this rule silently ate until W51-T21 (D-640).
1083
+
1084
+ ⭐⭐ THE NAMES LIVE IN `SHEET_TAB_KEYS` AND THIS FUNCTION EMITS THROUGH IT, which is D-640
1085
+ closed rather than patched. Before wave 54 the set was implicit: it existed only as the
1086
+ literals typed into this body, so nothing stated it, nothing could gate it, and the only way
1087
+ to learn that a new slot was being eaten was to save a tab and reload it. Walking the tuple
1088
+ means a stratum computed here but missing from the tuple is never written, and
1089
+ `verify_sheet.py` reds when the two disagree, so the next slot cannot repeat the defect.
1090
  """
1091
  if not isinstance(raw, dict):
1092
  raise SheetRefusal("sheet_not_an_object", "A sheet must be an object.")
 
1102
  #: silently un-described.
1103
  sheet = {"id": sid, "name": name, "cols": cols, "rows": rows,
1104
  "cells": _clean_cells(raw.get("cells"), sheet_name=name)}
1105
+
1106
+ #: ⚠ THE ORDER OF THIS DICT IS THE ORDER THE CLEANERS RUN IN, and it is load bearing: two of
1107
+ #: them REFUSE by name (`_clean_rules` on an unknown op, `_clean_imported` on a record that is
1108
+ #: not an object), so a reordering here would change which refusal a caller sees first when a
1109
+ #: tab is wrong in two places at once.
1110
+ optional = {
1111
+ "colWidths": _clean_col_widths(raw.get("colWidths"), cols),
1112
+ "freeze": _clean_freeze(raw.get("freeze"), cols, rows),
1113
+ "rules": _clean_rules(raw.get("rules")),
1114
+ "hiddenRows": _clean_hidden(raw.get("hiddenRows"), "rows"),
1115
+ "hiddenCols": _clean_hidden(raw.get("hiddenCols"), "columns"),
1116
+ "charts": _clean_charts(raw.get("charts")),
1117
+ "imported": _clean_imported(raw.get("imported")),
1118
+ }
1119
+
1120
+ #: β›” THE WALK IS THROUGH `SHEET_TAB_KEYS`, NOT THROUGH `optional`, AND THAT IS THE WHOLE
1121
+ #: POINT OF D-640'S FIX. A stratum cleaned above but never added to the tuple is dropped here
1122
+ #: rather than written, which is the same silent loss as before EXCEPT that the gate now sees
1123
+ #: it: `verify_sheet.py` drives a tab carrying every stratum and compares what comes back
1124
+ #: against the tuple, so the disagreement reds instead of shipping.
1125
+ #:
1126
+ #: Each is written only when it holds something, for `_clean_style`'s reason: a tab with no
1127
+ #: rules and a tab with `rules: []` read identically, so only one of them is stored and a
1128
+ #: reload compares equal to the thing it saved.
1129
+ for key in SHEET_TAB_KEYS:
1130
+ value = optional.get(key)
1131
+ if value:
1132
+ sheet[key] = value
1133
  return sheet
1134
 
1135
 
platform/core/table_store.py CHANGED
@@ -2133,6 +2133,34 @@ class TableStore:
2133
 
2134
  self._update(username, _drop, shared=lambda shared_fields: shared_fields.pop(key, None))
2135
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2136
  def _tenant_wide_keys(self):
2137
  """The columns of THIS table whose values live in the tenant-wide stratum.
2138
 
@@ -2148,7 +2176,7 @@ class TableStore:
2148
  """
2149
  try:
2150
  import core.shared_overlay as shared_overlay
2151
- return set(shared_overlay.fields(self.table_key, st=self._st) or ())
2152
  except Exception: # noqa: BLE001
2153
  return set()
2154
 
@@ -2186,7 +2214,7 @@ class TableStore:
2186
  # ⚠ `st=self._st`, NEVER the module default. The two strata must resolve to the SAME
2187
  # tenant handle, or a value written by one is invisible to the other and the user's
2188
  # edit vanishes the moment they save it (`_ProductTableStore` records the same rule).
2189
- shared_overlay.put_cells(self.table_key, pid, shared, st=self._st)
2190
  if not personal:
2191
  return
2192
 
@@ -2223,7 +2251,7 @@ class TableStore:
2223
  if shared:
2224
  import core.shared_overlay as shared_overlay
2225
  shared_overlay.put_cells_and_choice_options(
2226
- self.table_key, pid, shared, shared_additions, st=self._st)
2227
 
2228
  if not personal:
2229
  return
 
2133
 
2134
  self._update(username, _drop, shared=lambda shared_fields: shared_fields.pop(key, None))
2135
 
2136
+ def _shared_stratum_key(self):
2137
+ """WHICH document holds this table's tenant-wide stratum β€” D-643.
2138
+
2139
+ β›”β›” THE BUG THIS CLOSES, AND THE DIRECTION IT IS CLOSED IN. Every call below used to hand
2140
+ `self.table_key` straight to `core.shared_overlay`, whose `bucket()` appends `__shared`.
2141
+ For a user database that key is `ut_<x>_table_workspace`, so the three sites addressed
2142
+ `ut_<x>_table_workspace__shared` while the CREATE door
2143
+ (`core.grid_events._field_share_keys`, the authority) mints and every one of the seven
2144
+ readers reads the BARE `ut_<x>__shared`. `_tenant_wide_keys` therefore answered the empty
2145
+ set for every `ut_*` table that has a shared column, and `patch_overlay` routed a
2146
+ tenant-wide value into the caller's own per-user member.
2147
+
2148
+ β›” THIS IS THE OPPOSITE OF THE CHANGE WAVE 50 REFUSED, and the difference matters because
2149
+ the two look alike. Its lane D was asked to make `_field_storage_keys` resolve the
2150
+ WORKSPACE spelling, and refused: that would have pointed the share dialog at a bucket
2151
+ nothing writes and orphaned every `ut_*` shared column with every gate green
2152
+ ([[the-ut-shared-bucket-is-bare-on-purpose]]). This aligns `TableStore` DOWN to the bare
2153
+ spelling the create door and the readers already use, which is the same rule stated once.
2154
+
2155
+ ⚠ ONLY THE `ut_` BRANCH MOVES. `product_table_workspace` and `customer_table_workspace`
2156
+ are correct exactly as they stand (a gate asserts them), so every other key is returned
2157
+ unchanged.
2158
+ """
2159
+ raw = str(self.table_key or '')
2160
+ if raw.startswith('ut_') and raw.endswith('_table_workspace'):
2161
+ return raw[:-len('_table_workspace')]
2162
+ return raw
2163
+
2164
  def _tenant_wide_keys(self):
2165
  """The columns of THIS table whose values live in the tenant-wide stratum.
2166
 
 
2176
  """
2177
  try:
2178
  import core.shared_overlay as shared_overlay
2179
+ return set(shared_overlay.fields(self._shared_stratum_key(), st=self._st) or ())
2180
  except Exception: # noqa: BLE001
2181
  return set()
2182
 
 
2214
  # ⚠ `st=self._st`, NEVER the module default. The two strata must resolve to the SAME
2215
  # tenant handle, or a value written by one is invisible to the other and the user's
2216
  # edit vanishes the moment they save it (`_ProductTableStore` records the same rule).
2217
+ shared_overlay.put_cells(self._shared_stratum_key(), pid, shared, st=self._st)
2218
  if not personal:
2219
  return
2220
 
 
2251
  if shared:
2252
  import core.shared_overlay as shared_overlay
2253
  shared_overlay.put_cells_and_choice_options(
2254
+ self._shared_stratum_key(), pid, shared, shared_additions, st=self._st)
2255
 
2256
  if not personal:
2257
  return
platform/harness/runtime.py CHANGED
@@ -307,22 +307,40 @@ class TenantRuntime:
307
  return self._store().delete_path(self.store_key(path_in_repo))
308
 
309
  # ---------------------------------------------------------------- the Odoo source (R3)
310
- def odoo_source(self):
311
  """THIS tenant's Odoo connector, or None β€” the keychain CUTOVER's resolution seam
312
  (2026-08-04; `keychain.odoo_creds` was previously called by nothing but its test).
313
 
314
  Resolution, fail-closed:
315
- 1. a keychain `odoo` entry (any tenant) β†’ a connector bound to THOSE creds;
316
- 2. tenant #0 with an empty/locked keychain β†’ its compiled env connector (R3's
317
- "live with env fallback", which is what keeps Royal working unchanged);
 
 
318
  3. anyone else β†’ None. NEVER the environment: env is tenant #0's connection, and
319
  handing it to another tenant is the leak this method exists to prevent.
320
 
 
 
 
 
 
 
 
 
321
  Rebuilt per call on purpose β€” `core.odoo` caches the CLIENT per (slug, creds
322
  fingerprint), so this stays cheap while a rotated key reconnects on the next call."""
323
  import core.keychain as keychain
 
324
  try:
325
- creds = keychain.odoo_creds(self)
 
 
 
 
 
 
 
326
  except Exception: # locked or unreadable keychain β€” fall through, fail closed
327
  creds = None
328
  if creds:
@@ -332,34 +350,49 @@ class TenantRuntime:
332
  return OdooConnector(tenant_slug=self.key, creds=creds,
333
  scope={"team_ids": list(bus.values()) or None,
334
  "team_names": {v: k for k, v in bus.items()} or None})
 
 
 
 
335
  if self.key == "royal-imports":
336
  return (getattr(self.tenant, "sources", {}) or {}).get("odoo")
337
  return None
338
 
339
  # ------------------------------------------------------- the connector PAUSE (D-10, wave 24)
340
- def odoo_flag_key(self):
341
  """WHICH connector flag governs this tenant's Odoo β€” the key `connectors[<k>].paused`
342
  is stored under, or None when nothing would serve.
343
 
344
  THE SAME RESOLUTION AS `odoo_source()` ABOVE, expressed as an identity instead of a
345
- client: first unlocked keychain `odoo` entry, else tenant #0's compiled env source, else
346
- nothing. It lives here so there is ONE resolver β€” `routes_keychain._resolved_odoo_key`
347
- was a second copy of these three rules in the API layer, and a pause flag written against
348
- one resolution and read against the other freezes nothing while reporting success.
 
 
 
 
 
 
 
 
 
349
  """
350
  import core.keychain as keychain
 
351
  try:
352
- entries = keychain.list_entries(self)
353
  except Exception:
354
- entries = []
355
- first_odoo = next((e["id"] for e in entries if e.get("type") == "odoo"), None)
356
- if first_odoo and keychain.unlocked():
357
- return first_odoo
 
358
  if self.key == "royal-imports" and os.environ.get("ODOO_URL"):
359
  return ENV_ODOO_FLAG_KEY
360
  return None
361
 
362
- def odoo_paused(self):
363
  """Is THIS tenant's RESOLVED Odoo source paused?
364
 
365
  ⚠ RESOLVED, not "any entry" β€” pausing an entry that is not the one serving freezes
@@ -367,9 +400,13 @@ class TenantRuntime:
367
  False, because a store hiccup must not freeze a live surface. That policy is inherited
368
  from the API-layer function this one replaced, deliberately, so there is one answer to
369
  "what happens when we cannot tell" rather than two that can disagree.
 
 
 
 
370
  """
371
  try:
372
- flag_key = self.odoo_flag_key()
373
  if not flag_key:
374
  return False
375
  flags = self.get(CONNECTOR_FLAGS_KEY) or {}
 
307
  return self._store().delete_path(self.store_key(path_in_repo))
308
 
309
  # ---------------------------------------------------------------- the Odoo source (R3)
310
+ def odoo_source(self, connection_id=None):
311
  """THIS tenant's Odoo connector, or None β€” the keychain CUTOVER's resolution seam
312
  (2026-08-04; `keychain.odoo_creds` was previously called by nothing but its test).
313
 
314
  Resolution, fail-closed:
315
+ 1. the keychain `odoo` connection NAMED by `connection_id` (W54-T45 / R4), or the
316
+ tenant's DESIGNATED DEFAULT connection when no id is named β†’ a connector bound to
317
+ THOSE creds;
318
+ 2. tenant #0 with an empty/locked keychain and NO id named β†’ its compiled env
319
+ connector (R3's "live with env fallback", which keeps Royal working unchanged);
320
  3. anyone else β†’ None. NEVER the environment: env is tenant #0's connection, and
321
  handing it to another tenant is the leak this method exists to prevent.
322
 
323
+ β›”β›” W54-T45 β€” THE ENV FALLBACK NARROWS HERE AND MUST NEVER WIDEN. A caller that NAMES a
324
+ connection and gets nothing back is answered None, full stop: not the default connection,
325
+ not a sibling, and above all not tenant #0's `.env`. Under R4 an agency holds one Odoo
326
+ connection per client, and under R7 that isolation is strict β€” a named-but-unresolvable
327
+ connection quietly falling through to the environment would serve tenant #0's own Odoo to
328
+ a question asked about somebody else's books, with nothing red anywhere. Leg (2) is
329
+ reachable only on the UNNAMED path, which is exactly the pre-wave behaviour.
330
+
331
  Rebuilt per call on purpose β€” `core.odoo` caches the CLIENT per (slug, creds
332
  fingerprint), so this stays cheap while a rotated key reconnects on the next call."""
333
  import core.keychain as keychain
334
+ named = connection_id is not None
335
  try:
336
+ # ⚠ THE UNNAMED PATH IS SPELLED AS THE PRE-WAVE CALL, VERBATIM, and the branch is not
337
+ # decoration: `verify_api`'s R11 leg pins the literal `keychain.odoo_creds(self)` in
338
+ # this method's source as its proof that the resolver is KEYCHAIN-FIRST. Writing only
339
+ # the two-argument form would have turned that gate red for a reason that has nothing
340
+ # to do with the rule it guards, in a file this lane may not edit. The two arms are
341
+ # the same question; the left one is the one every existing caller asks.
342
+ creds = (keychain.odoo_creds(self) if not named
343
+ else keychain.odoo_creds(self, connection_id))
344
  except Exception: # locked or unreadable keychain β€” fall through, fail closed
345
  creds = None
346
  if creds:
 
350
  return OdooConnector(tenant_slug=self.key, creds=creds,
351
  scope={"team_ids": list(bus.values()) or None,
352
  "team_names": {v: k for k, v in bus.items()} or None})
353
+ # β›” THE NAMED LEG STOPS HERE. See the docstring: an explicit connection that did not
354
+ # resolve is None, never the environment and never another connection.
355
+ if named:
356
+ return None
357
  if self.key == "royal-imports":
358
  return (getattr(self.tenant, "sources", {}) or {}).get("odoo")
359
  return None
360
 
361
  # ------------------------------------------------------- the connector PAUSE (D-10, wave 24)
362
+ def odoo_flag_key(self, connection_id=None):
363
  """WHICH connector flag governs this tenant's Odoo β€” the key `connectors[<k>].paused`
364
  is stored under, or None when nothing would serve.
365
 
366
  THE SAME RESOLUTION AS `odoo_source()` ABOVE, expressed as an identity instead of a
367
+ client: the keychain `odoo` connection named (or the designated default when none is),
368
+ else tenant #0's compiled env source, else nothing. It lives here so there is ONE
369
+ resolver β€” `routes_keychain._resolved_odoo_key` was a second copy of these three rules in
370
+ the API layer, and a pause flag written against one resolution and read against the other
371
+ freezes nothing while reporting success.
372
+
373
+ β›”β›” W54-T45 β€” AND THE INLINE WALK IS GONE, WHICH IS WHAT MADE THE SENTENCE ABOVE TRUE.
374
+ This method claimed to be the one resolver while carrying its own copy of "the first
375
+ `odoo` entry", so `keychain` and `runtime` each decided which connection serves. Both now
376
+ ask `keychain.resolve_connection_id`, which decrypts nothing β€” a pause flag has to resolve
377
+ on a LOCKED keychain, which is why this is an identity call and not a credential one.
378
+ β›” A NAMED CONNECTION THAT DOES NOT RESOLVE IS None, exactly as in `odoo_source`: pausing
379
+ by a connection id must never silently address tenant #0's environment source instead.
380
  """
381
  import core.keychain as keychain
382
+ named = connection_id is not None
383
  try:
384
+ resolved = keychain.resolve_connection_id(self, "odoo", connection_id)
385
  except Exception:
386
+ resolved = None
387
+ if resolved and keychain.unlocked():
388
+ return resolved
389
+ if named:
390
+ return None
391
  if self.key == "royal-imports" and os.environ.get("ODOO_URL"):
392
  return ENV_ODOO_FLAG_KEY
393
  return None
394
 
395
+ def odoo_paused(self, connection_id=None):
396
  """Is THIS tenant's RESOLVED Odoo source paused?
397
 
398
  ⚠ RESOLVED, not "any entry" β€” pausing an entry that is not the one serving freezes
 
400
  False, because a store hiccup must not freeze a live surface. That policy is inherited
401
  from the API-layer function this one replaced, deliberately, so there is one answer to
402
  "what happens when we cannot tell" rather than two that can disagree.
403
+
404
+ ⭐ W54-T45 β€” `connection_id` passes straight through to `odoo_flag_key`, so "is the
405
+ connection serving THIS client paused" is answerable per connection under R4. No id keeps
406
+ meaning the tenant's designated default, which is every existing caller.
407
  """
408
  try:
409
+ flag_key = self.odoo_flag_key(connection_id)
410
  if not flag_key:
411
  return False
412
  flags = self.get(CONNECTOR_FLAGS_KEY) or {}
platform/odoo_client.py CHANGED
@@ -61,12 +61,28 @@ class OdooClient:
61
  def __init__(self, creds=None):
62
  """`creds` (R3 keychain cutover): an explicit {url, db, user, api_key} dict β€” a TENANT'S
63
  stored credentials β€” wins over the environment. None keeps the env/.env behavior every
64
- existing caller relies on (tenant #0's connection)."""
 
 
 
 
 
 
 
 
 
 
 
 
65
  creds = creds or {}
66
- self.url = str(creds.get('url') or os.environ.get('ODOO_URL', '')).rstrip('/')
67
- self.db = str(creds.get('db') or os.environ.get('ODOO_DB', ''))
68
- self.user = str(creds.get('user') or os.environ.get('ODOO_USER', ''))
69
- self.api_key = str(creds.get('api_key') or os.environ.get('ODOO_API_KEY', ''))
 
 
 
 
70
  missing = [k for k, v in [('ODOO_URL', self.url), ('ODOO_DB', self.db),
71
  ('ODOO_USER', self.user), ('ODOO_API_KEY', self.api_key)] if not v]
72
  if missing:
 
61
  def __init__(self, creds=None):
62
  """`creds` (R3 keychain cutover): an explicit {url, db, user, api_key} dict β€” a TENANT'S
63
  stored credentials β€” wins over the environment. None keeps the env/.env behavior every
64
+ existing caller relies on (tenant #0's connection).
65
+
66
+ β›”β›” W54-T45 / R7 β€” IT IS ALL-OR-NOTHING, AND THE PER-FIELD VERSION WAS A REAL LEAK SHAPE.
67
+ Each field used to read `creds.get(k) or os.environ.get(...)` INDIVIDUALLY, so an explicit
68
+ connection whose stored `db` was blank or missing silently inherited tenant #0's `ODOO_DB`
69
+ while keeping the caller's `url`, `user` and `api_key`. Under R4 an agency holds one Odoo
70
+ connection per client and under R7 that isolation is strict: a half-environment client is
71
+ one client's question authenticated against another's database, and it does not raise β€”
72
+ it returns real, plausible, wrong rows. So a supplied `creds` is used WHOLE, and a field
73
+ it is missing is MISSING (the `RuntimeError` below names it) rather than borrowed. With no
74
+ `creds` at all the environment builds the client exactly as it always did.
75
+ """
76
+ from_env = creds is None
77
  creds = creds or {}
78
+
79
+ def _f(key, env_key):
80
+ return str((os.environ.get(env_key, '') if from_env else creds.get(key)) or '')
81
+
82
+ self.url = _f('url', 'ODOO_URL').rstrip('/')
83
+ self.db = _f('db', 'ODOO_DB')
84
+ self.user = _f('user', 'ODOO_USER')
85
+ self.api_key = _f('api_key', 'ODOO_API_KEY')
86
  missing = [k for k, v in [('ODOO_URL', self.url), ('ODOO_DB', self.db),
87
  ('ODOO_USER', self.user), ('ODOO_API_KEY', self.api_key)] if not v]
88
  if missing:
web/src/connectors/ConnectorsPage.tsx CHANGED
@@ -169,18 +169,16 @@ export interface ConnectorRow {
169
  */
170
  scope?: string;
171
  /**
172
- * ⭐⭐ W53-T29 Β· RULING R6 β€” WHICH SCOPES THIS SOURCE MAY EVER CARRY, e.g. `["business"]` for
173
- * Odoo and both words for Gmail. The server's one declaration of it is
174
- * `routes_keychain.allowed_scopes`, built on the same `TENANT_WIDE_TYPES` tuple its refusals
175
- * are built on, and every directory row is stamped with it.
176
  *
177
- * β›” IT IS THE SOURCE'S RULE, NOT THIS READER'S PERMISSION β€” that is `canBusiness` on the
178
- * payload. The Company / Mine toggle needs both: eligibility decides which side a card COULD
179
- * appear on, permission decides whether the Company side exists for this reader at all.
180
- *
181
- * Absent (an older server) β‡’ treated as both, which is the honest degradation: this field only
182
- * ever NARROWS a tier, so a missing one leaves the page exactly as it was before this ticket
183
- * rather than hiding a connection the reader really holds.
184
  */
185
  allowedScopes?: string[];
186
  /** What the admin will be asked for β€” shown where the decision is made, not in a tour. */
@@ -245,13 +243,14 @@ type Load =
245
  gaps: ConnectorGap[];
246
  /** W49-T18: the category rail, exactly as the server counted it. */
247
  chips: DirectoryCategory[];
248
- /**
249
- * ⭐⭐ W53-T29 Β· RULING R6 β€” MAY THIS READER SEE THE COMPANY SIDE AT ALL. The server's
250
- * `bool(session.admin)`, under the name `routes_keychain` has used for it since W32-T11.
251
- * ⚠ FALSE UNLESS THE PAYLOAD SAYS OTHERWISE, and false on any failure: the safe direction
252
- * for an admin-only control is closed, the same discipline `canPull` keeps below.
 
 
253
  */
254
- canBusiness: boolean;
255
  }
256
  | { phase: "error"; message: string };
257
 
@@ -353,11 +352,13 @@ export function parseDirectory(body: unknown): ConnectorRow[] {
353
  ...(str(c.startUrl) ? { startUrl: str(c.startUrl) } : {}),
354
  ...(str(c.note) ? { note: str(c.note) } : {}),
355
  ...(str(c.scope) ? { scope: str(c.scope) } : {}),
356
- // ⭐⭐ W53-T29 / R6 β€” the source's declared eligibility, COPIED off the wire like every
357
- // other field here. `parseCategoryTags` is this file's one reader for a list of words from
358
- // the server (strings only, blanks dropped, deduped); a second identical parser would be a
359
- // second place for "read a string list" to go wrong. An empty or absent list yields no key
360
- // at all, which the tier filters read as "unrestricted".
 
 
361
  ...(parseCategoryTags(c.allowedScopes).length
362
  ? { allowedScopes: parseCategoryTags(c.allowedScopes) }
363
  : {}),
@@ -614,21 +615,17 @@ export default function ConnectorsPage({
614
  * spends money is closed.
615
  */
616
  const [canPull, setCanPull] = useState(false);
617
- /**
618
- * ⭐⭐ W53-T29 Β· OWNER RULING R6 β€” WHICH SIDE OF THE COMPANY / MINE TOGGLE IS SHOWING, HELD IN
619
- * THE SERVER'S OWN TWO WORDS.
620
- *
621
- * β›” `business` / `personal` RATHER THAN `company` / `mine`, and that is the whole discipline of
622
- * this ticket. `routes_keychain.py::SCOPES` already names these two ideas and every row on the
623
- * wire is filed by them; a second client-only pair of words for the same split would be one
624
- * rename away from a tier that filters on a word nothing sends. "Company" and "Mine" are the
625
- * ruling's LABELS, which is a copy decision, and they live in the buttons below and nowhere
626
- * else. Read as a string for the same reason `state` is (the wave-9 law).
627
  *
628
- * ⚠ MEANINGLESS FOR A NON-ADMIN, who never sees the control that changes it: their view is
629
- * decided structurally below, not by this value.
 
 
630
  */
631
- const [scopeTier, setScopeTier] = useState("business");
632
 
633
  useEffect(() => {
634
  let dead = false;
@@ -638,7 +635,7 @@ export default function ConnectorsPage({
638
  credentials: CREDENTIALS,
639
  });
640
  const body = (await res.json().catch(() => null)) as
641
- | { error?: { message?: string }; canBusiness?: unknown }
642
  | null;
643
  if (dead) return;
644
  if (!res.ok) {
@@ -653,11 +650,6 @@ export default function ConnectorsPage({
653
  rows: parseDirectory(body),
654
  gaps: parseGaps(body),
655
  chips: parseCategories(body),
656
- // ⭐⭐ W53-T29 / R6 β€” a LITERAL `true` is permission and anything else is not. An older
657
- // server sends nothing here and this reader gets no Company side, which is the safe way
658
- // round: the toggle appearing for a member would be the ruling broken, while a missing
659
- // toggle for an admin is a page that still lists every connection they have.
660
- canBusiness: (body as { canBusiness?: unknown } | null)?.canBusiness === true,
661
  });
662
  } catch {
663
  if (!dead) setLoad({ phase: "error", message: "Cannot reach the server." });
@@ -721,62 +713,21 @@ export default function ConnectorsPage({
721
  const databaseRows = rows.filter((r) => r.spawns_tables === true);
722
  const otherRows = rows.filter((r) => r.spawns_tables !== true);
723
  /**
724
- * ⭐⭐ W52-T02 Β· RULING R2 / CONTRACT C2 β€” WHO A CONNECTION IS FOR, ON THE PAGE ITSELF.
725
  *
726
- * R2, verbatim: "The module splits into 'Connected for the company' and 'Connected by you'."
727
- * A connector belongs to the second section when the SIGNED-IN USER holds a `personal` keychain
728
- * entry for it β€” `row.scope === "personal"`, the server's own two-word vocabulary
729
- * (`routes_keychain.py::SCOPES`), never a client union (the wave-9 law). Every other CONNECTED
730
- * card is the company's.
731
  *
732
- * ⚠ ONLY A CONNECTED CARD IS PARTITIONED HERE. An `available`/`planned`/`catalogue` row is not a
733
- * connection yet, so filing it under "Connected for the company" would claim a connection this
734
- * workspace does not have; it keeps its one home in the Databases / Other sources catalog below.
735
  *
736
- * ⚠ TWO DIFFERENT PARTITIONS OF THE SAME ROW SET, DELIBERATELY NOT MERGED WITH THE ONE ABOVE. R1
737
- * (W52-T01) tiers every card by whether it spawns tables; R2 tiers CONNECTED cards by who owns
738
- * the connection. A connected Odoo row therefore belongs to "Databases" above AND to "Connected
739
- * for the company" here, because the two headings answer different questions about it.
740
  */
741
  const connectedRows = rows.filter((r) => r.state === "connected");
742
- /**
743
- * ⭐⭐ W53-T29 Β· OWNER RULING R6 β€” TWO QUESTIONS PER CARD, AND BOTH ARE ASKED.
744
- *
745
- * `row.scope` is what this connection WAS STORED AS; `row.allowedScopes` is what its SOURCE may
746
- * ever be (`routes_keychain.allowed_scopes`, derived from the same `TENANT_WIDE_TYPES` tuple the
747
- * server's refusals are derived from). A tier needs both: without the second, one stray or
748
- * legacy `scope` value would put Odoo under Mine, and Odoo is the credential this whole
749
- * workspace's databases are read through.
750
- *
751
- * ⚠ IT ONLY EVER NARROWS. A row that carries no `allowedScopes` (an older server) is treated as
752
- * unrestricted, so the worst an absent declaration can do is leave the page as it was.
753
- */
754
- const eligible = (row: ConnectorRow, scope: string) =>
755
- !row.allowedScopes || row.allowedScopes.includes(scope);
756
- const companyRows = connectedRows.filter(
757
- (r) => r.scope !== "personal" && eligible(r, "business"),
758
- );
759
- const personalRows = connectedRows.filter(
760
- (r) => r.scope === "personal" && eligible(r, "personal"),
761
- );
762
- /**
763
- * ⭐⭐ W53-T29 Β· OWNER RULING R6 β€” THE NON-ADMIN CASE IS STRUCTURAL, NOT A HIDDEN BUTTON.
764
- *
765
- * R6, verbatim: *"A non-admin does not see the Company side at all; the toggle itself is hidden
766
- * for them."* So `showCompany` cannot be reached without `canBusiness` and `showPersonal` is
767
- * unconditionally true without it: a member sees their own connections and no toggle, and no
768
- * sequence of clicks, stale state or hot reload can produce a Company section for them, because
769
- * there is no state in which one renders. Hiding a control is not a permission check, which is
770
- * why the SERVER refuses a member's business-scoped create as well
771
- * (`routes_keychain.add_key` -> 403 `not_admin`).
772
- *
773
- * ⚠ THE TOGGLE NEEDS SOMETHING TO TOGGLE. With no connected card at all it renders nothing
774
- * rather than two chips over an empty page, the same rule the tier headings already keep.
775
- */
776
- const canBusiness = load.phase === "ready" && load.canBusiness;
777
- const showCompany = canBusiness && scopeTier !== "personal";
778
- const showPersonal = !canBusiness || scopeTier === "personal";
779
- const showScopeToggle = canBusiness && connectedRows.length > 0;
780
  // ⚠ Resolved against `allRows`, not the filtered list: typing in the search box while a modal is
781
  // open must not close the modal out from under the reader.
782
  const openRow = allRows.find((row) => row.key === openKey);
@@ -853,93 +804,29 @@ export default function ConnectorsPage({
853
  ) : null}
854
 
855
  {/*
856
- ⭐⭐ W52-T01 Β· RULING R1 / CONTRACT C1 β€” THE TWO HEADED SECTIONS.
857
 
858
- β›” EACH SECTION RENDERS ONLY WHEN IT HOLDS A CARD. A chip or a search term that empties
859
- one tier must not leave a heading standing over nothing β€” `rows.length === 0` above
860
- already covers "neither tier has anything", so this is the one-tier-emptied case one
861
- interaction later, and the same honesty rule the empty-state message already keeps.
862
-
863
- ⚠ SAME `ConnectorCard`, NOT A FORK. Both loops pass the identical props; only which array
864
- they map is different, so a connector's card behaves exactly as it did before this ticket
865
- wherever it lands.
866
- */}
867
- {/*
868
- ⭐⭐ W52-T02 Β· RULING R2 / CONTRACT C2 β€” THE TWO OWNERSHIP SECTIONS.
869
 
870
- β›” EACH RENDERS ONLY WHEN IT HOLDS A CARD, the same rule the Databases / Other sources
871
- pair below already keeps: a chip or a search term that empties one tier must not leave a
872
- heading standing over nothing.
873
 
874
- ⚠ SAME `ConnectorCard`, NOT A FORK β€” see the note on `companyRows`/`personalRows` above for
875
- why a card can appear here AND in the catalog tiers below.
876
  */}
877
- {/*
878
- ⭐⭐ W53-T29 Β· OWNER RULING R6 β€” THE COMPANY / MINE TOGGLE, AND ONLY AN ADMIN HAS ONE.
879
-
880
- β›” THE SAME CONTROL SHAPE THE CATEGORY RAIL ALREADY USES (`conn-chips` / `conn-chip` /
881
- `is-on`, styled in `styles/wave49/connectors.css`). DESIGN.md Β§4: a filter rail keeps one
882
- control shape, and this ticket ships no stylesheet, so a class invented here would render
883
- as unstyled native chrome.
884
- β›” REAL BUTTONS, NOT A DIV. `aria-pressed` carries the selected state to a screen reader
885
- and `type="button"` keeps it off any form; the visible word IS the accessible name, which
886
- is why neither carries an `aria-label` that would say something else.
887
- */}
888
- {showScopeToggle ? (
889
- <div className="conn-chips" role="group" aria-label="Which connections to show">
890
- <button
891
- type="button"
892
- className={"conn-chip" + (showCompany ? " is-on" : "")}
893
- aria-pressed={showCompany}
894
- onClick={() => setScopeTier("business")}
895
- >
896
- <span className="conn-chip-name">Company</span>
897
- </button>
898
- <button
899
- type="button"
900
- className={"conn-chip" + (showCompany ? "" : " is-on")}
901
- aria-pressed={!showCompany}
902
- onClick={() => setScopeTier("personal")}
903
- >
904
- <span className="conn-chip-name">Mine</span>
905
- </button>
906
- </div>
907
- ) : null}
908
- {/* ONE line and the way out, the same shape the empty grid above already uses: a side of
909
- the toggle with nothing on it must say so, or the reader reads the silence as a page
910
- that failed to load. */}
911
- {showScopeToggle && (showCompany ? companyRows.length === 0 : personalRows.length === 0) ? (
912
- <p className="conn-note">
913
- {showCompany
914
- ? "No connection is shared with the whole company yet."
915
- : "You have no personal connections yet."}
916
- </p>
917
- ) : null}
918
- {showCompany && companyRows.length > 0 ? (
919
- <section className="conn-tier" aria-labelledby="conn-tier-company-heading">
920
- <h2 id="conn-tier-company-heading" className="conn-tier-heading">
921
- Connected for the company
922
- </h2>
923
- <div className="conn-grid">
924
- {companyRows.map((row) => (
925
- <ConnectorCard
926
- key={row.key}
927
- row={row}
928
- onKeychain={onKeychain}
929
- onOpen={() => setOpenKey(row.key)}
930
- onPullReviews={pullHandler(row)}
931
- />
932
- ))}
933
- </div>
934
- </section>
935
- ) : null}
936
- {showPersonal && personalRows.length > 0 ? (
937
- <section className="conn-tier" aria-labelledby="conn-tier-personal-heading">
938
- <h2 id="conn-tier-personal-heading" className="conn-tier-heading">
939
- Connected by you
940
  </h2>
941
  <div className="conn-grid">
942
- {personalRows.map((row) => (
943
  <ConnectorCard
944
  key={row.key}
945
  row={row}
@@ -951,6 +838,18 @@ export default function ConnectorsPage({
951
  </div>
952
  </section>
953
  ) : null}
 
 
 
 
 
 
 
 
 
 
 
 
954
  {databaseRows.length > 0 ? (
955
  <section className="conn-tier" aria-labelledby="conn-tier-databases-heading">
956
  <h2 id="conn-tier-databases-heading" className="conn-tier-heading">
 
169
  */
170
  scope?: string;
171
  /**
172
+ * WHICH SCOPES THIS SOURCE MAY EVER CARRY, e.g. `["business"]` for Odoo and both words for
173
+ * Gmail. The server's one declaration of it is `routes_keychain.allowed_scopes`, built on the
174
+ * same `TENANT_WIDE_TYPES` tuple its refusals are built on, and every directory row is stamped
175
+ * with it.
176
  *
177
+ * β›” IT IS THE SOURCE'S RULE, NOT THIS READER'S PERMISSION, and since WAVE 54 Β· RULING R4 no
178
+ * section on this page branches on it: the Company / Mine toggle that read it is withdrawn.
179
+ * The field is still read off the wire because the server still declares it and the keychain
180
+ * surface in Settings still decides a scope with it. This page lists connections; it no longer
181
+ * sorts them by who they belong to.
 
 
182
  */
183
  allowedScopes?: string[];
184
  /** What the admin will be asked for β€” shown where the decision is made, not in a tour. */
 
243
  gaps: ConnectorGap[];
244
  /** W49-T18: the category rail, exactly as the server counted it. */
245
  chips: DirectoryCategory[];
246
+ /*
247
+ * β›”β›” THE ADMIN PERMISSION FLAG STOOD HERE AND IS DELETED BY W54-T42 Β· RULING R4
248
+ * (2026-09-06). It was the field the Company / Mine toggle branched on, and the toggle is
249
+ * withdrawn, so a permission this page reads and never uses would be one edit away from
250
+ * reviving a wall the owner removed. The server still sends it on the directory payload and
251
+ * `settings/SettingsModal.tsx` still reads it where a scope is actually chosen; what is gone
252
+ * is this page's copy, and the gate scan in `verify_schema_overlay.py` keeps it gone.
253
  */
 
254
  }
255
  | { phase: "error"; message: string };
256
 
 
352
  ...(str(c.startUrl) ? { startUrl: str(c.startUrl) } : {}),
353
  ...(str(c.note) ? { note: str(c.note) } : {}),
354
  ...(str(c.scope) ? { scope: str(c.scope) } : {}),
355
+ // The source's declared eligibility, COPIED off the wire like every other field here.
356
+ // `parseCategoryTags` is this file's one reader for a list of words from the server
357
+ // (strings only, blanks dropped, deduped); a second identical parser would be a second
358
+ // place for "read a string list" to go wrong. An empty or absent list yields no key at all.
359
+ // ⚠ W54-T42 Β· R4 β€” nothing on this page FILTERS on it any more; the tiers that did are
360
+ // withdrawn. It is kept because the server declares it on every row and the keychain
361
+ // surface in Settings still decides a scope with it.
362
  ...(parseCategoryTags(c.allowedScopes).length
363
  ? { allowedScopes: parseCategoryTags(c.allowedScopes) }
364
  : {}),
 
615
  * spends money is closed.
616
  */
617
  const [canPull, setCanPull] = useState(false);
618
+ /*
619
+ * β›”β›” THE COMPANY / MINE TOGGLE STOOD HERE AND IS WITHDRAWN BY W54-T42 Β· OWNER RULING R4
620
+ * (2026-09-06). Its state, its two chips, its permission read and the two connected tiers it
621
+ * partitioned are all deleted: one flat "Connected" section now lists every connected card, so
622
+ * a member reaches the same connections an admin does.
 
 
 
 
 
623
  *
624
+ * ⚠ THE SERVER'S REFUSAL IS DELIBERATELY UNTOUCHED. R4 replaces WHO may add a connector with a
625
+ * per-user grant on a third axis (Database, Module, Connector), which is a separate ticket's
626
+ * work; until that lands, `routes_keychain` still refuses a member's company-wide create and a
627
+ * personal scope on a tenant-wide source. Withdrawing a control is not opening a door.
628
  */
 
629
 
630
  useEffect(() => {
631
  let dead = false;
 
635
  credentials: CREDENTIALS,
636
  });
637
  const body = (await res.json().catch(() => null)) as
638
+ | { error?: { message?: string } }
639
  | null;
640
  if (dead) return;
641
  if (!res.ok) {
 
650
  rows: parseDirectory(body),
651
  gaps: parseGaps(body),
652
  chips: parseCategories(body),
 
 
 
 
 
653
  });
654
  } catch {
655
  if (!dead) setLoad({ phase: "error", message: "Cannot reach the server." });
 
713
  const databaseRows = rows.filter((r) => r.spawns_tables === true);
714
  const otherRows = rows.filter((r) => r.spawns_tables !== true);
715
  /**
716
+ * ⭐⭐ W54-T42 Β· OWNER RULING R4 β€” EVERY CONNECTED CARD, IN ONE SECTION.
717
  *
718
+ * R4 withdrew the Company / Mine toggle and the company-wide tier beside it, so who a
719
+ * connection belongs to is no longer a question this page asks. What is left is the one honest
720
+ * statement: these are the sources this workspace is connected to. Access is granted per user
721
+ * on a third axis instead (Database, Module, Connector), which lives in Settings.
 
722
  *
723
+ * ⚠ ONLY A CONNECTED CARD IS LIFTED HERE. An `available`/`planned`/`catalogue` row is not a
724
+ * connection yet, so putting it under "Connected" would claim one this workspace does not have;
725
+ * it keeps its one home in the Databases / Other sources catalog below.
726
  *
727
+ * ⚠ A CONNECTED ODOO ROW APPEARS HERE AND UNDER "Databases", deliberately: R1's tiering asks
728
+ * whether a card spawns tables, and this heading answers a different question about it.
 
 
729
  */
730
  const connectedRows = rows.filter((r) => r.state === "connected");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
731
  // ⚠ Resolved against `allRows`, not the filtered list: typing in the search box while a modal is
732
  // open must not close the modal out from under the reader.
733
  const openRow = allRows.find((row) => row.key === openKey);
 
804
  ) : null}
805
 
806
  {/*
807
+ ⭐⭐ W54-T42 Β· OWNER RULING R4 β€” ONE SECTION FOR EVERY CONNECTED CARD.
808
 
809
+ β›” WHAT STOOD HERE WAS THE COMPANY / MINE TOGGLE AND THE TWO OWNERSHIP TIERS UNDER IT,
810
+ one headed for the whole company and one for the reader's own connections, built by
811
+ W53-T29 ten days earlier. R4 withdraws the whole split: a workspace's connections are one
812
+ list, and access is granted per user on a third axis (Database, Module, Connector) from
813
+ Settings rather than by a scope wall on this page. Leaving only the personal tier would
814
+ have kept the other half of the same wall, so both went and this replaced them.
 
 
 
 
 
815
 
816
+ β›” IT RENDERS ONLY WHEN IT HOLDS A CARD, the same rule the Databases / Other sources pair
817
+ below already keeps: a chip or a search term that empties it must not leave a heading
818
+ standing over nothing.
819
 
820
+ ⚠ SAME `ConnectorCard`, NOT A FORK, and the same classes: no new control shape and no new
821
+ stylesheet, which is what keeps the page's rhythm exactly as it was minus a chip row.
822
  */}
823
+ {connectedRows.length > 0 ? (
824
+ <section className="conn-tier" aria-labelledby="conn-tier-connected-heading">
825
+ <h2 id="conn-tier-connected-heading" className="conn-tier-heading">
826
+ Connected
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
827
  </h2>
828
  <div className="conn-grid">
829
+ {connectedRows.map((row) => (
830
  <ConnectorCard
831
  key={row.key}
832
  row={row}
 
838
  </div>
839
  </section>
840
  ) : null}
841
+ {/*
842
+ ⭐⭐ W52-T01 Β· RULING R1 / CONTRACT C1 β€” THE TWO HEADED CATALOG SECTIONS.
843
+
844
+ β›” EACH SECTION RENDERS ONLY WHEN IT HOLDS A CARD. A chip or a search term that empties
845
+ one tier must not leave a heading standing over nothing β€” `rows.length === 0` above
846
+ already covers "neither tier has anything", so this is the one-tier-emptied case one
847
+ interaction later, and the same honesty rule the empty-state message already keeps.
848
+
849
+ ⚠ SAME `ConnectorCard`, NOT A FORK. Both loops pass the identical props; only which array
850
+ they map is different, so a connector's card behaves exactly as it did before this ticket
851
+ wherever it lands.
852
+ */}
853
  {databaseRows.length > 0 ? (
854
  <section className="conn-tier" aria-labelledby="conn-tier-databases-heading">
855
  <h2 id="conn-tier-databases-heading" className="conn-tier-heading">
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -100,6 +100,8 @@ import { DatePicker } from "./DatePicker";
100
  * shapes for one act is what R6 retires; the manager's copy is another lane's fence.
101
  */
102
  import { ConfirmDialog, DialogToggle } from "../ui/ConfirmDialog";
 
 
103
  // W49-T17: R32's pre-delete disclosure. A static import is safe here -- nothing else in the
104
  // tree imports this component, so it joins THIS chunk rather than pinning another one open
105
  // [[tsc-cannot-see-a-broken-code-split]].
@@ -3390,6 +3392,23 @@ function CustomerGridSurface({
3390
  const displaySpec = resolvedDisplaySpec;
3391
  const displayMode: DisplayMode = serverWindowed ? "grid" : displaySpec?.mode ?? "grid";
3392
  const [routePanelOpen, setRoutePanelOpen] = useState(false);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3393
  useEffect(() => {
3394
  const openRoute = (event: Event) => {
3395
  const detail = (event as CustomEvent<{ routeId?: string; forwarded?: boolean }>).detail;
 
100
  * shapes for one act is what R6 retires; the manager's copy is another lane's fence.
101
  */
102
  import { ConfirmDialog, DialogToggle } from "../ui/ConfirmDialog";
103
+ // D-673 / W54-T21 - the one Escape arbiter, for the route navigator's own close.
104
+ import { useEscapeClose } from "../ui/useEscapeClose";
105
  // W49-T17: R32's pre-delete disclosure. A static import is safe here -- nothing else in the
106
  // tree imports this component, so it joins THIS chunk rather than pinning another one open
107
  // [[tsc-cannot-see-a-broken-code-split]].
 
3392
  const displaySpec = resolvedDisplaySpec;
3393
  const displayMode: DisplayMode = serverWindowed ? "grid" : displaySpec?.mode ?? "grid";
3394
  const [routePanelOpen, setRoutePanelOpen] = useState(false);
3395
+ /**
3396
+ * ⭐⭐ D-673 / W54-T21 β€” THE TOP RUNG OF THE MAP'S ESCAPE LADDER, AND IT HAS TO BE HERE.
3397
+ *
3398
+ * W51-T28 built the rungs it could reach from lane G's fence: the kit dialog, then the open
3399
+ * Route, then the Zone editor and the Zone chooser. The route NAVIGATOR itself stayed
3400
+ * undismissable, and the register row says exactly why: `routePanelOpen` is this component's
3401
+ * own `useState`, handed to `MapView` as a read-only prop with no close callback, so no file
3402
+ * downstream can reach it. Threading a callback through `MapView.tsx` would touch three files
3403
+ * to arrive at this one line.
3404
+ *
3405
+ * β›” AND IT IS THE BOTTOM OF THE STACK, NOT A PRIORITY OF ITS OWN. The claim is pushed when the
3406
+ * panel opens, so everything opened INSIDE it - a row menu, the create menu, an open Route, a
3407
+ * rename, the delete confirm, the search query - registers later and is therefore topmost. One
3408
+ * press resolves to the innermost live surface and stops there; only when nothing is left above
3409
+ * it does Escape close the navigator.
3410
+ */
3411
+ useEscapeClose(routePanelOpen, () => setRoutePanelOpen(false));
3412
  useEffect(() => {
3413
  const openRoute = (event: Event) => {
3414
  const detail = (event as CustomEvent<{ routeId?: string; forwarded?: boolean }>).detail;
web/src/customer-grid/RecordDetail.css CHANGED
@@ -852,6 +852,53 @@
852
  white-space: nowrap;
853
  }
854
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
855
  .cg-record-insights {
856
  padding: 12px 16px 24px;
857
  }
@@ -1305,3 +1352,115 @@
1305
  margin-left: auto;
1306
  margin-right: 6px;
1307
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
852
  white-space: nowrap;
853
  }
854
 
855
+ /* ⭐⭐ W54-T39 (instruction 22) β€” THE RAIL WHILE `/related` IS IN FLIGHT.
856
+ The listing is roughly four times faster now, so most readers never see this; the ones on a
857
+ cold compute or a slow link do, and what they saw before was `Details` alone with no sign that
858
+ anything else was coming (`waves/wave54/shots/F-before-record.png`).
859
+
860
+ β›” NO SHIMMER AND NO SPIN, and this is the app's existing decision rather than a new one:
861
+ `shell/navExtras.css`'s `.shell-rail-skeleton-bar` states it in full β€” an animated sweep is a
862
+ second thing moving in a rail whose whole complaint is movement, and `prefers-reduced-motion`
863
+ would then need a third state. One flat tone at the same `--lp-surface-2` that rail uses. There
864
+ is no animation here for a reduced-motion query to have to undo.
865
+ ⚠ THE ROW GEOMETRY IS `.cg-record-rail-row`'S OWN, inherited rather than restated, so the
866
+ placeholder occupies exactly the height a real row will and nothing shifts when the listing
867
+ lands. Only `cursor` and the pointer wall are overridden; DESIGN section 4 asks a new nav
868
+ element to join the existing rhythm rather than introduce a shape. */
869
+ .cg-record-rail-row.is-skeleton {
870
+ cursor: default;
871
+ pointer-events: none;
872
+ }
873
+
874
+ /* Sized to read as a name that has not arrived: the same 9 px bar height and 4 px radius the page
875
+ rail's skeleton uses, at a width that sits under `.cg-record-rail-row-label`'s single line. */
876
+ .cg-record-rail-skeleton-bar {
877
+ width: 78%;
878
+ max-width: 108px;
879
+ height: 9px;
880
+ margin: 3px 0;
881
+ border-radius: 4px;
882
+ background: var(--lp-surface-2);
883
+ }
884
+
885
+ /* The SUBTITLE's stand-in: shorter and quieter, because that is what the second line of a real
886
+ row is. Together the pair occupies the two-line height 24 of the 25 real edges settle at, so
887
+ the rail does not step when the listing lands. */
888
+ .cg-record-rail-skeleton-bar.is-sub {
889
+ width: 58%;
890
+ max-width: 82px;
891
+ height: 7px;
892
+ opacity: 0.6;
893
+ }
894
+
895
+ /* Folded, the real rows show no labels at all, so the placeholders drop their bars for the same
896
+ reason `.shell-side.is-collapsed .shell-rail-skeleton-bar` does: otherwise the fold runs
897
+ against a width the settled rail never has. */
898
+ .cg-views.is-collapsed .cg-record-rail-skeleton-bar {
899
+ display: none;
900
+ }
901
+
902
  .cg-record-insights {
903
  padding: 12px 16px 24px;
904
  }
 
1352
  margin-left: auto;
1353
  margin-right: 6px;
1354
  }
1355
+
1356
+ /* ⭐⭐ W54-T38 (instruction 22, contract C5, DESIGN.md section 4) β€” A REFUSAL IS ONE SENTENCE,
1357
+ AND ITS DIAGNOSIS IS ONE CLICK DOWN.
1358
+
1359
+ The owner was shown a sixty-word paragraph four times over on one record. W54-T37 fixed the
1360
+ CAUSE and left the presentation, which is the other half of what he reported: section 4 says
1361
+ "never over-explain", and the block sat ABOVE the grid, so a tab's own rows started below the
1362
+ fold. The markup fix is in `RecordDetail.tsx` (the strip moved under the grid and each refusal
1363
+ became a `<details>`); these rules are what make it read as one quiet line.
1364
+
1365
+ β›” WHY THIS FILE AND NOT `index.css`. This ticket owns `RecordDetail.css` and does not own
1366
+ `index.css`, where the one existing disclosure-over-a-refusal (`.cg-ts-refused`) lives. These
1367
+ rules FOLLOW that precedent deliberately, down to both of its scars, rather than reaching for
1368
+ its classes: a shared class would put this surface's layout inside a stylesheet that another
1369
+ lane owns.
1370
+
1371
+ β›”β›” SCAR 1, INHERITED FROM `.cg-ts-refsum`: THE CARET IS DRAWN WITH BORDERS. A triangle glyph
1372
+ renders at a different size in every font on the three platforms this runs on, and this one has
1373
+ to sit on a line of 12px text. It is also not an icon, which matters twice over: this ticket may
1374
+ not extend `iconShapes.ts`.
1375
+ β›”β›” SCAR 2, AND IT SHIPPED ONCE AND WAS CAUGHT ONLY BY A SCREENSHOT: THE CLOSED STATE IS
1376
+ DECLARED. `<details>` hides its non-summary children through a UA rule, and ANY author `display`
1377
+ beats a UA declaration regardless of specificity, so `.cg-refusal-why { display: block }` alone
1378
+ would re-show the whole wall behind a summary claiming to hide it. Both states are stated. */
1379
+ .cg-refusal-strip {
1380
+ flex: 0 0 auto;
1381
+ display: flex;
1382
+ flex-direction: column;
1383
+ gap: 2px;
1384
+ padding: 10px 16px 12px;
1385
+ border-top: 1px solid var(--lp-line);
1386
+ }
1387
+
1388
+ .cg-refusal-sum {
1389
+ display: flex;
1390
+ align-items: baseline;
1391
+ gap: 6px;
1392
+ padding: 2px 0;
1393
+ color: var(--lp-muted);
1394
+ font-size: var(--lp-fs-2xs);
1395
+ line-height: 1.45;
1396
+ cursor: pointer;
1397
+ list-style: none; /* Safari and Chrome draw their own triangle; replaced below */
1398
+ user-select: none;
1399
+ }
1400
+
1401
+ .cg-refusal-sum::-webkit-details-marker {
1402
+ display: none;
1403
+ }
1404
+
1405
+ .cg-refusal-sum::before {
1406
+ content: "";
1407
+ flex: 0 0 auto;
1408
+ align-self: center;
1409
+ width: 0;
1410
+ height: 0;
1411
+ border-left: 4px solid currentColor;
1412
+ border-top: 3.5px solid transparent;
1413
+ border-bottom: 3.5px solid transparent;
1414
+ transition: transform 120ms ease-out;
1415
+ }
1416
+
1417
+ .cg-refusal[open] > .cg-refusal-sum::before {
1418
+ transform: rotate(90deg);
1419
+ }
1420
+
1421
+ .cg-refusal-sum:hover {
1422
+ color: var(--lp-ink);
1423
+ }
1424
+
1425
+ .cg-refusal-sum:focus-visible {
1426
+ outline: 2px solid var(--lp-blue-deep);
1427
+ outline-offset: 1px;
1428
+ border-radius: var(--lp-r-md);
1429
+ }
1430
+
1431
+ /* The subject the server named, on the same line as its sentence rather than above it: a second
1432
+ line per refusal is the stacking this ticket is removing. */
1433
+ .cg-refusal-who {
1434
+ flex: 0 0 auto;
1435
+ color: var(--lp-ink);
1436
+ font-weight: 600;
1437
+ }
1438
+
1439
+ .cg-refusal-say {
1440
+ min-width: 0;
1441
+ }
1442
+
1443
+ .cg-refusal-why {
1444
+ display: none;
1445
+ margin: 2px 0 6px;
1446
+ padding: 0 0 0 10px;
1447
+ color: var(--lp-muted);
1448
+ font-size: var(--lp-fs-2xs);
1449
+ line-height: 1.5;
1450
+ }
1451
+
1452
+ .cg-refusal[open] > .cg-refusal-why {
1453
+ display: block;
1454
+ }
1455
+
1456
+ /* A refusal the server sent with no diagnosis (a pinned read: `_refusal_error` carries the
1457
+ sentence and no second string) keeps the panel's ordinary note voice and grows no caret. */
1458
+ .cg-refusal-flat {
1459
+ padding: 16px;
1460
+ }
1461
+
1462
+ @media (prefers-reduced-motion: reduce) {
1463
+ .cg-refusal-sum::before {
1464
+ transition: none;
1465
+ }
1466
+ }
web/src/customer-grid/RecordDetail.tsx CHANGED
@@ -47,7 +47,7 @@ import { AI_STATE_PREFIX, choiceOptions, codeLanguageOf, isPickType, mayEditFiel
47
  declares what a `/related` entry and a pinned read ARE, so this panel and `CustomerGrid`
48
  cannot come to hold two opinions about one wire contract
49
  [[two-lanes-one-contract-dead-feature]]. */
50
- import { CUSTOMER_TOPIC, PRODUCT_TOPIC, RELATED_REFUSAL, relatedTabs,
51
  topicForScope } from "./types";
52
  import type { CustomerDoc, Field, RelatedEntry, RelatedPin, RelatedRefusal, RelatedVia, Row,
53
  Viewer } from "./types";
@@ -505,9 +505,139 @@ function refusalSubject(
505
  if (code === RELATED_REFUSAL.noRelatedRows) return "";
506
  if (code === RELATED_REFUSAL.forbiddenTable && table) return labelFor(table) || table;
507
  if (code === RELATED_REFUSAL.hopFiltered && hop) return hopWords(hop);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
508
  return "";
509
  }
510
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511
  /**
512
  * ⭐ W51-T06 CLAUSE 9 β€” ONE HOP of the record view's navigation, carrying everything needed to
513
  * render it. See the shadow note inside the component for why the row and the field contract
@@ -542,6 +672,8 @@ interface RecordFrame {
542
  const EMPTY_ENTRIES: RelatedEntry[] = [];
543
  /** ⭐ W53-T24 β€” and the listing's refusals need one for exactly the same reason. */
544
  const EMPTY_REFUSALS: RelatedRefusal[] = [];
 
 
545
  const EMPTY_ROWS: Row[] = [];
546
  const EMPTY_FIELDS: Field[] = [];
547
 
@@ -971,10 +1103,39 @@ export default function RecordDetail({
971
  };
972
  }, [scope, recordTable]);
973
 
974
- /** Clause 1 + clause 2 β€” the tab strip, in the server's order (forward, reverse, bridge). */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
975
  const tabs = useMemo(
976
- () => relatedTabs(entries, (target) => tableLabels[target] ?? ""),
977
- [entries, tableLabels]
 
 
978
  );
979
 
980
  /**
@@ -1297,7 +1458,22 @@ export default function RecordDetail({
1297
  setTabState({ status: "projected" });
1298
  return;
1299
  }
1300
- const refused = await probeRelatedRead(target, pin);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1301
  if (!live) return;
1302
  /* ⚠ A `null` here means the pinned door answered 200 while the ROSTER said no, which is
1303
  the one state with no server sentence (see `unpinnableNote`) and therefore no code
@@ -1306,7 +1482,11 @@ export default function RecordDetail({
1306
  status: "refused",
1307
  reason: refused?.reason ?? unpinnableNote(target),
1308
  code: refused?.code ?? "",
1309
- table: refused?.table,
 
 
 
 
1310
  hop: refused?.hop,
1311
  });
1312
  })();
@@ -1315,6 +1495,9 @@ export default function RecordDetail({
1315
  };
1316
  }, [activeRelated, relatedPin, projectedIds]);
1317
 
 
 
 
1318
  /** ⭐ W53-T24 Β· R13 β€” the emphasised subject of the open tab's refusal, or `""` for the two
1319
  * states that have none (`no_related_rows`, and any code this client does not know). */
1320
  const refusedSubject = tabState.status === "refused"
@@ -2247,35 +2430,6 @@ export default function RecordDetail({
2247
  β›” THE GRID IS THE PANEL, not a card inside one. DESIGN section 4 allows ONE
2248
  containment layer and the drawer is already it; a bordered box around a grid
2249
  inside a drawer inside a modal is the card-in-card the section names. */}
2250
- {/* ⭐⭐ W53-T24 Β· RULING R13 β€” **WHAT THE LISTING WOULD NOT SHOW YOU**, said out loud.
2251
- A traversal filtered out of the rail is otherwise a tab that never appears, and
2252
- a tab that never appears is indistinguishable from an edge that was never
2253
- declared. `refusals` is `[]` whenever nothing was walled off, so this block is
2254
- absent on every ordinary record rather than a permanent apology.
2255
- ⚠ IN THE PANEL, NOT AN OVERLAY, and a FLEX ITEM of `.cg-record-related` rather
2256
- than a sibling of it: that wrapper is `height: 100%` of the scrolling body
2257
- (`styles/wave51/grid.css`), so a paragraph placed BEFORE it would push a
2258
- full-height block down and overflow the drawer. Inside, the grid keeps
2259
- `flex: 1 1 auto` and simply takes the remaining height. */}
2260
- {refusals.map((refusal) => {
2261
- const subject = refusalSubject(
2262
- refusal.code,
2263
- (table) => tableLabels[table] ?? "",
2264
- refusal.table,
2265
- refusal.hop,
2266
- );
2267
- return (
2268
- <p
2269
- key={`${refusal.code}:${refusal.path.join(">")}`}
2270
- className="cg-record-related-note"
2271
- role="status"
2272
- data-refusal={refusal.code}
2273
- >
2274
- {subject ? <><strong>{subject}</strong><br /></> : null}
2275
- {refusal.message}
2276
- </p>
2277
- );
2278
- })}
2279
  {tabState.status === "refused" ? (
2280
  /* ⭐ R6's SECOND SENTENCE β€” the limit, its cause and what to do instead, in the
2281
  SERVER's words. `role="status"` rather than `alert`: a declared relation that
@@ -2295,14 +2449,17 @@ export default function RecordDetail({
2295
  ⚠ `data-refusal` IS THE STATE, MACHINE-READABLE. Three renders that differ only
2296
  in prose cannot be told apart by QA or by a gate; this attribute is how the
2297
  distinction survives a screenshot. */
2298
- <p
2299
- className="cg-record-related-note"
2300
- role="status"
2301
- data-refusal={tabState.code || undefined}
2302
- >
2303
- {refusedSubject ? <><strong>{refusedSubject}</strong><br /></> : null}
2304
- {tabState.reason}
2305
- </p>
 
 
 
2306
  ) : tabState.status === "probing" ? (
2307
  /* Owner R6 β€” one small bare rotating mark, NO WORDS on screen. The `aria-label`
2308
  is not a word on screen and stays, or the wait is announced as nothing at all
@@ -2380,6 +2537,47 @@ export default function RecordDetail({
2380
  />
2381
  </Suspense>
2382
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2383
  </div>
2384
  ) : (
2385
  <>
 
47
  declares what a `/related` entry and a pinned read ARE, so this panel and `CustomerGrid`
48
  cannot come to hold two opinions about one wire contract
49
  [[two-lanes-one-contract-dead-feature]]. */
50
+ import { CUSTOMER_TOPIC, PRODUCT_TOPIC, RELATED_REFUSAL, relatedTabs, skeletonTabs,
51
  topicForScope } from "./types";
52
  import type { CustomerDoc, Field, RelatedEntry, RelatedPin, RelatedRefusal, RelatedVia, Row,
53
  Viewer } from "./types";
 
505
  if (code === RELATED_REFUSAL.noRelatedRows) return "";
506
  if (code === RELATED_REFUSAL.forbiddenTable && table) return labelFor(table) || table;
507
  if (code === RELATED_REFUSAL.hopFiltered && hop) return hopWords(hop);
508
+ /* ⭐⭐ W54-T38 · C5's FOURTH STATE, AND IT IS THE ONE BRANCH THAT MUST NOT FALL BACK TO THE
509
+ RAW KEY. The other two subjects name something the reader can be shown: a database they hold
510
+ a name for, or a hop. A RETIRED table has no roster entry by definition, so `labelFor` is
511
+ empty and the `|| table` fallback above would print `ut_odoo_customers` in bold, which is
512
+ exactly the screen the owner pasted back at us in instruction 22. The short sentence already
513
+ names the absent database in the server's own words, so there is nothing for a subject line
514
+ to add and it stays empty unless a display name genuinely exists. */
515
+ if (code === RELATED_REFUSAL.retiredTarget && table) return labelFor(table);
516
+ /* ⭐⭐ W54-T40 β€” THE ONE STATE WITH NO SERVER **CODE** STILL HAS A SUBJECT, AND IT IS THE TAB
517
+ THE OWNER NAMED. `unpinnableNote` is the client's own sentence for "the read-through roster
518
+ does not name this database", so no code comes back with it and every branch above misses;
519
+ the refusal then rendered as a lone paragraph with nothing saying WHICH database it was
520
+ about. β›” THE DISPLAY NAME OR NOTHING, exactly as the retired branch above decided: this
521
+ falls through to `labelFor` with no `|| table`, so a database with no roster entry stays
522
+ silent rather than putting a raw key in bold on the owner's screen. */
523
+ if (!code && table) return labelFor(table);
524
  return "";
525
  }
526
 
527
+ /**
528
+ * ⭐⭐ W54-T38 Β· INSTRUCTION 22 Β· DESIGN.md SECTION 4 β€” **ONE REFUSAL, AS ONE SENTENCE, WITH THE
529
+ * DIAGNOSIS ONE CLICK DOWN.**
530
+ *
531
+ * The owner, verbatim: *"I still get refusals like ... and a wall of ..."*, pasting one sixty-word
532
+ * paragraph that his screen was showing him FOUR TIMES over. W54-T37 fixed the CAUSE (a retired
533
+ * database reported as a permission problem) and left the presentation exactly as it was, which
534
+ * is half the defect: DESIGN.md section 4 says *"never over-explain"*, and four paragraphs stacked
535
+ * above a grid push the rows a reader asked for below the fold.
536
+ *
537
+ * β›”β›” THE DIAGNOSIS IS NOT CUT, IT IS MOVED. W53-T18 wrote those paragraphs on purpose, so that a
538
+ * traversal is never served short and silent; deleting them would trade this defect for the one
539
+ * they were written against. The server now authors BOTH strings (`relations.py`, the banner above
540
+ * `no_related_rows_refusal`) and this component only chooses the treatment.
541
+ * β›” SO THIS FILE STILL AUTHORS NO PROSE AND STILL SPLITS NOTHING. Cutting `message` at its first
542
+ * full stop would make the client a second author of one wire contract, which is the rule this
543
+ * file already carries beside the refusal render below.
544
+ *
545
+ * ⚠ NO `detail` MEANS NO DISCLOSURE, and that is a measured case rather than defensive habit: a
546
+ * PIN-time refusal is authored by `routes_odoo_tables._related_pin`, which raises one sentence and
547
+ * no diagnosis at all. Such a refusal renders as the short sentence in the ordinary muted voice,
548
+ * exactly as it did before, and never as a caret with nothing behind it.
549
+ * β›” W54-T40 CORRECTS THE ROUTE NAMED HERE. The old text said this refusal arrived through
550
+ * `routes_grid._refusal_error`; it does not. `probeRelatedRead` addresses the ROWS door, and
551
+ * `_refusal_error` belongs to `GET /grid/{table}/related`, whose refusals reach this file through
552
+ * `fetchRelated` and DO carry their diagnosis (W54-T40 added `detail` to the keys it copies, which
553
+ * is the row W54-T38 booked). The two doors are now consistent; the pin door is simply the one
554
+ * with nothing to disclose.
555
+ *
556
+ * β›” `data-refusal` STAYS THE MACHINE-READABLE STATE, on the outermost element either way. It
557
+ * carries the SERVER's code and nothing else may be spelled into it (see the empty-link note
558
+ * below, which deliberately uses a different attribute).
559
+ * β›” THE CARET IS DRAWN IN CSS, NOT AN ICON. `RecordDetail.css` owns it, following
560
+ * `.cg-ts-refsum` in `index.css`: a triangle glyph renders at a different size in every font, and
561
+ * this ticket may not extend the icon vocabulary.
562
+ */
563
+ function RelatedRefusalNote(
564
+ { code, subject, message, details }:
565
+ { code: string; subject: string; message: string; details: string[] },
566
+ ) {
567
+ if (details.length === 0) {
568
+ return (
569
+ <p
570
+ className="cg-record-related-note cg-refusal-flat"
571
+ role="status"
572
+ data-refusal={code || undefined}
573
+ >
574
+ {subject ? <><strong>{subject}</strong><br /></> : null}
575
+ {message}
576
+ </p>
577
+ );
578
+ }
579
+ return (
580
+ <details className="cg-refusal" data-refusal={code || undefined}>
581
+ <summary className="cg-refusal-sum">
582
+ {subject ? <strong className="cg-refusal-who">{subject}</strong> : null}
583
+ <span className="cg-refusal-say">{message}</span>
584
+ </summary>
585
+ {/* ⚠ MORE THAN ONE ONLY WHERE THE SERVER SENT MORE THAN ONE DIAGNOSIS UNDER ONE SENTENCE.
586
+ See `groupRefusals`: the paths differ, the sentence does not, so they share a line and
587
+ each keeps its own paragraph. */}
588
+ {details.map((why) => <p key={why} className="cg-refusal-why">{why}</p>)}
589
+ </details>
590
+ );
591
+ }
592
+
593
+ /**
594
+ * ⭐⭐ W54-T38 β€” **ONE LINE PER SENTENCE, NOT ONE LINE PER PATH**, and this is the half of the
595
+ * repetition that shortening the copy CREATED rather than removed.
596
+ *
597
+ * `relations.wall_refusals` collapses its answer on `(code, table, hop)`, which was exactly right
598
+ * while every sentence quoted its own path: a dozen removed paths through one closed table came
599
+ * back as a handful of genuinely different paragraphs. Now that the sentence a reader meets is
600
+ * SHORT, it names less than that key does, and four paths onto one absent database render as four
601
+ * identical lines. Measured on `customer_data` with a staged retirement: four copies of *"is no
602
+ * longer part of this workspace"*, which is instruction 22's wall again at one line each.
603
+ *
604
+ * β›” IT GROUPS, IT DOES NOT DROP. Each member's diagnosis is kept and stacked inside the one
605
+ * disclosure, so nothing the server said is lost and the count of removed paths is still
606
+ * recoverable by opening it. Dropping the duplicates would delete real answers.
607
+ * β›” AND IT AUTHORS NOTHING. The group key is the server's own `code` plus the server's own
608
+ * sentence, compared byte for byte; this file writes no summary line, no count and no prose.
609
+ * ⚠ THE SUBJECT IS TAKEN FROM THE FIRST MEMBER and that is safe by construction: a group shares
610
+ * one sentence, and each code's sentence quotes whichever of `table` / `hop` its subject is drawn
611
+ * from, so two members with one sentence cannot disagree about it.
612
+ */
613
+ interface GroupedRefusal {
614
+ code: string;
615
+ table?: string;
616
+ hop?: string;
617
+ message: string;
618
+ details: string[];
619
+ }
620
+
621
+ function groupRefusals(refusals: RelatedRefusal[]): GroupedRefusal[] {
622
+ const byLine = new Map<string, GroupedRefusal>();
623
+ for (const refusal of refusals) {
624
+ const key = `${refusal.code}\u0000${refusal.message}`;
625
+ const seen = byLine.get(key);
626
+ if (!seen) {
627
+ byLine.set(key, {
628
+ code: refusal.code,
629
+ table: refusal.table,
630
+ hop: refusal.hop,
631
+ message: refusal.message,
632
+ details: refusal.detail ? [refusal.detail] : [],
633
+ });
634
+ } else if (refusal.detail && !seen.details.includes(refusal.detail)) {
635
+ seen.details.push(refusal.detail);
636
+ }
637
+ }
638
+ return [...byLine.values()];
639
+ }
640
+
641
  /**
642
  * ⭐ W51-T06 CLAUSE 9 β€” ONE HOP of the record view's navigation, carrying everything needed to
643
  * render it. See the shadow note inside the component for why the row and the field contract
 
672
  const EMPTY_ENTRIES: RelatedEntry[] = [];
673
  /** ⭐ W53-T24 β€” and the listing's refusals need one for exactly the same reason. */
674
  const EMPTY_REFUSALS: RelatedRefusal[] = [];
675
+ /** ⭐ W54-T38 β€” and so does the diagnosis list a PIN-time refusal never has. */
676
+ const EMPTY_DIAGNOSES: string[] = [];
677
  const EMPTY_ROWS: Row[] = [];
678
  const EMPTY_FIELDS: Field[] = [];
679
 
 
1103
  };
1104
  }, [scope, recordTable]);
1105
 
1106
+ /**
1107
+ * ⭐⭐ W54-T39 β€” IS THE LISTING STILL IN FLIGHT? Derived, never a fourth piece of state, and it
1108
+ * is already exactly what `related.table` records: the state is stamped with the table it was
1109
+ * fetched FOR, so a stamp that does not match this record's table means no answer for this
1110
+ * table has landed yet. `scope == null` is the fail-closed branch that never fetches at all and
1111
+ * therefore never waits.
1112
+ * ⚠ IT ALWAYS TERMINATES. `apiBridge.ts::fetchRelated` resolves `EMPTY_LISTING` on a non-ok
1113
+ * response and on a thrown fetch, so the effect's `setRelated` runs on every outcome and the
1114
+ * stamp always catches up. A skeleton that could outlive its request would be worse than the
1115
+ * bare rail it replaces.
1116
+ */
1117
+ const relatedPending = scope != null && related.table !== recordTable;
1118
+
1119
+ /**
1120
+ * Clause 1 + clause 2 β€” the tab strip, in the server's order (forward, reverse, bridge).
1121
+ *
1122
+ * ⭐⭐ W54-T39 β€” AND THE PLACEHOLDER ROWS WHILE IT IS STILL COMING. Before this, the rail
1123
+ * rendered `Details` alone for as long as `/related` took, with nothing to say more was on the
1124
+ * way: `waves/wave54/shots/F-before-record.png` is that frame, and *"the left-side rail takes
1125
+ * forever to load"* is the owner reading it. The listing itself is now roughly four times
1126
+ * faster (`routes_grid.py::_relation_context`), so this is the smaller half of the fix and it
1127
+ * has to stay honest about which state it is in.
1128
+ * β›” THE PLACEHOLDERS REPLACE AN EMPTY LIST, THEY NEVER SIT BESIDE A REAL ROW. `entries` is
1129
+ * empty until the answer lands, so there is no frame in which four grey bars and a real tab are
1130
+ * on screen together β€” the two-row-states defect `shell/navExtras.css` fixed in the page rail.
1131
+ * β›” AND AN EMPTY ANSWER IS NOT A LOADING ONE. A database with no relations settles to zero
1132
+ * tabs and the placeholders go, because `relatedPending` is false the moment the stamp matches.
1133
+ */
1134
  const tabs = useMemo(
1135
+ () => (relatedPending && !entries.length
1136
+ ? skeletonTabs()
1137
+ : relatedTabs(entries, (target) => tableLabels[target] ?? "")),
1138
+ [entries, tableLabels, relatedPending]
1139
  );
1140
 
1141
  /**
 
1458
  setTabState({ status: "projected" });
1459
  return;
1460
  }
1461
+ /* ⭐⭐ W54-T40 Β· INSTRUCTION 22 β€” **THE PROBE IS ONLY ASKED OF A DOOR THAT KNOWS THIS
1462
+ TARGET**, and skipping it is the whole of the owner's third error.
1463
+ `probeRelatedRead` addresses `odoo-tables/<key>/rows`, whose vocabulary is the
1464
+ read-through roster and nothing else. MEASURED 2026-09-06: opening **Products ordered**
1465
+ asked that door for `product_data`, a compiled registry module it has never heard of, and
1466
+ got `404 unknown_table` back. Its message is the honest answer to the question that door
1467
+ was asked and the WRONG answer to the one the reader asked, so the tab rendered a bare
1468
+ lower-case *"that database does not exist"* about a database that plainly does exist.
1469
+ β›” THE ROSTER IS ALREADY THE MOUNT CONDITION (see `pinnable` above), so a target it does
1470
+ not name has no pinned read to probe: there is nothing this call can learn and one wrong
1471
+ sentence it can bring back. The state that is left is exactly the one `unpinnableNote`
1472
+ was written for, and it says what was asked, why it cannot be answered here and what to
1473
+ do instead.
1474
+ ⚠ THE PROBE SURVIVES FOR THE STATE IT EXISTS FOR: a target the roster DOES name whose
1475
+ edge is `served: false`. That door has a real sentence and it is still the server's. */
1476
+ const refused = through.has(target) ? await probeRelatedRead(target, pin) : null;
1477
  if (!live) return;
1478
  /* ⚠ A `null` here means the pinned door answered 200 while the ROSTER said no, which is
1479
  the one state with no server sentence (see `unpinnableNote`) and therefore no code
 
1482
  status: "refused",
1483
  reason: refused?.reason ?? unpinnableNote(target),
1484
  code: refused?.code ?? "",
1485
+ /* ⭐ W54-T40 β€” THE SERVER'S SUBJECT WHERE THERE IS ONE, AND THIS TAB'S TARGET WHERE THERE
1486
+ IS NOT. A refusal the client authored is still ABOUT a database, and the only one it
1487
+ can be about is the target of the tab that is open. See `refusalSubject`'s last
1488
+ branch, which turns this into a display name or into nothing. */
1489
+ table: refused?.table ?? target,
1490
  hop: refused?.hop,
1491
  });
1492
  })();
 
1495
  };
1496
  }, [activeRelated, relatedPin, projectedIds]);
1497
 
1498
+ /** ⭐ W54-T38 β€” the listing's refusals, one row per distinct sentence. See `groupRefusals`. */
1499
+ const groupedRefusals = useMemo(() => groupRefusals(refusals), [refusals]);
1500
+
1501
  /** ⭐ W53-T24 Β· R13 β€” the emphasised subject of the open tab's refusal, or `""` for the two
1502
  * states that have none (`no_related_rows`, and any code this client does not know). */
1503
  const refusedSubject = tabState.status === "refused"
 
2430
  β›” THE GRID IS THE PANEL, not a card inside one. DESIGN section 4 allows ONE
2431
  containment layer and the drawer is already it; a bordered box around a grid
2432
  inside a drawer inside a modal is the card-in-card the section names. */}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2433
  {tabState.status === "refused" ? (
2434
  /* ⭐ R6's SECOND SENTENCE β€” the limit, its cause and what to do instead, in the
2435
  SERVER's words. `role="status"` rather than `alert`: a declared relation that
 
2449
  ⚠ `data-refusal` IS THE STATE, MACHINE-READABLE. Three renders that differ only
2450
  in prose cannot be told apart by QA or by a gate; this attribute is how the
2451
  distinction survives a screenshot. */
2452
+ <RelatedRefusalNote
2453
+ code={tabState.code}
2454
+ subject={refusedSubject}
2455
+ message={tabState.reason}
2456
+ /* ⚠ EMPTY, AND MEASURED: a PIN-time refusal is one sentence raised by
2457
+ `routes_odoo_tables._related_pin` with no diagnosis beside it, so there is
2458
+ none to disclose here. It renders as the sentence alone. See
2459
+ `RelatedRefusalNote` for why the LISTING's refusals are the ones that carry a
2460
+ disclosure, and for the route this comment used to name wrongly. */
2461
+ details={EMPTY_DIAGNOSES}
2462
+ />
2463
  ) : tabState.status === "probing" ? (
2464
  /* Owner R6 β€” one small bare rotating mark, NO WORDS on screen. The `aria-label`
2465
  is not a word on screen and stays, or the wait is announced as nothing at all
 
2537
  />
2538
  </Suspense>
2539
  )}
2540
+
2541
+ {/* ⭐⭐ W53-T24 Β· R13 β€” **WHAT THE LISTING WOULD NOT SHOW YOU**, said out loud. A
2542
+ traversal filtered out of the rail is otherwise a tab that never appears, and a
2543
+ tab that never appears is indistinguishable from an edge that was never declared.
2544
+ `refusals` is `[]` whenever nothing was walled off, so this block is absent on
2545
+ every ordinary record rather than a permanent apology.
2546
+
2547
+ ⭐⭐ W54-T38 Β· INSTRUCTION 22 β€” AND IT MOVED **BELOW THE TAB'S OWN CONTENT**,
2548
+ which is the half of the owner's report that was about layout rather than about
2549
+ words. These refusals belong to the RAIL: they describe edges that are missing
2550
+ from the tab strip, not the tab that is open. Rendered first, they appeared at
2551
+ the top of EVERY related tab, so opening Orders meant scrolling past five
2552
+ paragraphs about other edges to reach the orders. See
2553
+ `shots/F-before-orders-tab.png`, which is that exact frame.
2554
+ β›” STILL A FLEX ITEM OF `.cg-record-related`, NEVER AN OVERLAY AND NEVER A
2555
+ SIBLING OF IT: that wrapper is `height: 100%` of the scrolling body
2556
+ (`styles/wave51/grid.css`) and the grid inside it is `flex: 1 1 auto`, so this
2557
+ strip is `flex: 0 0 auto` and takes only the lines it needs while the grid keeps
2558
+ the rest. A block placed before it pushed a full-height element down and
2559
+ overflowed the drawer, which is why the ordering is written down here.
2560
+ ⚠ ONE `role="status"` FOR THE GROUP rather than one per row: each row is a
2561
+ `<details>` whose summary is a real disclosure control, and wrapping every one of
2562
+ them in its own live region would announce the same strip N times. */}
2563
+ {groupedRefusals.length > 0 && (
2564
+ <div className="cg-refusal-strip" role="status">
2565
+ {groupedRefusals.map((refusal) => (
2566
+ <RelatedRefusalNote
2567
+ key={`${refusal.code}:${refusal.message}`}
2568
+ code={refusal.code}
2569
+ subject={refusalSubject(
2570
+ refusal.code,
2571
+ (table) => tableLabels[table] ?? "",
2572
+ refusal.table,
2573
+ refusal.hop,
2574
+ )}
2575
+ message={refusal.message}
2576
+ details={refusal.details}
2577
+ />
2578
+ ))}
2579
+ </div>
2580
+ )}
2581
  </div>
2582
  ) : (
2583
  <>
web/src/customer-grid/RecordRail.tsx CHANGED
@@ -90,7 +90,14 @@ export default function RecordRail({ tabs, activeTab, onSelect }: RecordRailProp
90
  </button>
91
  </div>
92
 
93
- <div className="cg-views-scroll cg-record-rail-list">
 
 
 
 
 
 
 
94
  {/* R6 calls this "Details" in words even though the state key underneath (and the old
95
  tablist strip) both spelled it "fields" β€” the reader never sees that key, and "Fields"
96
  over a panel that also shows a picture upload and a rating row is a name for the data
@@ -103,7 +110,31 @@ export default function RecordRail({ tabs, activeTab, onSelect }: RecordRailProp
103
  >
104
  <span className="cg-record-rail-row-label">Details</span>
105
  </button>
106
- {tabs.map((tab) => (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  <button
108
  key={tab.entry.key}
109
  type="button"
@@ -137,7 +168,7 @@ export default function RecordRail({ tabs, activeTab, onSelect }: RecordRailProp
137
  prop would redden two gates to carry a number that belongs to one row. */}
138
  {tab.hops === 2 && <span className="cg-record-rail-row-sub">2 hops</span>}
139
  </button>
140
- ))}
141
  </div>
142
  </nav>
143
  );
 
90
  </button>
91
  </div>
92
 
93
+ {/* ⭐⭐ W54-T39 β€” `aria-busy` IS THE WHOLE ANNOUNCEMENT, and it is deliberately not a
94
+ sentence. The placeholder rows below say "more is coming" to a sighted reader; this says
95
+ the same thing to a screen reader without adding a line of copy that would then have to
96
+ be un-said the moment the listing lands. */}
97
+ <div
98
+ className="cg-views-scroll cg-record-rail-list"
99
+ aria-busy={tabs.some((tab) => tab.skeleton) || undefined}
100
+ >
101
  {/* R6 calls this "Details" in words even though the state key underneath (and the old
102
  tablist strip) both spelled it "fields" β€” the reader never sees that key, and "Fields"
103
  over a panel that also shows a picture upload and a rating row is a name for the data
 
110
  >
111
  <span className="cg-record-rail-row-label">Details</span>
112
  </button>
113
+ {tabs.map((tab) => (tab.skeleton ? (
114
+ /* ⭐⭐ W54-T39 β€” THE RAIL WHILE `/related` IS IN FLIGHT.
115
+ β›” A `<div>`, NOT A DISABLED BUTTON, and that is the accessibility half rather than a
116
+ preference: a disabled button is still in the accessibility tree and still announced,
117
+ so a reader would be told about four controls that are not there. `aria-hidden` on an
118
+ inert element says the honest thing, and `aria-busy` on the list above says the rest.
119
+ β›” NO SHIMMER. `shell/navExtras.css`'s `.shell-rail-skeleton` is this app's rail
120
+ skeleton and its own note gives the reason in full: an animated sweep is a second
121
+ thing moving in a rail whose complaint is movement, and `prefers-reduced-motion`
122
+ would then need a third state. This follows it, so there is nothing to reduce.
123
+ ⚠ SAME ROW GEOMETRY as `.cg-record-rail-row` (DESIGN §4, join the existing rhythm),
124
+ and TWO bars rather than one for the same reason: a real row is a label over a
125
+ subtitle on 24 of the 25 edges tenant #0's `customer_data` offers, so a one-line
126
+ placeholder would settle by growing and the rail would step down under the reader's
127
+ eye. The bars stand in for `.cg-record-rail-row-label` and
128
+ `.cg-record-rail-row-sub`, in that order and at their two widths. */
129
+ <div
130
+ key={tab.entry.key}
131
+ className="cg-record-rail-row is-skeleton"
132
+ aria-hidden="true"
133
+ >
134
+ <span className="cg-record-rail-skeleton-bar" />
135
+ <span className="cg-record-rail-skeleton-bar is-sub" />
136
+ </div>
137
+ ) : (
138
  <button
139
  key={tab.entry.key}
140
  type="button"
 
168
  prop would redden two gates to carry a number that belongs to one row. */}
169
  {tab.hops === 2 && <span className="cg-record-rail-row-sub">2 hops</span>}
170
  </button>
171
+ )))}
172
  </div>
173
  </nav>
174
  );
web/src/customer-grid/RouteNav.tsx CHANGED
@@ -313,6 +313,8 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
313
  | null
314
  >(null);
315
  const [renameId, setRenameId] = useState<string | null>(null);
 
 
316
  const [busy, setBusy] = useState(false);
317
  const [deliveryMapsPerLink, setDeliveryMapsPerLink] = useState(10);
318
  const [deliveryNotice, setDeliveryNotice] = useState<string | null>(null);
@@ -992,6 +994,39 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
992
  const backToRoutes = useCallback(() => onActiveRouteChange(null), [onActiveRouteChange]);
993
  useEscapeClose(route !== null && titleDraft === null && !deleteConfirm, backToRoutes);
994
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
995
  if (route) {
996
  // ⭐ W46-T25 / RULING R2's guard stood here: a Route projected from a legacy `route_order`
997
  // column was refused until an administrator migrated it, because unlocking an unmigrated one
@@ -1736,9 +1771,16 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
1736
  <input className="cg-input cg-fold-rename" autoFocus defaultValue={folder.name}
1737
  aria-label={`Rename ${folder.name}`} onClick={(event) => event.stopPropagation()}
1738
  onBlur={(event) => {
 
 
 
1739
  const value = event.target.value.trim();
1740
- if (value && value !== folder.name) finish(onFolderUpdate(folder, { name: value }));
1741
- setRenameId(null);
 
 
 
 
1742
  }}
1743
  onKeyDown={(event) => {
1744
  if (event.key === "Enter") event.currentTarget.blur();
 
313
  | null
314
  >(null);
315
  const [renameId, setRenameId] = useState<string | null>(null);
316
+ /** W54-T21 - raised by the rename's Escape claim so the blur it causes does not save. */
317
+ const renameEscaping = useRef(false);
318
  const [busy, setBusy] = useState(false);
319
  const [deliveryMapsPerLink, setDeliveryMapsPerLink] = useState(10);
320
  const [deliveryNotice, setDeliveryNotice] = useState<string | null>(null);
 
994
  const backToRoutes = useCallback(() => onActiveRouteChange(null), [onActiveRouteChange]);
995
  useEscapeClose(route !== null && titleDraft === null && !deleteConfirm, backToRoutes);
996
 
997
+ /* ═════════ W54-T21 / D-673 β€” THE RUNGS THAT USED TO BE COVERED BY SILENCE ═══════════════
998
+ *
999
+ * β›”β›” THE STAND-DOWNS ABOVE ONLY WORKED WHILE NOTHING ELSE CLAIMED ESCAPE. Standing down means
1000
+ * "let the key fall through", and until this ticket it fell through to NOBODY, so React's own
1001
+ * handlers on the rename input and the search box still saw it and the delete confirm simply
1002
+ * ignored the press. D-673 puts a claim UNDERNEATH this whole panel - `CustomerGrid.tsx` closes
1003
+ * the navigator - so a fall-through now closes the entire navigator instead. Every surface the
1004
+ * open Route stands down for therefore has to claim the key itself, or the press it was meant
1005
+ * to reach would take the panel down with it.
1006
+ *
1007
+ * β›” THE LINE ABOVE IS UNTOUCHED, DELIBERATELY. `verify_map.py` slices the FIRST
1008
+ * `useEscapeClose` statement in this file and asserts each of its terms, so these three sit
1009
+ * BELOW it; putting one above would hand that leg the wrong statement to read.
1010
+ *
1011
+ * ⚠ `renameEscaping` IS THE SAME ORDERING PROBLEM THE SHEET'S FORMULA EDITOR HAS. The arbiter
1012
+ * blurs the focused element before it calls close, and the folder rename input's blur is what
1013
+ * SAVES the new name, so a bare claim would have made Escape commit a rename it was pressed to
1014
+ * cancel. The blur defers its decision by one microtask and this flag, raised by the close,
1015
+ * wins that race by construction rather than by luck.
1016
+ *
1017
+ * ⚠ THE QUERY RUNG IS THE ONE BEHAVIOUR CHANGE, AND IT IS THE SMALL ONE. Escape with a typed
1018
+ * route filter clears the filter and leaves the panel open, which is what the box's own
1019
+ * handler always did; with the box empty there is nothing to clear and the press reaches the
1020
+ * navigator's close. The box keeps its own handler because `verify_map.py` pins it.
1021
+ */
1022
+ useEscapeClose(titleDraft !== null, () => setTitleDraft(null));
1023
+ useEscapeClose(deleteConfirm, () => setDeleteConfirm(false));
1024
+ useEscapeClose(renameId !== null, () => {
1025
+ renameEscaping.current = true;
1026
+ setRenameId(null);
1027
+ });
1028
+ useEscapeClose(routeQuery !== "", () => setRouteQuery(""));
1029
+
1030
  if (route) {
1031
  // ⭐ W46-T25 / RULING R2's guard stood here: a Route projected from a legacy `route_order`
1032
  // column was refused until an administrator migrated it, because unlocking an unmigrated one
 
1771
  <input className="cg-input cg-fold-rename" autoFocus defaultValue={folder.name}
1772
  aria-label={`Rename ${folder.name}`} onClick={(event) => event.stopPropagation()}
1773
  onBlur={(event) => {
1774
+ // W54-T21 - deferred by ONE microtask so an Escape that blurred this input on
1775
+ // its way to cancelling the rename gets to say so first. A click away, a Tab
1776
+ // and the Enter path all still save, one microtask later, unchanged.
1777
  const value = event.target.value.trim();
1778
+ renameEscaping.current = false;
1779
+ queueMicrotask(() => {
1780
+ if (renameEscaping.current) return;
1781
+ if (value && value !== folder.name) finish(onFolderUpdate(folder, { name: value }));
1782
+ setRenameId(null);
1783
+ });
1784
  }}
1785
  onKeyDown={(event) => {
1786
  if (event.key === "Enter") event.currentTarget.blur();
web/src/customer-grid/Toolbar.tsx CHANGED
@@ -55,6 +55,17 @@ import { FilterBuilderPanel, FieldsHidePanel, Popover } from "../filter-kit";
55
  import { MEASURE_OP_LIST, countConditions, newRuleId, opsForType } from "../filter-kit/ops";
56
  import "./filters.css";
57
 
 
 
 
 
 
 
 
 
 
 
 
58
  interface ToolbarBaseProps {
59
  fields: Field[];
60
  /** Identity used only to classify shared fields into ownership sections. */
@@ -257,6 +268,30 @@ interface ToolbarBaseProps {
257
  */
258
  frozen?: boolean;
259
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
260
  /**
261
  * ⭐ W41-T42 Β· RULING R9 β€” what this table can pivot to: its LINK FIELDS. Empty means the table
262
  * has no link yet, and the control says exactly that rather than offering nothing silently.
@@ -398,6 +433,26 @@ function IconRelational() {
398
  </svg>
399
  );
400
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
  function IconGroup() {
402
  return (
403
  <svg {...ic} aria-hidden>
@@ -814,6 +869,9 @@ export default function Toolbar({
814
  filterSeed = null,
815
  modeControl,
816
  frozen = false,
 
 
 
817
  relationalTargets = [],
818
  relational = null,
819
  onRelational,
@@ -952,6 +1010,25 @@ export default function Toolbar({
952
  // W41-T42 β€” the same idiom `colorLabel` and `groupLabel` already use: a control that HAS a
953
  // current answer names it on the trigger, so the reader does not have to open it to find out.
954
  const relationalLabel = relational ? `Related: ${relational.label}` : "Related";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
955
 
956
  /**
957
  * R11's greying, as one attribute. `inert` is not in React 18's JSX typings (it landed with
@@ -976,6 +1053,41 @@ export default function Toolbar({
976
  on. */}
977
  {modeControl}
978
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
979
  {/* Fields β€” show / hide columns, searchable, Pre-set chips (item 7 remainder) */}
980
  {/* Owner item 23 β€” "Hide fields", the panel's actual job and Airtable's wording. */}
981
  <Popover label="Fields" icon={<EyeOffIcon />} active={shownCount < fields.length}>
 
55
  import { MEASURE_OP_LIST, countConditions, newRuleId, opsForType } from "../filter-kit/ops";
56
  import "./filters.css";
57
 
58
+ /**
59
+ * ⭐⭐ W54-T49 Β· C4 β€” ONE connection, as the selector sees it: a stable id and the EDITABLE label
60
+ * its owner gave it. Two members and no third, because "which client's numbers are these" is
61
+ * answered by the id and read by the label; anything else a connection knows belongs to the
62
+ * Connectors panel, not to a picker above a grid.
63
+ */
64
+ export interface ConnectionChoice {
65
+ id: string;
66
+ label: string;
67
+ }
68
+
69
  interface ToolbarBaseProps {
70
  fields: Field[];
71
  /** Identity used only to classify shared fields into ownership sections. */
 
268
  */
269
  frozen?: boolean;
270
 
271
+ /**
272
+ * ⭐⭐ W54-T49 Β· RULING R7 / CONTRACT C4 β€” THE CONNECTION THIS TABLE IS READ THROUGH.
273
+ *
274
+ * R7, verbatim: *"Every Odoo-reading module gains a connection selector; picking one client
275
+ * shows only that client's numbers. β›” There is no 'All' option that blends two clients."*
276
+ * So the list carries real connections and nothing else: this control has no "All" row, and
277
+ * there is no value of `connectionId` that means "both".
278
+ *
279
+ * ⚠ OPTIONAL, AND A CALLER THAT PASSES NOTHING RENDERS NO CONTROL AT ALL β€” not an empty one,
280
+ * not an inert one. Same posture as `ViewSidebar`'s folder props (*"a caller that passes no
281
+ * `folders` and no handlers renders exactly the pre-wave-8 flat rail"*), and it is what keeps
282
+ * every existing mount of this toolbar byte-identical: a workspace with one connection has
283
+ * nothing to choose between and is shown nothing to choose with.
284
+ *
285
+ * β›” SUPPLIED, NEVER DERIVED. Which connections exist and which one is in force are SERVER
286
+ * answers (`perm_scope.connection_options` / `perm_scope.connection_scope`); a toolbar that
287
+ * guessed them would be wrong the moment an administrator added a client.
288
+ */
289
+ connections?: ConnectionChoice[];
290
+ /** The connection in force. It is always one id, because a read is always one connection. */
291
+ connectionId?: string | null;
292
+ /** Read this table through that connection instead. One id, never a set. */
293
+ onConnection?: (connectionId: string) => void;
294
+
295
  /**
296
  * ⭐ W41-T42 Β· RULING R9 β€” what this table can pivot to: its LINK FIELDS. Empty means the table
297
  * has no link yet, and the control says exactly that rather than offering nothing silently.
 
433
  </svg>
434
  );
435
  }
436
+ /**
437
+ * ⭐ W54-T49 β€” the connection selector's mark, and it is a REUSED glyph rather than a new one.
438
+ *
439
+ * The path is `icons.tsx::MENU_ICONS.swap` verbatim: the two opposed arrows this app already
440
+ * uses for "switch which of these is in force", which is exactly what choosing a connection
441
+ * does. It is drawn here at the toolbar's own 14px / 1.5 stroke rather than imported through
442
+ * `MenuIcon`, because that renders the menu's 16px / 1.3 and the controls in this row share a
443
+ * height and a baseline. `icons.tsx` and `iconShapes.ts` are untouched: the vocabulary has no
444
+ * plug or database mark, and inventing one belongs to whoever owns that file.
445
+ */
446
+ function IconConnection() {
447
+ return (
448
+ <svg {...ic} aria-hidden>
449
+ <path
450
+ d="M3.5 6h9M10.2 3.7 12.5 6l-2.3 2.3M12.5 10.5h-9M5.8 8.2 3.5 10.5l2.3 2.3"
451
+ {...stroke}
452
+ />
453
+ </svg>
454
+ );
455
+ }
456
  function IconGroup() {
457
  return (
458
  <svg {...ic} aria-hidden>
 
869
  filterSeed = null,
870
  modeControl,
871
  frozen = false,
872
+ connections = [],
873
+ connectionId = null,
874
+ onConnection,
875
  relationalTargets = [],
876
  relational = null,
877
  onRelational,
 
1010
  // W41-T42 β€” the same idiom `colorLabel` and `groupLabel` already use: a control that HAS a
1011
  // current answer names it on the trigger, so the reader does not have to open it to find out.
1012
  const relationalLabel = relational ? `Related: ${relational.label}` : "Related";
1013
+ // ⭐⭐ W54-T49 (R7) β€” the same idiom again, and here it is load bearing rather than convenient:
1014
+ // two connections show the same databases under the same column names, so the ONE thing on
1015
+ // screen that says whose numbers these are is this trigger. It names the client, always.
1016
+ const currentConnection =
1017
+ connections.find((conn) => conn.id === connectionId) ?? connections[0];
1018
+ const connectionLabel = currentConnection
1019
+ ? `Connection: ${currentConnection.label}`
1020
+ : "Connection";
1021
+ /**
1022
+ * β›” R7 β€” the control renders when there is a connection to name AND a host to take the choice.
1023
+ *
1024
+ * BOTH halves: a picker nothing listens to is a lie, and a picker with no connection behind it
1025
+ * would name a client this workspace does not have. ⚠ ONE connection still renders it, unlike
1026
+ * the nav rail's per-connection folders, and the asymmetry is deliberate: the rail is naming
1027
+ * FOLDERS, which a single connection does not need, while this says whose numbers are on the
1028
+ * screen, which is exactly as true at one client as at two. A caller that supplies neither
1029
+ * prop renders nothing, which is every mount of this toolbar today.
1030
+ */
1031
+ const canPickConnection = !!onConnection && connections.length > 0;
1032
 
1033
  /**
1034
  * R11's greying, as one attribute. `inert` is not in React 18's JSX typings (it landed with
 
1053
  on. */}
1054
  {modeControl}
1055
 
1056
+ {/* ⭐⭐ W54-T49 (R7 / C4) β€” WHICH CONNECTION THIS TABLE IS READ THROUGH.
1057
+ FIRST in the strip, and first is the argument: every other control here operates on
1058
+ rows, and this one decides which client's rows exist at all. It takes no `order:` of
1059
+ its own, so it sits in the initial cluster with Fields, Filter, Sort and Color and
1060
+ paints where the DOM puts it; the run W50-T07 froze (Color, Rows, Edit, Related, Notes,
1061
+ Full screen) is untouched, in the markup and in the tab sequence alike.
1062
+
1063
+ β›” NO "ALL" ROW, AND THERE IS NOWHERE TO PUT ONE. R7 is explicit that no option may
1064
+ blend two clients, and the server agrees by construction: `perm_scope.connection_scope`
1065
+ returns one connection or refuses. A radio group, never checkboxes, for the same
1066
+ reason β€” the control's SHAPE has to say "exactly one" before anybody reads a label. */}
1067
+ {canPickConnection && (
1068
+ <Popover label={connectionLabel} icon={<IconConnection />} active={connections.length > 1}>
1069
+ {(close) => (
1070
+ <div className="cg-pop-body">
1071
+ <div className="cg-pop-title">Connection</div>
1072
+ {connections.map((conn) => (
1073
+ <label key={conn.id} className="cg-radio-row">
1074
+ <input
1075
+ type="radio"
1076
+ name="cg-connection"
1077
+ checked={conn.id === currentConnection?.id}
1078
+ onChange={() => {
1079
+ onConnection?.(conn.id);
1080
+ close();
1081
+ }}
1082
+ />
1083
+ <span>{conn.label}</span>
1084
+ </label>
1085
+ ))}
1086
+ </div>
1087
+ )}
1088
+ </Popover>
1089
+ )}
1090
+
1091
  {/* Fields β€” show / hide columns, searchable, Pre-set chips (item 7 remainder) */}
1092
  {/* Owner item 23 β€” "Hide fields", the panel's actual job and Airtable's wording. */}
1093
  <Popover label="Fields" icon={<EyeOffIcon />} active={shownCount < fields.length}>
web/src/customer-grid/ViewSidebar.tsx CHANGED
@@ -994,7 +994,25 @@ function DataDatabaseNavigator({
994
  onClick={() => pushDataLevel({ kind: "origin", label: group.label })}
995
  >
996
  <FolderMark size={16} />
997
- <span className="cg-fold-name">{group.label}</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
998
  <span className="cg-fold-count">{group.databases.length}</span>
999
  </button>
1000
  </div>
 
994
  onClick={() => pushDataLevel({ kind: "origin", label: group.label })}
995
  >
996
  <FolderMark size={16} />
997
+ {/* ⭐ W54-T48 (R4 / C4) β€” THE FULL NAME ON HOVER, BECAUSE THIS NAME IS NOW THE
998
+ USER'S. This row used to read the literal "Odoo" for every connected
999
+ database and could not truncate; it now reads the CONNECTION's keychain
1000
+ label once a tenant has two connections to tell apart, and a label may run
1001
+ to 80 characters against a rail measured to the pixel. `.cg-fold-name`
1002
+ (index.css:5929) is `overflow:hidden; text-overflow:ellipsis;
1003
+ white-space:nowrap`, so "Royal Production (Jakarta warehouse)" reads as
1004
+ "Royal Production (Jakart…" with nothing to open it.
1005
+ ⚠ ON THE SPAN, NOT ON THE BUTTON, and that is the accessibility half. The
1006
+ button's accessible name is its `aria-label` ("Open folder <name>"), which
1007
+ already carries the whole label to a screen reader; a `title` on the button
1008
+ would be a second name competing with it. On the text span it is a POINTER
1009
+ affordance only and adds nothing to the accessibility tree.
1010
+ ⚠ The same treatment `PathCrumbs` gives a truncatable path segment
1011
+ (`title={segment.label}`, this file) and the shape `.cg-fold-name` already
1012
+ takes in the view layer below. No CSS: a title needs none. */}
1013
+ <span className="cg-fold-name" title={group.label}>
1014
+ {group.label}
1015
+ </span>
1016
  <span className="cg-fold-count">{group.databases.length}</span>
1017
  </button>
1018
  </div>
web/src/customer-grid/iconShapes.ts CHANGED
@@ -437,6 +437,37 @@ export const FOLDER_TONE_LABELS: Record<FolderTone, string> = {
437
  * as two icon vocabularies, and a second source of colour would let the two marks drift apart.
438
  * β›” IT IS STILL NOT A `FolderShape`. A folder's mark is user-chosen and stored in nav prefs; this
439
  * one is what the row IS, so nothing offers it in the shape picker.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
440
  */
441
  export function DatabaseMark({ size = 16 }: { size?: number }): ReactElement {
442
  const paint = folderTonePaint(DATABASE_MARK_TONE);
@@ -449,16 +480,22 @@ export function DatabaseMark({ size = 16 }: { size?: number }): ReactElement {
449
  viewBox: "0 0 16 16",
450
  "aria-hidden": true,
451
  },
452
- DATABASE_SHAPE_PATHS.map((s) =>
453
- createElement("path", {
454
- key: s.d,
455
- d: s.d,
456
- fill: "none",
457
- stroke: paint.stroke,
458
- strokeWidth: 1.35,
459
- strokeLinecap: "round",
460
- strokeLinejoin: "round",
461
- })
 
 
 
 
 
 
462
  )
463
  );
464
  }
 
437
  * as two icon vocabularies, and a second source of colour would let the two marks drift apart.
438
  * β›” IT IS STILL NOT A `FolderShape`. A folder's mark is user-chosen and stored in nav prefs; this
439
  * one is what the row IS, so nothing offers it in the shape picker.
440
+ *
441
+ * ⭐⭐ W54-T41 (owner instruction 23) β€” THE OPTICAL NORMALISATION, AND WHY IT IS A TRANSFORM
442
+ * RATHER THAN NEW PATH DATA.
443
+ *
444
+ * Owner, verbatim: *"Under the view navigation rail, the height of the Database icon and the
445
+ * Folder icon is not the same, making the rail asymmetric and unpleasant when going back and
446
+ * forth along a path."* Both marks already shared the 16x16 box, the 16px render size and the
447
+ * 1.35 stroke, so nothing about the ATTRIBUTES said anything was wrong. The INK did: the cylinder
448
+ * draws from y 2.0 to y 14.0 and the default folder from y 3.6 to y 13.2, which is 12.0 units of
449
+ * geometry against 9.6 β€” about 19% taller, and a rail alternating between the two steps up and
450
+ * down as you walk a path.
451
+ *
452
+ * The fix is a UNIFORM scale of 0.8 about the group, offset by 1.6 across and 2.0 down, with the
453
+ * stroke pre-divided so it still RENDERS at 1.35:
454
+ * - vertical ink 0.8 x 12.0 + 1.35 = 10.95, the folder's 9.6 + 1.35 exactly;
455
+ * - top and bottom edges land on y 3.6 and y 13.2, the folder's own edges, so the two marks
456
+ * share a baseline as well as a height and the rail shows no step;
457
+ * - horizontal ink 0.8 x 9.0 = 7.2 wide, centred on x 8. Narrower than the folder, which is
458
+ * what the note above already documents as intended: the silhouettes must differ.
459
+ *
460
+ * β›” UNIFORM, never a y-only squash. The rim-depth note above is the reason: `ry` 1.9 against
461
+ * `rx` 4.5 is what stops the cylinder reading as a rectangle at 16px, and flattening only the
462
+ * vertical axis would push it straight back toward one. A uniform scale preserves the ratio.
463
+ *
464
+ * β›” AND THE `d` STRINGS ARE UNTOUCHED BY DESIGN. `shell/icons.tsx::DatabaseIcon` carries a
465
+ * deliberate byte-identical COPY of these three paths (importing the constant would drag the
466
+ * grid's 48 kB icon chunk into the eager shell entry), and `verify_icons.py::t35_database_faults`
467
+ * compares the two byte for byte. Editing the geometry here would red that leg from a file the
468
+ * shell copy cannot follow, so the normalisation lives in the RENDERER and the data stays data.
469
+ * `verify_icons.py::t41_ink_faults` measures the drawn ink of both marks β€” arcs sampled through
470
+ * the SVG centre parameterisation, so the rim's bulge counts β€” and holds the two extents equal.
471
  */
472
  export function DatabaseMark({ size = 16 }: { size?: number }): ReactElement {
473
  const paint = folderTonePaint(DATABASE_MARK_TONE);
 
480
  viewBox: "0 0 16 16",
481
  "aria-hidden": true,
482
  },
483
+ createElement(
484
+ "g",
485
+ { transform: "translate(1.6 2) scale(0.8)" },
486
+ DATABASE_SHAPE_PATHS.map((s) =>
487
+ createElement("path", {
488
+ key: s.d,
489
+ d: s.d,
490
+ fill: "none",
491
+ stroke: paint.stroke,
492
+ // Pre-divided by the group's scale, so what reaches the screen is still the 1.35 every
493
+ // sibling mark in this vocabulary strokes at.
494
+ strokeWidth: 1.35 / 0.8,
495
+ strokeLinecap: "round",
496
+ strokeLinejoin: "round",
497
+ })
498
+ )
499
  )
500
  );
501
  }
web/src/customer-grid/types.ts CHANGED
@@ -4234,17 +4234,40 @@ export interface RelatedEntry {
4234
  */
4235
  export interface RelatedRefusal {
4236
  code: string;
 
 
 
 
 
 
 
4237
  message: string;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4238
  path: string[];
4239
  table?: string;
4240
  hop?: string;
4241
  }
4242
 
4243
  /**
4244
- * ⭐⭐ W53-T24 Β· RULING R13 Β· C3 β€” **THE THREE CODES, SPELLED EXACTLY ONCE IN THIS CLIENT.**
 
4245
  *
4246
- * β›” A CONSTANT RATHER THAN THREE STRING LITERALS SCATTERED THROUGH A RENDER, because R13's
4247
- * whole content is that these three are DIFFERENT ANSWERS: a typo in one literal at one call
4248
  * site silently collapses that answer back into the default treatment, which is the empty-grid
4249
  * failure wearing a new disguise, and no gate on either side of the wire would see it. Imported
4250
  * where the states are chosen, so `tsc` binds the declaration to its consumer.
@@ -4255,6 +4278,16 @@ export const RELATED_REFUSAL = {
4255
  noRelatedRows: "no_related_rows",
4256
  forbiddenTable: "forbidden_table",
4257
  hopFiltered: "hop_filtered",
 
 
 
 
 
 
 
 
 
 
4258
  } as const;
4259
 
4260
  /**
@@ -4284,6 +4317,68 @@ export interface RelatedTab {
4284
  * fourth prop would redden two gates for a mark that belongs to one row anyway.
4285
  */
4286
  hops: 1 | 2;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4287
  }
4288
 
4289
  /**
@@ -4378,6 +4473,13 @@ export function relatedRefusals(body: unknown): RelatedRefusal[] {
4378
  };
4379
  if (typeof raw?.table === "string" && raw.table) refusal.table = raw.table;
4380
  if (typeof raw?.hop === "string" && raw.hop) refusal.hop = raw.hop;
 
 
 
 
 
 
 
4381
  out.push(refusal);
4382
  }
4383
  return out;
 
4234
  */
4235
  export interface RelatedRefusal {
4236
  code: string;
4237
+ /**
4238
+ * ⭐⭐ W54-T38 Β· INSTRUCTION 22 β€” **ONE SHORT SENTENCE**, and that is now a
4239
+ * property of the wire rather than a hope about the server. The owner was shown this string
4240
+ * four times on one screen at sixty words each, which DESIGN.md section 4 forbids in as many
4241
+ * words ("never over-explain"). `relations.py` now authors two strings per refusal and this is
4242
+ * the first one.
4243
+ */
4244
  message: string;
4245
+ /**
4246
+ * ⭐⭐ THE DIAGNOSIS, for the disclosure. Word for word what `message` used to be:
4247
+ * which hop went, which door is shut, what to do about it.
4248
+ *
4249
+ * β›”β›” OPTIONAL, AND THE ONE PLACE IT IS GENUINELY ABSENT IS MEASURED RATHER THAN
4250
+ * GUESSED. The LISTING carries it (`routes_grid.related_refusals` returns `wall_refusals`'
4251
+ * bags whole), so every refusal drawn from `/related` has one. A PIN-time refusal does not:
4252
+ * `routes_grid._refusal_error` copies only `table`, `hop`, `path` and `candidates` into the X2
4253
+ * envelope, and that file is another ticket's fence. So an absent `detail` means "the server
4254
+ * sent no diagnosis", which renders as the short sentence alone, never as an invented one.
4255
+ * β›” THE CLIENT NEVER SPLITS `message` TO FILL THIS. Cutting a paragraph at its first full
4256
+ * stop would make this file a second author of one wire contract, which is the rule
4257
+ * `RecordDetail.tsx` already carries beside the refusal render.
4258
+ */
4259
+ detail?: string;
4260
  path: string[];
4261
  table?: string;
4262
  hop?: string;
4263
  }
4264
 
4265
  /**
4266
+ * ⭐⭐ W53-T24 Β· R13 Β· C3, EXTENDED BY W54-T38 Β· C5 β€” **THE FOUR CODES,
4267
+ * SPELLED EXACTLY ONCE IN THIS CLIENT.**
4268
  *
4269
+ * β›” A CONSTANT RATHER THAN FOUR STRING LITERALS SCATTERED THROUGH A RENDER, because R13's
4270
+ * whole content is that these four are DIFFERENT ANSWERS: a typo in one literal at one call
4271
  * site silently collapses that answer back into the default treatment, which is the empty-grid
4272
  * failure wearing a new disguise, and no gate on either side of the wire would see it. Imported
4273
  * where the states are chosen, so `tsc` binds the declaration to its consumer.
 
4278
  noRelatedRows: "no_related_rows",
4279
  forbiddenTable: "forbidden_table",
4280
  hopFiltered: "hop_filtered",
4281
+ /**
4282
+ * ⭐⭐ W54-T38 · CONTRACT C5's FOURTH ANSWER, and it is the one instruction 22 is
4283
+ * about: the edge opens a database this deployment does not have any more. It is NOT a
4284
+ * permission answer, it must never be treated as one, and the whole complaint was a reader
4285
+ * being told to ask an administrator for access to a table nobody can grant.
4286
+ * ⚠ `unknown_via` is a FIFTH code on the wire and is deliberately not spelled here: this
4287
+ * client renders no branch of its own for it, and a constant nothing reads would be a
4288
+ * declaration pretending to be a consumer.
4289
+ */
4290
+ retiredTarget: "retired_target",
4291
  } as const;
4292
 
4293
  /**
 
4317
  * fourth prop would redden two gates for a mark that belongs to one row anyway.
4318
  */
4319
  hops: 1 | 2;
4320
+ /**
4321
+ * ⭐⭐ W54-T39 β€” TRUE ONLY ON A PLACEHOLDER, AND IT TRAVELS HERE FOR THE SAME REASON `hops`
4322
+ * DOES. While `/related` is in flight the rail knows about exactly one row, `Details`, and
4323
+ * shows it alone with nothing to say more is coming β€” the owner's *"the left-side rail takes
4324
+ * forever to load"*, photographed at `waves/wave54/shots/F-before-record.png`. The rail needs
4325
+ * to be told it is waiting, and `verify_wiring.py` plus `verify_record_layout.py` both assert
4326
+ * its mount as the exact string `<RecordRail tabs={tabs} activeTab={activeTab}
4327
+ * onSelect={setTab} />`, so a fourth prop is not available to say it. The signal rides the tab.
4328
+ *
4329
+ * β›” A SKELETON TAB IS NEVER SELECTABLE AND NEVER RESOLVES TO AN EDGE. Its `entry.key` is
4330
+ * `SKELETON_TAB_PREFIX + n`, a spelling no server edge can carry, so `RecordDetail`'s
4331
+ * `activeTab` falls back to `"fields"` and `activeRelated` stays null exactly as it does before
4332
+ * any listing arrives. `RecordRail` renders these rows as inert `<div>`s rather than buttons,
4333
+ * so neither a click nor a Tab key can reach one.
4334
+ * ⚠ OPTIONAL, and absent on every real tab: `relatedTabs` never sets it, so a tab built from
4335
+ * the server's own answer cannot be mistaken for a placeholder.
4336
+ */
4337
+ skeleton?: true;
4338
+ }
4339
+
4340
+ /**
4341
+ * β›” THE ONE SPELLING A PLACEHOLDER ROW'S KEY MAY TAKE, and it is deliberately not a legal edge
4342
+ * key: `relations.py` mints edge keys out of field, table and bridge names, none of which can
4343
+ * begin with a space. So no listing can ever collide with one of these, and no stale selection
4344
+ * can point at one.
4345
+ */
4346
+ export const SKELETON_TAB_PREFIX = " skeleton:";
4347
+
4348
+ /**
4349
+ * ⭐⭐ W54-T39 β€” THE RAIL'S IN-FLIGHT ROWS. Four, because the rail's real answer on tenant #0's
4350
+ * `customer_data` is twenty-five and on its smallest database is two; four fills the fold without
4351
+ * promising a count, which is what a skeleton is for.
4352
+ *
4353
+ * β›” DESIGN Β§4 β€” A SKELETON, NOT A SPINNER, and the same one the app already uses. `.lp-spin`
4354
+ * belongs to a per-tab row load, where one small thing is fetching inside a settled page; this is
4355
+ * the whole rail arriving, and the house answer to that is `shell/navExtras.css`'s
4356
+ * `.shell-rail-skeleton`, which is flat-toned and does not animate at all. Following it means
4357
+ * there is no shimmer for `prefers-reduced-motion` to have to undo.
4358
+ * ⚠ NO COPY. The rows carry no words, so there is nothing here to get the dash rule or sentence
4359
+ * case wrong; `RecordRail` marks the list `aria-busy` instead, which is what a screen reader
4360
+ * wants and a sighted reader does not need told twice.
4361
+ */
4362
+ export function skeletonTabs(count = 4): RelatedTab[] {
4363
+ const out: RelatedTab[] = [];
4364
+ for (let i = 0; i < count; i += 1) {
4365
+ out.push({
4366
+ entry: {
4367
+ key: `${SKELETON_TAB_PREFIX}${i}`,
4368
+ label: "",
4369
+ target: "",
4370
+ served: false,
4371
+ via: { direction: "forward", key: `${SKELETON_TAB_PREFIX}${i}` },
4372
+ path: [`${SKELETON_TAB_PREFIX}${i}`],
4373
+ hops: 1,
4374
+ },
4375
+ label: "",
4376
+ subtitle: "",
4377
+ hops: 1,
4378
+ skeleton: true,
4379
+ });
4380
+ }
4381
+ return out;
4382
  }
4383
 
4384
  /**
 
4473
  };
4474
  if (typeof raw?.table === "string" && raw.table) refusal.table = raw.table;
4475
  if (typeof raw?.hop === "string" && raw.hop) refusal.hop = raw.hop;
4476
+ /* ⭐⭐ W54-T38 β€” THE DIAGNOSIS, WHEN THE SERVER SENT ONE. Read exactly as `table` and `hop`
4477
+ are: present and non-empty or absent entirely, never `""`, so the render can branch on
4478
+ "is there a disclosure to draw" with a truth test and no second convention.
4479
+ β›” AND IT IS NEVER SYNTHESISED FROM `message`. A client that cut the sentence at its first
4480
+ full stop would be authoring copy out of a regular expression; the split is the server's,
4481
+ and a refusal that arrives without one shows its sentence alone. */
4482
+ if (typeof raw?.detail === "string" && raw.detail) refusal.detail = raw.detail;
4483
  out.push(refusal);
4484
  }
4485
  return out;
web/src/filter-kit/FilterBuilderPanel.tsx CHANGED
@@ -646,6 +646,19 @@ interface LevelContext {
646
  */
647
  viewChoices: { id: string; name: string }[];
648
  choicesFor: ChoicesFor;
 
 
 
 
 
 
 
 
 
 
 
 
 
649
  }
650
 
651
  /**
@@ -789,7 +802,8 @@ function LeafRow({
789
  onRule: (r: FilterRule) => void;
790
  onRemove: () => void;
791
  }) {
792
- const { fields, fieldByKey, measures, measureByKey, lists, viewChoices, choicesFor } = ctx;
 
793
  const isMeasure = isMeasureRule(rule);
794
  const isCohort = rule.colId === COHORT_FIELD;
795
  const hasCohorts = lists.length > 0;
@@ -966,10 +980,15 @@ function LeafRow({
966
  you pick a thing to filter on, and a measure simply also asks for a period. Item 20
967
  adds the type MARK to each row and takes NO grouping with it: the marks are what the
968
  optgroup was reaching for, and they say it per row instead of splitting the list. */}
 
 
 
 
 
969
  <FieldSelectButton
970
  className={fieldClass}
971
  ariaLabel={fieldAria}
972
- title={goneColumn ? DELETED_FIELD_NOTE : undefined}
973
  value={rule.colId}
974
  onChange={onField}
975
  fields={[
@@ -1253,6 +1272,18 @@ export interface FilterBuilderPanelProps {
1253
  * serves an admin editor should know about.
1254
  */
1255
  footerExtra?: ReactNode;
 
 
 
 
 
 
 
 
 
 
 
 
1256
  /*
1257
  * β›” W47-T13 (owner instruction 15) DELETED `onClose` FROM THIS TYPE, and the deletion is the
1258
  * point. W38-T02 had added a header close button behind an optional `onClose`; the owner has
@@ -1274,6 +1305,7 @@ export function FilterBuilderPanel({
1274
  statusValues,
1275
  cohortLock,
1276
  footerExtra,
 
1277
  }: FilterBuilderPanelProps) {
1278
  const nodes = filterTreeNodes(filters);
1279
  const conj = filterTreeConj(filters);
@@ -1304,8 +1336,9 @@ export function FilterBuilderPanel({
1304
  );
1305
  const ctx = useMemo<LevelContext>(
1306
  () => ({ fields: condFields, fieldByKey, measures, measureByKey, lists: cohorts,
1307
- viewChoices, choicesFor }),
1308
- [condFields, fieldByKey, measures, measureByKey, cohorts, viewChoices, choicesFor]
 
1309
  );
1310
 
1311
  return (
 
646
  */
647
  viewChoices: { id: string; name: string }[];
648
  choicesFor: ChoicesFor;
649
+ /**
650
+ * ⭐⭐ W54-T31 (R8) β€” the HEADING the condition row's field list wears, or nothing.
651
+ *
652
+ * R8: the Fields list appears in exactly two places, and each one is labelled with what it is
653
+ * picking, so several `sales.. metrics` entries are distinguishable. This is the second place;
654
+ * the first is the Aggregate's column list in `sheet/BindingEditor.tsx`.
655
+ *
656
+ * β›” UNDEFINED IS THE DEFAULT AND IT MUST STAY PIXEL-IDENTICAL. The Data module's inline
657
+ * filter, the admin permission editor and the view builder all pass nothing, and
658
+ * `FieldSelectButton` renders no heading node at all when its `title` is undefined. A hardcoded
659
+ * string here would have put a Sheet sentence into three surfaces that did not ask for one.
660
+ */
661
+ fieldPickerTitle?: string;
662
  }
663
 
664
  /**
 
802
  onRule: (r: FilterRule) => void;
803
  onRemove: () => void;
804
  }) {
805
+ const { fields, fieldByKey, measures, measureByKey, lists, viewChoices, choicesFor,
806
+ fieldPickerTitle } = ctx;
807
  const isMeasure = isMeasureRule(rule);
808
  const isCohort = rule.colId === COHORT_FIELD;
809
  const hasCohorts = lists.length > 0;
 
980
  you pick a thing to filter on, and a measure simply also asks for a period. Item 20
981
  adds the type MARK to each row and takes NO grouping with it: the marks are what the
982
  optgroup was reaching for, and they say it per row instead of splitting the list. */}
983
+ {/* ⭐⭐ W54-T31 (R8) β€” THE HEADING GOES IN THE ELSE BRANCH, NEVER OVER THE WHOLE
984
+ EXPRESSION. `DELETED_FIELD_NOTE` explains a column that is gone; a heading merely says
985
+ what the list picks. A refusal outranks a label, so the note keeps winning on exactly
986
+ the rows it won on before, and a host that passes no heading gets `undefined` here, the
987
+ same value this expression has always produced. */}
988
  <FieldSelectButton
989
  className={fieldClass}
990
  ariaLabel={fieldAria}
991
+ title={goneColumn ? DELETED_FIELD_NOTE : fieldPickerTitle}
992
  value={rule.colId}
993
  onChange={onField}
994
  fields={[
 
1272
  * serves an admin editor should know about.
1273
  */
1274
  footerExtra?: ReactNode;
1275
+ /**
1276
+ * ⭐⭐ W54-T31 (R8) β€” a heading for the condition row's FIELD LIST, saying what that list is
1277
+ * picking. R8 asks for it because a tenant can carry several entries reading `sales.. metrics`
1278
+ * and the list itself is where that ambiguity is answered.
1279
+ *
1280
+ * β›” OPTIONAL, AND ABSENT MEANS NO HEADING NODE AT ALL. Every existing caller (the Data
1281
+ * module's inline filter, the admin permission editor, the view builder) passes nothing and
1282
+ * renders exactly as it did before this prop existed; only the Sheet's centred filter dialog
1283
+ * passes one, because only there is the list floating free of a panel that names it.
1284
+ * The deleted-column note still wins on a row whose column is gone: see `LeafRow`.
1285
+ */
1286
+ fieldPickerTitle?: string;
1287
  /*
1288
  * β›” W47-T13 (owner instruction 15) DELETED `onClose` FROM THIS TYPE, and the deletion is the
1289
  * point. W38-T02 had added a header close button behind an optional `onClose`; the owner has
 
1305
  statusValues,
1306
  cohortLock,
1307
  footerExtra,
1308
+ fieldPickerTitle,
1309
  }: FilterBuilderPanelProps) {
1310
  const nodes = filterTreeNodes(filters);
1311
  const conj = filterTreeConj(filters);
 
1336
  );
1337
  const ctx = useMemo<LevelContext>(
1338
  () => ({ fields: condFields, fieldByKey, measures, measureByKey, lists: cohorts,
1339
+ viewChoices, choicesFor, fieldPickerTitle }),
1340
+ [condFields, fieldByKey, measures, measureByKey, cohorts, viewChoices, choicesFor,
1341
+ fieldPickerTitle]
1342
  );
1343
 
1344
  return (
web/src/filter-kit/SheetFilterPopup.tsx CHANGED
@@ -45,10 +45,17 @@
45
 
46
  import { useId, useRef } from "react";
47
  import { BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/OverlaySurface";
48
- import type { Field, FilterTree } from "../customer-grid/types";
49
- import { filterTreeNodes } from "../customer-grid/types";
 
 
50
  // Through the barrel, which is how every other consumer of this kit imports the panel.
51
  import { FilterBuilderPanel, countConditions } from "./index";
 
 
 
 
 
52
 
53
  export interface SheetFilterPopupProps {
54
  /** The cell this filter belongs to, e.g. `B4`. Named in the title so the dialog says which
@@ -71,9 +78,100 @@ export function conditionCountLabel(filters: FilterTree): string {
71
  return n === 1 ? "1 condition" : `${n} conditions`;
72
  }
73
 
74
- /** The dialog itself. Split from the export ONLY so that `useOverlayLayer` runs BELOW the
75
- * provider and therefore joins the same stack the value picker will join. */
76
- function SheetFilterDialog({
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  addr, onClose, fields, filters, onChange, statusValues,
78
  }: SheetFilterPopupProps) {
79
  const panelRef = useRef<HTMLDivElement>(null);
@@ -139,20 +237,45 @@ function SheetFilterDialog({
139
  {/* `min-width: 0` so the builder's rows may shrink inside this flex column instead of
140
  pushing the dialog wider than the viewport on a small screen. */}
141
  <div className="sheet-filter-popup-body" style={{ minWidth: 0 }}>
 
 
 
 
 
 
 
 
 
142
  <FilterBuilderPanel
143
  fields={fields}
144
  filters={filters}
145
  onChange={onChange}
146
  statusValues={statusValues}
 
147
  />
148
  </div>
149
  <div className="lp-dialog-actions">
150
- {/* β›” NOT "Save", AND DELIBERATELY QUIET. Nothing is held back, so a Save button would
151
- imply a discard door that cannot exist without a draft copy of the tree, and the
152
- filled `lp-dialog-btn-primary` (`--lp-primary`, a violet) would give a control that
153
- merely closes the weight of a commit, in a palette the Sheet does not otherwise
154
- wear. `lp-dialog-btn-quiet` is a hairline on the dialog's own surface. */}
155
- <button type="button" className="lp-dialog-btn lp-dialog-btn-quiet" onClick={onClose}>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
  Done
157
  </button>
158
  </div>
 
45
 
46
  import { useId, useRef } from "react";
47
  import { BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/OverlaySurface";
48
+ import type {
49
+ Conjunction, Field, FilterNode, FilterOp, FilterRule, FilterTree,
50
+ } from "../customer-grid/types";
51
+ import { filterTreeConj, filterTreeNodes, isFilterGroup, isRuleActive } from "../customer-grid/types";
52
  // Through the barrel, which is how every other consumer of this kit imports the panel.
53
  import { FilterBuilderPanel, countConditions } from "./index";
54
+ // ⚠ DIRECT, NOT THROUGH THE BARREL, because `index.ts` re-exports four names from `ops.ts` and
55
+ // `opLabel` is not one of them. Widening the barrel would change what every other consumer of
56
+ // this kit can reach for a sentence only this file writes; a sibling import inside the same
57
+ // directory changes nothing outside it.
58
+ import { opLabel } from "./ops";
59
 
60
  export interface SheetFilterPopupProps {
61
  /** The cell this filter belongs to, e.g. `B4`. Named in the title so the dialog says which
 
78
  return n === 1 ? "1 condition" : `${n} conditions`;
79
  }
80
 
81
+ /**
82
+ * ⭐⭐ W54-T35 (ruling R8, owner instruction 8) β€” WHAT THE FILTER SAYS, AS A SENTENCE.
83
+ *
84
+ * Owner, verbatim: *"the Filter module itself will show exactly what the filter is when we click
85
+ * 'View row' so its easy for user also to know what this filter is."* A count answers "how many
86
+ * rules are there"; it does not answer "what is this filter". So the drill needs the second
87
+ * thing, and `conditionCountLabel` directly above stays the answer to the first.
88
+ *
89
+ * β›” IT IS BUILT FROM `opLabel`, NOT FROM A SECOND OPERATOR VOCABULARY. `FilterBuilderPanel`
90
+ * paints each condition row's operator with `opLabel(op, fieldType)`, so the sentence and the
91
+ * builder behind the Edit door say the same words for the same rule. A local table would drift
92
+ * the first time the owner reworded one of them, and the reader would be told two things.
93
+ *
94
+ * β›” INACTIVE RULES ARE OMITTED, and that is the honest reading rather than a tidy one. A rule
95
+ * with a blank value is IGNORED by the engine (`isRuleActive`, whose Python mirror
96
+ * `filter_sql.is_rule_active` decides the same thing server-side), so the rows on screen were
97
+ * not narrowed by it. Naming it here would describe rows nobody is looking at.
98
+ *
99
+ * ⚠ THREE LEAVES AND THEN A COUNT. The band this feeds is one line across the foot of a modal
100
+ * whose job is the rows above it; a filter with nine rules cannot be read there whatever we do, and an ellipsis in the
101
+ * middle of a value is worse than a number. The dialog behind the Edit door is where a long
102
+ * filter is actually read, which is what makes the truncation safe rather than lossy.
103
+ */
104
+ const MAX_SPOKEN_LEAVES = 3;
105
+
106
+ /** One leaf, in the builder's own words. `fields` is a map so a nested walk stays linear. */
107
+ function ruleSentence(rule: FilterRule, byKey: Map<string, Field>): string {
108
+ const field = byKey.get(rule.colId);
109
+ const name = field?.label || rule.colId;
110
+ // A column whose type is no longer known reads as text, which is what `opsForType` offers a
111
+ // missing column too: the op still has a label, so the rule still has a sentence.
112
+ const phrase = opLabel(rule.op as FilterOp, field?.type ?? "text");
113
+ const listed = rule.values?.length ? rule.values.join(", ") : "";
114
+ const single = typeof rule.value === "string" ? rule.value.trim() : "";
115
+ const operand = listed || single;
116
+ // `value2` is the far end of a `between`, and the builder reads it as a pair.
117
+ const both = rule.value2 ? `${operand} and ${String(rule.value2).trim()}` : operand;
118
+ return both ? `${name} ${phrase} ${both}` : `${name} ${phrase}`;
119
+ }
120
+
121
+ /** Does this node narrow anything? A group of blanks narrows nothing, same as a blank rule. */
122
+ function nodeIsActive(node: FilterNode): boolean {
123
+ return isFilterGroup(node)
124
+ ? node.children.some(nodeIsActive)
125
+ : isRuleActive(node as FilterRule);
126
+ }
127
+
128
+ function nodesSentence(nodes: FilterNode[], conj: Conjunction, byKey: Map<string, Field>): string {
129
+ const joiner = conj === "or" ? " or " : " and ";
130
+ const live = nodes.filter(nodeIsActive);
131
+ const spoken = live.slice(0, MAX_SPOKEN_LEAVES).map((node) =>
132
+ isFilterGroup(node)
133
+ ? `(${nodesSentence(node.children, node.conj, byKey)})`
134
+ : ruleSentence(node as FilterRule, byKey));
135
+ const rest = live.length - spoken.length;
136
+ if (rest > 0) spoken.push(rest === 1 ? "1 more condition" : `${rest} more conditions`);
137
+ return spoken.join(joiner);
138
+ }
139
+
140
+ /**
141
+ * The filter, in readable terms.
142
+ *
143
+ * β›” EMPTY MEANS EMPTY: a filter that narrows nothing returns `""` rather than a sentence saying
144
+ * so. The caller is the one that knows what to say instead, and it already has
145
+ * `conditionCountLabel` for exactly that, so returning a phrase here would be a THIRD wording of
146
+ * "nothing yet" for the two surfaces to drift apart on. A caller that wants the count says
147
+ * `filterSentence(t, f) || conditionCountLabel(t)`, which is one line and reads as the rule.
148
+ */
149
+ export function filterSentence(
150
+ filters: FilterTree | null | undefined, fields: Field[],
151
+ ): string {
152
+ const byKey = new Map(fields.map((f) => [f.key, f]));
153
+ return nodesSentence(filterTreeNodes(filters), filterTreeConj(filters), byKey);
154
+ }
155
+
156
+ /**
157
+ * The dialog itself. Split from `SheetFilterPopup` ONLY so that `useOverlayLayer` runs BELOW the
158
+ * provider and therefore joins the same stack the value picker will join.
159
+ *
160
+ * ⭐⭐ W54-T35 β€” AND THAT IS WHY IT IS NOW EXPORTED. `SheetFilterPopup` brings its OWN
161
+ * `OverlayProvider`, which is exactly right when the dialog is the only surface of its family on
162
+ * screen (the binding panel's case). It is exactly WRONG when the caller already has another
163
+ * body-level overlay open that the dialog must be ranked against: a private provider is a private
164
+ * stack, so the surface underneath would keep answering `isTop` true and would dismiss itself on
165
+ * the first pointerdown inside this dialog. `sheet/DrillModal.tsx` opens this over the linked
166
+ * record grid, and it supplies ONE provider for both, so both join one stack and the outside-click
167
+ * contract can order them. Callers with nothing else open should keep using `SheetFilterPopup`.
168
+ *
169
+ * ⚠ ESCAPE IS NOT WHAT THIS FIXES, and confusing the two is how the wrong shape gets shipped.
170
+ * Escape is arbitrated by the module-level stack in `ui/useEscapeClose` (topmost claimant wins,
171
+ * by push order) and has never needed a provider. `OverlayStackContext` orders OUTSIDE CLICKS and
172
+ * the Tab trap, and only for layers that can see each other.
173
+ */
174
+ export function SheetFilterDialog({
175
  addr, onClose, fields, filters, onChange, statusValues,
176
  }: SheetFilterPopupProps) {
177
  const panelRef = useRef<HTMLDivElement>(null);
 
237
  {/* `min-width: 0` so the builder's rows may shrink inside this flex column instead of
238
  pushing the dialog wider than the viewport on a small screen. */}
239
  <div className="sheet-filter-popup-body" style={{ minWidth: 0 }}>
240
+ {/* ⭐⭐ W54-T31 (R8) β€” THE SECOND OF THE TWO LABELLED FIELDS LISTS. R8: "Each Fields
241
+ list is labelled with what it is picking, so several `sales.. metrics` entries are
242
+ distinguishable." The first is the Aggregate's column list in `BindingEditor`,
243
+ whose heading names the database and the fold; this one names the CELL, in the same
244
+ words this dialog's own title uses, because that is what tells a reader whose
245
+ filter they are choosing a field for. One line, sentence case: a heading says what
246
+ the list is for and then gets out of the way.
247
+ β›” Passed HERE and nowhere else. The prop is optional, so the Data module's inline
248
+ filter and the admin permission editor keep the picker they have. */}
249
  <FilterBuilderPanel
250
  fields={fields}
251
  filters={filters}
252
  onChange={onChange}
253
  statusValues={statusValues}
254
+ fieldPickerTitle={`Fields to filter ${addr} by`}
255
  />
256
  </div>
257
  <div className="lp-dialog-actions">
258
+ {/* β›” STILL NOT "Save", AND NO LONGER QUIET. The first half of that stands: nothing is
259
+ held back, so a Save button would imply a discard door that cannot exist without a
260
+ draft copy of the tree, and the word stays "Done".
261
+
262
+ ⭐ THE SECOND HALF WAS OVERTURNED BY THE OWNER, W54-T30 / instruction 26, verbatim:
263
+ "the Done button under 'Build a filter' is not on brand and is really ugly". The
264
+ argument this comment used to carry β€” that a filled `lp-dialog-btn-primary` gives a
265
+ control that merely closes the weight of a commit, in a palette the Sheet does not
266
+ otherwise wear β€” is now a decision that was made and reversed, so it is recorded as
267
+ history rather than left standing over code that contradicts it.
268
+
269
+ What replaces it: `Done` is the only action in this dialog's footer and it is the
270
+ affirmative one, which is the definition `DESIGN.md` gives `--lp-primary` when it
271
+ reserves the #5433CC family for the primary CTA. `lp-dialog-btn-primary` is that
272
+ token pairing already built in `styles/wave51/kit.css`, so this is a class change
273
+ and not one line of new paint: no local override, no hex, nothing for the Sheet to
274
+ keep in sync with the kit. `--lp-primary` measures 7.71:1 against the white it puts
275
+ its label on, so the filled treatment is the more legible one as well as the
276
+ on-brand one. The hairline `lp-dialog-btn-quiet` remains the right treatment for a
277
+ SECONDARY action, and this footer does not have one. */}
278
+ <button type="button" className="lp-dialog-btn lp-dialog-btn-primary" onClick={onClose}>
279
  Done
280
  </button>
281
  </div>
web/src/settings/PermsEditor.tsx CHANGED
@@ -70,12 +70,14 @@ import { DatabasePermsPane } from "./DatabasePermsPane";
70
  // C4: this lane's own stylesheet. `index.css` is B's and nothing here touches it.
71
  import "./perms.css";
72
  import {
 
73
  getUserPerms,
74
  patchUser,
 
75
  putUserPerms,
76
  setPassword,
77
  } from "./settingsApi";
78
- import type { AdminUser } from "./settingsApi";
79
  import type { PermsModule, PermsPayload, PermsRecord } from "./permsModel";
80
  import {
81
  accessSummary,
@@ -182,6 +184,28 @@ export function PermsEditor({
182
  const [role, setRole] = useState(user.role ?? "user");
183
  const [pw, setPw] = useState("");
184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  useEffect(() => {
186
  let dead = false;
187
  setLoad({ phase: "loading" });
@@ -211,6 +235,33 @@ export function PermsEditor({
211
  };
212
  }, [username]);
213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  const payload = load.phase === "ready" ? load.payload : null;
215
  /**
216
  * ⭐ W40-T14 β€” the drill-in RESOLVED, which is the only form the render is allowed to trust.
@@ -270,7 +321,14 @@ export function PermsEditor({
270
  */
271
  const accountDirty =
272
  name.trim() !== (user.name ?? "").trim() || role !== (user.role ?? "user");
273
- const anyDirty = dirty || accountDirty;
 
 
 
 
 
 
 
274
  /**
275
  * ⭐⭐ W47-T19 (owner instruction 11) β€” WHAT THE ONE SAVE SAYS IT SAVES. With the two buttons
276
  * merged there is a single control committing two different kinds of work, and a fixed label
@@ -289,7 +347,9 @@ export function PermsEditor({
289
  * `saves_show_they_are_working`'s own NC strips to prove leg 1 can still fire. Changing either
290
  * word means changing the gate that pins it, in the same commit, on purpose.
291
  */
292
- const saveLabel = dirty && !accountDirty ? "Save access" : "Save account";
 
 
293
 
294
  const goBack = useCallback(() => {
295
  if (anyDirty) setAsk({ kind: "discard" });
@@ -400,6 +460,29 @@ export function PermsEditor({
400
  return;
401
  }
402
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
403
  if (!payload) {
404
  setBusy(false);
405
  setAsk(null);
@@ -429,7 +512,7 @@ export function PermsEditor({
429
  } else {
430
  setError(r.message);
431
  }
432
- }, [payload, draft, username, onSaved, accountDirty, name, role]);
433
 
434
  /** The account half's write. ⚠ THE PATCH STILL CARRIES NO `bus` (R1), and
435
  * that is load-bearing rather than tidy: with the picker gone this form
@@ -860,6 +943,73 @@ export function PermsEditor({
860
  </>
861
  )}
862
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
863
  </div>
864
  </>
865
  ) : null}
@@ -931,7 +1081,7 @@ export function PermsEditor({
931
  that only asked about access would be understating what the click does. */}
932
  <h4 className="set-h4">Save these changes for {displayName}?</h4>
933
  <p className="set-help">
934
- {unsavedWords(dirty, accountDirty)} are written now, and a change to access takes
935
  effect the next time they load a page. {accessSummaryLine(payload, draft)}
936
  </p>
937
  </>
@@ -942,7 +1092,7 @@ export function PermsEditor({
942
  work now, and "your changes" over a form the reader cannot
943
  see behind the scrim is a question they cannot answer. */}
944
  <p className="set-help">
945
- {unsavedWords(dirty, accountDirty)} for {displayName} stay as they were.
946
  </p>
947
  </>
948
  )}
 
70
  // C4: this lane's own stylesheet. `index.css` is B's and nothing here touches it.
71
  import "./perms.css";
72
  import {
73
+ getConnectorGrants,
74
  getUserPerms,
75
  patchUser,
76
+ putConnectorGrants,
77
  putUserPerms,
78
  setPassword,
79
  } from "./settingsApi";
80
+ import type { AdminUser, ConnectorKind } from "./settingsApi";
81
  import type { PermsModule, PermsPayload, PermsRecord } from "./permsModel";
82
  import {
83
  accessSummary,
 
184
  const [role, setRole] = useState(user.role ?? "user");
185
  const [pw, setPw] = useState("");
186
 
187
+ /**
188
+ * ⭐⭐ W54-T47 / R4 / contract C4 β€” THE THIRD AXIS. Owner, verbatim: *"Under Settings, an Admin
189
+ * should grant a user access to add connectors, so access becomes Database / Module /
190
+ * Connector."*
191
+ *
192
+ * β›” IT IS ITS OWN STATE RATHER THAN A THIRD GROUP OF `draft`, because it is not a registry key.
193
+ * `payload.modules` are databases and surfaces the perms record governs; a connector is a
194
+ * CREDENTIAL KIND out of `core/keychain.py::ENTRY_TYPES`, carried by its own route so the perms
195
+ * PUT body stays exactly the whole-record replace `permsModel.toPutBody` builds. Folding it in
196
+ * would have made every existing perms leg negotiate a key that is not a module.
197
+ *
198
+ * ⚠ `kinds` EMPTY IS ALSO THE FAILURE STATE, deliberately. A server that cannot answer, or one
199
+ * that predates this route, leaves the list empty and the section renders NO HEADING at all,
200
+ * which is the same rule the Database and Module groups already follow: a group with no members
201
+ * is not a labelled empty room.
202
+ */
203
+ const [connKinds, setConnKinds] = useState<ConnectorKind[]>([]);
204
+ /** The grants as the SERVER holds them, and the draft beside it. Same pairing, same reason, as
205
+ * `saved` / `draft` above: without the baseline there is nothing for "unsaved" to mean. */
206
+ const [connSaved, setConnSaved] = useState<string[]>([]);
207
+ const [connDraft, setConnDraft] = useState<string[]>([]);
208
+
209
  useEffect(() => {
210
  let dead = false;
211
  setLoad({ phase: "loading" });
 
235
  };
236
  }, [username]);
237
 
238
+ /**
239
+ * ⭐ W54-T47 β€” THE CONNECTOR AXIS IS READ ON ITS OWN WIRE, AND A FAILURE HERE IS SILENT.
240
+ *
241
+ * β›” IT MUST NOT BE ABLE TO BREAK THE PAGE. The perms GET above puts the whole editor into an
242
+ * error state when it cannot be read, and rightly: an admin must never be invited to save a
243
+ * record they were not shown. This one is the opposite case. The grants it fetches are the ONLY
244
+ * thing it can affect, absence of a grant is the ordinary state of every account in the product,
245
+ * and the wall is on the server either way. So a refusal leaves `connKinds` empty, the section
246
+ * renders nothing, and Database and Module keep working exactly as they did.
247
+ */
248
+ useEffect(() => {
249
+ let dead = false;
250
+ setConnKinds([]);
251
+ setConnSaved([]);
252
+ setConnDraft([]);
253
+ void getConnectorGrants(username).then((r) => {
254
+ if (dead || !r.ok) return;
255
+ const granted = Array.isArray(r.data?.granted) ? r.data.granted.map(String) : [];
256
+ setConnKinds(Array.isArray(r.data?.kinds) ? r.data.kinds : []);
257
+ setConnSaved(granted);
258
+ setConnDraft(granted);
259
+ });
260
+ return () => {
261
+ dead = true;
262
+ };
263
+ }, [username]);
264
+
265
  const payload = load.phase === "ready" ? load.payload : null;
266
  /**
267
  * ⭐ W40-T14 β€” the drill-in RESOLVED, which is the only form the render is allowed to trust.
 
321
  */
322
  const accountDirty =
323
  name.trim() !== (user.name ?? "").trim() || role !== (user.role ?? "user");
324
+ /**
325
+ * ⭐ W54-T47 β€” the Connector axis's own baseline comparison. Compared as SORTED text rather than
326
+ * by reference or length: the checkbox writes a new array on every click, so identity says
327
+ * nothing, and two lists of the same size can hold different kinds.
328
+ */
329
+ const connKey = (list: string[]) => [...list].sort().join("");
330
+ const connDirty = connKey(connDraft) !== connKey(connSaved);
331
+ const anyDirty = dirty || accountDirty || connDirty;
332
  /**
333
  * ⭐⭐ W47-T19 (owner instruction 11) β€” WHAT THE ONE SAVE SAYS IT SAVES. With the two buttons
334
  * merged there is a single control committing two different kinds of work, and a fixed label
 
347
  * `saves_show_they_are_working`'s own NC strips to prove leg 1 can still fire. Changing either
348
  * word means changing the gate that pins it, in the same commit, on purpose.
349
  */
350
+ /** ⚠ W54-T47 β€” the Connector axis counts as ACCESS, which is what the owner called it. Widening
351
+ * the first operand rather than adding a third word keeps both pinned spellings intact. */
352
+ const saveLabel = (dirty || connDirty) && !accountDirty ? "Save access" : "Save account";
353
 
354
  const goBack = useCallback(() => {
355
  if (anyDirty) setAsk({ kind: "discard" });
 
460
  return;
461
  }
462
  }
463
+ /**
464
+ * ⭐ W54-T47 β€” THE CONNECTOR AXIS COMMITS HERE, BETWEEN THE TWO, AND THAT POSITION IS THE
465
+ * ARGUMENT ABOVE APPLIED ONCE MORE.
466
+ *
467
+ * β›” AFTER THE ACCOUNT PATCH, because promoting the account to Admin makes every rule below
468
+ * inert and a refused PATCH must still write nothing at all.
469
+ * β›” BEFORE the `!payload` early return, because this grant does not live in the perms record
470
+ * and has its own route: a failing perms GET must not take the Connector axis down with it,
471
+ * for the same reason it does not take Deactivate down with it.
472
+ * β›” AND A FAILURE STOPS THE ACTION rather than being swallowed. This is a permission write;
473
+ * a half-save that reports success is how somebody comes to believe they revoked a connector
474
+ * they did not.
475
+ */
476
+ if (connDirty) {
477
+ const g = await putConnectorGrants(username, connDraft);
478
+ if (!g.ok) {
479
+ setBusy(false);
480
+ setAsk(null);
481
+ setError(g.message);
482
+ return;
483
+ }
484
+ setConnSaved(connDraft);
485
+ }
486
  if (!payload) {
487
  setBusy(false);
488
  setAsk(null);
 
512
  } else {
513
  setError(r.message);
514
  }
515
+ }, [payload, draft, username, onSaved, accountDirty, name, role, connDirty, connDraft]);
516
 
517
  /** The account half's write. ⚠ THE PATCH STILL CARRIES NO `bus` (R1), and
518
  * that is load-bearing rather than tidy: with the picker gone this form
 
943
  </>
944
  )}
945
 
946
+ {/* ⭐⭐ W54-T47 / R4 / contract C4 β€” THE THIRD ROOM. Owner, verbatim: *"Under
947
+ Settings, an Admin should grant a user access to add connectors, so access becomes
948
+ Database / Module / Connector. This allows many connectors per tenant … depending
949
+ on the admin's configuration per user."*
950
+
951
+ β›” IT SITS OUTSIDE THE `payload.modules.length` TERNARY ABOVE, and that is not a
952
+ layout choice. A connector is not a registry module, so a deployment that governs
953
+ no databases at all can still have an administrator deciding who may wire up
954
+ Shopify; nesting this inside that branch would have made the new axis disappear
955
+ for exactly the tenant with the least already set up.
956
+
957
+ β›” A GROUP WITH NO MEMBERS RENDERS NO HEADING, the same rule the two groups above
958
+ follow and the same reason: an empty labelled room says the deployment lost
959
+ something rather than that it never had it. An older server, or one whose route
960
+ refused, leaves `connKinds` empty and nothing paints.
961
+
962
+ ⚠ A CHECKBOX PER KIND AND NO `ModulePermsList`. That component's furniture is a
963
+ filter, a field list and a drill-in room; a connector has none of the three, and
964
+ borrowing the card would have promised three controls that cannot exist. The card
965
+ idiom is shared, the list component is not. */}
966
+ {connKinds.length ? (
967
+ <>
968
+ <h5 className="set-h4 set-perm-group">Connector</h5>
969
+ {/* ⚠ THE SECOND SENTENCE IS THE ONE A READER CANNOT GET BY LOOKING, and it is
970
+ what stops an admin reading an empty list as a lockout: no grant is the
971
+ ordinary state and it takes nothing away. */}
972
+ <p className="set-help set-perm-intro">
973
+ Ticked connectors are the ones this account can add for the whole workspace.
974
+ Everyone can already add their own personal connections, so leaving these clear
975
+ takes nothing away.
976
+ </p>
977
+ {connKinds.map((k) => {
978
+ const on = connDraft.includes(k.key);
979
+ return (
980
+ <section className="set-card set-perm-mod" key={k.key}>
981
+ <div className="set-perm-modhead">
982
+ <label className="set-check set-perm-toggle">
983
+ <input
984
+ type="checkbox"
985
+ checked={on}
986
+ onChange={(e) =>
987
+ setConnDraft((cur) =>
988
+ e.target.checked
989
+ ? [...cur, k.key]
990
+ : cur.filter((x) => x !== k.key)
991
+ )
992
+ }
993
+ />
994
+ <span className="set-perm-modname">{k.label}</span>
995
+ </label>
996
+ {/* ⚠ Wrapped for the reason `ModulePermsList` wraps its own trailing
997
+ controls: `.set-perm-modhead` is `space-between` and lives in
998
+ `index.css`, which this lane does not own. One flex child in, one out. */}
999
+ <span className="set-perm-headend">
1000
+ {k.tenantWide ? (
1001
+ <span className="set-perm-sum">
1002
+ Every database in this workspace reads through it
1003
+ </span>
1004
+ ) : null}
1005
+ </span>
1006
+ </div>
1007
+ </section>
1008
+ );
1009
+ })}
1010
+ </>
1011
+ ) : null}
1012
+
1013
  </div>
1014
  </>
1015
  ) : null}
 
1081
  that only asked about access would be understating what the click does. */}
1082
  <h4 className="set-h4">Save these changes for {displayName}?</h4>
1083
  <p className="set-help">
1084
+ {unsavedWords(dirty || connDirty, accountDirty)} are written now, and a change to access takes
1085
  effect the next time they load a page. {accessSummaryLine(payload, draft)}
1086
  </p>
1087
  </>
 
1092
  work now, and "your changes" over a form the reader cannot
1093
  see behind the scrim is a question they cannot answer. */}
1094
  <p className="set-help">
1095
+ {unsavedWords(dirty || connDirty, accountDirty)} for {displayName} stay as they were.
1096
  </p>
1097
  </>
1098
  )}
web/src/settings/settingsApi.ts CHANGED
@@ -196,6 +196,61 @@ export function putUserPerms(
196
  });
197
  }
198
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  /** Wave 14 C-AVATAR β€” own-profile photo. The server returns the refreshed `{user}` envelope;
200
  * the caller parses it with `session.parseUserEnvelope` so the shell chip updates live. */
201
  export function setAvatar(dataUrl: string): Promise<ApiResult<{ user: unknown }>> {
@@ -260,6 +315,12 @@ export function listKeychain(): Promise<
260
  /** Types that are always business-wide β€” the whole workspace reads its databases through
261
  * them, so "personal" would be a label rather than a boundary. */
262
  tenantWideTypes?: string[];
 
 
 
 
 
 
263
  }>
264
  > {
265
  return call("/admin/keychain");
 
196
  });
197
  }
198
 
199
+ // --- wave 54, W54-T47 / R4 / contract C4: the THIRD grant axis ---------------
200
+ //
201
+ // Owner, verbatim: *"Under Settings, an Admin should grant a user access to add
202
+ // connectors, so access becomes Database / Module / Connector."* Database and
203
+ // Module are two groupings of the `perms` record above; Connector is not a
204
+ // registry key at all, it is a CREDENTIAL KIND, so it has its own pair of calls
205
+ // rather than a third section of the perms body.
206
+ //
207
+ // β›” ADMIN-ONLY AND FAIL-CLOSED AT THE SERVER, exactly like the two above. And
208
+ // the grant these write is consulted by `POST /admin/keychain` itself
209
+ // (`core/perm_scope.may_add_connection`), so a client that never called them
210
+ // changes nothing: absence is the behaviour that shipped before this wave.
211
+
212
+ /** One connectable kind, as the server declares it. */
213
+ export interface ConnectorKind {
214
+ key: string;
215
+ label: string;
216
+ /** True when the whole workspace reads its databases through this source, so a
217
+ * connection of it is never personal. Granting it hands the member the
218
+ * workspace's own credential slot, which an admin should read before ticking. */
219
+ tenantWide: boolean;
220
+ }
221
+
222
+ export interface ConnectorGrants {
223
+ username: string;
224
+ /** The vocabulary, served rather than hard-coded here: it is
225
+ * `core/keychain.py::ENTRY_TYPES`, and a client copy is the drift a parity
226
+ * gate exists to stop. */
227
+ kinds: ConnectorKind[];
228
+ /** The kinds this account may create a business-wide connection of. Empty is
229
+ * the ordinary state and means "no grant", never "denied everything". */
230
+ granted: string[];
231
+ }
232
+
233
+ export function getConnectorGrants(
234
+ username: string
235
+ ): Promise<ApiResult<ConnectorGrants>> {
236
+ return call<ConnectorGrants>(
237
+ `/admin/users/${encodeURIComponent(username)}/connector-grants`
238
+ );
239
+ }
240
+
241
+ /** WHOLE-LIST REPLACE, for the reason `putUserPerms` is one: revoking has to be
242
+ * expressible, and a merge cannot express a deletion without a second
243
+ * vocabulary for it. An empty list is a legal body and it revokes. */
244
+ export function putConnectorGrants(
245
+ username: string,
246
+ granted: string[]
247
+ ): Promise<ApiResult<ConnectorGrants>> {
248
+ return call<ConnectorGrants>(
249
+ `/admin/users/${encodeURIComponent(username)}/connector-grants`,
250
+ { method: "PUT", body: JSON.stringify({ granted }) }
251
+ );
252
+ }
253
+
254
  /** Wave 14 C-AVATAR β€” own-profile photo. The server returns the refreshed `{user}` envelope;
255
  * the caller parses it with `session.parseUserEnvelope` so the shell chip updates live. */
256
  export function setAvatar(dataUrl: string): Promise<ApiResult<{ user: unknown }>> {
 
315
  /** Types that are always business-wide β€” the whole workspace reads its databases through
316
  * them, so "personal" would be a label rather than a boundary. */
317
  tenantWideTypes?: string[];
318
+ /** W54-T47 / R4 β€” the kinds THIS reader may create a business-wide connection of without
319
+ * being an admin, because an admin granted them the Connector axis.
320
+ * β›” COURTESY, NEVER THE WALL: `POST /admin/keychain` asks the server-side predicate
321
+ * regardless of what a client believes about this list. Absent reads as none, which is the
322
+ * behaviour every account had before this wave. */
323
+ connectorGrants?: string[];
324
  }>
325
  > {
326
  return call("/admin/keychain");
web/src/sheet/BindingEditor.tsx CHANGED
@@ -36,10 +36,11 @@
36
  // ⚠ DESIGN CONTRACT: sentence case, quiet buttons, token-only colour and type, motion 150 ms
37
  // ease-out on opacity and transform, no emoji, and no em dash or en dash in any string on screen.
38
 
39
- import { useCallback, useEffect, useMemo, useRef, useState } from "react";
40
  import { fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge";
41
  import type { SurfaceScope } from "../customer-grid/apiBridge";
42
  import { FieldTypeIcon } from "../customer-grid/icons";
 
43
  import type { Field, FilterTree, Row } from "../customer-grid/types";
44
  import { choiceVocabulary, topicForScope } from "../customer-grid/types";
45
  // ⭐⭐ W53-T15 (ruling R8) β€” THE FILTER BUILDER IS NO LONGER MOUNTED IN THIS COLUMN. The SHARED
@@ -59,6 +60,13 @@ const AGGREGATES = [
59
  { fn: "max", label: "Maximum" },
60
  ] as const;
61
 
 
 
 
 
 
 
 
62
  // ══ W53-T13: WHICH COLUMNS THE SERVER CAN ACTUALLY TOTAL (R7, standing rule 9) ═══════════════
63
  //
64
  // ⭐⭐ THE PICKER MUST NOT OFFER A COLUMN THAT WILL REFUSE. `isNumericType` answers "does this
@@ -333,6 +341,250 @@ function viewList(raw: unknown): { id: string; name: string }[] {
333
  return (raw as { id: string; name: string }[]).map((v) => ({ id: v.id, name: v.name }));
334
  }
335
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
336
  export interface BindingEditorProps {
337
  workbookId: string;
338
  addr: string;
@@ -370,10 +622,34 @@ export default function BindingEditor({
370
  // arrives the list is legitimately empty, and a notice keyed on emptiness would flash "that view
371
  // is gone" at every perfectly valid binding for as long as the fetch took.
372
  const [viewsLoaded, setViewsLoaded] = useState(false);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
  // ⭐⭐ W53-T15 (ruling R8) β€” WHETHER THE CENTRED FILTER DIALOG IS ON SCREEN, and the ONLY state
374
  // this ticket adds. The tree itself stays in `tree`/`setTree` below and the dialog writes
375
  // straight into that setter, so there is no draft to reconcile when it closes.
376
  const [filterPopupOpen, setFilterPopupOpen] = useState(false);
 
 
 
 
 
377
  // ⭐⭐ W52-T14 (instruction 11) β€” THE FILTER'S VALUE VOCABULARY NEEDS ROWS, NOT ONLY FIELDS.
378
  // A declared select/status carries its own list on `field.options`, which the filter kit
379
  // already falls back to with no `statusValues` at all. A SERVER-COMPUTED one (a `select` whose
@@ -383,6 +659,22 @@ export default function BindingEditor({
383
  // them the same way CustomerGrid does (`topicForScope` + `fetchTopicRows`, the exact pair the
384
  // grid's own load path uses), sharing that call's cache so a database already open elsewhere in
385
  // this session costs nothing extra here.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
386
  const [rawRows, setRawRows] = useState<Row[]>([]);
387
  const [userOptions, setUserOptions] = useState<string[]>([]);
388
  const [preview, setPreview] = useState<string>("");
@@ -442,55 +734,103 @@ export default function BindingEditor({
442
  // the server) is the one that knows what exists NOW, and the list is rebuilt from whichever
443
  // answer arrived last.
444
  //
 
 
 
 
 
 
 
 
445
  // β›” A NULL REVALIDATE LEAVES THE CACHED LIST STANDING. `fetchWorkspace` answers null when the
446
  // call fails, and blanking a working dropdown because the network blinked would refuse a person
447
- // their own saved views for a reason that has nothing to do with the views.
 
 
448
  useEffect(() => {
449
  let live = true;
450
  const scope = scopeOf(database);
451
  setViewsLoaded(false);
 
 
 
 
452
  if (!scope) {
453
  setFields([]);
454
  setViews([]);
455
- setRawRows([]);
456
  setUserOptions([]);
 
 
 
 
457
  return () => { live = false; };
458
  }
459
  (async () => {
460
- // Run in parallel: the schema/views door and the rows door answer different questions and
461
- // neither is gated on the other. `fetchTopicRows` shares `rowsCache` with the grid itself.
462
- const [ws, rowsPayload] = await Promise.all([
463
- fetchWorkspace(scope, { allowCached: true }),
464
- fetchTopicRows(topicForScope(scope)),
465
- ]);
466
- if (!live) return;
467
- if (ws) {
468
- setFields((ws.fields ?? []) as Field[]);
469
- setViews(viewList(ws.views));
470
- }
471
- setRawRows(rowsPayload?.rows ?? []);
472
- setUserOptions(rowsPayload?.userOptions ?? ws?.userOptions ?? []);
473
-
474
  const fresh = await fetchWorkspace(scope);
475
  if (!live) return;
476
  if (!fresh) {
477
- // Offline or refused. Only claim the list is settled if the cached read produced one.
478
- if (ws) setViewsLoaded(true);
 
 
 
 
 
 
 
 
 
 
 
 
479
  return;
480
  }
481
  const list = viewList(fresh.views);
482
  setFields((fresh.fields ?? []) as Field[]);
483
  setViews(list);
 
 
 
 
484
  setViewsLoaded(true);
485
  // β›” A SELECTED VIEW THAT NO LONGER EXISTS IS CLEARED, so Save cannot store a dead id β€” that
486
  // stored id is exactly the state this ticket was reported for. The notice in `Rows to
487
  // include` is what explains the empty control; clearing without saying so would read as the
488
  // panel losing the choice on its own.
489
  setViewId((cur) => (cur && !list.some((v) => v.id === cur) ? "" : cur));
 
 
 
 
490
  })();
491
  return () => { live = false; };
492
  }, [database]);
493
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
494
  /** The binding names a view the fresh list does not have. Said in the panel, not after a save.
495
  *
496
  * β›” IT STOPS BEING SAID THE MOMENT THE PERSON ANSWERS IT. The sentence asks for one of two acts,
@@ -535,9 +875,9 @@ export default function BindingEditor({
535
  [fields],
536
  );
537
 
538
- /** True when at least one Metric column is on offer, which is what the hint under the list is
539
- * for: a Metric answers over the PERIOD chosen below, and no other column here does. */
540
- const offersMetric = useMemo(() => numericFields.some(isMetricField), [numericFields]);
541
 
542
  /** The saved binding names a column this database will not total. Said in the panel, where the
543
  * choice is made, rather than as a refusal after a save.
@@ -584,6 +924,15 @@ export default function BindingEditor({
584
  || String(f.key).toLowerCase().includes(q));
585
  }, [fieldQuery, numericFields]);
586
 
 
 
 
 
 
 
 
 
 
587
  const binding = useMemo(() => {
588
  const agg: Record<string, unknown> = fn === "count" ? { fn } : { fn, field };
589
  const scope: Record<string, unknown> = scopeKind === "view"
@@ -626,7 +975,10 @@ export default function BindingEditor({
626
  setPreview(got.value.display || String(got.value.value ?? ""));
627
  };
628
 
629
- const ready = Boolean(database) && (fn === "count" || Boolean(field))
 
 
 
630
  && (scopeKind === "filter" || Boolean(viewId));
631
 
632
  const { y: startYear, m: startMonth } = splitYm(start);
@@ -668,383 +1020,380 @@ export default function BindingEditor({
668
  builder is taller than the page, and a panel that scrolls as a whole pushes Save below
669
  the fold with nothing on screen saying it is there. */}
670
  <div className="sheet-binding-scroll">
671
- <label className="sheet-field">
672
- <span>Database</span>
673
- <select value={database} onChange={(e) => setDatabase(e.target.value)}>
674
- {databases.map((d) => <option key={d.key} value={d.key}>{d.label}</option>)}
675
- </select>
676
- </label>
677
-
678
- <div className="sheet-field-row">
679
- <label className="sheet-field">
680
- <span>Aggregate</span>
681
- <select value={fn} onChange={(e) => setFn(e.target.value)}>
682
- {AGGREGATES.map((a) => <option key={a.fn} value={a.fn}>{a.label}</option>)}
683
- </select>
684
- </label>
685
- {/* Count takes no column, and offering one would suggest count(column), which skips
686
- blanks and answers a smaller number than the person meant. */}
687
- {fn !== "count" && (
688
- <div className="sheet-field sheet-field--pick">
689
- <span id="sheet-col-pick-label">Column</span>
690
- {/* ⭐ THE SEARCH BOX HAS NO CONDITION AROUND IT (R16). See the note on `shownFields`. */}
691
- <div className="cg-type-search sheet-pick-search">
692
- <svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden>
693
- <circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" />
694
- <path d="m10.4 10.4 3.1 3.1" stroke="currentColor" strokeWidth="1.35"
695
- strokeLinecap="round" />
696
- </svg>
697
- <input
698
- type="text"
699
- value={fieldQuery}
700
- placeholder="Find a column…"
701
- aria-label="Find a column"
702
- onChange={(e) => setFieldQuery(e.currentTarget.value)}
703
- />
704
- </div>
705
- <div className="cg-type-list sheet-pick-list" role="listbox"
706
- aria-labelledby="sheet-col-pick-label">
707
- {shownFields.map((f) => (
708
  <button
709
- key={f.key}
710
  type="button"
711
- role="option"
712
- aria-selected={f.key === field}
713
- className={"cg-type-row" + (f.key === field ? " is-on" : "")}
714
- onClick={() => setField(f.key)}
 
 
 
715
  >
716
- {/* ⭐ THE ICON COMES BEFORE THE NAME, which is owner instruction 24 and also
717
- what the Fields panel and the grid header already do. One glyph vocabulary,
718
- one source: `iconShapes.ts::TYPE_SHAPES`.
719
- ⭐⭐ W53-T13 β€” A METRIC COLUMN WEARS THE MEASURE GLYPH, NOT ITS STORAGE
720
- TYPE'S. The two live ones are typed `currency` and `int`, so the plain type
721
- icon showed them as ordinary money and count columns and nothing on screen
722
- said they are measured over a window. `measure` is a member of
723
- `FieldTypeIcon`'s own type union and `TYPE_SHAPES` already carries its
724
- shape, so this is the SAME glyph vocabulary rather than a new mark. */}
725
- <FieldTypeIcon
726
- type={isMetricField(f) ? "measure" : f.type}
727
- title={isMetricField(f) ? "Metric" : f.type}
728
- />
729
- <span className="cg-type-label">{f.label}</span>
730
- {/* ⚠ THE WORD IS THERE TOO, because a glyph alone is only legible to somebody
731
- who already knows the vocabulary, and the whole point is telling a person
732
- what they are about to pick. `sheet-period-note` is this panel's existing
733
- quiet muted note and is already used twice below; it carries no margin, so
734
- it sits on the row's baseline without a rule of its own. */}
735
- {isMetricField(f) && (
736
- <span className="sheet-period-note">Metric</span>
737
  )}
 
 
 
 
 
 
 
 
738
  </button>
739
- ))}
740
- </div>
741
- {/* β›” AN EMPTY LIST SAYS WHY (R16), because a blank box reads as a broken picker and
742
- the causes need different acts from the reader. ⭐ W53-T13 adds the third one:
743
- a database CAN carry number columns that this database cannot total, and "no
744
- number column" would be a false sentence in front of somebody looking at one. */}
745
- {shownFields.length === 0 && (
746
- <p className="sheet-pick-empty">
747
- {numericFields.length > 0
748
- ? "No column matches that search."
749
- : (fields.some((f) => isNumericType(f.type))
750
- ? "The number columns on this database are worked out in the browser for "
751
- + "each row, so there is nothing stored here to total."
752
- : "This database has no number column to total.")}
753
- </p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
754
  )}
755
- {/* ⭐ R7, said where the choice is made: a Metric is the one kind of column here
756
- that answers over the period below, and that is why the period control matters. */}
757
- {offersMetric && shownFields.length > 0 && (
758
- <p className="sheet-pick-empty">
759
- A Metric column is measured over the period you choose below. Every other column
760
- holds one stored value per record.
761
- </p>
 
 
 
 
 
 
 
762
  )}
763
- {/* ⭐⭐ THE BIND TIME REFUSAL, SURFACED WHERE THE PERSON CAN ACT ON IT. The server
764
- refuses this column by name (`field_not_aggregable`), but only once a number is
765
- asked for; saying it here means the choice is corrected before a save. */}
766
- {savedFieldUnavailable && (
767
  <p className="sheet-notice" role="alert">
768
- {`The saved column ${field} cannot be totalled on this database. `
769
- + "Pick a column from the list, or count the records instead."}
770
  </p>
771
  )}
772
- </div>
773
- )}
774
- </div>
775
-
776
- <fieldset className="sheet-scope">
777
- <legend>Rows to include</legend>
778
- <label className="sheet-radio">
779
- <input type="radio" checked={scopeKind === "view"}
780
- onChange={() => setScopeKind("view")} />
781
- <span>A saved view</span>
782
- </label>
783
- {scopeKind === "view" && (
784
- <select value={viewId} onChange={(e) => setViewId(e.target.value)}>
785
- <option value="">Choose a view</option>
786
- {views.map((v) => <option key={v.id} value={v.id}>{v.name}</option>)}
787
- </select>
788
- )}
789
- {/* ⭐ W53-T12 β€” SAID HERE, THE MOMENT THE LIST RESOLVES, rather than as a refusal after
790
- a save or a refresh. `sheet-notice` with `role="alert"` is this panel's established
791
- inline shape, so the sentence lands where the choice is made. */}
792
- {savedViewMissing && (
793
- <p className="sheet-notice" role="alert">
794
- {`The saved view ${savedView.name || savedView.id} is not available any more. `
795
- + "Pick a view that still exists, or build a filter here."}
796
- </p>
797
- )}
798
- <label className="sheet-radio">
799
- <input type="radio" checked={scopeKind === "filter"}
800
- onChange={() => setScopeKind("filter")} />
801
- <span>A filter I build here</span>
802
- </label>
803
- {/* ⭐⭐ W53-T15 (ruling R8) β€” A DOOR, NOT THE BUILDER. The same shared panel now opens
804
- in a centred dialog: this column is `flex: 0 0 380px` and a condition row cannot fit
805
- in it, so four conditions could only be reached by scrolling sideways. The button
806
- says how many conditions the cell already carries, because the builder that used to
807
- say so is now behind it. */}
808
- {scopeKind === "filter" && (
809
- <>
810
- <button
811
- type="button"
812
- className="sheet-action"
813
- style={{ alignSelf: "flex-start" }}
814
- aria-haspopup="dialog"
815
- aria-expanded={filterPopupOpen}
816
- onClick={() => setFilterPopupOpen(true)}
817
- >
818
- {conditionCount === 0
819
- ? "Build a filter"
820
- : `Edit filter (${conditionCount === 1
821
- ? "1 condition" : `${conditionCount} conditions`})`}
822
- </button>
823
- {/* β›”β›” MOUNTED ONLY WHILE OPEN, and that is what orders Escape correctly rather
824
- than a flag inside the dialog. `useOverlayLayer` claims Escape as soon as it
825
- runs and `ui/useEscapeClose` gives the key to the LAST entry pushed, so a
826
- dialog mounted with the panel would have claimed Escape from the moment this
827
- editor opened. Mounting it here, later in time, puts it ABOVE this panel's own
828
- claim (pushed at mount, a few hundred lines up) and unmounting it hands Escape
829
- straight back, so one press closes the filter and the next closes the panel. */}
830
- {filterPopupOpen && (
831
- <SheetFilterPopup
832
- addr={addr}
833
- fields={fields}
834
- filters={tree}
835
- onChange={setTree}
836
- statusValues={statusValues}
837
- onClose={() => setFilterPopupOpen(false)}
838
- />
839
- )}
840
- </>
841
- )}
842
- </fieldset>
843
-
844
- {/* ══ R9: THE PERIOD ══════════════════════════════════════════════════════════════════ */}
845
- <fieldset className="sheet-scope sheet-period">
846
- <legend>Period</legend>
847
-
848
- {/* ⭐⭐ W53-T16 / D-660 - WHETHER THIS CELL HAS A PERIOD AT ALL, said out loud. The
849
- pickers below show a unit and a month whether or not the cell is using them, so
850
- without this switch an all-time total read as "September 2026" on screen and the next
851
- save made that true. It is also the only way back to all time once a period is set. */}
852
- <div className="sheet-period-lock">
853
- <button
854
- type="button"
855
- role="switch"
856
- aria-checked={periodOn}
857
- className={"sheet-lock-toggle" + (periodOn ? " is-on" : "")}
858
- onClick={() => setPeriodOn((v) => !v)}
859
- >
860
- <span className="sheet-lock-dot" aria-hidden />
861
- <span>Limit this cell to a period</span>
862
- </button>
863
- <p className="sheet-period-note">
864
- {periodOn
865
- ? "Only rows dated inside the period below are counted."
866
- : "All time, so every row this cell's filter matches is counted whatever its date. "
867
- + "Saving leaves it that way."}
868
- </p>
869
- </div>
870
-
871
- {periodOn && (
872
- <>
873
- <label className="sheet-field">
874
- <span>Unit</span>
875
- <select
876
- value={unit}
877
- aria-label="Period unit"
878
- onChange={(e) => {
879
- const next = e.target.value as PeriodUnit;
880
- setUnit(next);
881
- // Re-seat the start on the new unit's first month, or the pair stops naming one
882
- // period: `2026-08` under `quarter` is not a quarter anybody can compile.
883
- setStart(normalizePeriodStart(next, start));
884
- }}
885
- >
886
- {PERIOD_UNITS.map((u) => <option key={u.unit} value={u.unit}>{u.label}</option>)}
887
- </select>
888
  </label>
889
-
890
- <div className="sheet-field-row">
891
- <label className="sheet-field">
892
- <span>Year</span>
893
- <select
894
- value={String(startYear)}
895
- aria-label="Period year"
896
- onChange={(e) => setYear(Number(e.target.value))}
 
 
 
 
 
 
897
  >
898
- {years.map((y) => <option key={y} value={String(y)}>{y}</option>)}
899
- </select>
900
- </label>
901
- {unit === "month" && (
902
- <label className="sheet-field">
903
- <span>Month</span>
904
- <select
905
- value={String(startMonth)}
906
- aria-label="Period month"
907
- onChange={(e) => setMonthOfYear(Number(e.target.value))}
908
- >
909
- {MONTH_NAMES.map((name, i) => (
910
- <option key={name} value={String(i + 1)}>{name}</option>
911
- ))}
912
- </select>
913
- </label>
914
- )}
915
- {unit === "quarter" && (
916
- <label className="sheet-field">
917
- <span>Quarter</span>
918
- <select
919
- value={String(Math.floor((startMonth - 1) / 3) + 1)}
920
- aria-label="Period quarter"
921
- onChange={(e) => setMonthOfYear(1 + 3 * (Number(e.target.value) - 1))}
922
- >
923
- {[1, 2, 3, 4].map((q) => <option key={q} value={String(q)}>{`Q${q}`}</option>)}
924
- </select>
925
- </label>
926
- )}
927
- </div>
928
 
929
- {/* THE QUICK PICKS. They normalize through the same function the pickers do, so This
930
- never stamps today's month under a quarter or a year. */}
931
- <div className="sheet-period-quick">
932
- <button
933
- type="button"
934
- className="sheet-period-pick"
935
- onClick={() => setStart(normalizePeriodStart(unit, todayYm()))}
936
- >
937
- This {UNIT_NOUN[unit]}
938
- </button>
939
- <button
940
- type="button"
941
- className="sheet-period-pick"
942
- onClick={() => setStart(shiftPeriodStart(unit, todayYm(), -1))}
943
- >
944
- Last {UNIT_NOUN[unit]}
945
- </button>
946
- </div>
947
 
948
- {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the
949
- sentence under it says what each one costs when the cell is copied. */}
 
 
950
  <div className="sheet-period-lock">
951
  <button
952
  type="button"
953
  role="switch"
954
- aria-checked={locked}
955
- className={"sheet-lock-toggle" + (locked ? " is-on" : "")}
956
- onClick={() => setLocked((v) => !v)}
957
  >
958
  <span className="sheet-lock-dot" aria-hidden />
959
- <span>Lock this period</span>
960
  </button>
961
  <p className="sheet-period-note">
962
- {locked
963
- ? "Locked, so any copy of this cell keeps this period."
964
- : `Not locked, so copying right or left moves the period by one ${UNIT_NOUN[unit]} `
965
- + "per column, and copying up or down keeps it."}
966
  </p>
967
  </div>
968
 
969
- {/* ⭐ "Use a cell" STAYS A LINK (R9). It reveals the A1 input rather than replacing the
970
- picker, so the ordinary reader never meets a cell reference and the person who wants
971
- one is one click away from it. */}
972
- {!refOpen && (
973
- <button
974
- type="button"
975
- className="sheet-period-link"
976
- onClick={() => setRefOpen(true)}
977
- >
978
- Use a cell
979
- </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
980
  )}
981
- {refOpen && (
982
- <label className="sheet-field">
983
- <span>Period from a cell</span>
984
- <input
985
- type="text"
986
- value={periodRef}
987
- onChange={(e) => setPeriodRef(e.target.value)}
988
- placeholder="$B$1"
989
- />
990
- </label>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
991
  )}
992
- </>
993
- )}
994
- </fieldset>
995
-
996
- {/* ══ R10: THE DRAG RULES ═════════════════════════════════════════════════════════════ */}
997
- <fieldset className="sheet-scope sheet-drag">
998
- <legend>When dragged</legend>
999
-
1000
- <label className="sheet-field">
1001
- <span>Across</span>
1002
- <select
1003
- value={across}
1004
- aria-label="When dragged across columns"
1005
- onChange={(e) => setAcross(e.target.value === "none" ? "none" : "period")}
1006
- >
1007
- <option value="period">Period</option>
1008
- <option value="none">Nothing</option>
1009
- </select>
1010
- </label>
1011
-
1012
- <label className="sheet-field">
1013
- <span>Down</span>
1014
- <select
1015
- value={downField}
1016
- aria-label="When dragged down rows"
1017
- onChange={(e) => setDownField(e.target.value)}
1018
- >
1019
- <option value="">Nothing</option>
1020
- {dragDownFields.map((f) => (
1021
- <option key={f.key} value={f.key}>{`Next value of ${f.label}`}</option>
1022
- ))}
1023
- </select>
1024
- </label>
1025
-
1026
- {dragDownFields.length === 0 && (
1027
- <p className="sheet-period-note">
1028
- This database has no single select or link column to walk, so dragging down repeats
1029
- the same rows.
1030
- </p>
1031
- )}
1032
- </fieldset>
1033
-
1034
- {/* β›”β›” W53-T16 (owner instruction 13) - THE FOUR SENTENCE SUMMARY IS DELETED, NOT HIDDEN.
1035
- It restated the period, the lock and the two drag rules that the controls immediately
1036
- above already say, in a panel 380px wide where every line it took pushed Save further
1037
- off screen. The one line kept is R11's, because it is the only sentence here that names
1038
- something NO control shows: the filter in this cell was copied out of a view that has
1039
- since been deleted, and nothing else remembers that. */}
1040
- {adoptedFrom && (
1041
- <p className="sheet-binding-line sheet-binding-adopted">
1042
- {`Filter adopted from the deleted view ${adoptedFrom}`}
1043
- </p>
1044
  )}
1045
-
1046
- {preview && <p className="sheet-preview">{`This cell would show ${preview}`}</p>}
1047
- {notice && <p className="sheet-notice" role="alert">{notice}</p>}
1048
  </div>
1049
 
1050
  <div className="sheet-binding-actions">
 
36
  // ⚠ DESIGN CONTRACT: sentence case, quiet buttons, token-only colour and type, motion 150 ms
37
  // ease-out on opacity and transform, no emoji, and no em dash or en dash in any string on screen.
38
 
39
+ import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
40
  import { fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge";
41
  import type { SurfaceScope } from "../customer-grid/apiBridge";
42
  import { FieldTypeIcon } from "../customer-grid/icons";
43
+ import { BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/OverlaySurface";
44
  import type { Field, FilterTree, Row } from "../customer-grid/types";
45
  import { choiceVocabulary, topicForScope } from "../customer-grid/types";
46
  // ⭐⭐ W53-T15 (ruling R8) β€” THE FILTER BUILDER IS NO LONGER MOUNTED IN THIS COLUMN. The SHARED
 
60
  { fn: "max", label: "Maximum" },
61
  ] as const;
62
 
63
+ /** The fold's name inside a sentence. `AGGREGATES` carries the capitalised option text a select
64
+ * needs; a heading reading "takes its Sum over" would be title case in the middle of a line,
65
+ * which the design contract's sentence-case rule forbids. Same five folds, said the other way. */
66
+ const AGGREGATE_NOUN: Record<string, string> = {
67
+ sum: "sum", count: "count", avg: "average", min: "minimum", max: "maximum",
68
+ };
69
+
70
  // ══ W53-T13: WHICH COLUMNS THE SERVER CAN ACTUALLY TOTAL (R7, standing rule 9) ═══════════════
71
  //
72
  // ⭐⭐ THE PICKER MUST NOT OFFER A COLUMN THAT WILL REFUSE. `isNumericType` answers "does this
 
341
  return (raw as { id: string; name: string }[]).map((v) => ({ id: v.id, name: v.name }));
342
  }
343
 
344
+ // ══ ⭐⭐ W54-T31 (ruling R8; owner instructions 6 and 8) β€” THE AGGREGATE'S COLUMN LIST ═════════
345
+ //
346
+ // ⭐⭐ R8, VERBATIM: "Aggregate is always visible. The Fields list appears in exactly two places:
347
+ // choosing the Aggregate's column, and choosing a field inside 'A filter I build here'. It is
348
+ // hidden everywhere else, including under 'A saved view', where the view already fixes the rows.
349
+ // Each Fields list is labelled with what it is picking, so several `sales.. metrics` entries are
350
+ // distinguishable."
351
+ //
352
+ // β›” WHAT CHANGED IS WHERE THE LIST LIVES, NOT WHETHER IT EXISTS. Before this ticket the list was
353
+ // a permanently expanded box inside a 380px column: it painted under "A saved view" as well, and
354
+ // it spent about 90px of the panel's height on a list nobody was currently choosing from
355
+ // (`shots/T31-fields-before.png`). Instruction 6 asks for the Data module's Fields presentation
356
+ // "but the popup in the middle, just like building a Filter under 'Rows to include'", so the list
357
+ // becomes a centred dialog opened from a control that shows the CHOSEN column. The panel keeps a
358
+ // single line for Column in every configuration, which is what instruction 8's "Fields should auto
359
+ // hide for everything that is not part of the Aggregate value Column or the Filter fields" buys.
360
+ //
361
+ // β›”β›” THE PROVIDER AROUND THE DIALOG IS THE SAME LOAD-BEARING ONE `SheetFilterPopup` DOCUMENTS,
362
+ // and it is why `SheetColumnPicker` is split from the dialog below it. The Sheet route mounts NO
363
+ // `OverlayProvider` of its own (`App.tsx` gives one to the hosted-grid branch only), so a
364
+ // body-level overlay opened here has a null `OverlayStackContext` and `useOverlayLayer` cannot
365
+ // tell whether a higher layer owns a pointerdown. Wrapping puts every layer opened underneath
366
+ // this dialog on one stack, so a click inside a nested picker is never read as an outside click
367
+ // that dismisses the surface below it. That failure is exactly the "clicking Fields just closes
368
+ // the window" report instruction 8 names.
369
+ //
370
+ // β›” AND IT IS MOUNTED LATE, CONDITIONALLY, for the reason the filter popup already records:
371
+ // `useOverlayLayer` claims Escape the moment it runs and `ui/useEscapeClose` hands the key to the
372
+ // LAST entry pushed. The editor's own claim was pushed at mount; this one is pushed when the
373
+ // dialog opens, so one Escape closes the column list and the next closes the panel.
374
+
375
+ interface ColumnPickerProps {
376
+ /** The cell being bound, so the title says which cell this list is about. */
377
+ addr: string;
378
+ /** The fold, said inside a sentence: "sum", "average", "minimum". */
379
+ aggregateNoun: string;
380
+ /** The database's own label. Two databases can both offer a column called "Total". */
381
+ databaseLabel: string;
382
+ /** The offer after the search box, which is what the list renders. */
383
+ shown: Field[];
384
+ /** The offer before the search box. The empty state must tell a search miss from an empty
385
+ * database, and those two ask different things of the reader. */
386
+ offered: Field[];
387
+ /** Every field the database has, for the third empty-state sentence. */
388
+ all: Field[];
389
+ chosen: string;
390
+ query: string;
391
+ onQuery: (next: string) => void;
392
+ onPick: (key: string) => void;
393
+ onClose: () => void;
394
+ }
395
+
396
+ /** The dialog itself. Split from the export ONLY so `useOverlayLayer` runs BELOW the provider. */
397
+ function ColumnPickerDialog({
398
+ addr, aggregateNoun, databaseLabel, shown, offered, all, chosen, query,
399
+ onQuery, onPick, onClose,
400
+ }: ColumnPickerProps) {
401
+ const panelRef = useRef<HTMLDivElement>(null);
402
+ const titleId = useId();
403
+ const listId = useId();
404
+ useOverlayLayer({
405
+ panelRef,
406
+ onDismiss: onClose,
407
+ dismissOnOutside: true,
408
+ initialFocus: "first",
409
+ restoreFocus: true,
410
+ trapFocus: true,
411
+ });
412
+
413
+ const offersMetric = offered.some(isMetricField);
414
+
415
+ return (
416
+ <BodyPortal>
417
+ <div className="lp-dialog-scrim">
418
+ <div
419
+ ref={panelRef}
420
+ className="lp-dialog sheet-column-popup"
421
+ role="dialog"
422
+ aria-modal="true"
423
+ aria-labelledby={titleId}
424
+ data-overlay-kind="sheet-column"
425
+ >
426
+ <div className="lp-dialog-head">
427
+ <h2 className="lp-dialog-title" id={titleId}>
428
+ {`The column ${addr} takes its ${aggregateNoun} over`}
429
+ </h2>
430
+ <button
431
+ type="button"
432
+ className="lp-dialog-x"
433
+ aria-label={`Close the column list for ${addr}`}
434
+ onClick={onClose}
435
+ >
436
+ <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false">
437
+ <path d="M4 4l8 8M12 4l-8 8" stroke="currentColor" strokeWidth="1.5"
438
+ strokeLinecap="round" />
439
+ </svg>
440
+ </button>
441
+ </div>
442
+
443
+ {/* ⭐ THE SHAPE IS `filter-kit/FieldsHidePanel.tsx`'s, which is what instruction 6 asks
444
+ for by name: a quiet heading, then a find box, then the rows. Nothing here is a new
445
+ control; `cg-fields-section-title`, `cg-type-search`, `cg-type-list`, `cg-type-row`
446
+ and `cg-fsel-hint` are all shipped, top-level classes in `index.css`. */}
447
+ <div className="sheet-col-pick">
448
+ {/* ⭐⭐ THE HEADING R8 ASKS FOR, AND IT NAMES BOTH HALVES OF WHAT IS BEING PICKED:
449
+ which database the columns come from, and what they are going to be used for. The
450
+ owner's report was several entries reading "sales.. metrics" with nothing saying
451
+ which list they belonged to; a list that says what it is picking answers that
452
+ before a single row is read. */}
453
+ <div className="cg-fields-section-title" id={listId}>
454
+ {`Fields on ${databaseLabel} to take the ${aggregateNoun} over`}
455
+ </div>
456
+
457
+ {/* ⭐ THE SEARCH BOX HAS NO CONDITION AROUND IT (wave-50 R16). A control that appears
458
+ at eleven fields and not at ten is a control nobody learns is there. */}
459
+ <div className="cg-type-search sheet-pick-search">
460
+ <svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden>
461
+ <circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" />
462
+ <path d="m10.4 10.4 3.1 3.1" stroke="currentColor" strokeWidth="1.35"
463
+ strokeLinecap="round" />
464
+ </svg>
465
+ <input
466
+ type="text"
467
+ value={query}
468
+ placeholder="Find a column…"
469
+ aria-label="Find a column"
470
+ onChange={(e) => onQuery(e.currentTarget.value)}
471
+ />
472
+ </div>
473
+
474
+ {/* β›” THE LIST IS NOT RENDERED WHEN IT HAS NO ROWS. `.sheet-pick-list` carries a
475
+ border and 3px of padding, so an empty one painted a thin bordered strip under
476
+ the search box with the explanation sitting outside it, which reads as a picker
477
+ that failed rather than a database with nothing to offer. */}
478
+ {shown.length > 0 && (
479
+ <div className="cg-type-list sheet-pick-list" role="listbox"
480
+ aria-labelledby={listId}>
481
+ {shown.map((f) => (
482
+ <button
483
+ key={f.key}
484
+ type="button"
485
+ role="option"
486
+ aria-selected={f.key === chosen}
487
+ className={"cg-type-row" + (f.key === chosen ? " is-on" : "")}
488
+ onClick={() => onPick(f.key)}
489
+ >
490
+ {/* ⭐ THE ICON COMES BEFORE THE NAME (owner instruction 24), and a Metric
491
+ wears the measure glyph rather than its storage type's. One glyph
492
+ vocabulary, one source: `iconShapes.ts::TYPE_SHAPES`. */}
493
+ <FieldTypeIcon
494
+ type={isMetricField(f) ? "measure" : f.type}
495
+ title={isMetricField(f) ? "Metric" : f.type}
496
+ />
497
+ <span className="cg-type-label">
498
+ {f.label}
499
+ {/* ⭐⭐ WHAT MAKES TWO ROWS TELLABLE APART. Labels collide - the owner saw
500
+ several reading "sales.. metrics" - and the field's own key never does,
501
+ because it is what the database stores the column under. `cg-fsel-hint`
502
+ is the shipped quiet second line `FieldSelect` already paints under a
503
+ label, so this is that pattern's second caller and not a new one. */}
504
+ <span className="cg-fsel-hint">{f.key}</span>
505
+ </span>
506
+ {/* ⚠ THE WORD IS THERE TOO, because a glyph alone is only legible to somebody
507
+ who already knows the vocabulary. */}
508
+ {isMetricField(f) && (
509
+ <span className="sheet-period-note">Metric</span>
510
+ )}
511
+ </button>
512
+ ))}
513
+ </div>
514
+ )}
515
+
516
+ {/* β›” AN EMPTY LIST SAYS WHY (R16). The three causes need different acts from the
517
+ reader, and a database CAN carry number columns this database cannot total. */}
518
+ {shown.length === 0 && (
519
+ <p className="sheet-pick-empty">
520
+ {offered.length > 0
521
+ ? "No column matches that search."
522
+ : (all.some((f) => isNumericType(f.type))
523
+ ? "The number columns on this database are worked out in the browser for "
524
+ + "each row, so there is nothing stored here to total."
525
+ : "This database has no number column to total.")}
526
+ </p>
527
+ )}
528
+
529
+ {/* ⭐ R7, said where the choice is made: a Metric is the one kind of column here that
530
+ answers over the period the panel sets. */}
531
+ {offersMetric && shown.length > 0 && (
532
+ <p className="sheet-pick-empty">
533
+ A Metric column is measured over the period you choose in the panel. Every other
534
+ column holds one stored value per record.
535
+ </p>
536
+ )}
537
+ </div>
538
+ </div>
539
+ </div>
540
+ </BodyPortal>
541
+ );
542
+ }
543
+
544
+ /** The centred column list, on its own overlay stack. See the block above for why the provider
545
+ * is not decoration. */
546
+ export function SheetColumnPicker(props: ColumnPickerProps) {
547
+ return (
548
+ <OverlayProvider>
549
+ <ColumnPickerDialog {...props} />
550
+ </OverlayProvider>
551
+ );
552
+ }
553
+
554
+ /**
555
+ * ⭐⭐ W54-T33 (owner instruction 24) β€” WHAT THE PANEL SHOWS WHILE ITS OPTIONS RESOLVE.
556
+ *
557
+ * β›” THE PRECEDENT IS `sheet/SheetRail.tsx::RailSkeleton` AND ITS DECISION IS NOT REOPENED HERE:
558
+ * one flat `--lp-surface-2` tone and no shimmer, because an animated sweep is a second thing moving
559
+ * on a surface whose whole job is to sit still, and `prefers-reduced-motion` would then need a
560
+ * third state. The bars are `aria-hidden` under ONE `role="status"`, so a screen reader hears
561
+ * "loading" once rather than six times.
562
+ *
563
+ * ⭐ THE SHAPE IS THE SETTLED PANEL'S. Three stacked label-plus-control lines (Database,
564
+ * Aggregate and Column, which W54-T30 gave a line each) and three blocks for the three fieldsets,
565
+ * at the scroller's own 12px gap, so the controls land where the bars were rather than shunting the
566
+ * column when they arrive. A skeleton shaped unlike the panel it stands in is worse than none.
567
+ */
568
+ function BindingSkeleton({ addr }: { addr: string }) {
569
+ return (
570
+ <div
571
+ className="sheet-binding-skeleton"
572
+ role="status"
573
+ aria-label={`Loading what ${addr} points at`}
574
+ >
575
+ {[0, 1, 2].map((i) => (
576
+ <div className="sheet-binding-skeleton-field" key={i} aria-hidden="true">
577
+ <span className="sheet-binding-skeleton-label" />
578
+ <span className="sheet-binding-skeleton-control" />
579
+ </div>
580
+ ))}
581
+ <span className="sheet-binding-skeleton-block" aria-hidden="true" />
582
+ <span className="sheet-binding-skeleton-block" aria-hidden="true" />
583
+ <span className="sheet-binding-skeleton-block is-tall" aria-hidden="true" />
584
+ </div>
585
+ );
586
+ }
587
+
588
  export interface BindingEditorProps {
589
  workbookId: string;
590
  addr: string;
 
622
  // arrives the list is legitimately empty, and a notice keyed on emptiness would flash "that view
623
  // is gone" at every perfectly valid binding for as long as the fetch took.
624
  const [viewsLoaded, setViewsLoaded] = useState(false);
625
+ // ⭐⭐ W54-T33 (owner instruction 24) β€” WHETHER THE OPTIONS ON SCREEN ARE KNOWN TO BE THIS
626
+ // CELL'S. The cached read below is KEPT, and it is still not allowed to paint a configuration.
627
+ // `fetchWorkspace(scope, {allowCached: true})` is keyed per scope so it can never hand back
628
+ // another database's envelope, but it can be minutes old: a view deleted or renamed in another
629
+ // tab is still in it, the panel seated the saved view against that list, and `savedViewMissing`
630
+ // is held back until the fresh answer lands. So for the five to eight seconds this panel's three
631
+ // mount calls take warm, and up to seventy-eight on a cold compute, the reader was shown a
632
+ // plausible configuration nobody had saved. The scroller now paints a skeleton until the
633
+ // UNCACHED read for the CURRENT database has landed.
634
+ //
635
+ // β›” AND IT IS RAISED ON EVERY EXIT, INCLUDING THE FAILURES. A skeleton with no end is a worse
636
+ // answer than an empty list: offline, refused, or a database with no workspace door at all, the
637
+ // panel reveals what it has and the person can still read, cancel or close it.
638
+ //
639
+ // ⚠ IT IS NOT `viewsLoaded`, WHICH MEANS SOMETHING NARROWER AND HAS TO KEEP MEANING IT. That
640
+ // flag says the list of views is known to be current, which is what the "saved view is gone"
641
+ // notice needs before it may accuse anybody; a failed revalidate is no evidence a view was
642
+ // deleted, so it stays false there. This one only asks whether there is anything honest to show.
643
+ const [optionsResolved, setOptionsResolved] = useState(false);
644
  // ⭐⭐ W53-T15 (ruling R8) β€” WHETHER THE CENTRED FILTER DIALOG IS ON SCREEN, and the ONLY state
645
  // this ticket adds. The tree itself stays in `tree`/`setTree` below and the dialog writes
646
  // straight into that setter, so there is no draft to reconcile when it closes.
647
  const [filterPopupOpen, setFilterPopupOpen] = useState(false);
648
+ // ⭐⭐ W54-T31 (ruling R8) β€” WHETHER THE CENTRED COLUMN LIST IS ON SCREEN. It starts CLOSED on
649
+ // every configuration including an unbound cell: the panel's job on open is to show what the
650
+ // cell points at, and a list that opens itself would be back to spending the panel's height on
651
+ // a choice nobody has asked to make.
652
+ const [colPickerOpen, setColPickerOpen] = useState(false);
653
  // ⭐⭐ W52-T14 (instruction 11) β€” THE FILTER'S VALUE VOCABULARY NEEDS ROWS, NOT ONLY FIELDS.
654
  // A declared select/status carries its own list on `field.options`, which the filter kit
655
  // already falls back to with no `statusValues` at all. A SERVER-COMPUTED one (a `select` whose
 
659
  // them the same way CustomerGrid does (`topicForScope` + `fetchTopicRows`, the exact pair the
660
  // grid's own load path uses), sharing that call's cache so a database already open elsewhere in
661
  // this session costs nothing extra here.
662
+ //
663
+ // ⭐⭐ W54-T36 (owner instruction 8: *"Adding a database cell takes forever to load now"*) β€” AND
664
+ // THAT READ IS NO LONGER PAID ON OPEN. MEASURED at tenant #0: the rows door answers 13.6 MB /
665
+ // 33,493 rows on `ut_odoo_orders`, 11.1 MB / 5,899 on `product_data` and 4.8 MB / 3,673 on
666
+ // `customer_data`, and the panel was awaiting all of it before it could show a Database select.
667
+ // Its ONLY consumer is `statusValues`, which is handed to `SheetFilterPopup` and to nothing
668
+ // else, and that dialog is behind a button that is itself behind the "A filter I build here"
669
+ // radio. So the pool is fetched when the filter is REACHED rather than when the panel opens.
670
+ //
671
+ // β›” "REACHED" MEANS THE RADIO, NOT THE BUTTON, and that is deliberate: the request starts the
672
+ // moment somebody chooses to build a filter, which is at least one click before the dialog can
673
+ // be on screen, and a cell SAVED with a filter asks for it at mount. A vocabulary that arrived
674
+ // after the dialog opened would be a picker offering nothing, which is worse than a slow panel.
675
+ // The rows land into `rawRows` and `statusValues` recomputes, so a dialog opened during the
676
+ // request fills itself in rather than staying empty.
677
+ const [rowsWanted, setRowsWanted] = useState<boolean>(savedScope.kind === "filter");
678
  const [rawRows, setRawRows] = useState<Row[]>([]);
679
  const [userOptions, setUserOptions] = useState<string[]>([]);
680
  const [preview, setPreview] = useState<string>("");
 
734
  // the server) is the one that knows what exists NOW, and the list is rebuilt from whichever
735
  // answer arrived last.
736
  //
737
+ // β›”β›” W54-T36 β€” THE UNCACHED READ GOES FIRST NOW AND IS USUALLY THE ONLY ONE, and the reason is
738
+ // W54-T33: the skeleton holds the whole scroller until `optionsResolved`, so the cached envelope
739
+ // PAINTS NOTHING. Reading it first therefore bought no earlier frame, while a cache MISS spent a
740
+ // second full server assembly ahead of the read that decides what is shown. MEASURED at tenant
741
+ // #0, warm: one workspace read is 2,646 ms on `customer` and 4,122 ms on `product`, and the two
742
+ // in parallel are 2,878 ms and 4,587 ms. Its remaining job is the failure fallback, which is
743
+ // where it is asked for now.
744
+ //
745
  // β›” A NULL REVALIDATE LEAVES THE CACHED LIST STANDING. `fetchWorkspace` answers null when the
746
  // call fails, and blanking a working dropdown because the network blinked would refuse a person
747
+ // their own saved views for a reason that has nothing to do with the views. That is why the
748
+ // cached read survives on that path: it is the panel's only offer when the server will not
749
+ // answer, and it costs nothing when the memo already holds this scope.
750
  useEffect(() => {
751
  let live = true;
752
  const scope = scopeOf(database);
753
  setViewsLoaded(false);
754
+ setOptionsResolved(false);
755
+ // ⭐ W54-T36 β€” THE POOL BELONGS TO THE DATABASE THAT WAS OPEN. Switching database drops it, and
756
+ // the rows effect below refetches only if the filter is still being used.
757
+ setRawRows([]);
758
  if (!scope) {
759
  setFields([]);
760
  setViews([]);
 
761
  setUserOptions([]);
762
+ // β›” W54-T33 β€” RESOLVED, NOT LOADING. This database has no workspace door, so its empty
763
+ // lists are the true and final answer; leaving the flag down would leave a skeleton running
764
+ // forever over a panel that is never going to be given anything else.
765
+ setOptionsResolved(true);
766
  return () => { live = false; };
767
  }
768
  (async () => {
769
+ // ONE door, and it is the one that knows what exists now.
 
 
 
 
 
 
 
 
 
 
 
 
 
770
  const fresh = await fetchWorkspace(scope);
771
  if (!live) return;
772
  if (!fresh) {
773
+ // Offline or refused. The memo is the only offer left; only claim the list is settled if
774
+ // it produced one.
775
+ const ws = await fetchWorkspace(scope, { allowCached: true });
776
+ if (!live) return;
777
+ if (ws) {
778
+ setFields((ws.fields ?? []) as Field[]);
779
+ setViews(viewList(ws.views));
780
+ setUserOptions(ws.userOptions ?? []);
781
+ setViewsLoaded(true);
782
+ }
783
+ // β›” W54-T33 β€” BUT THE PANEL REVEALS EITHER WAY. Nothing better is coming for this
784
+ // database, and a skeleton that outlives the request it was waiting on tells the reader
785
+ // the panel is broken rather than that the server would not answer.
786
+ setOptionsResolved(true);
787
  return;
788
  }
789
  const list = viewList(fresh.views);
790
  setFields((fresh.fields ?? []) as Field[]);
791
  setViews(list);
792
+ // ⚠ THE `user` FIELDS' VOCABULARY COMES OFF THIS ENVELOPE, not off the rows. It was read
793
+ // from the rows payload with this as its fallback; the rows are no longer fetched here, so
794
+ // the fallback is the answer, and the rows effect below overwrites it when it does run.
795
+ setUserOptions(fresh.userOptions ?? []);
796
  setViewsLoaded(true);
797
  // β›” A SELECTED VIEW THAT NO LONGER EXISTS IS CLEARED, so Save cannot store a dead id β€” that
798
  // stored id is exactly the state this ticket was reported for. The notice in `Rows to
799
  // include` is what explains the empty control; clearing without saying so would read as the
800
  // panel losing the choice on its own.
801
  setViewId((cur) => (cur && !list.some((v) => v.id === cur) ? "" : cur));
802
+ // β›” W54-T33 β€” LAST, AFTER THE DEAD ID IS CLEARED. React batches these into one paint, so
803
+ // the first frame the reader sees is the settled one: a view that no longer exists has
804
+ // already been dropped and its notice is already computed, rather than showing for a frame.
805
+ setOptionsResolved(true);
806
  })();
807
  return () => { live = false; };
808
  }, [database]);
809
 
810
+ // ⭐⭐ W54-T36 β€” THE FILTER'S VALUE POOL, ASKED FOR WHEN THE FILTER IS REACHED. See `rowsWanted`
811
+ // above for the measurement that moved it off the open path. Once wanted it stays wanted, so
812
+ // switching back to a saved view and returning does not re-ask.
813
+ useEffect(() => {
814
+ if (scopeKind === "filter" || filterPopupOpen) setRowsWanted(true);
815
+ }, [scopeKind, filterPopupOpen]);
816
+
817
+ // β›” THE PANEL IS NEVER HELD ON THIS READ. It sets no loading flag and gates no control: the
818
+ // dialog opens with the declared vocabularies it already has and the computed ones fill in when
819
+ // the pool lands, which is what keeps a slow rows door out of the open path for good.
820
+ useEffect(() => {
821
+ if (!rowsWanted) return undefined;
822
+ const scope = scopeOf(database);
823
+ if (!scope) return undefined;
824
+ let live = true;
825
+ (async () => {
826
+ const payload = await fetchTopicRows(topicForScope(scope));
827
+ if (!live) return;
828
+ setRawRows(payload?.rows ?? []);
829
+ if (payload?.userOptions) setUserOptions(payload.userOptions);
830
+ })();
831
+ return () => { live = false; };
832
+ }, [database, rowsWanted]);
833
+
834
  /** The binding names a view the fresh list does not have. Said in the panel, not after a save.
835
  *
836
  * β›” IT STOPS BEING SAID THE MOMENT THE PERSON ANSWERS IT. The sentence asks for one of two acts,
 
875
  [fields],
876
  );
877
 
878
+ // ⚠ W54-T31 - `offersMetric` MOVED, it was not dropped. The hint it gated belongs beside the
879
+ // rows it describes, and those rows now live in `ColumnPickerDialog`, which derives the same
880
+ // answer from the same list. A second copy here would have had no reader.
881
 
882
  /** The saved binding names a column this database will not total. Said in the panel, where the
883
  * choice is made, rather than as a refusal after a save.
 
924
  || String(f.key).toLowerCase().includes(q));
925
  }, [fieldQuery, numericFields]);
926
 
927
+ /** The chosen column, resolved over the FULL field list rather than over the offer, so a saved
928
+ * column this database cannot total still shows its own name beside the notice that says so.
929
+ * That is the same three-state rule `customer-grid/FieldSelect.tsx` documents at its head. */
930
+ const chosenField = useMemo(() => fields.find((f) => f.key === field), [fields, field]);
931
+
932
+ /** The database's own label, which the column list's heading names. Two databases can both
933
+ * carry a column called "Total", and the heading is where that ambiguity is answered. */
934
+ const databaseLabel = databases.find((d) => d.key === database)?.label || database;
935
+
936
  const binding = useMemo(() => {
937
  const agg: Record<string, unknown> = fn === "count" ? { fn } : { fn, field };
938
  const scope: Record<string, unknown> = scopeKind === "view"
 
975
  setPreview(got.value.display || String(got.value.value ?? ""));
976
  };
977
 
978
+ // ⭐ W54-T33 β€” `optionsResolved` FIRST, so Preview and Save are inert while the skeleton is up.
979
+ // A cell bound to a live view satisfies every other clause the moment the panel mounts, and a
980
+ // Save taken then would write back a binding assembled from a list nobody had seen yet.
981
+ const ready = optionsResolved && Boolean(database) && (fn === "count" || Boolean(field))
982
  && (scopeKind === "filter" || Boolean(viewId));
983
 
984
  const { y: startYear, m: startMonth } = splitYm(start);
 
1020
  builder is taller than the page, and a panel that scrolls as a whole pushes Save below
1021
  the fold with nothing on screen saying it is there. */}
1022
  <div className="sheet-binding-scroll">
1023
+ {/* ⭐⭐ W54-T33 (owner instruction 24) β€” NOTHING BELOW PAINTS UNTIL THE OPTIONS ARE
1024
+ THIS CELL'S. See `optionsResolved` above for what that means and why the cached
1025
+ read is still made. The skeleton replaces the scroller's CONTENT rather than the
1026
+ panel, which is what keeps the header, the close control and Cancel reachable, and
1027
+ it must never be lifted to the panel itself: `migratePeriod`, `readOnDrag` and the
1028
+ saved aggregate are seeded once at mount, so a remount here would re-read `initial`
1029
+ and forget an edit somebody had already made. */}
1030
+ {!optionsResolved && <BindingSkeleton addr={addr} />}
1031
+ {optionsResolved && (
1032
+ <>
1033
+ <label className="sheet-field">
1034
+ <span>Database</span>
1035
+ <select value={database} onChange={(e) => setDatabase(e.target.value)}>
1036
+ {databases.map((d) => <option key={d.key} value={d.key}>{d.label}</option>)}
1037
+ </select>
1038
+ </label>
1039
+
1040
+ <div className="sheet-field-row">
1041
+ <label className="sheet-field">
1042
+ <span>Aggregate</span>
1043
+ <select value={fn} onChange={(e) => setFn(e.target.value)}>
1044
+ {AGGREGATES.map((a) => <option key={a.fn} value={a.fn}>{a.label}</option>)}
1045
+ </select>
1046
+ </label>
1047
+ {/* Count takes no column, and offering one would suggest count(column), which skips
1048
+ blanks and answers a smaller number than the person meant. */}
1049
+ {fn !== "count" && (
1050
+ <div className="sheet-field sheet-field--pick">
1051
+ <span id="sheet-col-pick-label">Column</span>
1052
+ {/* ⭐⭐ W54-T31 (R8) β€” THE CONTROL SHOWS WHAT IS CHOSEN AND OPENS THE LIST; IT IS
1053
+ NOT THE LIST. `cg-select cg-fsel` is the shipped footprint every replaced
1054
+ `<select>` in this product already wears, so the Column line shares its height
1055
+ and its baseline with the Aggregate select above it rather than introducing a
1056
+ new control shape. The three states are `FieldSelect`'s own: unset reads as a
1057
+ prompt, a resolved column shows its mark and its name, and a column this
1058
+ database cannot offer shows its raw key in the amber `is-missing` slot instead
1059
+ of a plausible substitute. */}
1060
  <button
 
1061
  type="button"
1062
+ className={"cg-select cg-fsel sheet-col-open"
1063
+ + (chosenField ? "" : field ? " is-missing" : " is-empty")}
1064
+ aria-haspopup="dialog"
1065
+ aria-expanded={colPickerOpen}
1066
+ aria-labelledby="sheet-col-pick-label"
1067
+ title={chosenField ? chosenField.key : undefined}
1068
+ onClick={() => setColPickerOpen(true)}
1069
  >
1070
+ {chosenField ? (
1071
+ <FieldTypeIcon
1072
+ type={isMetricField(chosenField) ? "measure" : chosenField.type}
1073
+ title={isMetricField(chosenField) ? "Metric" : chosenField.type}
1074
+ />
1075
+ ) : (
1076
+ // No mark, but the SLOT stays, so the name sits in the same column whether or
1077
+ // not anything is chosen yet.
1078
+ <span className="cg-fsel-nomark" aria-hidden />
 
 
 
 
 
 
 
 
 
 
 
 
1079
  )}
1080
+ <span className="cg-fsel-label">
1081
+ {chosenField?.label ?? (field || "Choose a column")}
1082
+ </span>
1083
+ <svg className="cg-fsel-caret" width="10" height="10" viewBox="0 0 16 16"
1084
+ fill="none" aria-hidden>
1085
+ <path d="M4 6l4 4 4-4" stroke="currentColor" strokeWidth="1.6"
1086
+ strokeLinecap="round" strokeLinejoin="round" />
1087
+ </svg>
1088
  </button>
1089
+ {/* β›”β›” MOUNTED ONLY WHILE OPEN, which is what orders Escape. See the block above
1090
+ `ColumnPickerDialog`: the editor's own Escape claim was pushed at mount, this
1091
+ one is pushed on open, and unmounting hands the key straight back. */}
1092
+ {colPickerOpen && (
1093
+ <SheetColumnPicker
1094
+ addr={addr}
1095
+ aggregateNoun={AGGREGATE_NOUN[fn] ?? "total"}
1096
+ databaseLabel={databaseLabel}
1097
+ shown={shownFields}
1098
+ offered={numericFields}
1099
+ all={fields}
1100
+ chosen={field}
1101
+ query={fieldQuery}
1102
+ onQuery={setFieldQuery}
1103
+ onPick={(key) => {
1104
+ setField(key);
1105
+ setColPickerOpen(false);
1106
+ }}
1107
+ onClose={() => setColPickerOpen(false)}
1108
+ />
1109
+ )}
1110
+ {/* ⭐⭐ THE BIND TIME REFUSAL, SURFACED WHERE THE PERSON CAN ACT ON IT. The server
1111
+ refuses this column by name (`field_not_aggregable`), but only once a number is
1112
+ asked for; saying it here means the choice is corrected before a save. */}
1113
+ {savedFieldUnavailable && (
1114
+ <p className="sheet-notice" role="alert">
1115
+ {`The saved column ${field} cannot be totalled on this database. `
1116
+ + "Pick a column from the list, or count the records instead."}
1117
+ </p>
1118
+ )}
1119
+ </div>
1120
  )}
1121
+ </div>
1122
+
1123
+ <fieldset className="sheet-scope">
1124
+ <legend>Rows to include</legend>
1125
+ <label className="sheet-radio">
1126
+ <input type="radio" checked={scopeKind === "view"}
1127
+ onChange={() => setScopeKind("view")} />
1128
+ <span>A saved view</span>
1129
+ </label>
1130
+ {scopeKind === "view" && (
1131
+ <select value={viewId} onChange={(e) => setViewId(e.target.value)}>
1132
+ <option value="">Choose a view</option>
1133
+ {views.map((v) => <option key={v.id} value={v.id}>{v.name}</option>)}
1134
+ </select>
1135
  )}
1136
+ {/* ⭐ W53-T12 β€” SAID HERE, THE MOMENT THE LIST RESOLVES, rather than as a refusal after
1137
+ a save or a refresh. `sheet-notice` with `role="alert"` is this panel's established
1138
+ inline shape, so the sentence lands where the choice is made. */}
1139
+ {savedViewMissing && (
1140
  <p className="sheet-notice" role="alert">
1141
+ {`The saved view ${savedView.name || savedView.id} is not available any more. `
1142
+ + "Pick a view that still exists, or build a filter here."}
1143
  </p>
1144
  )}
1145
+ <label className="sheet-radio">
1146
+ <input type="radio" checked={scopeKind === "filter"}
1147
+ onChange={() => setScopeKind("filter")} />
1148
+ <span>A filter I build here</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1149
  </label>
1150
+ {/* ⭐⭐ W53-T15 (ruling R8) β€” A DOOR, NOT THE BUILDER. The same shared panel now opens
1151
+ in a centred dialog: this column is `flex: 0 0 380px` and a condition row cannot fit
1152
+ in it, so four conditions could only be reached by scrolling sideways. The button
1153
+ says how many conditions the cell already carries, because the builder that used to
1154
+ say so is now behind it. */}
1155
+ {scopeKind === "filter" && (
1156
+ <>
1157
+ <button
1158
+ type="button"
1159
+ className="sheet-action"
1160
+ style={{ alignSelf: "flex-start" }}
1161
+ aria-haspopup="dialog"
1162
+ aria-expanded={filterPopupOpen}
1163
+ onClick={() => setFilterPopupOpen(true)}
1164
  >
1165
+ {conditionCount === 0
1166
+ ? "Build a filter"
1167
+ : `Edit filter (${conditionCount === 1
1168
+ ? "1 condition" : `${conditionCount} conditions`})`}
1169
+ </button>
1170
+ {/* β›”β›” MOUNTED ONLY WHILE OPEN, and that is what orders Escape correctly rather
1171
+ than a flag inside the dialog. `useOverlayLayer` claims Escape as soon as it
1172
+ runs and `ui/useEscapeClose` gives the key to the LAST entry pushed, so a
1173
+ dialog mounted with the panel would have claimed Escape from the moment this
1174
+ editor opened. Mounting it here, later in time, puts it ABOVE this panel's own
1175
+ claim (pushed at mount, a few hundred lines up) and unmounting it hands Escape
1176
+ straight back, so one press closes the filter and the next closes the panel. */}
1177
+ {filterPopupOpen && (
1178
+ <SheetFilterPopup
1179
+ addr={addr}
1180
+ fields={fields}
1181
+ filters={tree}
1182
+ onChange={setTree}
1183
+ statusValues={statusValues}
1184
+ onClose={() => setFilterPopupOpen(false)}
1185
+ />
1186
+ )}
1187
+ </>
1188
+ )}
1189
+ </fieldset>
 
 
 
 
 
1190
 
1191
+ {/* ══ R9: THE PERIOD ══════════════════════════════════════════════════════════════════ */}
1192
+ <fieldset className="sheet-scope sheet-period">
1193
+ <legend>Period</legend>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1194
 
1195
+ {/* ⭐⭐ W53-T16 / D-660 - WHETHER THIS CELL HAS A PERIOD AT ALL, said out loud. The
1196
+ pickers below show a unit and a month whether or not the cell is using them, so
1197
+ without this switch an all-time total read as "September 2026" on screen and the next
1198
+ save made that true. It is also the only way back to all time once a period is set. */}
1199
  <div className="sheet-period-lock">
1200
  <button
1201
  type="button"
1202
  role="switch"
1203
+ aria-checked={periodOn}
1204
+ className={"sheet-lock-toggle" + (periodOn ? " is-on" : "")}
1205
+ onClick={() => setPeriodOn((v) => !v)}
1206
  >
1207
  <span className="sheet-lock-dot" aria-hidden />
1208
+ <span>Limit this cell to a period</span>
1209
  </button>
1210
  <p className="sheet-period-note">
1211
+ {periodOn
1212
+ ? "Only rows dated inside the period below are counted."
1213
+ : "All time, so every row this cell's filter matches is counted whatever its date. "
1214
+ + "Saving leaves it that way."}
1215
  </p>
1216
  </div>
1217
 
1218
+ {periodOn && (
1219
+ <>
1220
+ <label className="sheet-field">
1221
+ <span>Unit</span>
1222
+ <select
1223
+ value={unit}
1224
+ aria-label="Period unit"
1225
+ onChange={(e) => {
1226
+ const next = e.target.value as PeriodUnit;
1227
+ setUnit(next);
1228
+ // Re-seat the start on the new unit's first month, or the pair stops naming one
1229
+ // period: `2026-08` under `quarter` is not a quarter anybody can compile.
1230
+ setStart(normalizePeriodStart(next, start));
1231
+ }}
1232
+ >
1233
+ {PERIOD_UNITS.map((u) => <option key={u.unit} value={u.unit}>{u.label}</option>)}
1234
+ </select>
1235
+ </label>
1236
+
1237
+ <div className="sheet-field-row">
1238
+ <label className="sheet-field">
1239
+ <span>Year</span>
1240
+ <select
1241
+ value={String(startYear)}
1242
+ aria-label="Period year"
1243
+ onChange={(e) => setYear(Number(e.target.value))}
1244
+ >
1245
+ {years.map((y) => <option key={y} value={String(y)}>{y}</option>)}
1246
+ </select>
1247
+ </label>
1248
+ {unit === "month" && (
1249
+ <label className="sheet-field">
1250
+ <span>Month</span>
1251
+ <select
1252
+ value={String(startMonth)}
1253
+ aria-label="Period month"
1254
+ onChange={(e) => setMonthOfYear(Number(e.target.value))}
1255
+ >
1256
+ {MONTH_NAMES.map((name, i) => (
1257
+ <option key={name} value={String(i + 1)}>{name}</option>
1258
+ ))}
1259
+ </select>
1260
+ </label>
1261
+ )}
1262
+ {unit === "quarter" && (
1263
+ <label className="sheet-field">
1264
+ <span>Quarter</span>
1265
+ <select
1266
+ value={String(Math.floor((startMonth - 1) / 3) + 1)}
1267
+ aria-label="Period quarter"
1268
+ onChange={(e) => setMonthOfYear(1 + 3 * (Number(e.target.value) - 1))}
1269
+ >
1270
+ {[1, 2, 3, 4].map((q) => <option key={q} value={String(q)}>{`Q${q}`}</option>)}
1271
+ </select>
1272
+ </label>
1273
+ )}
1274
+ </div>
1275
+
1276
+ {/* THE QUICK PICKS. They normalize through the same function the pickers do, so This
1277
+ never stamps today's month under a quarter or a year. */}
1278
+ <div className="sheet-period-quick">
1279
+ <button
1280
+ type="button"
1281
+ className="sheet-period-pick"
1282
+ onClick={() => setStart(normalizePeriodStart(unit, todayYm()))}
1283
+ >
1284
+ This {UNIT_NOUN[unit]}
1285
+ </button>
1286
+ <button
1287
+ type="button"
1288
+ className="sheet-period-pick"
1289
+ onClick={() => setStart(shiftPeriodStart(unit, todayYm(), -1))}
1290
+ >
1291
+ Last {UNIT_NOUN[unit]}
1292
+ </button>
1293
+ </div>
1294
+
1295
+ {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the
1296
+ sentence under it says what each one costs when the cell is copied. */}
1297
+ <div className="sheet-period-lock">
1298
+ <button
1299
+ type="button"
1300
+ role="switch"
1301
+ aria-checked={locked}
1302
+ className={"sheet-lock-toggle" + (locked ? " is-on" : "")}
1303
+ onClick={() => setLocked((v) => !v)}
1304
+ >
1305
+ <span className="sheet-lock-dot" aria-hidden />
1306
+ <span>Lock this period</span>
1307
+ </button>
1308
+ <p className="sheet-period-note">
1309
+ {locked
1310
+ ? "Locked, so any copy of this cell keeps this period."
1311
+ : `Not locked, so copying right or left moves the period by one ${UNIT_NOUN[unit]} `
1312
+ + "per column, and copying up or down keeps it."}
1313
+ </p>
1314
+ </div>
1315
+
1316
+ {/* ⭐ "Use a cell" STAYS A LINK (R9). It reveals the A1 input rather than replacing the
1317
+ picker, so the ordinary reader never meets a cell reference and the person who wants
1318
+ one is one click away from it. */}
1319
+ {!refOpen && (
1320
+ <button
1321
+ type="button"
1322
+ className="sheet-period-link"
1323
+ onClick={() => setRefOpen(true)}
1324
+ >
1325
+ Use a cell
1326
+ </button>
1327
+ )}
1328
+ {refOpen && (
1329
+ <label className="sheet-field">
1330
+ <span>Period from a cell</span>
1331
+ <input
1332
+ type="text"
1333
+ value={periodRef}
1334
+ onChange={(e) => setPeriodRef(e.target.value)}
1335
+ placeholder="$B$1"
1336
+ />
1337
+ </label>
1338
+ )}
1339
+ </>
1340
  )}
1341
+ </fieldset>
1342
+
1343
+ {/* ══ R10: THE DRAG RULES ═════════════════════════════════════════════════════════════ */}
1344
+ <fieldset className="sheet-scope sheet-drag">
1345
+ <legend>When dragged</legend>
1346
+
1347
+ <label className="sheet-field">
1348
+ <span>Across</span>
1349
+ <select
1350
+ value={across}
1351
+ aria-label="When dragged across columns"
1352
+ onChange={(e) => setAcross(e.target.value === "none" ? "none" : "period")}
1353
+ >
1354
+ <option value="period">Period</option>
1355
+ <option value="none">Nothing</option>
1356
+ </select>
1357
+ </label>
1358
+
1359
+ <label className="sheet-field">
1360
+ <span>Down</span>
1361
+ <select
1362
+ value={downField}
1363
+ aria-label="When dragged down rows"
1364
+ onChange={(e) => setDownField(e.target.value)}
1365
+ >
1366
+ <option value="">Nothing</option>
1367
+ {dragDownFields.map((f) => (
1368
+ <option key={f.key} value={f.key}>{`Next value of ${f.label}`}</option>
1369
+ ))}
1370
+ </select>
1371
+ </label>
1372
+
1373
+ {dragDownFields.length === 0 && (
1374
+ <p className="sheet-period-note">
1375
+ This database has no single select or link column to walk, so dragging down repeats
1376
+ the same rows.
1377
+ </p>
1378
  )}
1379
+ </fieldset>
1380
+
1381
+ {/* β›”β›” W53-T16 (owner instruction 13) - THE FOUR SENTENCE SUMMARY IS DELETED, NOT HIDDEN.
1382
+ It restated the period, the lock and the two drag rules that the controls immediately
1383
+ above already say, in a panel 380px wide where every line it took pushed Save further
1384
+ off screen. The one line kept is R11's, because it is the only sentence here that names
1385
+ something NO control shows: the filter in this cell was copied out of a view that has
1386
+ since been deleted, and nothing else remembers that. */}
1387
+ {adoptedFrom && (
1388
+ <p className="sheet-binding-line sheet-binding-adopted">
1389
+ {`Filter adopted from the deleted view ${adoptedFrom}`}
1390
+ </p>
1391
+ )}
1392
+
1393
+ {preview && <p className="sheet-preview">{`This cell would show ${preview}`}</p>}
1394
+ {notice && <p className="sheet-notice" role="alert">{notice}</p>}
1395
+ </>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1396
  )}
 
 
 
1397
  </div>
1398
 
1399
  <div className="sheet-binding-actions">
web/src/sheet/ChartDialog.tsx ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // sheet/ChartDialog.tsx β€” the Insert tab's CHART dialog (wave 54, W54-T11, ruling R5).
2
+ //
3
+ // ⭐⭐ R5, VERBATIM: "A chart reads BOTH. A cell range, exactly like Excel, is the primary path; a
4
+ // database source is a second tab in the same dialog. Ship both." So this is ONE dialog with two
5
+ // source tabs, and the cell range tab is the one that opens.
6
+ //
7
+ // β›”β›” HOW THE DATABASE TAB SURVIVES `SheetChart.tsx`'s RULING R9, WHICH SAYS THE OPPOSITE THING
8
+ // AND IS STILL TRUE. That file's header reads: "A CHART IS A CAPABILITY, NOT A VIEW TYPE. It
9
+ // occupies a rectangle of cells and READS those cells; it has no binding, no database and no query
10
+ // of its own. If this file ever calls the sheet preview door it has become a second way to fetch a
11
+ // number, and the sheet would then have two answers for one cell."
12
+ //
13
+ // The two reconcile in exactly one way, and it is the design below: THE DATABASE TAB DOES NOT GIVE
14
+ // THE CHART A QUERY. It writes BOUND CELLS into the sheet and then anchors an ordinary cell range
15
+ // chart over them. The chart still reads cells. The numbers still come from the one existing
16
+ // binding path, evaluated server side for a bound cell exactly as a hand bound cell is. Nothing
17
+ // here fetches a value, and `SheetChartSpec` gains no field: it is the same three keys it has
18
+ // carried since W49-T08.
19
+ //
20
+ // ⭐ WHAT THE DATABASE TAB WRITES, in ONE call through the door, so it is ONE history step and ONE
21
+ // save: a header row of period labels as typed literals, and beneath it one bound cell per period,
22
+ // every one carrying the same database, aggregate and scope and its OWN period. Then the chart,
23
+ // then a refresh, because a stale cell holds no value until the workbook refreshes.
24
+ //
25
+ // β›” THE BINDING VOCABULARY IS COPIED, NOT INVENTED. `BindingEditor.tsx` is the declaration of it
26
+ // and the server fixture in `aios-web/api/verify_sheet.py` is the proof; this file reuses the same
27
+ // names (`database`, `aggregate.fn`, `aggregate.field`, `scope.filter`, `period.unit`,
28
+ // `period.start`, `period.locked`) and imports nothing from that panel, because W54-T11 may not
29
+ // reach into lane E's files. A second spelling of the vocabulary would be a second dialect.
30
+ //
31
+ // β›” ESCAPE COMES FROM THE KIT AND FROM NOWHERE ELSE. `useOverlayLayer` registers this surface on
32
+ // the shared stack and calls `ui/useEscapeClose.ts` itself, which is why there is no local keydown
33
+ // listener anywhere in this file. DESIGN.md section 4: a local keydown listener is the defect, not
34
+ // the shortcut.
35
+ //
36
+ // ⚠ MOUNTED CONDITIONALLY BY ITS CALLER, never rendered behind an `open` prop. `useOverlayLayer`
37
+ // has no active flag: it claims Escape the moment it runs, and the stack hands the key to the LAST
38
+ // entry pushed. Mounting late is what puts this dialog above anything already open, and popping it
39
+ // on close hands Escape straight back.
40
+ //
41
+ // ⚠ DESIGN CONTRACT (DESIGN.md 2 through 5): centred modal on the base kit's `.lp-dialog` surface,
42
+ // tokens only, sentence case, inline SVG in the house vocabulary and never an emoji, a skeleton
43
+ // rather than a spinner while the database list is in flight, press feedback that does not change
44
+ // layout, reduced motion honoured, and no em dash or en dash in any string that reaches a screen.
45
+
46
+ import { useEffect, useId, useMemo, useRef, useState } from "react";
47
+ import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
48
+ // The document's own addresser, in SHEET coordinates. A second spelling of A1 in this file would
49
+ // be a second answer to a question the document already answers.
50
+ import { addressOf } from "./sheetState";
51
+ import type { Cell, SheetChartSpec } from "./types";
52
+
53
+ export interface ChartRange {
54
+ col0: number;
55
+ row0: number;
56
+ col1: number;
57
+ row1: number;
58
+ }
59
+
60
+ /**
61
+ * ⭐ THE EIGHT KINDS THE DOCUMENT CARRIES. `types.ts::SheetChartSpec` declares all eight and
62
+ * `platform/core/sheets.py::SHEET_CHART_KINDS` keeps all eight since W54-T09, so every one of them
63
+ * survives a save and a reload. Four are DRAWN today (`types.ts::SHEET_CHART_DRAWN_KINDS`) and the
64
+ * renderer widens next, so the stored kind is the person's real choice either way.
65
+ */
66
+ export const CHART_KINDS: { kind: SheetChartSpec["kind"]; label: string }[] = [
67
+ { kind: "bar", label: "Bar" },
68
+ { kind: "column", label: "Column" },
69
+ { kind: "line", label: "Line" },
70
+ { kind: "area", label: "Area" },
71
+ { kind: "pie", label: "Pie" },
72
+ { kind: "donut", label: "Donut" },
73
+ { kind: "scatter", label: "Scatter" },
74
+ { kind: "combo", label: "Combo" },
75
+ ];
76
+
77
+ /**
78
+ * ⭐ THE AGGREGATE VOCABULARY, COPIED FROM `BindingEditor.tsx::AGGREGATES` NAME FOR NAME. The
79
+ * server normalizes `aggregate.fn` against this same set, so a name invented here would bind a
80
+ * cell the panel could never reopen.
81
+ */
82
+ const AGGREGATES: { fn: string; label: string }[] = [
83
+ { fn: "sum", label: "Sum" },
84
+ { fn: "count", label: "Count" },
85
+ { fn: "avg", label: "Average" },
86
+ { fn: "min", label: "Minimum" },
87
+ { fn: "max", label: "Maximum" },
88
+ ];
89
+
90
+ type PeriodUnit = "month" | "quarter" | "year";
91
+
92
+ const PERIOD_UNITS: { unit: PeriodUnit; label: string }[] = [
93
+ { unit: "month", label: "Month" },
94
+ { unit: "quarter", label: "Quarter" },
95
+ { unit: "year", label: "Year" },
96
+ ];
97
+
98
+ /** How many months one step of a unit covers. Same arithmetic the binding panel states. */
99
+ const MONTHS_PER_UNIT: Record<PeriodUnit, number> = { month: 1, quarter: 3, year: 12 };
100
+
101
+ const MONTH_ABBR = [
102
+ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
103
+ ];
104
+
105
+ /**
106
+ * ⚠ THE FALLBACK RECTANGLE, AND WHY IT IS A FALLBACK RATHER THAN A REFUSAL. A chart OCCUPIES the
107
+ * rectangle it reads, so a one cell range is a chart nobody can see and an absent range is no
108
+ * chart at all. When the selection is a single cell the range grows from that cell to this size,
109
+ * and with no selection at all it starts at A1, which is the only anchor available. The dialog
110
+ * SAYS which rectangle it will cover, so the growth is visible before anything is inserted.
111
+ */
112
+ const CHART_COLS = 4;
113
+ const CHART_ROWS = 6;
114
+
115
+ /** How many periods the database tab writes, and the fence around what a person may ask for. */
116
+ const DEFAULT_PERIODS = 6;
117
+ const MIN_PERIODS = 2;
118
+ const MAX_PERIODS = 24;
119
+
120
+ const pad2 = (n: number) => String(n).padStart(2, "0");
121
+
122
+ const joinYm = (y: number, m: number) => `${y}-${pad2(m)}`;
123
+
124
+ /** `{y, m}` out of a `"YYYY-MM"`; today when the string is absent or malformed. */
125
+ function splitYm(ym: string): { y: number; m: number } {
126
+ const hit = /^(\d{4})-(\d{2})$/.exec(ym ?? "");
127
+ if (!hit) {
128
+ const now = new Date();
129
+ return { y: now.getFullYear(), m: now.getMonth() + 1 };
130
+ }
131
+ const m = Number(hit[2]);
132
+ return { y: Number(hit[1]), m: m >= 1 && m <= 12 ? m : 1 };
133
+ }
134
+
135
+ /**
136
+ * ⭐ `start` IS THE PERIOD'S FIRST MONTH, which is what contract C2 means by it: `unit` and `start`
137
+ * have to jointly name exactly one window, so Q3 2026 is `2026-07` and the year 2026 is `2026-01`.
138
+ */
139
+ export function periodStartOf(unit: PeriodUnit, ym: string): string {
140
+ const { y, m } = splitYm(ym);
141
+ if (unit === "year") return joinYm(y, 1);
142
+ if (unit === "quarter") return joinYm(y, 1 + 3 * Math.floor((m - 1) / 3));
143
+ return joinYm(y, m);
144
+ }
145
+
146
+ /** Move a start by whole periods. Negative steps go back. */
147
+ export function shiftPeriod(unit: PeriodUnit, ym: string, steps: number): string {
148
+ const { y, m } = splitYm(periodStartOf(unit, ym));
149
+ const total = y * 12 + (m - 1) + steps * MONTHS_PER_UNIT[unit];
150
+ return joinYm(Math.floor(total / 12), (total % 12) + 1);
151
+ }
152
+
153
+ /** What a header cell says for one period. Sentence case, and no dash anywhere near it. */
154
+ export function periodLabel(unit: PeriodUnit, ym: string): string {
155
+ const { y, m } = splitYm(periodStartOf(unit, ym));
156
+ if (unit === "year") return String(y);
157
+ if (unit === "quarter") return `Q${1 + Math.floor((m - 1) / 3)} ${y}`;
158
+ return `${MONTH_ABBR[m - 1]} ${y}`;
159
+ }
160
+
161
+ const todayYm = (): string => {
162
+ const now = new Date();
163
+ return joinYm(now.getFullYear(), now.getMonth() + 1);
164
+ };
165
+
166
+ /** The rectangle a cell range chart occupies, grown to something visible when it has to be. */
167
+ export function chartRangeOf(sel: ChartRange | null): ChartRange {
168
+ const col0 = sel ? Math.min(sel.col0, sel.col1) : 0;
169
+ const row0 = sel ? Math.min(sel.row0, sel.row1) : 0;
170
+ const col1 = sel ? Math.max(sel.col0, sel.col1) : 0;
171
+ const row1 = sel ? Math.max(sel.row0, sel.row1) : 0;
172
+ if (col1 > col0 || row1 > row0) return { col0, row0, col1, row1 };
173
+ return { col0, row0, col1: col0 + CHART_COLS - 1, row1: row0 + CHART_ROWS - 1 };
174
+ }
175
+
176
+ /** Where a database block lands: the selection's top left, or A1 when there is no selection. */
177
+ export function landingOf(sel: ChartRange | null): { col: number; row: number } {
178
+ if (!sel) return { col: 0, row: 0 };
179
+ return { col: Math.min(sel.col0, sel.col1), row: Math.min(sel.row0, sel.row1) };
180
+ }
181
+
182
+ export interface DatabaseBlockPlan {
183
+ cells: Record<string, Cell>;
184
+ range: ChartRange;
185
+ }
186
+
187
+ /**
188
+ * ⭐⭐ THE WHOLE OF THE DATABASE TAB'S WRITE, AS A PURE FUNCTION so a reader can see that it
189
+ * produces CELLS and a RECTANGLE and never a query. Two rows: period labels on top, one bound cell
190
+ * per period beneath. The chart is anchored over both rows, because the header row is the axis.
191
+ */
192
+ export function planDatabaseBlock(opts: {
193
+ anchor: { col: number; row: number };
194
+ database: string;
195
+ fn: string;
196
+ field: string;
197
+ unit: PeriodUnit;
198
+ periods: number;
199
+ }): DatabaseBlockPlan {
200
+ const { anchor, database, fn, field, unit } = opts;
201
+ const asked = Math.round(opts.periods);
202
+ const count = Math.max(MIN_PERIODS, Math.min(MAX_PERIODS, Number.isFinite(asked) ? asked : DEFAULT_PERIODS));
203
+ const latest = periodStartOf(unit, todayYm());
204
+ const cells: Record<string, Cell> = {};
205
+ for (let i = 0; i < count; i += 1) {
206
+ const start = shiftPeriod(unit, latest, i - (count - 1));
207
+ const col = anchor.col + i;
208
+ cells[addressOf(col, anchor.row)] = {
209
+ kind: "literal",
210
+ state: "typed",
211
+ text: periodLabel(unit, start),
212
+ };
213
+ cells[addressOf(col, anchor.row + 1)] = {
214
+ kind: "bound",
215
+ state: "stale",
216
+ binding: {
217
+ database,
218
+ // A count folds no column, exactly as the binding panel writes it.
219
+ aggregate: fn === "count" ? { fn } : { fn, field },
220
+ scope: { filter: { conj: "and", nodes: [] } },
221
+ // LOCKED, and that is not a default worth glossing: each cell names one fixed window, and
222
+ // an unlocked period would shift the moment somebody dragged the block sideways, moving a
223
+ // number with no edit behind it.
224
+ period: { unit, start, locked: true },
225
+ },
226
+ };
227
+ }
228
+ return {
229
+ cells,
230
+ range: { col0: anchor.col, row0: anchor.row, col1: anchor.col + count - 1, row1: anchor.row + 1 },
231
+ };
232
+ }
233
+
234
+ /** The eight glyphs, in the house vocabulary: 16 by 16, on `currentColor`, at most three paths. */
235
+ function ChartKindIcon({ kind }: { kind: SheetChartSpec["kind"] }) {
236
+ const cls = "sheet-chart-kind-icon";
237
+ if (kind === "bar") {
238
+ return (
239
+ <svg viewBox="0 0 16 16" aria-hidden="true" className={cls}>
240
+ <path d="M2.5 2.5v11" />
241
+ <path d="M3.5 5h7M3.5 8h4.5M3.5 11h9" />
242
+ </svg>
243
+ );
244
+ }
245
+ if (kind === "column") {
246
+ return (
247
+ <svg viewBox="0 0 16 16" aria-hidden="true" className={cls}>
248
+ <path d="M2.5 13.5h11" />
249
+ <path d="M4.5 12V8M8 12V4M11.5 12V6" />
250
+ </svg>
251
+ );
252
+ }
253
+ if (kind === "line") {
254
+ return (
255
+ <svg viewBox="0 0 16 16" aria-hidden="true" className={cls}>
256
+ <path d="M2.5 13.5h11" />
257
+ <path d="M3.2 11.2l3.2-4 2.6 2 4.2-5.2" />
258
+ </svg>
259
+ );
260
+ }
261
+ if (kind === "area") {
262
+ return (
263
+ <svg viewBox="0 0 16 16" aria-hidden="true" className={cls}>
264
+ <path d="M2.5 13.5h11" />
265
+ <path d="M3.2 11.6l3.2-4 2.6 2 4.2-5.1v7.1z" />
266
+ </svg>
267
+ );
268
+ }
269
+ if (kind === "pie") {
270
+ return (
271
+ <svg viewBox="0 0 16 16" aria-hidden="true" className={cls}>
272
+ <path d="M8 2.5a5.5 5.5 0 1 0 5.5 5.5" />
273
+ <path d="M8 2.5V8h5.5" />
274
+ </svg>
275
+ );
276
+ }
277
+ if (kind === "donut") {
278
+ return (
279
+ <svg viewBox="0 0 16 16" aria-hidden="true" className={cls}>
280
+ <path d="M8 2.5a5.5 5.5 0 1 0 0 11 5.5 5.5 0 1 0 0-11z" />
281
+ <path d="M8 6a2 2 0 1 0 0 4 2 2 0 1 0 0-4z" />
282
+ </svg>
283
+ );
284
+ }
285
+ if (kind === "scatter") {
286
+ return (
287
+ <svg viewBox="0 0 16 16" aria-hidden="true" className={cls}>
288
+ <path d="M2.5 13.5h11" />
289
+ <path className="sheet-chart-kind-dots" d="M5 10.2h.01M8.2 6.4h.01M11.4 8.8h.01" />
290
+ </svg>
291
+ );
292
+ }
293
+ return (
294
+ <svg viewBox="0 0 16 16" aria-hidden="true" className={cls}>
295
+ <path d="M2.5 13.5h11" />
296
+ <path d="M4.5 12V8.6M8 12V6M11.5 12V9.4" />
297
+ <path d="M3.4 10.4l4-3.6 4 2.6 2.2-1.9" />
298
+ </svg>
299
+ );
300
+ }
301
+
302
+ type SourceTab = "range" | "database";
303
+
304
+ const SOURCE_TABS: { id: SourceTab; label: string }[] = [
305
+ { id: "range", label: "A cell range" },
306
+ { id: "database", label: "A database" },
307
+ ];
308
+
309
+ export interface ChartDialogProps {
310
+ /** The current selection, in SHEET coordinates, or null when there is none. */
311
+ selection: ChartRange | null;
312
+ /** Escape, an outside pointerdown, the close mark, or Cancel. All the same event. */
313
+ onClose: () => void;
314
+ /**
315
+ * The one door out. `cells` is present only on the database tab, and the caller commits it in a
316
+ * single call so the block, the chart and the refresh are one step.
317
+ */
318
+ onCreate: (
319
+ kind: SheetChartSpec["kind"],
320
+ range: ChartRange,
321
+ cells?: Record<string, Cell>,
322
+ ) => void;
323
+ }
324
+
325
+ export default function ChartDialog({ selection, onClose, onCreate }: ChartDialogProps) {
326
+ const panelRef = useRef<HTMLDivElement>(null);
327
+ const titleId = useId();
328
+
329
+ const [tab, setTab] = useState<SourceTab>("range");
330
+ const [kind, setKind] = useState<SheetChartSpec["kind"]>("bar");
331
+ const [databases, setDatabases] = useState<{ key: string; label: string }[]>([]);
332
+ const [loading, setLoading] = useState(true);
333
+ const [database, setDatabase] = useState("");
334
+ const [fn, setFn] = useState("count");
335
+ const [field, setField] = useState("");
336
+ const [unit, setUnit] = useState<PeriodUnit>("month");
337
+ const [periods, setPeriods] = useState(String(DEFAULT_PERIODS));
338
+
339
+ // β›” RESTORE FOCUS IS OFF, AND THAT IS THE RIBBON'S RULE RATHER THAN AN OMISSION. Every ribbon
340
+ // button prevents default on mouse down so that pressing it never blurs the grid canvas, so the
341
+ // element this dialog would restore is the CANVAS. `Ribbon.tsx::closePop` already returns focus
342
+ // to the trigger on close, and it must win.
343
+ useOverlayLayer({
344
+ panelRef,
345
+ onDismiss: onClose,
346
+ dismissOnOutside: true,
347
+ initialFocus: "first",
348
+ restoreFocus: false,
349
+ trapFocus: true,
350
+ });
351
+
352
+ /**
353
+ * ⭐ THE SAME DOOR THE RAIL AND THE BINDING PANEL READ, spelled the same way `SheetPage.tsx`
354
+ * spells it. FAILS SOFT ON PURPOSE: a refused or broken fetch leaves the picker with nothing to
355
+ * offer and the panel says so, which is a refusal a person can act on. A thrown error inside a
356
+ * dialog is not.
357
+ */
358
+ useEffect(() => {
359
+ let live = true;
360
+ (async () => {
361
+ try {
362
+ const res = await fetch("/api/v1/nav", { credentials: "same-origin" });
363
+ if (!res.ok) return;
364
+ const body = (await res.json()) as { pages?: { key: string; label: string }[] };
365
+ if (!live) return;
366
+ const rows = (body.pages ?? [])
367
+ .filter((p) => p && typeof p.key === "string")
368
+ .map((p) => ({ key: p.key, label: p.label || p.key }));
369
+ setDatabases(rows);
370
+ setDatabase(rows[0]?.key ?? "");
371
+ } catch {
372
+ /* the picker simply offers nothing, and the panel says so */
373
+ } finally {
374
+ if (live) setLoading(false);
375
+ }
376
+ })();
377
+ return () => { live = false; };
378
+ }, []);
379
+
380
+ const range = useMemo(() => chartRangeOf(selection), [selection]);
381
+ const rangeSentence = `The chart will cover ${addressOf(range.col0, range.row0)} to `
382
+ + `${addressOf(range.col1, range.row1)}.`;
383
+
384
+ const wantsField = fn !== "count";
385
+ const ready = tab === "range"
386
+ ? true
387
+ : Boolean(database) && (!wantsField || field.trim().length > 0);
388
+
389
+ const create = () => {
390
+ if (tab === "range") {
391
+ onCreate(kind, range);
392
+ return;
393
+ }
394
+ if (!ready) return;
395
+ const plan = planDatabaseBlock({
396
+ anchor: landingOf(selection),
397
+ database,
398
+ fn,
399
+ field: field.trim(),
400
+ unit,
401
+ periods: Number(periods),
402
+ });
403
+ onCreate(kind, plan.range, plan.cells);
404
+ };
405
+
406
+ const kindPicker = (
407
+ <div className="sheet-chart-gallery" role="group" aria-label="Chart type">
408
+ {CHART_KINDS.map((entry) => (
409
+ <button
410
+ key={entry.kind}
411
+ type="button"
412
+ className="sheet-chart-kind"
413
+ aria-pressed={kind === entry.kind}
414
+ onClick={() => setKind(entry.kind)}
415
+ >
416
+ <ChartKindIcon kind={entry.kind} />
417
+ <span className="sheet-chart-kind-label">{entry.label}</span>
418
+ </button>
419
+ ))}
420
+ </div>
421
+ );
422
+
423
+ return (
424
+ <BodyPortal>
425
+ <div className="lp-dialog-scrim">
426
+ <div
427
+ ref={panelRef}
428
+ // `sheet-chart-dialog` carries no rule of its own and is not meant to: it is the name a
429
+ // gate, a screenshot or a person in the inspector can point at. The paint is `.lp-dialog`.
430
+ className="lp-dialog sheet-chart-dialog"
431
+ style={{ width: "min(680px, calc(100vw - 32px))" }}
432
+ role="dialog"
433
+ aria-modal="true"
434
+ aria-labelledby={titleId}
435
+ data-overlay-kind="sheet-chart"
436
+ >
437
+ <div className="lp-dialog-head">
438
+ <h2 className="lp-dialog-title" id={titleId}>Insert a chart</h2>
439
+ <button
440
+ type="button"
441
+ className="lp-dialog-x"
442
+ aria-label="Close the chart dialog"
443
+ onClick={onClose}
444
+ >
445
+ <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false">
446
+ <path
447
+ d="M4 4l8 8M12 4l-8 8"
448
+ stroke="currentColor"
449
+ strokeWidth="1.5"
450
+ strokeLinecap="round"
451
+ />
452
+ </svg>
453
+ </button>
454
+ </div>
455
+
456
+ <div className="sheet-chart-tabs" role="tablist" aria-label="What the chart reads">
457
+ {SOURCE_TABS.map((entry) => (
458
+ <button
459
+ key={entry.id}
460
+ type="button"
461
+ role="tab"
462
+ id={`${titleId}-tab-${entry.id}`}
463
+ className="sheet-chart-tab"
464
+ aria-selected={tab === entry.id}
465
+ aria-controls={`${titleId}-panel`}
466
+ onClick={() => setTab(entry.id)}
467
+ >
468
+ {entry.label}
469
+ </button>
470
+ ))}
471
+ </div>
472
+
473
+ <div
474
+ className="sheet-chart-panel"
475
+ id={`${titleId}-panel`}
476
+ role="tabpanel"
477
+ aria-labelledby={`${titleId}-tab-${tab}`}
478
+ >
479
+ {tab === "range" ? (
480
+ <>
481
+ <p className="sheet-chart-caption">{rangeSentence}</p>
482
+ {kindPicker}
483
+ </>
484
+ ) : (
485
+ <>
486
+ <div className="sheet-chart-fields" aria-busy={loading}>
487
+ <label className="sheet-chart-label" htmlFor={`${titleId}-db`}>Database</label>
488
+ {loading ? (
489
+ <div className="sheet-chart-skeleton" />
490
+ ) : databases.length === 0 ? (
491
+ <p className="sheet-chart-caption">No databases are available to read.</p>
492
+ ) : (
493
+ <select
494
+ id={`${titleId}-db`}
495
+ // `sheet-chart-db` carries no rule: it is the name a screenshot waits on,
496
+ // so a shot of this tab cannot be taken while the list is still in flight.
497
+ className="sheet-chart-select sheet-chart-db"
498
+ value={database}
499
+ onChange={(event) => setDatabase(event.target.value)}
500
+ >
501
+ {databases.map((db) => (
502
+ <option key={db.key} value={db.key}>{db.label}</option>
503
+ ))}
504
+ </select>
505
+ )}
506
+
507
+ <label className="sheet-chart-label" htmlFor={`${titleId}-fn`}>Total</label>
508
+ <select
509
+ id={`${titleId}-fn`}
510
+ className="sheet-chart-select"
511
+ value={fn}
512
+ onChange={(event) => setFn(event.target.value)}
513
+ >
514
+ {AGGREGATES.map((agg) => (
515
+ <option key={agg.fn} value={agg.fn}>{agg.label}</option>
516
+ ))}
517
+ </select>
518
+
519
+ {wantsField && (
520
+ <>
521
+ <label className="sheet-chart-label" htmlFor={`${titleId}-field`}>
522
+ Column
523
+ </label>
524
+ <input
525
+ id={`${titleId}-field`}
526
+ className="sheet-chart-text"
527
+ type="text"
528
+ value={field}
529
+ placeholder="amount_total"
530
+ onChange={(event) => setField(event.target.value)}
531
+ />
532
+ </>
533
+ )}
534
+
535
+ <label className="sheet-chart-label" htmlFor={`${titleId}-unit`}>Period</label>
536
+ <select
537
+ id={`${titleId}-unit`}
538
+ className="sheet-chart-select"
539
+ value={unit}
540
+ onChange={(event) => setUnit(event.target.value as PeriodUnit)}
541
+ >
542
+ {PERIOD_UNITS.map((p) => (
543
+ <option key={p.unit} value={p.unit}>{p.label}</option>
544
+ ))}
545
+ </select>
546
+
547
+ <label className="sheet-chart-label" htmlFor={`${titleId}-count`}>
548
+ How many
549
+ </label>
550
+ <input
551
+ id={`${titleId}-count`}
552
+ className="sheet-chart-number"
553
+ type="number"
554
+ min={MIN_PERIODS}
555
+ max={MAX_PERIODS}
556
+ value={periods}
557
+ onChange={(event) => setPeriods(event.target.value)}
558
+ />
559
+ </div>
560
+ {/* The gallery is the same one the cell range tab shows, and the chosen kind is
561
+ shared between the two: the source is what the tabs choose, never the picture. */}
562
+ <div className="sheet-chart-kindblock">
563
+ <span className="sheet-chart-label">Chart type</span>
564
+ {kindPicker}
565
+ </div>
566
+ {/* ⚠ SAID AT THE POINT OF CREATION, because a person who expected only a picture
567
+ must not be surprised to find a block of numbers. One sentence, not a
568
+ paragraph (DESIGN.md section 4: never over-explain). */}
569
+ <p className="sheet-chart-note">
570
+ The periods are written into the sheet as cells, and the chart reads them.
571
+ </p>
572
+ </>
573
+ )}
574
+ </div>
575
+
576
+ <div className="lp-dialog-actions">
577
+ <button type="button" className="lp-dialog-btn lp-dialog-btn-quiet" onClick={onClose}>
578
+ Cancel
579
+ </button>
580
+ <button
581
+ type="button"
582
+ className="lp-dialog-btn lp-dialog-btn-primary"
583
+ disabled={!ready}
584
+ onClick={create}
585
+ >
586
+ Insert chart
587
+ </button>
588
+ </div>
589
+ </div>
590
+ </div>
591
+ </BodyPortal>
592
+ );
593
+ }
web/src/sheet/DrillModal.tsx CHANGED
@@ -16,9 +16,59 @@
16
  // chrome and NO comparison text: no "was 24,920", no badge, nothing. The staleness is a property of
17
  // the CELL and it is marked on the grid; repeating it here would be answering a question the person
18
  // did not ask, at the moment they asked a different one.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  import { Suspense, lazy, useCallback, useEffect, useRef, useState } from "react";
 
 
21
  import type { SurfaceScope } from "../customer-grid/apiBridge";
 
 
 
 
 
 
22
  import { useEscapeClose } from "../ui/useEscapeClose";
23
  import { drillCell } from "./sheetApi";
24
  import type { CellDrill } from "./sheetApi";
@@ -40,6 +90,23 @@ const LinkGridModal = lazy(() =>
40
  import("../customer-grid/CustomerGrid").then((m) => ({ default: m.LinkGridModal })),
41
  );
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  /**
44
  * A Sheet binding names a DATABASE KEY; `LinkGridModal` wants a `SurfaceScope`. The two are not
45
  * the same vocabulary and the difference is only visible for the two compiled modules.
@@ -54,17 +121,233 @@ const scopeOf = (database: string): SurfaceScope | null => {
54
  return database.startsWith("ut_") ? (database as SurfaceScope) : null;
55
  };
56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  export interface DrillModalProps {
58
  workbookId: string;
59
  addr: string;
60
  /** The label the popup wears. The cell's own address is the honest one: it is what was clicked. */
61
  label: string;
62
  onClose: () => void;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  }
64
 
65
- export default function DrillModal({ workbookId, addr, label, onClose }: DrillModalProps) {
 
 
66
  const [drill, setDrill] = useState<CellDrill | null>(null);
67
  const [error, setError] = useState("");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  /**
70
  * ⭐⭐ W51-T12 - THE REFUSAL CARDS CLOSE ON ESCAPE TOO, AND THAT WAS THE HOLE.
@@ -87,11 +370,39 @@ export default function DrillModal({ workbookId, addr, label, onClose }: DrillMo
87
  const escapeContainer = useCallback(() => cardRef.current as HTMLElement | null, []);
88
  useEscapeClose(showingCard, onEscape, { container: escapeContainer });
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  useEffect(() => {
91
  let live = true;
92
  (async () => {
93
  const got = await drillCell(workbookId, addr);
94
  if (!live) return;
 
95
  if (!got.ok) {
96
  setError(got.message);
97
  return;
@@ -101,7 +412,186 @@ export default function DrillModal({ workbookId, addr, label, onClose }: DrillMo
101
  return () => {
102
  live = false;
103
  };
104
- }, [workbookId, addr]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
  if (error) {
107
  // A refusal is a plain sentence naming the cause and the subject, per the design contract.
@@ -116,7 +606,10 @@ export default function DrillModal({ workbookId, addr, label, onClose }: DrillMo
116
  );
117
  }
118
 
119
- if (!drill) return null;
 
 
 
120
 
121
  if (!scope) {
122
  // Named rather than swallowed: a database the popup cannot address is a real gap, and a blank
@@ -132,16 +625,63 @@ export default function DrillModal({ workbookId, addr, label, onClose }: DrillMo
132
  }
133
 
134
  return (
135
- // No fallback chrome: the popup either opens or it does not, and a skeleton behind a modal
136
- // that is about to cover it would be a flash of furniture nobody asked for.
137
- <Suspense fallback={null}>
138
- <LinkGridModal
139
- label={label}
140
- table={scope}
141
- recordIds={drill.record_ids}
142
- editable={false}
143
- onClose={onClose}
144
- />
145
- </Suspense>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  );
147
  }
 
16
  // chrome and NO comparison text: no "was 24,920", no badge, nothing. The staleness is a property of
17
  // the CELL and it is marked on the grid; repeating it here would be answering a question the person
18
  // did not ask, at the moment they asked a different one.
19
+ //
20
+ // ⭐⭐ W54-T34 (owner instruction 10) β€” NINE SECONDS OF NOTHING WAS THE DEFECT.
21
+ // Owner, verbatim: *"Clicking View rows still takes a long time; if it must, we need a loading
22
+ // button so the user knows their click worked."* This component used to render `null` for the whole
23
+ // of that wait, so a drill that was working and a click that never landed looked identical. Measured
24
+ // on tenant #0 (`.claude/wiki/waves/wave54/lanes/E/T36-baseline.md`): `drill_cell` costs 55 to 90 ms
25
+ // against a `ut_*` table but 9,248 to 9,448 ms against `customer_data`, which goes through the
26
+ // registry-module mirror rather than a DuckDB query. So the wait is real and it is long.
27
+ //
28
+ // β›” BOTH `null`S WERE THE DEFECT, NOT ONE. The request had no loading state and neither did the
29
+ // LAZY CHUNK behind it, so a warm answer could still be followed by a second blank window while
30
+ // 1,850 kB of `CustomerGrid` downloaded. The Suspense fallback's old note argued that "a skeleton
31
+ // behind a modal that is about to cover it would be a flash of furniture nobody asked for" - which
32
+ // was right when there was no skeleton at all and the two states were nothing and everything. Now
33
+ // the skeleton is ALREADY on screen when the answer lands, so keeping it up for the chunk is
34
+ // CONTINUITY rather than new furniture: the surface never blinks back to nothing.
35
+ //
36
+ // ⭐⭐ W54-T35 (owner instruction 8, ruling R8) β€” THE ROWS ARE HERE, SO THE REASON FOR THEM
37
+ // SHOULD BE TOO. Owner, verbatim: *"the Filter module itself will show exactly what the filter is
38
+ // when we click 'View row' so its easy for user also to know what this filter is. In fact, they
39
+ // should be able to change the filter there too. And if they make a mistake etc, they can just
40
+ // CTRL + Z to return the Cell to its original filter."* Three clauses, and each one is a decision
41
+ // recorded beside the code that answers it: the BAND (`DrillFilterBand`) states it, the shared
42
+ // `SheetFilterDialog` edits it, and one cell-scoped step of undo takes it back.
43
+ //
44
+ // β›”β›” THE BAND IS PORTALLED INTO `LinkGridModal`'s OWN CARD, WHICH LOOKS LIKE A LIBERTY AND IS
45
+ // THE CONSERVATIVE CHOICE. `LinkGridModal` has no slot for extra chrome and it is not this lane's
46
+ // file, so the two alternatives were a floating strip positioned over its header by copied
47
+ // geometry, or this. A floating strip fails three ways at once and every one of them is silent:
48
+ // it is OUTSIDE `panelRef`, so the shared dismissal contract reads a click on it as an outside
49
+ // pointerdown and closes the drill the instant you reach for Edit; it is outside the focus trap,
50
+ // so the control is mouse-only; and it re-derives a card size it does not own. A portal into the
51
+ // card is inside all three. The host is found by `data-overlay-kind="linked-record-grid"`, the
52
+ // attribute that component already publishes for exactly this kind of identification, and when
53
+ // it is absent the band simply does not render.
54
+ //
55
+ // β›” AND THE BAND MAY WEAR `.cg-link-grid-foot`, WHICH THE SKELETON ABOVE MAY NOT. The rule that
56
+ // stops `DrillSkeleton` borrowing `customer-grid/RecordDetail.css` is that the skeleton stands in
57
+ // for a chunk that has not arrived, so on a cold cache its class names would exist and its rules
58
+ // would not. This band renders ONLY as a child of a mounted `LinkGridModal`, i.e. only once that
59
+ // same chunk is in hand, so the stylesheet is guaranteed present. Same file, opposite verdict,
60
+ // for one reason: WHEN it paints.
61
 
62
  import { Suspense, lazy, useCallback, useEffect, useRef, useState } from "react";
63
+ import { createPortal } from "react-dom";
64
+ import { fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge";
65
  import type { SurfaceScope } from "../customer-grid/apiBridge";
66
+ import { OverlayProvider } from "../customer-grid/OverlaySurface";
67
+ import type { Field, FilterTree, Row } from "../customer-grid/types";
68
+ import { choiceVocabulary, topicForScope } from "../customer-grid/types";
69
+ import {
70
+ SheetFilterDialog, conditionCountLabel, filterSentence,
71
+ } from "../filter-kit/SheetFilterPopup";
72
  import { useEscapeClose } from "../ui/useEscapeClose";
73
  import { drillCell } from "./sheetApi";
74
  import type { CellDrill } from "./sheetApi";
 
90
  import("../customer-grid/CustomerGrid").then((m) => ({ default: m.LinkGridModal })),
91
  );
92
 
93
+ /**
94
+ * ⭐⭐ W54-T34 β€” THE CHUNK IS ASKED FOR WHEN THE READER ASKS FOR THE ROWS, NOT AFTER THEY ARRIVE.
95
+ *
96
+ * `React.lazy` starts its import on the first render that actually reaches `<LinkGridModal>`, which
97
+ * on the success path is AFTER the drill has answered. On `customer_data` that is nine seconds, and
98
+ * the 1,850 kB download then begins from zero: two waits, back to back, for one click. Warming the
99
+ * module the moment this component mounts runs them together instead. Nothing is imported twice -
100
+ * the two dynamic imports name the same module, so the second one resolves off the registry.
101
+ *
102
+ * β›” AND THE BOOLEAN IT FEEDS IS NOT A CONVENIENCE, IT IS THE ESCAPE CLAIM. `LinkGridModal` joins
103
+ * the base kit's stack from inside itself, through `useOverlayLayer`, so it claims Escape only once
104
+ * it has MOUNTED. The window while its chunk is still in flight belongs to nobody. Knowing when the
105
+ * module is in hand is what lets the skeleton hold the claim for exactly that window and hand it
106
+ * over, rather than overlap it - the double-push the W51-T12 note below is careful to avoid.
107
+ */
108
+ const warmLinkChunk = () => import("../customer-grid/CustomerGrid");
109
+
110
  /**
111
  * A Sheet binding names a DATABASE KEY; `LinkGridModal` wants a `SurfaceScope`. The two are not
112
  * the same vocabulary and the difference is only visible for the two compiled modules.
 
121
  return database.startsWith("ut_") ? (database as SurfaceScope) : null;
122
  };
123
 
124
+ /**
125
+ * ⭐⭐ W54-T34 β€” WHAT VIEW ROWS OPENS INTO WHILE ITS ROWS ARE FETCHED.
126
+ *
127
+ * β›” THE SKELETON LANGUAGE IS INHERITED, NOT INVENTED. `sheet/SheetRail.tsx::RailSkeleton` set it
128
+ * and `sheet/BindingEditor.tsx::BindingSkeleton` followed it one ticket ago: ONE flat
129
+ * `--lp-surface-2` tone, no shimmer (an animated sweep is a second thing moving on a surface whose
130
+ * whole job is to sit still, and `prefers-reduced-motion` would then need a third state), bars
131
+ * `aria-hidden` under ONE `role="status"` so a screen reader hears "loading" once, and 150 ms
132
+ * ease-out on opacity alone. A second skeleton dialect in the same stylesheet would be the cost.
133
+ *
134
+ * β›”β›” AND IT CANNOT BORROW `.cg-record-backdrop` / `.cg-link-grid-modal`, WHICH IS THE OBVIOUS
135
+ * SHORTCUT AND IS EXACTLY BACKWARDS. Those rules live in `customer-grid/RecordDetail.css`, imported
136
+ * by `RecordDetail.tsx` - inside the very chunk this skeleton is standing in for. On a cold cache
137
+ * the class names would be there and the rules would not, so the stand-in for a slow chunk would
138
+ * paint in native chrome, precisely when it is needed most.
139
+ * ([[portalling-drops-descendant-scoped-css]], same failure through a different door.)
140
+ *
141
+ * ⭐ THE GEOMETRY IS THE SETTLED MODAL'S, measured off `.cg-link-grid-modal`: the same
142
+ * `min(1320px, 100vw - 48px)` by `min(840px, 100vh - 48px)` card on the same centred scrim, a 54px
143
+ * head, then rows. That is what makes it a skeleton rather than a placeholder - the real grid lands
144
+ * where the bars were instead of resizing the surface under the reader's eyes.
145
+ */
146
+ function DrillSkeleton(
147
+ { label, nodeRef }: { label: string; nodeRef: { current: HTMLDivElement | null } },
148
+ ) {
149
+ return (
150
+ <div
151
+ className="sheet-drill-skeleton-backdrop"
152
+ role="status"
153
+ aria-label={`Loading the rows behind ${label}`}
154
+ ref={nodeRef}
155
+ >
156
+ <div className="sheet-drill-skeleton" aria-hidden="true">
157
+ <div className="sheet-drill-skeleton-head">
158
+ <span className="sheet-drill-skeleton-title" />
159
+ <span className="sheet-drill-skeleton-sub" />
160
+ </div>
161
+ <div className="sheet-drill-skeleton-rows">
162
+ <span className="sheet-drill-skeleton-row is-head" />
163
+ {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map((i) => (
164
+ <span className="sheet-drill-skeleton-row" key={i} />
165
+ ))}
166
+ </div>
167
+ </div>
168
+ </div>
169
+ );
170
+ }
171
+
172
+ /**
173
+ * ⭐⭐ W54-T35 / R8 β€” WHICH ROWS THE CELL ASKED FOR, IN THE TWO SHAPES A BINDING CAN SAY IT.
174
+ *
175
+ * β›” THE `view` ARM EXISTS SO THE EDITOR CAN BE WITHHELD, AND THAT IS R8 VERBATIM: *"The Fields
176
+ * list … is hidden everywhere else, including under 'A saved view', where the view already fixes
177
+ * the rows."* A saved view's rows are the VIEW's business; editing a filter here would either
178
+ * silently fork the cell off its view or edit the view for everybody who uses it. So a view-bound
179
+ * cell gets the sentence and no Edit door.
180
+ */
181
+ export type DrillCellScope =
182
+ | { kind: "filter"; tree: FilterTree }
183
+ | { kind: "view"; name: string };
184
+
185
+ /** What the drill's own answer says about the scope, for a caller that passed none. */
186
+ function scopeFromDrill(drill: CellDrill | null): DrillCellScope | null {
187
+ if (!drill) return null;
188
+ if (drill.view_id) return { kind: "view", name: "" };
189
+ const tree = drill.filter as FilterTree | null | undefined;
190
+ return { kind: "filter", tree: tree ?? { conj: "and", nodes: [] } };
191
+ }
192
+
193
+ /**
194
+ * ⚠ TREE EQUALITY BY SERIALISATION, deliberately, and the shape is what makes it safe. A
195
+ * `FilterTree` is plain JSON with no cycles and no undefined-versus-absent subtleties that matter
196
+ * here: both sides of every comparison this file makes came out of the SAME builder, so their key
197
+ * order is the builder's own. A hand-written deep-equal over `FilterRule`'s eleven optional
198
+ * members is the thing that would quietly stop noticing a member somebody added later.
199
+ */
200
+ const sameTree = (a: FilterTree | null, b: FilterTree | null): boolean =>
201
+ JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
202
+
203
+ /**
204
+ * ⭐⭐ W54-T35 β€” THE BAND THAT STATES THE FILTER, at the foot of the rows it produced.
205
+ *
206
+ * β›” IT IS A STATEMENT FIRST AND A CONTROL SECOND. The sentence is the whole of the owner's first
207
+ * clause, so it takes the width and truncates with an ellipsis rather than being shortened into a
208
+ * count; the full text stays reachable as the element's `title`. `Edit the filter` is one quiet
209
+ * button in the card's own `cg-btn` chrome, which is what the editable footer of this same modal
210
+ * already uses, so nothing new is introduced into the surface's control vocabulary.
211
+ */
212
+ function DrillFilterBand(
213
+ { text, onEdit, editing }: { text: string; onEdit: (() => void) | null; editing: boolean },
214
+ ) {
215
+ return (
216
+ <div
217
+ // `cg-link-grid-foot` is the paint (a 52px hairline-topped band, already declared for this
218
+ // card); `sheet-drill-filter` carries no rule anywhere and is not meant to, exactly like
219
+ // `sheet-filter-popup`: it is the name a gate, a screenshot or a person in the inspector
220
+ // can point at.
221
+ className="cg-link-grid-foot sheet-drill-filter"
222
+ // ⚠ THE ONE GEOMETRY OVERRIDE, and it is a single word: the shipped footer is
223
+ // `justify-content: flex-end` because it holds two buttons at the right. This band holds a
224
+ // sentence and a button, so they take opposite ends. Declaring it here rather than in a
225
+ // stylesheet keeps the rule beside the only element that wants it.
226
+ style={{ justifyContent: "space-between" }}
227
+ >
228
+ <span
229
+ className="sheet-drill-filter-text"
230
+ style={{
231
+ minWidth: 0,
232
+ overflow: "hidden",
233
+ textOverflow: "ellipsis",
234
+ whiteSpace: "nowrap",
235
+ color: "var(--lp-muted)",
236
+ }}
237
+ title={text}
238
+ >
239
+ {text}
240
+ </span>
241
+ {onEdit && (
242
+ <button
243
+ type="button"
244
+ className="cg-btn"
245
+ aria-haspopup="dialog"
246
+ aria-expanded={editing}
247
+ onClick={onEdit}
248
+ >
249
+ Edit the filter
250
+ </button>
251
+ )}
252
+ </div>
253
+ );
254
+ }
255
+
256
  export interface DrillModalProps {
257
  workbookId: string;
258
  addr: string;
259
  /** The label the popup wears. The cell's own address is the honest one: it is what was clicked. */
260
  label: string;
261
  onClose: () => void;
262
+ /**
263
+ * W54-T34: the drill has stopped waiting - it answered, or it was refused. The page uses this to
264
+ * take the busy state back off the control that was clicked. It is NOT "the rows are on screen":
265
+ * a refusal settles too, and a control left spinning over a refusal is the worse failure.
266
+ */
267
+ onSettled?: () => void;
268
+ /**
269
+ * W54-T35: the cell's OWN rows-to-include, read off its binding by the page.
270
+ *
271
+ * ⚠ NOT THE SAME THING AS THE DRILL ANSWER'S `filter`, and the difference is worth a prop. The
272
+ * answer describes what the SERVER used for the rows on screen; this describes what the cell
273
+ * holds NOW, which is what an edit changes and what an undo restores. On a healthy save the two
274
+ * agree within one round trip. Absent, the answer is used instead, so a caller that passes
275
+ * nothing still gets a drill that states its filter.
276
+ */
277
+ cellScope?: DrillCellScope | null;
278
+ /**
279
+ * W54-T35: persist a new filter for this cell and recompute it. Absent means no Edit door.
280
+ *
281
+ * β›” IT RESOLVES WHEN THE WRITE HAS SETTLED, which is what lets the rows be re-read afterwards
282
+ * rather than immediately: `GET …/drill` reads the STORED binding, so a re-read fired before
283
+ * the save landed would answer with the filter that is being replaced and paint the old rows
284
+ * over the new filter.
285
+ */
286
+ onFilterChange?: (addr: string, tree: FilterTree) => void | Promise<void>;
287
  }
288
 
289
+ export default function DrillModal(
290
+ { workbookId, addr, label, onClose, onSettled, cellScope, onFilterChange }: DrillModalProps,
291
+ ) {
292
  const [drill, setDrill] = useState<CellDrill | null>(null);
293
  const [error, setError] = useState("");
294
+ /** Is `LinkGridModal`'s module in hand? See `warmLinkChunk` for why this is a state and not a
295
+ * detail of Suspense. */
296
+ const [linkReady, setLinkReady] = useState(false);
297
+
298
+ /** ⚠ A REF, so a page that hands this an inline arrow does not re-run the fetch effect below on
299
+ * every one of its own renders. */
300
+ const settledRef = useRef(onSettled);
301
+ settledRef.current = onSettled;
302
+ /** Same reason, one ticket later: the page hands this an inline arrow too. */
303
+ const filterChangeRef = useRef(onFilterChange);
304
+ filterChangeRef.current = onFilterChange;
305
+
306
+ // ── W54-T35 state ─────────────────────────────────────────────────────────────────────────
307
+ /** Is the centred filter dialog on screen? */
308
+ const [filterOpen, setFilterOpen] = useState(false);
309
+ /**
310
+ * β›”β›” THE DRAFT IS THIS COMPONENT'S, NOT THE DIALOG'S, AND THE DIALOG'S OWN CONTRACT IS WHY.
311
+ * `SheetFilterPopup` holds no draft on purpose: `onChange` is the caller's setter and every
312
+ * keystroke commits. The binding panel can afford that because its setter is a `useState`. Here
313
+ * the setter would be a PUT plus a recompute, so a value typed into a condition box would be one
314
+ * save per character. So the keystrokes land here, and the dialog closing is the commit.
315
+ * ⚠ THAT IS ALSO WHY CLOSING IT IS NOT A CANCEL. Escape, an outside click and Done are the same
316
+ * event with three names in that dialog, and they stay the same event here: all three APPLY.
317
+ */
318
+ const [draft, setDraft] = useState<FilterTree | null>(null);
319
+ /**
320
+ * ⭐⭐ THE UNDO, AND IT IS ONE STEP SCOPED TO THIS CELL. Owner: *"if they make a mistake etc,
321
+ * they can just CTRL + Z to return the Cell to its original filter."*
322
+ *
323
+ * β›”β›” IT IS DELIBERATELY NOT `SheetPage`'s `historyRef`. That stack snapshots the WHOLE `sheets`
324
+ * array on every commit, so pushing a filter edit onto it would make one Ctrl+Z walk back
325
+ * whatever else the reader had typed since - an undo that reaches past the surface it was
326
+ * pressed on, into cells nobody was looking at. This holds ONE tree: the cell's filter as it
327
+ * stood when the dialog was opened. A second Ctrl+Z therefore has nothing to pop and does not
328
+ * go further back, which is the done-when clause spelled as a data structure rather than as a
329
+ * guard somebody has to remember to write.
330
+ */
331
+ const [undoTree, setUndoTree] = useState<FilterTree | null>(null);
332
+ /** The tree as it stood when the Edit door was last opened. See `openFilter`. */
333
+ const preEditRef = useRef<FilterTree | null>(null);
334
+ /** Bumped when a filter change has landed, so the rows are read again. */
335
+ const [reloadSeq, setReloadSeq] = useState(0);
336
+ /** The filter kit's two vocabularies for this database. Fetched once the drill has answered. */
337
+ const [fields, setFields] = useState<Field[]>([]);
338
+ const [statusValues, setStatusValues] = useState<Record<string, string[]>>({});
339
+
340
+ useEffect(() => {
341
+ let live = true;
342
+ // ⚠ BOTH OUTCOMES SET IT. A chunk that fails to load is React's own error path once
343
+ // `<LinkGridModal>` renders, exactly as it was before this ticket; holding the skeleton up
344
+ // forever instead would turn a loud failure into a silent one that looks like a slow server.
345
+ void warmLinkChunk().then(
346
+ () => { if (live) setLinkReady(true); },
347
+ () => { if (live) setLinkReady(true); },
348
+ );
349
+ return () => { live = false; };
350
+ }, []);
351
 
352
  /**
353
  * ⭐⭐ W51-T12 - THE REFUSAL CARDS CLOSE ON ESCAPE TOO, AND THAT WAS THE HOLE.
 
370
  const escapeContainer = useCallback(() => cardRef.current as HTMLElement | null, []);
371
  useEscapeClose(showingCard, onEscape, { container: escapeContainer });
372
 
373
+ /**
374
+ * ⭐⭐ W54-T34 β€” AND THE SKELETON IS A SURFACE OF OURS TOO, SO IT CLAIMS ESCAPE ON THE SAME TERMS.
375
+ *
376
+ * It renders OUTSIDE `LinkGridModal`, like the two refusal cards above it, so without a claim of
377
+ * its own Escape would do nothing for the whole nine seconds the reader is most likely to press
378
+ * it. β›” A LOCAL `keydown` LISTENER IS THE DEFECT, NOT THE SHORTCUT: the arbiter in
379
+ * `ui/useEscapeClose.ts` exists because per-overlay listeners resolve by registration order.
380
+ *
381
+ * β›” STILL EXACTLY ONE CLAIMANT AT A TIME, WHICH IS THE PROPERTY W51-T12 BOUGHT AND THIS MUST NOT
382
+ * SPEND. The predicate is the complement of every other state this component can be in: a refusal
383
+ * card is up (`showingCard`), or the popup itself is up (`drill && scope && linkReady`), or this
384
+ * is. A second `useEscapeClose` call is the right shape for that - the hook pushes only while its
385
+ * flag is true, so two calls that are never true together are never two entries.
386
+ */
387
+ const skeletonRef = useRef<HTMLDivElement | null>(null);
388
+ const showingSkeleton = !showingCard && !(drill && scope && linkReady);
389
+ const skeletonContainer = useCallback(() => skeletonRef.current as HTMLElement | null, []);
390
+ useEscapeClose(showingSkeleton, onEscape, { container: skeletonContainer });
391
+
392
+ /**
393
+ * β›”β›” W54-T35 β€” `reloadSeq` IS A DEPENDENCY AND `setDrill(null)` IS STILL NOT CALLED. A filter
394
+ * that has just been changed has to be answered again, because the ids on screen were narrowed
395
+ * by the OLD one. But clearing the answer first would unmount `LinkGridModal`, put the skeleton
396
+ * back over a card the reader is already reading, and then remount the whole grid: a blink, in
397
+ * exactly the place W54-T34 spent a ticket removing one. The previous answer stays up and is
398
+ * REPLACED when the new one lands, so only the row list changes.
399
+ */
400
  useEffect(() => {
401
  let live = true;
402
  (async () => {
403
  const got = await drillCell(workbookId, addr);
404
  if (!live) return;
405
+ settledRef.current?.();
406
  if (!got.ok) {
407
  setError(got.message);
408
  return;
 
412
  return () => {
413
  live = false;
414
  };
415
+ }, [workbookId, addr, reloadSeq]);
416
+
417
+ /**
418
+ * ⭐⭐ W54-T35 β€” WHAT THE BAND SAYS, AND WHAT THE DIALOG EDITS.
419
+ *
420
+ * The page's own reading of the cell wins, because it is the one that MOVES: it is rebuilt from
421
+ * the workbook after every commit, so the sentence changes the moment a filter is applied. The
422
+ * drill answer is the fallback for a caller that passed none, and it is a real one rather than a
423
+ * courtesy: the server sends the scope on every drill.
424
+ */
425
+ const shown = cellScope ?? scopeFromDrill(drill);
426
+ const shownKind = shown?.kind ?? "";
427
+ const shownTree = shown?.kind === "filter" ? shown.tree : null;
428
+
429
+ /**
430
+ * ⭐ THE FIELD AND VALUE VOCABULARIES, FETCHED THE WAY `BindingEditor` FETCHES THEM, and warmed
431
+ * on the drill's answer rather than on the Edit click for the reason `warmLinkChunk` is warmed
432
+ * at mount: the two doors would otherwise run back to back for one gesture.
433
+ *
434
+ * β›” NEITHER CALL IS NEW TRAFFIC IN PRACTICE. `fetchWorkspace(scope, {allowCached: true})` is
435
+ * served from `wsCache` inside its freshness window, and `fetchTopicRows` shares `rowsCache`
436
+ * with the embedded grid that is loading the SAME topic one component away. ⚠ The cached read
437
+ * is enough here, unlike in the binding panel: nothing on this surface seats a saved view
438
+ * against the list, so a minutes-old field list cannot paint a configuration nobody saved.
439
+ */
440
+ useEffect(() => {
441
+ if (!scope || shownKind !== "filter") return;
442
+ let live = true;
443
+ (async () => {
444
+ const [ws, rowsPayload] = await Promise.all([
445
+ fetchWorkspace(scope, { allowCached: true }),
446
+ fetchTopicRows(topicForScope(scope)),
447
+ ]);
448
+ if (!live || !ws) return;
449
+ const list = (ws.fields ?? []) as Field[];
450
+ const rows: Row[] = rowsPayload?.rows ?? [];
451
+ const options: string[] = rowsPayload?.userOptions ?? ws.userOptions ?? [];
452
+ const map: Record<string, string[]> = {};
453
+ // The same rule `Toolbar.tsx` and `BindingEditor.tsx` compute, through the same pure
454
+ // function, so a server-computed select has a value list here as well.
455
+ for (const f of list) {
456
+ if (f.type === "user") {
457
+ map[f.key] = options;
458
+ continue;
459
+ }
460
+ if (f.type === "select" || f.type === "multiselect" || f.type === "status")
461
+ map[f.key] = choiceVocabulary(f, rows);
462
+ }
463
+ setFields(list);
464
+ setStatusValues(map);
465
+ })();
466
+ return () => { live = false; };
467
+ // ⚠ `shownKind` RATHER THAN `shown`. The page rebuilds that object on every one of its own
468
+ // renders, so depending on it would re-run these two fetches for reasons that have nothing to
469
+ // do with this cell; only the KIND decides whether they run at all.
470
+ }, [scope, shownKind]);
471
+
472
+ /** Persist a tree through the page's one binding writer, then read the rows again. */
473
+ const applyTree = useCallback(async (tree: FilterTree) => {
474
+ await Promise.resolve(filterChangeRef.current?.(addr, tree));
475
+ setReloadSeq((n) => n + 1);
476
+ }, [addr]);
477
+
478
+ /**
479
+ * β›” CLOSING THE DIALOG IS THE COMMIT, and an unchanged tree commits nothing. Without that test
480
+ * every open-and-look would write the cell back to itself, which is a PUT, a recompute and a
481
+ * spurious undo step for a gesture that changed nothing.
482
+ */
483
+ const closeFilter = useCallback(() => {
484
+ setFilterOpen(false);
485
+ const next = draft;
486
+ setDraft(null);
487
+ if (!next || sameTree(next, shownTree)) return;
488
+ // β›” THE UNDO STEP IS RECORDED HERE AND NOT AT THE OPEN, because a door that was opened and
489
+ // shut again changed nothing and must leave nothing to take back. Recording it on open would
490
+ // arm Ctrl+Z after a look, and the press would then write the cell back to itself: a PUT, a
491
+ // recompute and a stale mark, for a gesture that did nothing.
492
+ setUndoTree(preEditRef.current);
493
+ void applyTree(next);
494
+ }, [applyTree, draft, shownTree]);
495
+
496
+ const openFilter = useCallback(() => {
497
+ if (!shownTree) return;
498
+ // "The filter it had before the edit" is the filter it has at the moment the door opens. It
499
+ // is held in a ref rather than in state because nothing renders it: it is read once, by the
500
+ // close above, and putting it in state would re-render the drill for no visible reason.
501
+ preEditRef.current = shownTree;
502
+ setDraft(shownTree);
503
+ setFilterOpen(true);
504
+ }, [shownTree]);
505
+
506
+ /**
507
+ * ⭐⭐ WHERE THE KEYSTROKE ACTUALLY ARRIVES, WHICH IS NOT WHERE THE SHEET'S UNDO LIVES.
508
+ *
509
+ * Ctrl+Z on the Sheet belongs to `SheetGrid.tsx::onKeyDown` (through `shortcuts.ts`), a REACT
510
+ * handler on the grid's own wrapper. While this modal is open the grid canvas does not have
511
+ * focus - focus is trapped inside a body-level portal that is a SIBLING of the grid in the
512
+ * React tree, not a descendant - so that handler is not on the propagation path at all and
513
+ * cannot be reached from here. Nothing in lane D's file has to change, and nothing in it does.
514
+ *
515
+ * β›”β›” WHAT IS ON THE PATH IS `CustomerGrid.tsx`'s OWN Ctrl+Z, and it is the reason this is a
516
+ * capture-phase WINDOW listener rather than a React handler. That component installs
517
+ * `window.addEventListener("keydown", onKey, true)` for its per-database undo, and the drill
518
+ * mounts a CustomerGrid inside the linked-record popup. Capture listeners on one target run in
519
+ * registration order, and this component mounts BEFORE the lazy chunk that mounts that grid, so
520
+ * this one runs first and `stopImmediatePropagation` is what keeps a filter undo from also
521
+ * popping the data grid's stack. A React handler could not have got in front of it.
522
+ *
523
+ * β›” THE KEY IS CLAIMED FOR AS LONG AS THE DRILL IS OPEN, INCLUDING WHEN THERE IS NOTHING TO
524
+ * UNDO. That is the second half of the done-when: a second press must not go further back, and
525
+ * the only way to guarantee that is to consume it rather than to let it fall through to
526
+ * whichever stack is next in line.
527
+ *
528
+ * ⚠ AN INPUT KEEPS ITS OWN UNDO. The same guard `CustomerGrid` uses, for the same reason: a
529
+ * caret in a condition's value box is the browser's text undo, and stealing it would be worse
530
+ * than not having ours. Ctrl+Shift+Z and Ctrl+Y are not claimed; redo is not in this ticket.
531
+ */
532
+ const undoRef = useRef<() => void>(() => {});
533
+ undoRef.current = () => {
534
+ if (filterOpen || !undoTree) return;
535
+ setUndoTree(null);
536
+ void applyTree(undoTree);
537
+ };
538
+ useEffect(() => {
539
+ const onKey = (event: KeyboardEvent) => {
540
+ if (!(event.ctrlKey || event.metaKey) || event.altKey || event.shiftKey) return;
541
+ if (event.key.toLowerCase() !== "z") return;
542
+ const el = document.activeElement as HTMLElement | null;
543
+ if (el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.isContentEditable))
544
+ return;
545
+ event.preventDefault();
546
+ event.stopImmediatePropagation();
547
+ undoRef.current();
548
+ };
549
+ window.addEventListener("keydown", onKey, true);
550
+ return () => window.removeEventListener("keydown", onKey, true);
551
+ }, []);
552
+
553
+ /**
554
+ * ⭐ THE CARD THE BAND IS PORTALLED INTO. `LinkGridModal` publishes
555
+ * `data-overlay-kind="linked-record-grid"` on its own `<section>`, so this identifies it by the
556
+ * attribute it already declares rather than by a class the stylesheet owns.
557
+ *
558
+ * ⚠ ONE RETRY ON THE NEXT FRAME, AND NO MORE. Effects run after commit, so the card is normally
559
+ * in the DOM by the time this runs; the frame is there for the commit in which Suspense reveals
560
+ * the chunk. A poll would be a component watching for a sibling forever.
561
+ */
562
+ const showRows = Boolean(drill && scope && linkReady);
563
+ const [host, setHost] = useState<HTMLElement | null>(null);
564
+ useEffect(() => {
565
+ if (!showRows) {
566
+ setHost(null);
567
+ return;
568
+ }
569
+ const find = () =>
570
+ document.querySelector<HTMLElement>('[data-overlay-kind="linked-record-grid"]');
571
+ const found = find();
572
+ if (found) {
573
+ setHost(found);
574
+ return;
575
+ }
576
+ const frame = window.requestAnimationFrame(() => setHost(find()));
577
+ return () => window.cancelAnimationFrame(frame);
578
+ }, [showRows]);
579
+
580
+ /**
581
+ * The sentence. ⚠ NOT MEMOISED, and that is measured rather than lazy: `filterSentence` walks
582
+ * at most three live leaves and stops, so a memo keyed on a `shown` the page rebuilds every
583
+ * render would recompute exactly as often while costing an extra comparison.
584
+ */
585
+ const said = shown?.kind === "filter" ? filterSentence(shown.tree, fields) : "";
586
+ const bandText = !shown
587
+ ? ""
588
+ : shown.kind === "view"
589
+ ? (shown.name ? `Rows come from the saved view ${shown.name}` : "Rows come from a saved view")
590
+ // β›” THE FALLBACK IS THE COUNT, NOT A SECOND SENTENCE. `filterSentence` answers "" when the
591
+ // filter narrows nothing, which covers both an empty tree and one whose conditions are all
592
+ // still half typed; `conditionCountLabel` is the wording the dialog behind the Edit door
593
+ // already uses for that, so the two surfaces say the same thing about the same tree.
594
+ : said ? `Rows where ${said}` : conditionCountLabel(shown.tree);
595
 
596
  if (error) {
597
  // A refusal is a plain sentence naming the cause and the subject, per the design contract.
 
606
  );
607
  }
608
 
609
+ // β›”β›” W54-T34 β€” THIS WAS `return null`, AND IT IS THE OWNER'S REPORT IN ONE LINE. For as long as
610
+ // the drill is in flight the reader got a blank screen, which is what a dead control also looks
611
+ // like. The surface opens immediately and fills in.
612
+ if (!drill) return <DrillSkeleton label={label} nodeRef={skeletonRef} />;
613
 
614
  if (!scope) {
615
  // Named rather than swallowed: a database the popup cannot address is a real gap, and a blank
 
625
  }
626
 
627
  return (
628
+ // β›”β›” W54-T34 REVERSED THIS FALLBACK, DELIBERATELY. It read `fallback={null}` under the note
629
+ // "the popup either opens or it does not, and a skeleton behind a modal that is about to cover
630
+ // it would be a flash of furniture nobody asked for". That was a true statement about a tree
631
+ // with no skeleton in it: the choice then was between nothing and a brand new surface appearing
632
+ // for one frame. The same skeleton is now ALREADY on screen when the answer lands, so passing
633
+ // it here does not add a surface, it declines to REMOVE one - the chunk loads under the same
634
+ // card the reader has been looking at, and the popup replaces it in place. Handing `null` here
635
+ // now would blink the screen back to empty at the last moment, which is the defect this ticket
636
+ // exists to remove, arriving one step later.
637
+ /**
638
+ * ⭐⭐ W54-T35 β€” ONE `OverlayProvider` OVER BOTH SURFACES, AND WITHOUT IT THE EDIT DOOR CLOSES
639
+ * THE DRILL. `useOverlayLayer` defers to a higher layer only when it can SEE one:
640
+ * `if (!dismissOnOutside || (stack && !stack.isTop(id))) return;`, where `stack` is
641
+ * `useContext(OverlayStackContext)`. The Sheet route mounts no provider, so `LinkGridModal`
642
+ * ran with `stack === null` and treated a pointerdown ANYWHERE outside its own card as a
643
+ * dismissal - including one inside a filter dialog opened on top of it. Both layers register
644
+ * here instead, the dialog registers later, and the card stands down while it is up. This is
645
+ * the same trap `filter-kit/SheetFilterPopup.tsx` documents at the top of its own file, one
646
+ * layer further out, which is why the dialog is mounted through `SheetFilterDialog` (no
647
+ * provider of its own) rather than through `SheetFilterPopup` (which brings one).
648
+ *
649
+ * β›” ESCAPE IS UNAFFECTED AND STILL RESOLVES TO EXACTLY ONE SURFACE. That is the module-level
650
+ * stack in `ui/useEscapeClose`, not this one: the card claims when it mounts, the dialog
651
+ * claims when it opens and is therefore topmost, so one press closes the filter and the next
652
+ * closes the drill. The band claims nothing - it is a statement and a button inside the
653
+ * card, not an overlay - so the "exactly one claimant" property W51-T12 bought is unspent.
654
+ */
655
+ <OverlayProvider>
656
+ <Suspense fallback={<DrillSkeleton label={label} nodeRef={skeletonRef} />}>
657
+ <LinkGridModal
658
+ label={label}
659
+ table={scope}
660
+ recordIds={drill.record_ids}
661
+ editable={false}
662
+ onClose={onClose}
663
+ />
664
+ </Suspense>
665
+ {host && bandText && createPortal(
666
+ <DrillFilterBand
667
+ text={bandText}
668
+ // R8: no editor under a saved view, and none at all for a caller that gave us no
669
+ // writer. A button that cannot write is a control that lies.
670
+ onEdit={shownKind === "filter" && onFilterChange ? openFilter : null}
671
+ editing={filterOpen}
672
+ />,
673
+ host,
674
+ )}
675
+ {filterOpen && draft && (
676
+ <SheetFilterDialog
677
+ addr={addr}
678
+ fields={fields}
679
+ filters={draft}
680
+ onChange={setDraft}
681
+ statusValues={statusValues}
682
+ onClose={closeFilter}
683
+ />
684
+ )}
685
+ </OverlayProvider>
686
  );
687
  }
web/src/sheet/KeyTips.tsx CHANGED
@@ -71,6 +71,44 @@ function isTextChar(key: string): boolean {
71
  return /^[a-zA-Z0-9]$/.test(key);
72
  }
73
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  /** Every `[data-kt]` element visible AT THIS DEPTH, with its badge code. */
75
  function getTargets(container: HTMLElement | null, depth: Depth): Target[] {
76
  if (!container) return [];
@@ -198,6 +236,7 @@ export default function KeyTips({ containerRef }: KeyTipsProps) {
198
  */
199
  const activate = useCallback((el: HTMLButtonElement) => {
200
  const st = stateRef.current;
 
201
  if (st.depth === "tabs") {
202
  el.click();
203
  setKt({ depth: "home", prefix: "", focusedIdx: 0 });
@@ -241,6 +280,27 @@ export default function KeyTips({ containerRef }: KeyTipsProps) {
241
  if (e.key === "Alt") {
242
  altDownAtRef.current = Date.now();
243
  altChordRef.current = false;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  return;
245
  }
246
  if (altDownAtRef.current !== null) altChordRef.current = true; // a real chord, not a bare press
@@ -294,7 +354,7 @@ export default function KeyTips({ containerRef }: KeyTipsProps) {
294
  // no flash, since KT-17's soft signal is for an unmatched CHARACTER, not for every
295
  // non-actionable key a person might happen to touch.
296
  e.preventDefault(); e.stopPropagation();
297
- }, [activate, containerRef, flash, handleCharacter, stepBack, setKt]);
298
 
299
  const onDocKeyUp = useCallback((e: KeyboardEvent) => {
300
  if (e.key !== "Alt") return;
 
71
  return /^[a-zA-Z0-9]$/.test(key);
72
  }
73
 
74
+ /** ⭐⭐ W54-T24 (instruction 11) β€” THE MEASURED CAUSE OF "shortcuts do not work when done fast".
75
+ * Typed slowly, a person presses Alt, RELEASES it, then types H: the keyup toggles the layer on
76
+ * and every later letter lands. Typed fast, the same person is still HOLDING Alt when H arrives,
77
+ * which is how the owner writes the sequence and how Excel itself accepts it. On that path the
78
+ * old code marked the press a chord, refused to activate, and the whole sequence died: measured
79
+ * 0 of 5 held runs against 5 of 5 sequential runs, headless Chromium, 2026-09-06.
80
+ * This predicate is what keeps the fix narrow. A held Alt plus a letter only becomes a key-tip
81
+ * activation when that letter names a live FIRST-LEVEL badge (today: H for Home), so every other
82
+ * Alt chord the browser owns (Alt+D, Alt+F, Alt+Left) is never touched. */
83
+ function isFirstLevelCode(container: HTMLElement | null, ch: string): boolean {
84
+ return getTargets(container, "tabs").some((t) => t.code.startsWith(ch));
85
+ }
86
+
87
+ /** How long the pressed look stays on a control the key-tip layer fired. DESIGN's interaction
88
+ * layer: 100 to 200 ms, ease-out, transform and opacity ONLY. */
89
+ const PRESS_MS = 120;
90
+
91
+ /** ⭐ W54-T24, the second half of instruction 11. A key-tip activation calls `.click()` on a real
92
+ * button, so NO pointer event is ever dispatched and a `:active` or `pointerdown` rule on the
93
+ * ribbon can never fire for it. The key-tip path therefore needs its own brief press state, and
94
+ * this is it: a transform, which cannot move anything around it, degrading to a short opacity
95
+ * change when the reader asks for reduced motion. */
96
+ function pressFeedback(el: HTMLElement): void {
97
+ const reduced = typeof window.matchMedia === "function"
98
+ && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
99
+ const priorTransform = el.style.transform;
100
+ const priorOpacity = el.style.opacity;
101
+ const priorTransition = el.style.transition;
102
+ el.style.transition = reduced ? `opacity ${PRESS_MS}ms ease-out` : `transform ${PRESS_MS}ms ease-out`;
103
+ if (reduced) el.style.opacity = "0.72";
104
+ else el.style.transform = "scale(0.97)";
105
+ window.setTimeout(() => {
106
+ el.style.transform = priorTransform;
107
+ el.style.opacity = priorOpacity;
108
+ el.style.transition = priorTransition;
109
+ }, PRESS_MS);
110
+ }
111
+
112
  /** Every `[data-kt]` element visible AT THIS DEPTH, with its badge code. */
113
  function getTargets(container: HTMLElement | null, depth: Depth): Target[] {
114
  if (!container) return [];
 
236
  */
237
  const activate = useCallback((el: HTMLButtonElement) => {
238
  const st = stateRef.current;
239
+ pressFeedback(el); // W54-T24: the pressed look lands on the same tick as the command
240
  if (st.depth === "tabs") {
241
  el.click();
242
  setKt({ depth: "home", prefix: "", focusedIdx: 0 });
 
280
  if (e.key === "Alt") {
281
  altDownAtRef.current = Date.now();
282
  altChordRef.current = false;
283
+ // ⭐⭐ W54-T24 β€” TAKE THE BARE ALT AWAY FROM THE BROWSER, ON THE KEYDOWN. On Windows and
284
+ // Linux desktop Chrome an unconsumed Alt press-and-release moves focus into the browser's
285
+ // own menu bar, and everything typed next goes there instead of to this layer. The old code
286
+ // only prevented the default on the KEYUP, and only on the branch that toggled, so a press
287
+ // the layer rejected still armed the menu. Consuming it here costs nothing: a bare Alt has
288
+ // no other meaning on this page, and AltGr (which Windows delivers as Control plus Alt) is
289
+ // excluded so composed characters still work.
290
+ if (!e.ctrlKey && !e.metaKey && !e.shiftKey) e.preventDefault();
291
+ return;
292
+ }
293
+ // ⭐⭐ W54-T24 β€” ALT HELD PLUS A FIRST LEVEL LETTER IS THE SAME COMMAND AS ALT THEN THE
294
+ // LETTER. This is the fast typist's path and the one that used to die: see
295
+ // `isFirstLevelCode` above for the measurement and for why the match is required, which is
296
+ // what keeps every browser owned Alt chord untouched.
297
+ if ((altDownAtRef.current !== null || e.altKey) && !e.ctrlKey && !e.metaKey
298
+ && !stateRef.current.active && isTextChar(e.key)
299
+ && isFirstLevelCode(containerRef.current, e.key.toUpperCase())) {
300
+ e.preventDefault(); e.stopPropagation();
301
+ altChordRef.current = true; // the trailing Alt keyup must not toggle the layer a second time
302
+ activateFirstLevel();
303
+ handleCharacter(e.key.toUpperCase());
304
  return;
305
  }
306
  if (altDownAtRef.current !== null) altChordRef.current = true; // a real chord, not a bare press
 
354
  // no flash, since KT-17's soft signal is for an unmatched CHARACTER, not for every
355
  // non-actionable key a person might happen to touch.
356
  e.preventDefault(); e.stopPropagation();
357
+ }, [activate, activateFirstLevel, containerRef, flash, handleCharacter, stepBack, setKt]);
358
 
359
  const onDocKeyUp = useCallback((e: KeyboardEvent) => {
360
  if (e.key !== "Alt") return;
web/src/sheet/LinkDialog.tsx ADDED
@@ -0,0 +1,521 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // sheet/LinkDialog.tsx β€” A CELL WEARING AN ATTACHMENT: its link, its note, and the four surfaces
2
+ // those two need (wave 54, W54-T14, owner instruction 5, ruling R3).
3
+ //
4
+ // ⭐⭐ WHY A LINK AND A NOTE SHARE ONE FILE, AND THE NAME ON THE FILE IS ONLY HALF OF IT.
5
+ // A link and a note are the two things a cell can carry that are NEITHER VALUE NOR STYLE. Neither
6
+ // changes what the cell says, neither is read by a formula, and neither is drawn by the value
7
+ // renderer: both are painted BESIDE the text, on the same canvas, out of the same mark vocabulary
8
+ // (`paintCellMarks` below is one function drawing both, in one save/restore pair each). Splitting
9
+ // them would put one line of canvas painting in a file of its own and leave a reader hunting for
10
+ // the second half of a rule that is stated once here: the top-right corner belongs to the cell's
11
+ // STATE mark, so an attachment never paints there.
12
+ //
13
+ // ⭐ WHAT THIS FILE EXPORTS, and which side of the seam each one lives on:
14
+ // `LinkDialog` the authoring surface, opened from the Insert tab's Links group. All three
15
+ // link kinds, validated at the door.
16
+ // `paintCellMarks` the canvas half, called from `SheetGrid.tsx::paintCell` in BOTH of its
17
+ // branches. No React, no CSS, no measurement of the cell's own text.
18
+ // `NoteBubble` what a note shows on hover.
19
+ // `followLink` resolve and follow, and say so in one sentence when the target is not there.
20
+ //
21
+ // β›” THE SERVER PARSES NEITHER HALF, AND THAT IS THE CONTRACT THIS FILE IS THE OTHER SIDE OF.
22
+ // `platform/core/sheets.py::_clean_link` clamps the href and keeps BOTH halves or neither, because
23
+ // the kind is what decides which door opens the target; it never asks whether a URL is reachable
24
+ // or whether `Sheet2!B7` exists. Its own note puts that decision "in the door that opens it, which
25
+ // can say so at the moment somebody clicks". `followLink` is that door.
26
+ //
27
+ // ⚠ THIS IS NOT `web_record_comments`. That gate governs the RECORD comment surface in the Data
28
+ // module, which is a thread of authored comments hanging off a record. A cell note is one string
29
+ // on one cell, with no author, no thread and no reply. Nothing here borrows its vocabulary.
30
+ //
31
+ // ⚠ DESIGN CONTRACT (DESIGN.md 2 through 5): tokens only and type on the scale, sentence case, no
32
+ // emoji, inline SVG in this app's own glyph style, popovers originate at their trigger, refusals
33
+ // are one sentence, and no em dash or en dash in any string that reaches a screen.
34
+
35
+ import { useMemo, useState } from "react";
36
+ import type { FormEvent } from "react";
37
+ import type { Rectangle } from "@glideapps/glide-data-grid";
38
+ import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
39
+ import type { AnchorRect } from "../customer-grid/OverlaySurface";
40
+ // ⭐ THE DOCUMENT'S OWN A1 PARSER. A cell link's target is spelled exactly the way a formula
41
+ // reference is, so `Sheet2!B7` is split here by the same grammar that already reads one, rather
42
+ // than by a second regular expression that would disagree with it on the day a sheet name gains
43
+ // a space. `parseRef` returns the sheet name unquoted and the column as letters.
44
+ import { colToIndex, parseRef } from "./a1";
45
+ // ⭐ THE PALETTE RESOLVER, IMPORTED AND NEVER REWRITTEN. `cellBorders.ts` owns the one memoised
46
+ // `--lp-*` reader in this folder; a mark drawn on the canvas cannot be reached by CSS, so this is
47
+ // how a canvas colour stays a token (DESIGN.md 2).
48
+ import { tokenColour } from "./cellBorders";
49
+ import { MAX_LINK_HREF } from "./types";
50
+ import type { Cell } from "./types";
51
+ import "../styles/wave54/ribbon-insert.css";
52
+
53
+ /** The link a cell carries, with both halves present. `Cell["link"]` is the optional form. */
54
+ export type CellLink = NonNullable<Cell["link"]>;
55
+
56
+ // ═══════════════════════════════════════════════════════════════════════════════════════════════
57
+ // ⭐⭐ THE THREE KINDS, AND THE KIND IS WHAT DECIDES WHICH DOOR OPENS THE TARGET.
58
+ //
59
+ // `url` leaves the app entirely, in a new tab.
60
+ // `cell` is an A1 address inside THIS workbook: bare (`B7`) on the sheet the link sits on, or
61
+ // sheet qualified (`Summary!B7`) on any other tab of the same workbook.
62
+ // `sheet` is a tab, by name.
63
+ //
64
+ // β›” THE HREF IS ONE STRING FOR ALL THREE, because that is the shape the store already keeps
65
+ // (W54-T09 provisioned it and `verify_sheet.py` proves the round trip at 385/385). Widening it
66
+ // into a discriminated payload would be a second answer to a question the document has settled.
67
+ // ═══════════════════════════════════════════════════════════════════════════════════════════════
68
+
69
+ const KIND_LABEL: Record<CellLink["kind"], string> = {
70
+ url: "Web address",
71
+ cell: "Cell",
72
+ sheet: "Sheet",
73
+ };
74
+
75
+ /** Only a web address opens in a browser tab. Anything else is refused before `window.open`. */
76
+ const WEB_SCHEME = /^https?:\/\//i;
77
+
78
+ /** Does this look like it already carries a scheme of its own? */
79
+ const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
80
+
81
+ /**
82
+ * ⭐ THE TAB NAMES, READ OFF THE TAB BAR, AND THIS IS A REACH RATHER THAN A PROP FOR A REASON.
83
+ * `Ribbon.tsx::RibbonInsertDoor` carries a selection, the chart list and two cell doors, and it is
84
+ * a file this ticket may not widen. The workbook's own tab bar is in the document with a stable
85
+ * label, and `SheetGrid.tsx::switchTab` already reaches it exactly this way for Ctrl+PgUp, so this
86
+ * is the app's existing door rather than a new one.
87
+ *
88
+ * β›” `[aria-pressed]` IS WHAT TELLS A SHEET FROM "Add sheet". That bar's trailing button is an
89
+ * action rather than a tab and carries no pressed state, so filtering on the attribute is what
90
+ * keeps a sheet list from growing a phantom sheet at the end. An empty answer is honest: the
91
+ * dialog then asks for a typed name instead of pretending it knows the sheets.
92
+ */
93
+ const sheetNamesOnScreen = (): string[] => {
94
+ if (typeof document === "undefined") return [];
95
+ return Array.from(document.querySelectorAll<HTMLElement>('[aria-label="Sheets"] button[aria-pressed]'))
96
+ .map((button) => (button.textContent ?? "").trim())
97
+ .filter(Boolean);
98
+ };
99
+
100
+ /** Case-insensitive, because a person typing `summary` means the tab called `Summary`. */
101
+ const matchSheet = (names: readonly string[], want: string): string | null =>
102
+ names.find((name) => name.toLowerCase() === want.trim().toLowerCase()) ?? null;
103
+
104
+ // ═══════════════════════════════════════════════════════════════════════════════════════════════
105
+ // ⭐ THE AUTHORING SURFACE.
106
+ // ═══════════════════════════════════════════════════════════════════════════════════════════════
107
+
108
+ function IconLinkKind({ kind }: { kind: CellLink["kind"] }) {
109
+ return (
110
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-link-kind-icon">
111
+ {kind === "url" && (
112
+ <>
113
+ <circle cx="8" cy="8" r="5.5" />
114
+ <path d="M2.5 8h11" />
115
+ <path d="M8 2.5c1.6 1.7 2.4 3.6 2.4 5.5S9.6 12.3 8 13.5C6.4 12.3 5.6 10.4 5.6 8S6.4 4.2 8 2.5z" />
116
+ </>
117
+ )}
118
+ {kind === "cell" && (
119
+ <>
120
+ <path d="M2.5 2.5h11v11h-11z" />
121
+ <path d="M2.5 6.5h11M6.5 6.5v7" />
122
+ </>
123
+ )}
124
+ {kind === "sheet" && (
125
+ <>
126
+ <path d="M2.5 4.5h5l1.2 1.6h4.8v7.4h-11z" />
127
+ <path d="M2.5 8.5h11" />
128
+ </>
129
+ )}
130
+ </svg>
131
+ );
132
+ }
133
+
134
+ /**
135
+ * ⭐⭐ A POPOVER, NOT A MODAL, AND THE FILE NAME IS THE ONLY THING THAT SAYS OTHERWISE. DESIGN.md
136
+ * 4: "Menus and popovers originate at their trigger; modals remain centered." This surface asks
137
+ * for one short target and belongs beside the Link button that opened it, exactly as the Comment
138
+ * form does one group over; the chart dialog is centred because it is a chooser with two tabs and
139
+ * eight kinds. The overlay is mounted HERE rather than in `ribbonInsert.tsx` for the reason
140
+ * `ChartDialog` is: a tab module is a function the ribbon shell calls during its own render and
141
+ * cannot hold a hook, and a kind picker whose refusal survives a keystroke needs state.
142
+ *
143
+ * ⚠ NO LOCAL KEYDOWN LISTENER. Escape arrives through `AnchoredOverlay`, which registers with the
144
+ * one arbiter in `ui/useEscapeClose.ts`, and from nowhere else (DESIGN.md 5).
145
+ *
146
+ * ⚠ `restoreFocus={false}` IS LOAD BEARING FROM THE RIBBON. Every ribbon button cancels its own
147
+ * mouse-down so it never blurs the grid canvas, so the trigger never takes focus and the element
148
+ * this would restore is THE CANVAS. `Ribbon.tsx::closePop` already returns focus to the trigger
149
+ * and has to win.
150
+ */
151
+ export default function LinkDialog({
152
+ anchor,
153
+ held,
154
+ onClose,
155
+ onSubmit,
156
+ }: {
157
+ anchor: HTMLElement | null;
158
+ /** What the anchor cell already carries, so a second Insert > Link EDITS rather than replaces. */
159
+ held?: CellLink;
160
+ onClose: () => void;
161
+ onSubmit: (link: CellLink) => void;
162
+ }) {
163
+ const sheets = useMemo(sheetNamesOnScreen, []);
164
+ const [kind, setKind] = useState<CellLink["kind"]>(held?.kind ?? "url");
165
+ const [href, setHref] = useState(() => (held?.kind === "url" ? held.href : ""));
166
+ const [addr, setAddr] = useState(() => (held?.kind === "cell" ? held.href : ""));
167
+ const [sheet, setSheet] = useState(() => (
168
+ held?.kind === "sheet" ? held.href : (sheets[0] ?? "")
169
+ ));
170
+ const [why, setWhy] = useState("");
171
+
172
+ const pick = (next: CellLink["kind"]) => {
173
+ setKind(next);
174
+ setWhy("");
175
+ };
176
+
177
+ /**
178
+ * β›” VALIDATED AT THE DOOR, IN ONE SENTENCE (DESIGN.md 5). The server clamps the length and
179
+ * stores whatever it is given, so this is the only place a person can be told that `B0` is not
180
+ * an address before the link is saved and clicked. A web address with no scheme is COMPLETED
181
+ * rather than refused, because `example.com` is what people type and `https` is what they mean.
182
+ */
183
+ const submit = (event: FormEvent<HTMLFormElement>) => {
184
+ event.preventDefault();
185
+ if (kind === "url") {
186
+ const typed = href.trim();
187
+ if (!typed) {
188
+ setWhy("Type a web address first.");
189
+ return;
190
+ }
191
+ const full = HAS_SCHEME.test(typed) ? typed : `https://${typed}`;
192
+ if (!WEB_SCHEME.test(full)) {
193
+ setWhy("A web address has to start with http or https.");
194
+ return;
195
+ }
196
+ onSubmit({ href: full.slice(0, MAX_LINK_HREF), kind: "url" });
197
+ return;
198
+ }
199
+ if (kind === "cell") {
200
+ const typed = addr.trim();
201
+ const ref = parseRef(typed);
202
+ if (!ref) {
203
+ setWhy("That is not a cell address like B7 or Summary!B7.");
204
+ return;
205
+ }
206
+ if (ref.sheet && sheets.length && !matchSheet(sheets, ref.sheet)) {
207
+ setWhy(`This workbook has no sheet called ${ref.sheet}.`);
208
+ return;
209
+ }
210
+ onSubmit({ href: typed.slice(0, MAX_LINK_HREF), kind: "cell" });
211
+ return;
212
+ }
213
+ const typed = sheet.trim();
214
+ if (!typed) {
215
+ setWhy("Choose the sheet this cell should open.");
216
+ return;
217
+ }
218
+ if (sheets.length && !matchSheet(sheets, typed)) {
219
+ setWhy(`This workbook has no sheet called ${typed}.`);
220
+ return;
221
+ }
222
+ onSubmit({ href: typed.slice(0, MAX_LINK_HREF), kind: "sheet" });
223
+ };
224
+
225
+ return (
226
+ <AnchoredOverlay
227
+ anchor={anchor}
228
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal sheet-ribbon-insert-form sheet-link-form"
229
+ onDismiss={onClose}
230
+ role="dialog"
231
+ ariaLabel="Link"
232
+ restoreFocus={false}
233
+ >
234
+ <form className="sheet-ribbon-insert-fields" onSubmit={submit}>
235
+ <p className="sheet-ribbon-insert-title">Link this cell to</p>
236
+
237
+ {/* ⭐ THREE BUTTONS RATHER THAN A SELECT, and they share one height and one baseline with
238
+ each other (DESIGN.md 4). The choice is small, closed and worth seeing at a glance;
239
+ `aria-pressed` is what a reader with a screen reader hears as the current kind. */}
240
+ <div className="sheet-link-kinds" role="group" aria-label="Link kind">
241
+ {(["url", "cell", "sheet"] as const).map((option) => (
242
+ <button
243
+ key={option}
244
+ type="button"
245
+ className="sheet-link-kind"
246
+ aria-pressed={kind === option}
247
+ onClick={() => pick(option)}
248
+ >
249
+ <IconLinkKind kind={option} />
250
+ <span>{KIND_LABEL[option]}</span>
251
+ </button>
252
+ ))}
253
+ </div>
254
+
255
+ {kind === "url" && (
256
+ <>
257
+ <label className="sheet-ribbon-insert-caption" htmlFor="sheet-insert-link">
258
+ Web address
259
+ </label>
260
+ <input
261
+ id="sheet-insert-link"
262
+ name="href"
263
+ type="text"
264
+ className="sheet-ribbon-insert-input"
265
+ maxLength={MAX_LINK_HREF}
266
+ placeholder="https://"
267
+ value={href}
268
+ onChange={(event) => { setHref(event.target.value); setWhy(""); }}
269
+ />
270
+ </>
271
+ )}
272
+
273
+ {kind === "cell" && (
274
+ <>
275
+ <label className="sheet-ribbon-insert-caption" htmlFor="sheet-insert-link-cell">
276
+ Cell address
277
+ </label>
278
+ <input
279
+ id="sheet-insert-link-cell"
280
+ name="addr"
281
+ type="text"
282
+ className="sheet-ribbon-insert-input"
283
+ maxLength={MAX_LINK_HREF}
284
+ placeholder="B7"
285
+ value={addr}
286
+ onChange={(event) => { setAddr(event.target.value); setWhy(""); }}
287
+ />
288
+ <p className="sheet-ribbon-insert-hint">
289
+ A cell on this sheet, or Summary!B7 for a cell on another sheet of this workbook.
290
+ </p>
291
+ </>
292
+ )}
293
+
294
+ {kind === "sheet" && (
295
+ <>
296
+ <label className="sheet-ribbon-insert-caption" htmlFor="sheet-insert-link-sheet">
297
+ Sheet
298
+ </label>
299
+ {/* ⭐ THE TAB NAMES ARE OFFERED RATHER THAN TYPED wherever the tab bar is on screen.
300
+ Where it is not, the field falls back to a text box and the refusal below is the
301
+ only check left, which is the honest shape: this surface never claims to know a
302
+ list it could not read. */}
303
+ {sheets.length > 0 ? (
304
+ <select
305
+ id="sheet-insert-link-sheet"
306
+ name="sheet"
307
+ className="sheet-link-select"
308
+ value={sheet}
309
+ onChange={(event) => { setSheet(event.target.value); setWhy(""); }}
310
+ >
311
+ {sheets.map((name) => (
312
+ <option key={name} value={name}>{name}</option>
313
+ ))}
314
+ </select>
315
+ ) : (
316
+ <input
317
+ id="sheet-insert-link-sheet"
318
+ name="sheet"
319
+ type="text"
320
+ className="sheet-ribbon-insert-input"
321
+ maxLength={MAX_LINK_HREF}
322
+ placeholder="Summary"
323
+ value={sheet}
324
+ onChange={(event) => { setSheet(event.target.value); setWhy(""); }}
325
+ />
326
+ )}
327
+ </>
328
+ )}
329
+
330
+ {why && <p className="sheet-ribbon-insert-refusal" role="alert">{why}</p>}
331
+
332
+ <button type="submit" className="sheet-ribbon-item">
333
+ {held ? "Update link" : "Add link"}
334
+ </button>
335
+ </form>
336
+ </AnchoredOverlay>
337
+ );
338
+ }
339
+
340
+ // ═══════════════════════════════════════════════════════════════════════════════════════════════
341
+ // ⭐⭐ THE CANVAS HALF. ONE FUNCTION, TWO MARKS, AND IT IS CALLED FROM BOTH OF `paintCell`'S
342
+ // BRANCHES.
343
+ //
344
+ // β›” IT PAINTS BESIDE THE TEXT AND NEVER RE-RENDERS IT. The unstyled branch has already handed the
345
+ // cell to glide's own renderer and the styled branch has already laid the value out itself, so
346
+ // measuring or re-drawing here would be a third answer to "what does this cell say" and a smear
347
+ // on top of the second.
348
+ //
349
+ // β›” THE TOP-RIGHT CORNER IS TAKEN, AND THAT IS WHY THE NOTE MARK IS NOT WHERE EXCEL PUTS IT.
350
+ // `SheetGrid.tsx::MARK_STYLE` owns that corner for the cell's STATE (R19's blue and yellow
351
+ // triangles, the typed dot, the refused bar) and the validation caret sits on the right edge below
352
+ // it. Two facts stacked in one corner is neither fact read, so the attachment mark takes the
353
+ // TOP LEFT corner, which nothing else in this grid paints. The convention Excel is actually
354
+ // setting is "a corner triangle means this cell carries something the value does not show", and
355
+ // that survives the move; the exact corner does not.
356
+ //
357
+ // β›” NO CSS REACHES EITHER MARK. Both colours come from `--lp-*` tokens through `tokenColour`.
358
+ // ═══════════════════════════════════════════════════════════════════════════════════════════════
359
+
360
+ /** How far in from a cell edge a mark sits, so the grid's own hairlines survive under it. */
361
+ const MARK_INSET = 1;
362
+ /** The corner triangle's legs. Small enough to clear an ordinary value's first glyph. */
363
+ const MARK_LEG = 6;
364
+
365
+ export const paintCellMarks = (
366
+ ctx: CanvasRenderingContext2D,
367
+ rect: Rectangle,
368
+ cell: Cell | null | undefined,
369
+ ): void => {
370
+ if (!cell) return;
371
+
372
+ // ⭐ A LINK IS AN UNDERLINE, because that is the affordance a person recognises without being
373
+ // told. It spans the cell's own text inset rather than the measured run: the run cannot be
374
+ // measured here without adopting the font the branch above already chose, and an underline that
375
+ // is a little wider than its word still reads as a link while a missing one reads as nothing.
376
+ if (cell.link?.href) {
377
+ ctx.save();
378
+ ctx.fillStyle = tokenColour("--lp-blue-solid", "#5b8fd9");
379
+ const y = Math.round(rect.y + rect.height / 2 + 7);
380
+ ctx.fillRect(rect.x + 8, y, Math.max(0, rect.width - 16), 1);
381
+ ctx.restore();
382
+ }
383
+
384
+ // ⭐ A NOTE IS A CORNER INDICATOR, in the note stratum's own ink (`index.css` declares
385
+ // `--lp-yellow-deep` as "note + Pre-set tag text", which is exactly this).
386
+ if (cell.note) {
387
+ ctx.save();
388
+ ctx.fillStyle = tokenColour("--lp-yellow-deep", "#7e6428");
389
+ ctx.beginPath();
390
+ ctx.moveTo(rect.x + MARK_INSET, rect.y + MARK_INSET);
391
+ ctx.lineTo(rect.x + MARK_INSET + MARK_LEG, rect.y + MARK_INSET);
392
+ ctx.lineTo(rect.x + MARK_INSET, rect.y + MARK_INSET + MARK_LEG);
393
+ ctx.closePath();
394
+ ctx.fill();
395
+ ctx.restore();
396
+ }
397
+ };
398
+
399
+ // ═══════════════════════════════════════════════════════════════════════════════════════════════
400
+ // ⭐ WHAT A NOTE SHOWS ON HOVER.
401
+ // ═══════════════════════════════════════════════════════════════════════════════════════════════
402
+
403
+ /**
404
+ * ⭐⭐ IT ORIGINATES AT ITS CELL, IT IS NOT MODAL, AND IT DOES NOT TAKE THE KEYBOARD.
405
+ *
406
+ * β›” `initialFocus="none"` AND `restoreFocus={false}` ARE THE WHOLE OF "does not steal the
407
+ * keyboard from the grid". A hover surface that focused itself would move the caret off the canvas
408
+ * every time a pointer crossed a noted cell, and the arrow keys would stop moving the selection.
409
+ * With nothing inside focused, the kit's own restore has nothing to put back either.
410
+ *
411
+ * β›” IT IS POINTER TRANSPARENT (see the stylesheet). glide reports hover off the canvas UNDER
412
+ * this box, so a bubble that took a pointer would hide the cell it is describing from the very
413
+ * callback that opened it, and it would flicker.
414
+ *
415
+ * ⚠ Escape still reaches it, through `AnchoredOverlay` and the one arbiter, because an overlay
416
+ * that cannot be dismissed by the key every other overlay answers is the defect DESIGN.md 5 names.
417
+ */
418
+ export function NoteBubble({
419
+ anchor,
420
+ note,
421
+ onDismiss,
422
+ }: {
423
+ anchor: AnchorRect | null;
424
+ note: string;
425
+ onDismiss: () => void;
426
+ }) {
427
+ if (!note) return null;
428
+ return (
429
+ <AnchoredOverlay
430
+ anchor={anchor}
431
+ className="sheet-note-bubble"
432
+ onDismiss={onDismiss}
433
+ placement="bottom-start"
434
+ role="note"
435
+ ariaLabel="Cell note"
436
+ initialFocus="none"
437
+ restoreFocus={false}
438
+ >
439
+ <p className="sheet-note-bubble-text">{note}</p>
440
+ </AnchoredOverlay>
441
+ );
442
+ }
443
+
444
+ // ═══════════════════════════════════════════════════════════════════════════════════════════════
445
+ // ⭐⭐ THE DOOR THAT OPENS THE TARGET, AND THE ONE PLACE THAT CAN SAY IT IS NOT THERE.
446
+ // ═══════════════════════════════════════════════════════════════════════════════════════════════
447
+
448
+ /** What `followLink` needs from the grid, and nothing more. */
449
+ export interface FollowContext {
450
+ /** Every tab of this workbook, in the tab bar's own order. */
451
+ sheets: readonly { id: string; name: string }[];
452
+ /** The tab the grid is showing right now. */
453
+ tabId: string;
454
+ /** Show a tab, by id. */
455
+ goToSheet: (sheetId: string) => void;
456
+ /** Put the selection on a zero-based SHEET cell of that tab, switching tabs first if it must. */
457
+ goToCell: (sheetId: string, col: number, row: number) => void;
458
+ /** One sentence, and only ever one (DESIGN.md 5). */
459
+ onNotice: (message: string) => void;
460
+ }
461
+
462
+ /**
463
+ * Follow the link this cell carries. `false` means the cell carries none, which is what lets a
464
+ * click handler ask and fall through to its ordinary behaviour in one line.
465
+ *
466
+ * β›” EVERY REFUSAL IS ONE SENTENCE AND IS SAID AT THE MOMENT OF THE CLICK, which is where
467
+ * `platform/core/sheets.py` deliberately left it: the store keeps a target it never checked, so
468
+ * the check has to be here or it never happens at all.
469
+ */
470
+ export const followLink = (cell: Cell | null | undefined, ctx: FollowContext): boolean => {
471
+ const link = cell?.link;
472
+ if (!link?.href) return false;
473
+
474
+ if (link.kind === "url") {
475
+ if (!WEB_SCHEME.test(link.href)) {
476
+ ctx.onNotice("This link is not a web address, so it cannot be opened.");
477
+ return true;
478
+ }
479
+ // β›” `noopener,noreferrer` IS THE SECURITY HALF, not a preference: without `noopener` the page
480
+ // that opens keeps a handle on this one through `window.opener` and can navigate it.
481
+ //
482
+ // β›”β›” AND THE RETURN VALUE IS NOT AN ANSWER. `noopener` severs the handle BY DEFINITION, so
483
+ // the spec has `window.open` answer `null` on SUCCESS as well as on a blocked pop-up. Driven
484
+ // headless the day this was written: the tab really opened and the null check said the browser
485
+ // had blocked it, which is a refusal sentence in front of a person whose link worked. There is
486
+ // no way to tell the two apart while keeping the security half, so the security half wins and
487
+ // nothing is claimed about the result.
488
+ window.open(link.href, "_blank", "noopener,noreferrer");
489
+ return true;
490
+ }
491
+
492
+ if (link.kind === "sheet") {
493
+ const found = ctx.sheets.find(
494
+ (sheet) => sheet.name.toLowerCase() === link.href.trim().toLowerCase(),
495
+ );
496
+ if (!found) {
497
+ ctx.onNotice(`This workbook has no sheet called ${link.href}.`);
498
+ return true;
499
+ }
500
+ ctx.goToSheet(found.id);
501
+ return true;
502
+ }
503
+
504
+ const ref = parseRef(link.href);
505
+ if (!ref) {
506
+ ctx.onNotice(`${link.href} is not a cell address, so there is nothing to open.`);
507
+ return true;
508
+ }
509
+ // ⚠ A BARE ADDRESS MEANS THE SHEET THE LINK SITS ON, which is the tab the grid is showing: the
510
+ // link was authored there and it is stored on a cell of that tab. Only a qualified one is looked
511
+ // up by name, and only that one can fail to find a sheet.
512
+ const targetId = ref.sheet
513
+ ? (ctx.sheets.find((sheet) => sheet.name.toLowerCase() === ref.sheet.toLowerCase())?.id ?? null)
514
+ : ctx.tabId;
515
+ if (!targetId) {
516
+ ctx.onNotice(`This workbook has no sheet called ${ref.sheet}.`);
517
+ return true;
518
+ }
519
+ ctx.goToCell(targetId, colToIndex(ref.col) - 1, ref.row - 1);
520
+ return true;
521
+ };
web/src/sheet/Ribbon.tsx CHANGED
@@ -1,4 +1,12 @@
1
- // sheet/Ribbon.tsx β€” the Sheet's HOME ribbon (wave 50, W50-T19/A1; wave 51, W51-T15, ruling R8).
 
 
 
 
 
 
 
 
2
  //
3
  // ⭐⭐ WHAT THIS COMPONENT IS AND IS NOT. It is a `role="toolbar"` of STATELESS controls: every
4
  // button reports one patch or one named act and holds nothing. The selection, the cells and the
@@ -40,27 +48,26 @@
40
 
41
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
42
  import type { KeyboardEvent, MouseEvent as ReactMouseEvent, ReactNode } from "react";
43
- import { CELL_FORMAT_KINDS } from "./types";
44
- import type { CellFormatKind, CellStyle, CellStylePatch } from "./types";
45
  // ⭐ W52-T15 β€” a component-owned side-effect import, exactly like `customer-grid/Toolbar.tsx`'s
46
  // own `import "./filters.css"`. See the stylesheet's own header for why this is not an
47
  // `index.css` `@import` line.
48
  import "../styles/wave52/ribbon.css";
49
- // ⭐ W52-T16 (instruction 18, ruling R4) β€” the new Clipboard/Editing/Cells/Styles icons live in
50
- // their own file (`ribbonIcons.tsx`) rather than growing this one further; the icons already in
51
- // THIS file (IconAlign, IconVAlign, ...) stay here β€” see that file's own header for why.
52
- import {
53
- IconAutoSum, IconCellFormat, IconClear, IconConditional, IconCopy, IconCut, IconDelete,
54
- IconFillDown, IconFillRight, IconFormatPainter, IconInsert, IconPaste,
55
- } from "./ribbonIcons";
56
  // ⭐⭐ W52-T17 (instruction 20, ruling R7) β€” the KeyTips overlay is a SEPARATE keyboard-capture
57
  // layer, mounted once, that reads this file's DOM (`[data-kt]`, `[data-kt-opens]`) rather than
58
  // threading new props through 30+ `control()` call sites. See that file's own header for the
59
  // contract (C5) and the depth model (tabs -> Home controls -> one opened gallery).
60
  import KeyTips from "./KeyTips";
61
- import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
62
  // W53-T07 (instr 25): the portalled popover's own surface. A body-level node keeps no
63
  // ancestor rule, so its background, edge and shadow travel with it. See the file header.
 
 
64
  import "../styles/wave53/ribbon-pop.css";
65
 
66
  /**
@@ -80,14 +87,28 @@ export type RibbonActionKind =
80
  | "format-accounting" | "format-custom"
81
  // Styles
82
  | "conditional-formatting"
 
 
 
 
83
  // Cells
84
  | "insert-row" | "insert-column" | "delete-row" | "delete-column"
85
  | "add-rows" | "add-columns"
86
  | "row-height" | "column-width"
87
  | "hide-rows" | "hide-columns" | "unhide" | "freeze"
 
 
 
 
88
  // Editing
89
  | "autosum" | "fill-down" | "fill-right"
90
  | "clear-contents" | "clear-formats" | "clear-all"
 
 
 
 
 
 
91
  // ⭐ W52-T15 (instruction 14) β€” the workbook's own acts. Their CONTROLS moved out of the
92
  // groups row and into the tab strip (`sheet-ribbon-tabs`), in the SAME horizontal space as
93
  // the Home tab; the act NAMES stay here because `SheetGrid.tsx`'s exhaustive switch still owns
@@ -100,6 +121,35 @@ export interface RibbonAction {
100
  arg?: string | number;
101
  }
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  export interface RibbonProps {
104
  /**
105
  * The style of the cell the selection is ANCHORED on, which is what the toggles report as
@@ -115,45 +165,113 @@ export interface RibbonProps {
115
  canImport?: boolean;
116
  onApply: (patch: CellStylePatch) => void;
117
  onAction: (action: RibbonAction) => void;
 
 
118
  }
119
 
120
  // ═══════════════════════════════════════════════════════════════════════════════════════════════
121
- // THE ROVING ORDER, DERIVED FROM THE GROUPS RATHER THAN RESTATED BESIDE THEM.
122
  //
123
  // β›” A HAND MAINTAINED PARALLEL ARRAY IS HOW ROVING FOCUS DIES SILENTLY: one `data-ribbon` typo and
124
  // `focusControl`'s query returns null, with every gate still green. `ControlKey` is derived from
125
- // these arrays, so a control rendered under a name that is not in one of them is a TYPE ERROR.
126
  // ═══════════════════════════════════════════════════════════════════════════════════════════════
127
 
128
- // ⭐⭐ W52-T15 (instruction 14, contract C4) β€” IMPORT, REFRESH AND FULL SCREEN LIVE IN THE TAB
129
- // STRIP NOW, NOT IN A RIBBON GROUP. They render in `sheet-ribbon-tabs`, which is on screen
130
- // whether the groups row is collapsed or not, so they belong in `STRIP` (the set the roving
131
- // handler reaches even when collapsed) rather than in a group array that vanishes with the rest.
132
- const STRIP = ["tab-home", "import", "refresh", "fullscreen", "collapse"] as const;
133
- const CLIPBOARD = ["paste", "cut", "copy", "painter"] as const;
134
- const FONT = ["bold", "italic", "underline", "border", "fill", "color", "size"] as const;
135
- // ⭐⭐ W53-T05 (instruction 16) β€” TWO VISUAL ROWS, ONE ROVING ORDER, AND THE ORDER IS THE READING
136
- // ORDER. Excel lays Alignment out as two rows, so this array is re-sequenced to match what the eye
137
- // walks: top row (vertical align, then Wrap text), then bottom row (horizontal align, then the two
138
- // indents). β›” THE ARRAY IS THE ROVING SOURCE AND THE JSX IS NOT: a key listed here with no
139
- // `control(...)` call rendering it makes ArrowRight land on nothing, with every gate still green,
140
- // so the two are changed together or not at all.
141
- const ALIGNMENT = [
142
- "top", "middle", "bottom", "wrap", "left", "center", "right", "outdent", "indent",
143
- ] as const;
144
- const NUMBER = ["format", "currency", "percent", "comma", "decless", "decmore"] as const;
145
- const STYLES = ["conditional"] as const;
146
- const CELLS = ["insert", "delete", "cellformat"] as const;
147
- const EDITING = ["autosum", "filldown", "fillright", "clear"] as const;
148
 
149
- const ORDER = [
150
- ...STRIP, ...CLIPBOARD, ...FONT, ...ALIGNMENT, ...NUMBER, ...STYLES, ...CELLS, ...EDITING,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  ] as const;
152
 
153
- type ControlKey = (typeof ORDER)[number];
154
- type Popover =
155
- | "" | "color" | "fill" | "format" | "border" | "size" | "insert" | "delete" | "cellformat"
156
- | "clear";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
  /**
159
  * ⭐ COLLAPSE IS REMEMBERED PER PERSON, and the key is namespaced so nothing else in the app can
@@ -178,153 +296,6 @@ const writeCollapsed = (next: boolean) => {
178
  }
179
  };
180
 
181
- /**
182
- * The ink a person may choose, as TOKEN NAMES.
183
- *
184
- * β›” A HEX HERE WOULD OUTLIVE THE PALETTE. What is stored in the workbook is this string, and
185
- * `SheetGrid.tsx` resolves it against the document at paint time, so a palette change repaints
186
- * every sheet ever written. The `*-deep` tones are the text safe end of each hue (DESIGN.md 3);
187
- * the pale ones are fills and are never offered as ink.
188
- */
189
- const INKS: { token: string; label: string }[] = [
190
- { token: "--lp-ink", label: "Default" },
191
- { token: "--lp-muted", label: "Muted" },
192
- { token: "--lp-blue-deep", label: "Blue" },
193
- { token: "--lp-green-deep", label: "Green" },
194
- { token: "--lp-yellow-deep", label: "Amber" },
195
- { token: "--lp-red-deep", label: "Red" },
196
- { token: "--lp-purple-deep", label: "Purple" },
197
- ];
198
-
199
- /** The fills, which are the tint end of the same hues, so ink stays readable on every one. */
200
- const FILLS: { token: string; label: string }[] = [
201
- { token: "--lp-surface-2", label: "Grey" },
202
- { token: "--lp-blue-tint", label: "Blue" },
203
- { token: "--lp-green-tint", label: "Green" },
204
- { token: "--lp-yellow-tint", label: "Amber" },
205
- { token: "--lp-red-tint", label: "Red" },
206
- { token: "--lp-purple-tint", label: "Purple" },
207
- ];
208
-
209
- /**
210
- * β›” THE FIVE THE DOCUMENT MODEL CARRIES, AND ONLY THOSE. `CELL_FORMAT_KINDS` is mirrored in
211
- * `platform/core/sheets.py` and a sixth spelling is REFUSED by name on the way in, so R8's
212
- * Accounting and Custom code are offered as ACTS (`format-accounting`, `format-custom`) rather
213
- * than smuggled in here as a kind the server would reject.
214
- */
215
- const FORMAT_LABEL: Record<CellFormatKind, string> = {
216
- general: "General",
217
- number: "Number",
218
- currency: "Currency",
219
- percent: "Percent",
220
- date: "Date",
221
- };
222
-
223
- // ⭐ W52-T17 β€” each entry carries its own ONE-LETTER key-tip badge, painted fresh once `Alt, H, B`
224
- // opens this gallery (KT-11). Non-colliding within the gallery's own scope, which is all KT-11
225
- // requires: a two-letter code from a DIFFERENT depth (Home's own "B" for this same control, or
226
- // Styles' "L") means nothing here, because depth scopes the badge set entirely.
227
- const BORDERS: { id: string; label: string; sides: Record<string, boolean>; kt: string }[] = [
228
- { id: "all", label: "All sides", sides: { top: true, right: true, bottom: true, left: true }, kt: "A" },
229
- { id: "top", label: "Top", sides: { top: true }, kt: "T" },
230
- { id: "right", label: "Right", sides: { right: true }, kt: "R" },
231
- { id: "bottom", label: "Bottom", sides: { bottom: true }, kt: "B" },
232
- { id: "left", label: "Left", sides: { left: true }, kt: "L" },
233
- ];
234
-
235
- /** R8's four step size scale. Inter only, so a step is a SIZE and never a typeface. */
236
- const SIZE_STEPS: { id: string; label: string }[] = [
237
- { id: "small", label: "Small" },
238
- { id: "normal", label: "Normal" },
239
- { id: "large", label: "Large" },
240
- { id: "heading", label: "Heading" },
241
- ];
242
-
243
- function IconAlign({ to }: { to: "left" | "center" | "right" }) {
244
- // Four rules; the short ones move, which is what says left, centre or right without a word.
245
- const short = to === "left" ? "M2.5 8h6M2.5 12h7"
246
- : to === "center" ? "M4.5 8h7M3.5 12h9"
247
- : "M7.5 8h6M6.5 12h7";
248
- return (
249
- <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
250
- <path d="M2.5 4h11" />
251
- <path d={short} />
252
- </svg>
253
- );
254
- }
255
-
256
- /** The vertical three: a cell box, with the text rule sitting where the value would land. */
257
- function IconVAlign({ to }: { to: "top" | "middle" | "bottom" }) {
258
- const y = to === "top" ? 5 : to === "middle" ? 8 : 11;
259
- return (
260
- <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
261
- <rect x="2.6" y="2.6" width="10.8" height="10.8" rx="1" />
262
- <path d={`M5 ${y}h6`} />
263
- </svg>
264
- );
265
- }
266
-
267
- function IconWrap() {
268
- return (
269
- <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
270
- <path d="M2.5 4.5h11" />
271
- <path d="M2.5 8h8.5a2 2 0 0 1 0 4H7" />
272
- <path d="M8.6 10.4L7 12l1.6 1.6" />
273
- </svg>
274
- );
275
- }
276
-
277
- function IconIndent({ out }: { out: boolean }) {
278
- const arrow = out ? "M6.6 6.4L4.6 8l2 1.6" : "M4.6 6.4L6.6 8l-2 1.6";
279
- return (
280
- <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
281
- <path d="M2.5 3.5h11" />
282
- <path d="M8.5 6.5h5M8.5 9.5h5" />
283
- <path d="M2.5 12.5h11" />
284
- <path d={arrow} />
285
- </svg>
286
- );
287
- }
288
-
289
- function IconInk() {
290
- return (
291
- <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
292
- <path d="M4.5 11.5L8 3.2l3.5 8.3" />
293
- <path d="M5.9 9.1h4.2" />
294
- </svg>
295
- );
296
- }
297
-
298
- function IconFill() {
299
- return (
300
- <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
301
- <path d="M3.4 8.2l4.4-4.4 4.5 4.4-4.5 4.5z" />
302
- <path d="M13.4 10.4c.7 1 .7 2.2-.4 2.2s-1.1-1.2-.4-2.2z" />
303
- </svg>
304
- );
305
- }
306
-
307
- function IconBorder() {
308
- return (
309
- <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
310
- <rect x="2.6" y="2.6" width="10.8" height="10.8" rx="1" />
311
- <path d="M8 2.6v10.8M2.6 8h10.8" />
312
- </svg>
313
- );
314
- }
315
-
316
- /** Two decimal dots and the direction the count moves. Never a glyph, never a dash. */
317
- function IconDecimals({ more }: { more: boolean }) {
318
- const arrow = more ? "M9.4 6.2L11.4 8l-2 1.8" : "M11.4 6.2L9.4 8l2 1.8";
319
- return (
320
- <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
321
- <path d="M3 11.6h.01M6 11.6h.01" />
322
- <path d="M3 5.5v3.4M6 5.5v3.4" />
323
- <path d={arrow} />
324
- </svg>
325
- );
326
- }
327
-
328
  function IconRefresh() {
329
  return (
330
  <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
@@ -350,14 +321,6 @@ function IconFullScreen() {
350
  );
351
  }
352
 
353
- function IconCaret() {
354
- return (
355
- <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-caret">
356
- <path d="M5 6.5L8 9.5l3-3" />
357
- </svg>
358
- );
359
- }
360
-
361
  /** The collapse chevron. It points UP while the row is showing, because that is where it goes. */
362
  function IconChevron({ up }: { up: boolean }) {
363
  return (
@@ -368,9 +331,9 @@ function IconChevron({ up }: { up: boolean }) {
368
  }
369
 
370
  export default function Ribbon({
371
- style, disabled = false, frozen = false, canImport = false, onApply, onAction,
372
  }: RibbonProps) {
373
- const [focus, setFocus] = useState<ControlKey>("tab-home");
374
  const [open, setOpen] = useState<Popover>("");
375
  /**
376
  * ⭐⭐ W53-T07 (instruction 25) β€” THE TRIGGER ELEMENT, CAPTURED ON CLICK, because a portalled
@@ -385,14 +348,21 @@ export default function Ribbon({
385
  const [collapsed, setCollapsed] = useState<boolean>(readCollapsed);
386
  const rootRef = useRef<HTMLDivElement | null>(null);
387
 
 
 
 
 
388
  /**
389
  * The keys the arrows may reach right now. Collapsed, that is the strip and nothing else β€” and
390
  * the strip now carries Import, Refresh and Full screen too, since W52-T15 moved them there.
391
- * Import is only in the order on a page that actually has an import door, in both branches.
 
 
392
  */
393
  const reachable = useMemo<readonly ControlKey[]>(
394
- () => (collapsed ? STRIP : ORDER).filter((key) => key !== "import" || canImport),
395
- [canImport, collapsed],
 
396
  );
397
 
398
  // β›” FOCUS MUST LAND ON SOMETHING THAT EXISTS. Collapsing while the focus sits on a control that
@@ -603,97 +573,55 @@ export default function Ribbon({
603
  </button>
604
  );
605
 
606
- const swatches = (
607
- which: "color" | "fill",
608
- list: { token: string; label: string }[],
609
- ) => (
610
- <AnchoredOverlay
611
- anchor={anchorEl}
612
- className="sheet-ribbon-pop sheet-ribbon-pop-portal"
613
- onDismiss={closePop}
614
- role="menu"
615
- ariaLabel={which === "color" ? "Text colour" : "Fill colour"}
616
- initialFocus="none"
617
- >
618
- <div className="sheet-ribbon-swatches">
619
- {list.map((entry) => (
620
- <button
621
- key={entry.token}
622
- type="button"
623
- role="menuitem"
624
- className="sheet-ribbon-swatch"
625
- aria-label={entry.label}
626
- title={entry.label}
627
- onMouseDown={(e) => e.preventDefault()}
628
- onClick={() => apply({ [which]: entry.token } as CellStylePatch)}
629
- >
630
- <span className="sheet-ribbon-chip" style={{ background: `var(${entry.token})` }} />
631
- </button>
632
- ))}
633
- </div>
634
- <button
635
- type="button"
636
- role="menuitem"
637
- className="sheet-ribbon-item"
638
- onMouseDown={(e) => e.preventDefault()}
639
- onClick={() => apply({ [which]: null } as CellStylePatch)}
640
- >
641
- {which === "color" ? "Reset the text colour" : "No fill"}
642
- </button>
643
- </AnchoredOverlay>
644
- );
645
-
646
- const format = style?.format;
647
- const kind: CellFormatKind = format?.kind ?? "general";
648
- const decimals = format?.decimals ?? (kind === "currency" ? 2 : 0);
649
- /** Stepping decimals on a date or on an unformatted cell means the cell becomes a number. */
650
- const numeric: CellFormatKind =
651
- kind === "currency" || kind === "percent" ? kind : "number";
652
-
653
- const stepDecimals = (delta: number) => onApply({
654
- format: {
655
- ...format,
656
- kind: numeric,
657
- decimals: Math.min(10, Math.max(0, decimals + delta)),
658
- },
659
- });
660
-
661
  /** Same idiom as the Data module's own `fullscreenLabel` (`customer-grid/Toolbar.tsx`). */
662
  const fullscreenLabel = fullscreen ? "Exit full screen" : "Full screen";
663
 
 
 
 
 
 
664
  return (
665
  <div className="sheet-ribbon-shell" ref={rootRef} onKeyDown={onKeyDown}>
666
- {/* ⭐ THE TAB STRIP. One tab today, and it is still a tab strip: it is where the collapse
667
- chevron belongs and where a second tab would join without moving anything.
 
668
  ⭐⭐ W52-T15 (instruction 14, contract C4) β€” IMPORT, REFRESH AND FULL SCREEN SIT HERE
669
- NOW, in the SAME HORIZONTAL STRIP as the Home tab, rather than in a "Workbook" ribbon
670
  group that Excel has no equivalent of. That group is gone from this file entirely. */}
671
  <div className="sheet-ribbon-tabs">
672
  <div className="sheet-ribbon-tablist" role="tablist" aria-label="Ribbon tabs">
673
- <button
674
- type="button"
675
- role="tab"
676
- data-ribbon="tab-home"
677
- // ⭐ W52-T17 (instruction 20) β€” the FIRST-LEVEL key-tip badge (KT-4/KT-8): the only
678
- // "ribbon tab" this app has. `KeyTips.tsx` discovers it the same way it discovers
679
- // every group control, via `[data-kt]` under the ribbon root, never a hardcoded list.
680
- data-kt="H"
681
- className="sheet-ribbon-tab is-on"
682
- aria-selected="true"
683
- tabIndex={focus === "tab-home" ? 0 : -1}
684
- onFocus={() => setFocus("tab-home")}
685
- onMouseDown={(e) => e.preventDefault()}
686
- onClick={() => { if (collapsed) toggleCollapsed(); }}
687
- >
688
- Home
689
- </button>
 
 
 
690
  </div>
691
  <div className="sheet-ribbon-tabs-actions">
692
  {canImport && control("import", "Import", word("Import"), () => act("import"))}
693
  {control("refresh", "Refresh", <><IconRefresh />{word("Refresh")}</>,
694
  () => act("refresh"))}
695
- {control("fullscreen", fullscreenLabel, <IconFullScreen />, toggleFullscreen,
696
- fullscreen)}
 
 
 
 
697
  </div>
698
  <button
699
  type="button"
@@ -712,432 +640,19 @@ export default function Ribbon({
712
  </div>
713
 
714
  {!collapsed && (
715
- <div className="sheet-ribbon sheet-ribbon-home" role="toolbar" aria-label="Formatting">
 
 
 
 
716
  {/* β›” `min-width: 0` ON THE SCROLLER IS LOAD BEARING. A flex child will not scroll
717
  without it. Import, Refresh and Full screen no longer live in this row at all
718
  (W52-T15 moved them to the tab strip above), so the only thing that can walk off
719
  the right edge at a narrow window now is a group itself, which scrolling permits. */}
720
  <div className="sheet-ribbon-scroll">
721
-
722
- {/* ⭐⭐ W52-T16 (instruction 18, ruling R4) β€” THE ARRANGEMENT INSTRUCTION 18 NAMES
723
- EXPLICITLY: a large split Paste on the left (icon above, caption below) with Cut,
724
- Copy and Format painter stacked as three small icon+label rows to its right,
725
- exactly like Excel's own Clipboard group.
726
- ⚠ DOCUMENTED DEVIATION (contract C4) β€” real Excel's Paste is a SPLIT button: a
727
- direct click pastes, and a separate caret opens Paste Special and friends. This
728
- app's `RibbonActionKind` union (`SheetGrid.tsx`'s exhaustive switch, OUTSIDE this
729
- ticket's file fence) has no act for those sub-options, and adding one is lane B's
730
- surface, not this ticket's. So Paste stays a SINGLE button here β€” same tall
731
- left-slot layout Excel uses, still firing `act("paste")` directly on click, with
732
- `data-kt="V"` and no `data-kt-opens` (it does not actually open a menu in this
733
- codebase). The LAYOUT is what instruction 18 and R4 ask for; the backend act stays
734
- exactly what W51-T16 already built. */}
735
- {group("Clipboard", (
736
- <div className="sheet-ribbon-clip">
737
- <span className="sheet-ribbon-paste-large">
738
- {control("paste", "Paste", <>{<IconPaste />}{word("Paste")}</>,
739
- () => act("paste"), false, undefined, "V")}
740
- </span>
741
- {/* ⭐⭐ W53-T06 (owner instruction 17) β€” CUT, COPY AND FORMAT PAINTER ARE ICONS,
742
- WITH NO WORD BESIDE THEM. Excel's Clipboard group is one large captioned Paste
743
- and three small icon-only controls; a caption beside a 26px button is the one
744
- thing its Home ribbon never does. Paste KEEPS its caption, and that is the
745
- faithful reading rather than an inconsistency: the researched convention is
746
- that only a wide combo box or a TALL two-row-spanning button carries text, and
747
- the large Paste is exactly that.
748
- β›” THE LABEL IS NOT DELETED, ONLY THE PAINTED WORD. `control()` writes its
749
- `label` argument into BOTH `aria-label` and `title`, so a screen reader still
750
- announces "Format painter" and a hover still says it. That matters twice over:
751
- `verify_api.py`'s `_RIBBON_GROUPS` pins the literals `"Cut"`, `"Copy"` and
752
- `"Format painter"` as the proof this group still offers what R8 names, and an
753
- icon-only control with no accessible name is a regression no gate in this repo
754
- would catch. */}
755
- <div className="sheet-ribbon-clip-stack">
756
- {control("cut", "Cut", <IconCut />, () => act("cut"),
757
- false, undefined, "X")}
758
- {control("copy", "Copy", <IconCopy />, () => act("copy"),
759
- false, undefined, "C")}
760
- {control("painter", "Format painter", <IconFormatPainter />,
761
- () => act("format-painter"), false, undefined, "FP")}
762
- </div>
763
- </div>
764
- ))}
765
-
766
- {group("Font", (
767
- <>
768
- {control("bold", "Bold", <span className="sheet-ribbon-glyph is-bold">B</span>,
769
- () => apply({ bold: !style?.bold }), style?.bold === true, undefined, "1")}
770
- {control("italic", "Italic",
771
- <span className="sheet-ribbon-glyph is-italic">I</span>,
772
- () => apply({ italic: !style?.italic }), style?.italic === true, undefined, "2")}
773
- {control("underline", "Underline",
774
- <span className="sheet-ribbon-glyph is-underline">U</span>,
775
- () => apply({ underline: !style?.underline }), style?.underline === true,
776
- undefined, "3")}
777
-
778
- <span className="sheet-ribbon-slot">
779
- {control("border", "Borders", <><IconBorder /><IconCaret /></>,
780
- openPop("border"),
781
- Object.values(style?.border ?? {}).some(Boolean), open === "border",
782
- "B", "gallery")}
783
- {open === "border" && (
784
- <AnchoredOverlay
785
- anchor={anchorEl}
786
- className="sheet-ribbon-pop sheet-ribbon-pop-portal"
787
- onDismiss={closePop}
788
- role="menu"
789
- ariaLabel="Borders"
790
- initialFocus="none"
791
- >
792
- {BORDERS.map((entry) => item(
793
- entry.label, () => apply({ border: entry.sides }), false, "menuitem", entry.kt,
794
- ))}
795
- {item("No border", () => apply({ border: null }), false, "menuitem", "N")}
796
- </AnchoredOverlay>
797
- )}
798
- </span>
799
-
800
- {/* ⚠ FILL COLOUR AND TEXT COLOUR BOTH OPEN A SWATCH POPOVER IN THIS CODEBASE
801
- (`open === "fill"` / `open === "color"`), so both carry `data-kt-opens`
802
- per the general C4 rule even though the ticket's own inline example list did
803
- not annotate Fill colour with "/opens" β€” a judgment call, documented here and
804
- in the HANDOFF, resolved in favour of matching the code's real behaviour. */}
805
- <span className="sheet-ribbon-slot">
806
- {control("fill", "Fill colour",
807
- <><IconFill /><IconCaret /></>,
808
- openPop("fill"), !!style?.fill, open === "fill",
809
- "H", "gallery")}
810
- {open === "fill" && swatches("fill", FILLS)}
811
- </span>
812
- <span className="sheet-ribbon-slot">
813
- {control("color", "Text colour",
814
- <><IconInk /><IconCaret /></>,
815
- openPop("color"), !!style?.color,
816
- open === "color", "FC", "gallery")}
817
- {open === "color" && swatches("color", INKS)}
818
- </span>
819
-
820
- <span className="sheet-ribbon-slot">
821
- {control("size", "Font size", <>{word("Size")}<IconCaret /></>,
822
- openPop("size"), false, open === "size",
823
- "FS", "gallery")}
824
- {open === "size" && (
825
- <AnchoredOverlay
826
- anchor={anchorEl}
827
- className="sheet-ribbon-pop sheet-ribbon-pop-portal"
828
- onDismiss={closePop}
829
- role="menu"
830
- ariaLabel="Font size"
831
- initialFocus="none"
832
- >
833
- {SIZE_STEPS.map((step) => item(step.label, () => act("font-size", step.id)))}
834
- </AnchoredOverlay>
835
- )}
836
- </span>
837
- </>
838
- ))}
839
-
840
- {/* ⭐⭐ W53-T05 (instruction 16) β€” ALIGNMENT IS TWO ROWS, NOT ONE LINE. Excel stacks
841
- the vertical three over the horizontal three and hangs the rest to their right;
842
- one long line was this group's only real departure from it. The mechanism is the
843
- one `.sheet-ribbon-clip-stack` already established for Clipboard: a COLUMN wrapper
844
- inside `.sheet-ribbon-group-controls`, which is itself a row flex, with each row a
845
- plain row flex of the SAME `control()` buttons. No new control shape, no new
846
- button size, and the two rows total 52px, which is exactly the height Clipboard's
847
- large Paste already sets, so the ribbon does not grow by a pixel.
848
- ⚠ THE SIX ALIGNMENT BUTTONS STAY ICON ONLY, and so does Wrap text: the researched
849
- Excel convention is that only a WIDE combo box or a TALL two-row-spanning button
850
- carries a caption, and none of these is either. `control()` writes the label into
851
- both `aria-label` and `title`, so every one of them keeps its accessible name.
852
- β›” ORIENTATION AND MERGE AND CENTER, which the ticket also names, are NOT here.
853
- Both need a new `RibbonActionKind`, and `SheetGrid.tsx::onRibbonAction` closes its
854
- switch with `const _exhaustive: never = action.kind`, so a new member is a type
855
- error in a file this lane does not own; Merge additionally needs a merged-cell
856
- model that `sheet/types.ts` does not have. A control rendered anyway, wired to
857
- nothing, is the fake affordance `RibbonProps` refuses by name. Raised in the
858
- HANDOFF as a PRD amendment instead. */}
859
- {group("Alignment", (
860
- <div className="sheet-ribbon-align">
861
- <div className="sheet-ribbon-align-row">
862
- {/* ⚠ TOP/MIDDLE/BOTTOM VERTICAL ALIGN HAS NO ROW IN THE TICKET'S OWN INLINE
863
- KeyTip LIST (it names align top/middle/bottom as one of the examples with no
864
- row to copy). `AT`/`AM`/`AB` follows the same two-letter shape the spec's
865
- real Excel sequences use for the horizontal three (`AL`/`AC`/`AR`). */}
866
- {control("top", "Align top", <IconVAlign to="top" />, () => act("align-top"),
867
- false, undefined, "AT")}
868
- {control("middle", "Align middle", <IconVAlign to="middle" />,
869
- () => act("align-middle"), false, undefined, "AM")}
870
- {control("bottom", "Align bottom", <IconVAlign to="bottom" />,
871
- () => act("align-bottom"), false, undefined, "AB")}
872
- {control("wrap", "Wrap text", <IconWrap />, () => act("wrap-text"),
873
- false, undefined, "W")}
874
- </div>
875
- <div className="sheet-ribbon-align-row">
876
- {/* β›” THIS `.map` STAYS A MAP. Unrolling it into three literal `control("left",
877
- ...)` calls would delete the `to === "left" ? "AL" : ...` ternary that
878
- `verify_ui.py::_RIBBON_ALIGN_H_TERNARY` pins byte for byte β€” the horizontal
879
- three are the one trio whose key is a variable, which is why their key-tips
880
- are checked as that one expression rather than per call. */}
881
- {(["left", "center", "right"] as const).map((to) => control(
882
- to,
883
- to === "left" ? "Align left" : to === "center" ? "Align centre" : "Align right",
884
- <IconAlign to={to} />,
885
- () => apply({ align: style?.align === to ? null : to }),
886
- style?.align === to,
887
- undefined,
888
- to === "left" ? "AL" : to === "center" ? "AC" : "AR",
889
- ))}
890
- {control("outdent", "Decrease indent", <IconIndent out />,
891
- () => act("indent-decrease"), false, undefined, "5")}
892
- {control("indent", "Increase indent", <IconIndent out={false} />,
893
- () => act("indent-increase"), false, undefined, "6")}
894
- </div>
895
- </div>
896
- ))}
897
-
898
- {group("Number", (
899
- <>
900
- <span className="sheet-ribbon-slot">
901
- {control("format", "Number format",
902
- <><span className="sheet-ribbon-label">{FORMAT_LABEL[kind]}</span><IconCaret /></>,
903
- openPop("format"), kind !== "general",
904
- open === "format", "N", "gallery")}
905
- {open === "format" && (
906
- <AnchoredOverlay
907
- anchor={anchorEl}
908
- className="sheet-ribbon-pop sheet-ribbon-pop-portal"
909
- onDismiss={closePop}
910
- role="menu"
911
- ariaLabel="Number format"
912
- initialFocus="none"
913
- >
914
- {CELL_FORMAT_KINDS.map((entry) => (
915
- <button
916
- key={entry}
917
- type="button"
918
- role="menuitemradio"
919
- aria-checked={entry === kind}
920
- className={"sheet-ribbon-item" + (entry === kind ? " is-on" : "")}
921
- onMouseDown={(e) => e.preventDefault()}
922
- onClick={() => onApply(
923
- entry === "general"
924
- ? { format: null }
925
- : {
926
- format: {
927
- kind: entry,
928
- decimals: entry === "currency" ? 2 : entry === "date" ? undefined : 0,
929
- thousands: format?.thousands,
930
- },
931
- },
932
- )}
933
- >
934
- {FORMAT_LABEL[entry]}
935
- </button>
936
- ))}
937
- {/* ⚠ THE TWO R8 NAMES THE DOCUMENT MODEL DOES NOT CARRY YET. They are acts,
938
- not kinds: `clean_cell` refuses an unknown `format.kind` BY NAME, so
939
- writing `accounting` here would refuse the whole cell. */}
940
- {item("Accounting", () => act("format-accounting"))}
941
- {item("Custom code", () => act("format-custom"))}
942
- {/* ⚠ THE TWO OPTIONS A1 NAMES BY NAME: decimals, and thousands. They are
943
- shown only where they mean something; a date has neither and a percent
944
- groups by locale. */}
945
- {(kind === "number" || kind === "currency" || kind === "percent") && (
946
- <div className="sheet-ribbon-row">
947
- <span className="sheet-ribbon-row-label">Decimal places</span>
948
- <button
949
- type="button"
950
- className="sheet-ribbon-step"
951
- aria-label="Fewer decimal places"
952
- onMouseDown={(e) => e.preventDefault()}
953
- onClick={() => stepDecimals(-1)}
954
- >
955
- Fewer
956
- </button>
957
- <span className="sheet-ribbon-count">{decimals}</span>
958
- <button
959
- type="button"
960
- className="sheet-ribbon-step"
961
- aria-label="More decimal places"
962
- onMouseDown={(e) => e.preventDefault()}
963
- onClick={() => stepDecimals(1)}
964
- >
965
- More
966
- </button>
967
- </div>
968
- )}
969
- {kind === "number" && (
970
- <button
971
- type="button"
972
- role="menuitemcheckbox"
973
- aria-checked={format?.thousands === true}
974
- className={"sheet-ribbon-item" + (format?.thousands ? " is-on" : "")}
975
- onMouseDown={(e) => e.preventDefault()}
976
- onClick={() => onApply({
977
- format: { ...format, kind, thousands: !format?.thousands },
978
- })}
979
- >
980
- Thousands separator
981
- </button>
982
- )}
983
- </AnchoredOverlay>
984
- )}
985
- </span>
986
-
987
- {/* ⚠ CURRENCY HAS NO ROW IN THE TICKET'S OWN INLINE KeyTip LIST (named as one of
988
- the examples with no row to copy). `CU` is invented, non-colliding. */}
989
- {control("currency", "Currency",
990
- <span className="sheet-ribbon-glyph">$</span>,
991
- () => apply({ format: { kind: "currency", decimals: 2 } }),
992
- kind === "currency", undefined, "CU")}
993
- {control("percent", "Percent",
994
- <span className="sheet-ribbon-glyph">%</span>,
995
- () => apply({ format: { kind: "percent", decimals: 0 } }),
996
- kind === "percent", undefined, "P")}
997
- {control("comma", "Comma",
998
- <span className="sheet-ribbon-glyph">,</span>,
999
- () => apply({ format: { kind: "number", decimals: 2, thousands: true } }),
1000
- kind === "number" && format?.thousands === true, undefined, "K")}
1001
- {/* ⭐ THE TICKET'S OWN MAPPING: Increase decimal is the DIGIT `0`, decrease is `9`
1002
- (spec KT-T1 β€” Corporate Finance Institute's "Alt+H+O" for Increase Decimal is
1003
- almost certainly the digit rendered as a letter, since Decrease Decimal is
1004
- `9`). `decless` is this file's DECREASE control, `decmore` is INCREASE. */}
1005
- {control("decless", "Decrease decimals", <IconDecimals more={false} />,
1006
- () => stepDecimals(-1), false, undefined, "9")}
1007
- {control("decmore", "Increase decimals", <IconDecimals more />,
1008
- () => stepDecimals(1), false, undefined, "0")}
1009
- </>
1010
- ))}
1011
-
1012
- {/* ⭐⭐ W53-T05 (D-663) β€” STYLES, CELLS AND EDITING ARE ICON ONLY FROM HERE. Measured
1013
- at the contract viewport, the seven groups wanted about 1,680px of the 864px the
1014
- ribbon actually has, so Styles, Cells and Editing were off the right edge entirely
1015
- and the owner could not see that AutoSum, Insert, Delete and Clear already exist.
1016
- A caption beside a small same-size button is also the one thing Excel's Home ribbon
1017
- never does: only a wide combo box or a tall two-row-spanning button carries text.
1018
- β›” THE LABEL IS NOT DELETED, ONLY THE PAINTED WORD. `control()` passes its `label`
1019
- into BOTH `aria-label` and `title`, so a screen reader still announces "Conditional
1020
- formatting" and a hover still says it. `verify_api.py`'s `_RIBBON_GROUPS` pins each
1021
- of those label literals, and they are all still right there in the call. */}
1022
- {group("Styles", (
1023
- <>
1024
- {control("conditional", "Conditional formatting",
1025
- <IconConditional />,
1026
- () => act("conditional-formatting"), false, undefined, "L")}
1027
- </>
1028
- ))}
1029
-
1030
- {/* ⭐⭐ THE CELLS GROUP IS WHERE THE OLD "Rows and columns" STRIP WENT. Every act it
1031
- carried is still here and still reaches the same page callback; what is gone is a
1032
- second toolbar of its own. */}
1033
- {group("Cells", (
1034
- <>
1035
- <span className="sheet-ribbon-slot">
1036
- {control("insert", "Insert", <>{<IconInsert />}<IconCaret /></>,
1037
- openPop("insert"), false, open === "insert",
1038
- "I", "gallery")}
1039
- {open === "insert" && (
1040
- <AnchoredOverlay
1041
- anchor={anchorEl}
1042
- className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1043
- onDismiss={closePop}
1044
- role="menu"
1045
- ariaLabel="Insert"
1046
- initialFocus="none"
1047
- >
1048
- {item("Insert row above", () => act("insert-row"))}
1049
- {item("Insert column left", () => act("insert-column"))}
1050
- {item("Add rows", () => act("add-rows"))}
1051
- {item("Add columns", () => act("add-columns"))}
1052
- </AnchoredOverlay>
1053
- )}
1054
- </span>
1055
- <span className="sheet-ribbon-slot">
1056
- {control("delete", "Delete", <>{<IconDelete />}<IconCaret /></>,
1057
- openPop("delete"), false, open === "delete",
1058
- "D", "gallery")}
1059
- {open === "delete" && (
1060
- <AnchoredOverlay
1061
- anchor={anchorEl}
1062
- className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1063
- onDismiss={closePop}
1064
- role="menu"
1065
- ariaLabel="Delete"
1066
- initialFocus="none"
1067
- >
1068
- {item("Delete row", () => act("delete-row"))}
1069
- {item("Delete column", () => act("delete-column"))}
1070
- </AnchoredOverlay>
1071
- )}
1072
- </span>
1073
- <span className="sheet-ribbon-slot">
1074
- {control("cellformat", "Format",
1075
- <>{<IconCellFormat />}<IconCaret /></>,
1076
- openPop("cellformat"), false,
1077
- open === "cellformat", "O", "gallery")}
1078
- {open === "cellformat" && (
1079
- <AnchoredOverlay
1080
- anchor={anchorEl}
1081
- className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1082
- onDismiss={closePop}
1083
- role="menu"
1084
- ariaLabel="Format"
1085
- initialFocus="none"
1086
- >
1087
- {item("Row height", () => act("row-height"))}
1088
- {item("Column width", () => act("column-width"))}
1089
- {item("Hide rows", () => act("hide-rows"))}
1090
- {item("Hide columns", () => act("hide-columns"))}
1091
- {item("Unhide", () => act("unhide"))}
1092
- {/* ⭐ W51-T34 LANDED, so this OPENS a Freeze panes panel offering rows and
1093
- columns rather than toggling one column. The label had to move with the
1094
- behaviour: a control that says "Freeze first column" and opens a
1095
- two-axis panel is the kind of small lie an owner finds in the first
1096
- minute. `aria-checked` still reports whether ANYTHING is frozen, which
1097
- is the useful state for a person scanning the menu.
1098
- ⚠ THE LABEL IS BYTE-PINNED in `verify_api.py`'s `_RIBBON_GROUPS` Cells
1099
- tuple, so the two move in ONE commit or the rename reds a leg in a
1100
- ticket that never touched this file. */}
1101
- {item("Freeze panes", () => act("freeze"), frozen,
1102
- "menuitemcheckbox")}
1103
- </AnchoredOverlay>
1104
- )}
1105
- </span>
1106
- </>
1107
- ))}
1108
-
1109
- {group("Editing", (
1110
- <>
1111
- {control("autosum", "AutoSum", <IconAutoSum />,
1112
- () => act("autosum"), false, undefined, "U")}
1113
- {/* ⚠ FILL DOWN AND FILL RIGHT HAVE NO ROW IN THE TICKET'S OWN INLINE KeyTip LIST.
1114
- `FD`/`FR` are invented, non-colliding with `FP` (Format painter), `FS` (Font
1115
- size) or `FC` (Font colour). */}
1116
- {control("filldown", "Fill down", <IconFillDown />,
1117
- () => act("fill-down"), false, undefined, "FD")}
1118
- {control("fillright", "Fill right", <IconFillRight />,
1119
- () => act("fill-right"), false, undefined, "FR")}
1120
- <span className="sheet-ribbon-slot">
1121
- {control("clear", "Clear", <>{<IconClear />}<IconCaret /></>,
1122
- openPop("clear"), false, open === "clear",
1123
- "E", "gallery")}
1124
- {open === "clear" && (
1125
- <AnchoredOverlay
1126
- anchor={anchorEl}
1127
- className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1128
- onDismiss={closePop}
1129
- role="menu"
1130
- ariaLabel="Clear"
1131
- initialFocus="none"
1132
- >
1133
- {item("Clear contents", () => act("clear-contents"))}
1134
- {item("Clear formats", () => act("clear-formats"))}
1135
- {item("Clear all", () => act("clear-all"))}
1136
- </AnchoredOverlay>
1137
- )}
1138
- </span>
1139
- </>
1140
- ))}
1141
  </div>
1142
  </div>
1143
  )}
 
1
+ // sheet/Ribbon.tsx β€” the Sheet ribbon's SHELL (wave 50, W50-T19/A1; wave 51, W51-T15, ruling R8;
2
+ // split per tab by wave 54's base kit).
3
+ //
4
+ // ⭐⭐ W54 BASE KIT 2a β€” THIS FILE IS THE FRAME, AND THE TABS ARE MODULES. It carries the tab
5
+ // strip, the four action buttons, the roving-focus handler, the shared control vocabulary
6
+ // (`control`, `group`, `word`, `item`) and a REGISTRY. Every Home group lives in `ribbonHome.tsx`;
7
+ // a second tab is a second module registered in `TABS`, and neither module edits the other. The
8
+ // reason is mechanical rather than tidy: two wave-54 lanes both extend the ribbon, and two lanes
9
+ // cannot share one file.
10
  //
11
  // ⭐⭐ WHAT THIS COMPONENT IS AND IS NOT. It is a `role="toolbar"` of STATELESS controls: every
12
  // button reports one patch or one named act and holds nothing. The selection, the cells and the
 
48
 
49
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
50
  import type { KeyboardEvent, MouseEvent as ReactMouseEvent, ReactNode } from "react";
51
+ import type { Cell, CellStyle, CellStylePatch, SheetChartSpec } from "./types";
 
52
  // ⭐ W52-T15 β€” a component-owned side-effect import, exactly like `customer-grid/Toolbar.tsx`'s
53
  // own `import "./filters.css"`. See the stylesheet's own header for why this is not an
54
  // `index.css` `@import` line.
55
  import "../styles/wave52/ribbon.css";
56
+ // ⭐⭐ W54 base kit 2a β€” THE REGISTERED TABS. Each module exports its own descriptor and its own
57
+ // control keys; this file imports them and nothing else from either.
58
+ import { HOME_TAB } from "./ribbonHome";
59
+ // ⭐⭐ W54-T10 (lane B) β€” the second registered tab. Same three exports, same registry, and the
60
+ // shell learns nothing about it beyond its descriptor.
61
+ import { INSERT_TAB } from "./ribbonInsert";
 
62
  // ⭐⭐ W52-T17 (instruction 20, ruling R7) β€” the KeyTips overlay is a SEPARATE keyboard-capture
63
  // layer, mounted once, that reads this file's DOM (`[data-kt]`, `[data-kt-opens]`) rather than
64
  // threading new props through 30+ `control()` call sites. See that file's own header for the
65
  // contract (C5) and the depth model (tabs -> Home controls -> one opened gallery).
66
  import KeyTips from "./KeyTips";
 
67
  // W53-T07 (instr 25): the portalled popover's own surface. A body-level node keeps no
68
  // ancestor rule, so its background, edge and shadow travel with it. See the file header.
69
+ // ⚠ SHELL, NOT HOME: `.sheet-ribbon-pop` is the surface EVERY tab's gallery paints on, so the
70
+ // import stays here where both tabs inherit it.
71
  import "../styles/wave53/ribbon-pop.css";
72
 
73
  /**
 
87
  | "format-accounting" | "format-custom"
88
  // Styles
89
  | "conditional-formatting"
90
+ // ⭐ W54-T05 β€” the two Styles acts that build a rule FROM THE SELECTION rather than opening the
91
+ // editor. They are separate members because each reads the selection's own numbers to work out
92
+ // the range it spreads across, which no `arg` on the existing act could carry.
93
+ | "colour-scale" | "data-bars"
94
  // Cells
95
  | "insert-row" | "insert-column" | "delete-row" | "delete-column"
96
  | "add-rows" | "add-columns"
97
  | "row-height" | "column-width"
98
  | "hide-rows" | "hide-columns" | "unhide" | "freeze"
99
+ // ⭐ W54-T07 β€” the two AUTOFITS, which are the same two questions the manual sizes ask, asked
100
+ // from the content instead. They are separate members rather than an `arg` on the existing acts
101
+ // because neither opens the number dialog at all: each measures the selection and writes.
102
+ | "autofit-rows" | "autofit-columns"
103
  // Editing
104
  | "autosum" | "fill-down" | "fill-right"
105
  | "clear-contents" | "clear-formats" | "clear-all"
106
+ // ⭐ W54-T07 β€” FIND AND SELECT'S THREE, and all three reach a surface that ALREADY EXISTS:
107
+ // `find` and `replace` open the one find box `SheetGrid.tsx` has carried since W51-T17 (the
108
+ // second one with its replace row showing), and `go-to` focuses the formula bar's cell address
109
+ // input, which is this app's Name Box and already jumps to whatever is typed into it. No act
110
+ // here opens a second search surface, and none may.
111
+ | "find" | "replace" | "go-to"
112
  // ⭐ W52-T15 (instruction 14) β€” the workbook's own acts. Their CONTROLS moved out of the
113
  // groups row and into the tab strip (`sheet-ribbon-tabs`), in the SAME horizontal space as
114
  // the Home tab; the act NAMES stay here because `SheetGrid.tsx`'s exhaustive switch still owns
 
121
  arg?: string | number;
122
  }
123
 
124
+ /**
125
+ * ⭐⭐ W54-T10 (lane B) β€” THE INSERT TAB'S DOOR, AND WHY IT IS NOT A NEW `RibbonActionKind`.
126
+ *
127
+ * β›” THE ACT UNION IS CLOSED BY AN EXHAUSTIVE SWITCH IN A FILE THIS LANE DOES NOT OWN.
128
+ * `SheetGrid.tsx::onRibbonAction` ends on `const _exhaustive: never = action.kind`, so a new
129
+ * member there is a compile error until that switch grows an arm, and growing it is another
130
+ * ticket's surface. That is the mechanical reason. The DESIGN reason is the better one: a chart, a
131
+ * sparkline, a link and a note are not NAMED ACTS at all. They are DOCUMENT WRITES, and the
132
+ * document already has doors for both shapes of them, one per level. A chart is a TAB level key,
133
+ * so it takes the tab's own replace-the-list door; a sparkline, a link and a note are CELL keys,
134
+ * so they take the same one commit door a style patch takes, which is what makes an inserted
135
+ * sparkline one history step and one save exactly like a paste.
136
+ *
137
+ * ⚠ OPTIONAL, for the reason `SheetGrid.tsx::onRules` states in full: a required prop would break
138
+ * every other lane's tree at the merge. Where it is absent the Insert tab renders every control
139
+ * DISABLED rather than wired to nothing, which is the fake affordance `canImport` refuses by name.
140
+ */
141
+ export interface RibbonInsertDoor {
142
+ /** The selection as a SHEET-coordinate rectangle, or null when nothing is selected. */
143
+ selection: { col0: number; row0: number; col1: number; row1: number } | null;
144
+ /** This tab's charts, and the one door that replaces the list. */
145
+ charts: readonly SheetChartSpec[];
146
+ onCharts: (next: SheetChartSpec[]) => void;
147
+ /** One or many cells, through the SAME commit door a style patch takes. */
148
+ onCells: (edits: Record<string, Cell | null>) => void;
149
+ /** Read a cell in SHEET coordinates, so a link or a note AMENDS rather than replaces. */
150
+ cellAt: (col: number, row: number) => Cell | null;
151
+ }
152
+
153
  export interface RibbonProps {
154
  /**
155
  * The style of the cell the selection is ANCHORED on, which is what the toggles report as
 
165
  canImport?: boolean;
166
  onApply: (patch: CellStylePatch) => void;
167
  onAction: (action: RibbonAction) => void;
168
+ /** ⭐ W54-T10 β€” the Insert tab's document doors. See {@link RibbonInsertDoor}. */
169
+ insert?: RibbonInsertDoor;
170
  }
171
 
172
  // ═══════════════════════════════════════════════════════════════════════════════════════════════
173
+ // THE REGISTRY, AND THE ROVING ORDER DERIVED FROM IT RATHER THAN RESTATED BESIDE IT.
174
  //
175
  // β›” A HAND MAINTAINED PARALLEL ARRAY IS HOW ROVING FOCUS DIES SILENTLY: one `data-ribbon` typo and
176
  // `focusControl`'s query returns null, with every gate still green. `ControlKey` is derived from
177
+ // the registry below, so a control rendered under a name that is not in it is a TYPE ERROR.
178
  // ═══════════════════════════════════════════════════════════════════════════════════════════════
179
 
180
+ /**
181
+ * ⭐⭐ THE REGISTERED TABS, IN STRIP ORDER. A tab module owns its own groups, its own control keys
182
+ * and its own descriptor; this list is the whole of what the shell knows about any of them.
183
+ *
184
+ * ⭐⭐ INSERT IS REGISTERED AS OF W54-T10, AND IT WAS HELD BACK UNTIL IT HAD SOMETHING TO SHOW.
185
+ * The base kit shipped `ribbonInsert.tsx` exporting its descriptor with an EMPTY group list and
186
+ * deliberately left this array one entry long, because a registered empty tab paints a clickable
187
+ * tab that opens a blank toolbar row, and a visibly broken strip is worse than an unregistered
188
+ * module. W54-T10 gave the tab its four groups (Charts, Sparklines, Links, Comments) and added its
189
+ * descriptor here in the same change. Nothing else in this file moved to do it: `ControlKey`,
190
+ * `STRIP`, `reachable`, the tab-strip JSX and `Popover` are every one of them derived from this
191
+ * array, so a THIRD tab is the same one line.
192
+ */
193
+ const TABS = [HOME_TAB, INSERT_TAB] as const;
 
 
 
 
 
 
194
 
195
+ /**
196
+ * ⭐⭐ W52-T15 (instruction 14, contract C4) β€” IMPORT, REFRESH AND FULL SCREEN LIVE IN THE TAB
197
+ * STRIP, NOT IN A RIBBON GROUP. They render in `sheet-ribbon-tabs`, which is on screen whether the
198
+ * groups row is collapsed or not, so they belong with the collapse chevron in the set the roving
199
+ * handler reaches even when collapsed rather than in a group array that vanishes with the rest.
200
+ *
201
+ * ⚠ THE KEY IS HERE AND THE BUTTON IS IN THE JSX, because the four differ in shape: one is gated
202
+ * on `canImport`, two carry an icon beside a word, one of those two also reports a pressed state,
203
+ * and the chevron is not a plain control button at all. `ControlKey` is derived from these keys,
204
+ * so the JSX still cannot render an action under a name this list does not carry.
205
+ *
206
+ * ⭐⭐ W54-T08 (owner instruction 7) β€” FULL SCREEN IS NO LONGER THE ODD ONE OUT. It used to paint
207
+ * its mark with the label living only in `aria-label` and `title`, and this note used to read as
208
+ * though that shape were settled. The owner has overruled it: the Sheet's control says
209
+ * "Full screen" on screen, the way the Data module's always has.
210
+ */
211
+ const ACTIONS = [
212
+ { key: "import" }, { key: "refresh" }, { key: "fullscreen" }, { key: "collapse" },
213
  ] as const;
214
 
215
+ type TabId = (typeof TABS)[number]["id"];
216
+ type ControlKey =
217
+ | (typeof TABS)[number]["key"]
218
+ | (typeof ACTIONS)[number]["key"]
219
+ | (typeof TABS)[number]["keys"][number];
220
+
221
+ /**
222
+ * ⭐ WHICH POPOVER IS OPEN, NAMED BY THE CONTROL THAT OWNS IT. Every popover hangs off a control,
223
+ * so the state is a `ControlKey` or nothing, and `closePop` reads it back to return focus to that
224
+ * exact button. Derived rather than hand-listed since W54, so a newly registered tab's gallery
225
+ * needs no edit here.
226
+ */
227
+ export type Popover = "" | ControlKey;
228
+
229
+ /**
230
+ * The strip: the tab buttons and the four actions. This is exactly what stays on screen when the
231
+ * groups row is collapsed, which is why it is also the collapsed roving order.
232
+ */
233
+ const STRIP: readonly ControlKey[] = [
234
+ ...TABS.map((tab) => tab.key),
235
+ ...ACTIONS.map((action) => action.key),
236
+ ];
237
+
238
+ /**
239
+ * ⭐⭐ WHAT A TAB MODULE RENDERS AGAINST. Everything a group needs and nothing more: the shared
240
+ * control vocabulary, the state a control reads back, and the two emissions. A tab module is a
241
+ * pure function of this, which is what lets two lanes own two tabs without either one reaching
242
+ * into the shell's state or holding any of its own.
243
+ */
244
+ export interface RibbonTabContext {
245
+ style: CellStyle | null;
246
+ frozen: boolean;
247
+ open: Popover;
248
+ anchorEl: HTMLElement | null;
249
+ /** The page's own door, unfiltered: an act that must NOT close an open gallery uses this. */
250
+ onApply: (patch: CellStylePatch) => void;
251
+ apply: (patch: CellStylePatch) => void;
252
+ act: (kind: RibbonActionKind, arg?: string | number) => void;
253
+ openPop: (which: Popover) => (event: ReactMouseEvent<HTMLButtonElement>) => void;
254
+ closePop: () => void;
255
+ control: (
256
+ key: ControlKey,
257
+ label: string,
258
+ body: ReactNode,
259
+ onClick: (event: ReactMouseEvent<HTMLButtonElement>) => void,
260
+ pressed?: boolean,
261
+ expanded?: boolean,
262
+ kt?: string,
263
+ ktOpens?: "gallery",
264
+ ) => ReactNode;
265
+ group: (name: string, body: ReactNode, extra?: string) => ReactNode;
266
+ word: (text: string) => ReactNode;
267
+ item: (label: string, onClick: () => void, on?: boolean, role?: string, kt?: string) => ReactNode;
268
+ /**
269
+ * ⭐ W54-T10 β€” the Insert tab's document doors, handed through unchanged. Undefined on a page
270
+ * that has not wired them, which is what the Insert tab reads to render itself disabled rather
271
+ * than offering a control with nothing behind it. See {@link RibbonInsertDoor}.
272
+ */
273
+ insert?: RibbonInsertDoor;
274
+ }
275
 
276
  /**
277
  * ⭐ COLLAPSE IS REMEMBERED PER PERSON, and the key is namespaced so nothing else in the app can
 
296
  }
297
  };
298
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299
  function IconRefresh() {
300
  return (
301
  <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
 
321
  );
322
  }
323
 
 
 
 
 
 
 
 
 
324
  /** The collapse chevron. It points UP while the row is showing, because that is where it goes. */
325
  function IconChevron({ up }: { up: boolean }) {
326
  return (
 
331
  }
332
 
333
  export default function Ribbon({
334
+ style, disabled = false, frozen = false, canImport = false, onApply, onAction, insert,
335
  }: RibbonProps) {
336
+ const [focus, setFocus] = useState<ControlKey>(TABS[0].key);
337
  const [open, setOpen] = useState<Popover>("");
338
  /**
339
  * ⭐⭐ W53-T07 (instruction 25) β€” THE TRIGGER ELEMENT, CAPTURED ON CLICK, because a portalled
 
348
  const [collapsed, setCollapsed] = useState<boolean>(readCollapsed);
349
  const rootRef = useRef<HTMLDivElement | null>(null);
350
 
351
+ /** Which tab is showing. One registered tab today, so this never changes hands yet. */
352
+ const [active, setActive] = useState<TabId>(TABS[0].id);
353
+ const activeTab = TABS.find((tab) => tab.id === active) ?? TABS[0];
354
+
355
  /**
356
  * The keys the arrows may reach right now. Collapsed, that is the strip and nothing else β€” and
357
  * the strip now carries Import, Refresh and Full screen too, since W52-T15 moved them there.
358
+ * Expanded, it is the strip plus the controls of the tab that is actually showing, read off its
359
+ * own descriptor rather than a list kept beside it. Import is only in the order on a page that
360
+ * actually has an import door, in both branches.
361
  */
362
  const reachable = useMemo<readonly ControlKey[]>(
363
+ () => (collapsed ? STRIP : [...STRIP, ...activeTab.keys])
364
+ .filter((key) => key !== "import" || canImport),
365
+ [activeTab, canImport, collapsed],
366
  );
367
 
368
  // β›” FOCUS MUST LAND ON SOMETHING THAT EXISTS. Collapsing while the focus sits on a control that
 
573
  </button>
574
  );
575
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
576
  /** Same idiom as the Data module's own `fullscreenLabel` (`customer-grid/Toolbar.tsx`). */
577
  const fullscreenLabel = fullscreen ? "Exit full screen" : "Full screen";
578
 
579
+ const tabContext: RibbonTabContext = {
580
+ style, frozen, open, anchorEl, onApply, apply, act, openPop, closePop,
581
+ control, group, word, item, insert,
582
+ };
583
+
584
  return (
585
  <div className="sheet-ribbon-shell" ref={rootRef} onKeyDown={onKeyDown}>
586
+ {/* ⭐ THE TAB STRIP, PAINTED FROM THE REGISTRY. One registered tab today, and it is still a
587
+ tab strip: it is where the collapse chevron belongs and where a second tab joins without
588
+ moving anything, because the button below is written once for whatever is registered.
589
  ⭐⭐ W52-T15 (instruction 14, contract C4) β€” IMPORT, REFRESH AND FULL SCREEN SIT HERE
590
+ NOW, in the SAME HORIZONTAL STRIP as the tabs, rather than in a "Workbook" ribbon
591
  group that Excel has no equivalent of. That group is gone from this file entirely. */}
592
  <div className="sheet-ribbon-tabs">
593
  <div className="sheet-ribbon-tablist" role="tablist" aria-label="Ribbon tabs">
594
+ {TABS.map((tab) => (
595
+ <button
596
+ key={tab.id}
597
+ type="button"
598
+ role="tab"
599
+ data-ribbon={tab.key}
600
+ // ⭐ W52-T17 (instruction 20) β€” the FIRST-LEVEL key-tip badge (KT-4/KT-8), carried by
601
+ // the tab's own descriptor now. `KeyTips.tsx` discovers it the same way it discovers
602
+ // every group control, via `[data-kt]` under the ribbon root, never a hardcoded list.
603
+ data-kt={tab.kt}
604
+ className={"sheet-ribbon-tab" + (tab.id === active ? " is-on" : "")}
605
+ aria-selected={tab.id === active}
606
+ tabIndex={focus === tab.key ? 0 : -1}
607
+ onFocus={() => setFocus(tab.key)}
608
+ onMouseDown={(e) => e.preventDefault()}
609
+ onClick={() => { setActive(tab.id); if (collapsed) toggleCollapsed(); }}
610
+ >
611
+ {tab.label}
612
+ </button>
613
+ ))}
614
  </div>
615
  <div className="sheet-ribbon-tabs-actions">
616
  {canImport && control("import", "Import", word("Import"), () => act("import"))}
617
  {control("refresh", "Refresh", <><IconRefresh />{word("Refresh")}</>,
618
  () => act("refresh"))}
619
+ {/* ⭐⭐ W54-T08 (owner instruction 7) β€” THE WORD IS PAINTED, exactly like Refresh one
620
+ line above and exactly like the Data module's own control, which renders its
621
+ `fullscreenLabel` in a span beside the same mark. This used to be the mark alone.
622
+ The string already flipped with the state, so only the paint was missing. */}
623
+ {control("fullscreen", fullscreenLabel,
624
+ <><IconFullScreen />{word(fullscreenLabel)}</>, toggleFullscreen, fullscreen)}
625
  </div>
626
  <button
627
  type="button"
 
640
  </div>
641
 
642
  {!collapsed && (
643
+ <div
644
+ className={"sheet-ribbon " + activeTab.bodyClass}
645
+ role="toolbar"
646
+ aria-label={activeTab.toolbarLabel}
647
+ >
648
  {/* β›” `min-width: 0` ON THE SCROLLER IS LOAD BEARING. A flex child will not scroll
649
  without it. Import, Refresh and Full screen no longer live in this row at all
650
  (W52-T15 moved them to the tab strip above), so the only thing that can walk off
651
  the right edge at a narrow window now is a group itself, which scrolling permits. */}
652
  <div className="sheet-ribbon-scroll">
653
+ {/* ⭐⭐ THE ACTIVE TAB'S OWN GROUPS. `ribbonHome.tsx` holds every one of them, in R8's
654
+ order, and this is the whole of the shell's knowledge of what they are. */}
655
+ {activeTab.groups(tabContext)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
656
  </div>
657
  </div>
658
  )}
web/src/sheet/RulesDialog.tsx CHANGED
@@ -29,12 +29,14 @@
29
  import { useCallback, useId, useState } from "react";
30
  import { ConfirmDialog } from "../ui/ConfirmDialog";
31
  import {
32
- RULE_FILLS, RULE_INKS, RULE_OPS, RULE_OP_LABEL,
33
- addRule, blankRule, moveRule, removeRule, ruleArity, rulesRefusal, updateRule,
 
 
34
  } from "./rules";
35
  import { listText, parseList } from "./validation";
36
- import { MAX_SHEET_RULES, MAX_VALIDATION_LIST } from "./types";
37
- import type { SheetRule, SheetRuleOp } from "./types";
38
 
39
  export interface RulesDialogProps {
40
  open: boolean;
@@ -182,7 +184,37 @@ interface RuleCardProps {
182
 
183
  function RuleCard({ rule, index, count, onPatch, onMove, onRemove }: RuleCardProps) {
184
  const ids = useId();
 
185
  const arity = ruleArity(rule.op);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  return (
187
  <li className="sheet-rules-card">
188
  <div className="sheet-rules-row">
@@ -192,7 +224,7 @@ function RuleCard({ rule, index, count, onPatch, onMove, onRemove }: RuleCardPro
192
  <input
193
  className="sheet-rules-input"
194
  type="text"
195
- value={rule.range}
196
  aria-labelledby={`${ids}-range`}
197
  placeholder="B2:D40"
198
  onChange={(e) => onPatch(rule.id, { range: e.target.value })}
@@ -232,19 +264,38 @@ function RuleCard({ rule, index, count, onPatch, onMove, onRemove }: RuleCardPro
232
  </div>
233
 
234
  <div className="sheet-rules-row">
 
 
 
 
235
  <label className="sheet-rules-field">
236
- <span className="sheet-rules-label" id={`${ids}-op`}>Condition</span>
237
  <select
238
  className="sheet-rules-select"
239
- value={rule.op}
240
- aria-labelledby={`${ids}-op`}
241
- onChange={(e) => onPatch(rule.id, { op: e.target.value as SheetRuleOp })}
242
  >
243
- {RULE_OPS.map((op) => (
244
- <option key={op} value={op}>{RULE_OP_LABEL[op]}</option>
245
  ))}
246
  </select>
247
  </label>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
248
  {arity >= 1 ? (
249
  <label className="sheet-rules-field">
250
  <span className="sheet-rules-label" id={`${ids}-value`}>
@@ -276,8 +327,41 @@ function RuleCard({ rule, index, count, onPatch, onMove, onRemove }: RuleCardPro
276
  {/* β›” THE PALETTE IS TOKEN NAMES (`rules.ts::RULE_FILLS` / `RULE_INKS`), the ribbon's own,
277
  so a palette change repaints every rule ever written. `var(--lp-*)` in the swatch is a
278
  token reference and never a hue (DESIGN.md 3). */}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
  <div className="sheet-rules-row sheet-rules-paint">
280
- <span className="sheet-rules-label">Paint</span>
281
  <div className="sheet-rules-swatches" role="group" aria-label="Fill colour">
282
  {RULE_FILLS.map((entry) => (
283
  <button
@@ -297,6 +381,7 @@ function RuleCard({ rule, index, count, onPatch, onMove, onRemove }: RuleCardPro
297
  />
298
  ))}
299
  </div>
 
300
  <div className="sheet-rules-swatches" role="group" aria-label="Text colour">
301
  {RULE_INKS.map((entry) => (
302
  <button
@@ -319,6 +404,8 @@ function RuleCard({ rule, index, count, onPatch, onMove, onRemove }: RuleCardPro
319
  </button>
320
  ))}
321
  </div>
 
 
322
  <button
323
  type="button"
324
  className={"sheet-rules-bold" + (rule.style?.bold ? " is-on" : "")}
@@ -331,7 +418,9 @@ function RuleCard({ rule, index, count, onPatch, onMove, onRemove }: RuleCardPro
331
  >
332
  B
333
  </button>
 
334
  </div>
 
335
  </li>
336
  );
337
  }
 
29
  import { useCallback, useId, useState } from "react";
30
  import { ConfirmDialog } from "../ui/ConfirmDialog";
31
  import {
32
+ DEFAULT_BAR_FILL, DEFAULT_RULE_SCALE,
33
+ RULE_FILLS, RULE_INKS, RULE_KIND_LABEL, RULE_OPS, RULE_OP_LABEL, RULE_SCALES,
34
+ addRule, blankRule, moveRule, rampBackground, rangeText, removeRule, ruleArity, ruleKind,
35
+ rulesRefusal, updateRule,
36
  } from "./rules";
37
  import { listText, parseList } from "./validation";
38
+ import { MAX_SHEET_RULES, MAX_VALIDATION_LIST, SHEET_RULE_KINDS } from "./types";
39
+ import type { SheetRule, SheetRuleKind, SheetRuleOp } from "./types";
40
 
41
  export interface RulesDialogProps {
42
  open: boolean;
 
184
 
185
  function RuleCard({ rule, index, count, onPatch, onMove, onRemove }: RuleCardProps) {
186
  const ids = useId();
187
+ const kind = ruleKind(rule);
188
  const arity = ruleArity(rule.op);
189
+
190
+ /**
191
+ * ⭐⭐ CHANGING THE KIND CHANGES WHAT THE RULE NEEDS TO BE COMPLETE, so it carries those needs
192
+ * with it rather than leaving a half-formed rule the save would refuse with a sentence about a
193
+ * control the card is no longer showing. A scale and a bar both ride `op: "between"`, which is
194
+ * what makes the server persist their two bounds with no new field; a scale gains the default
195
+ * ramp and a bar gains a fill.
196
+ *
197
+ * ⚠ `kind: undefined` IS HOW `cell` IS WRITTEN. It is the default and is stored as an absence
198
+ * (`types.ts::SHEET_RULE_KINDS`), so a rule switched to a scale and back is byte for byte the
199
+ * rule it started as. `JSON.stringify` drops an undefined value, which is what makes that true
200
+ * all the way to the document rather than only in this component.
201
+ */
202
+ const setKind = (next: SheetRuleKind) => {
203
+ if (next === kind) return;
204
+ if (next === "cell") {
205
+ onPatch(rule.id, { kind: undefined });
206
+ return;
207
+ }
208
+ onPatch(rule.id, {
209
+ kind: next,
210
+ op: "between",
211
+ scale: next === "scale"
212
+ ? (rule.scale ?? { low: DEFAULT_RULE_SCALE.low, high: DEFAULT_RULE_SCALE.high })
213
+ : rule.scale,
214
+ style: next === "bar" ? { fill: rule.style?.fill || DEFAULT_BAR_FILL } : rule.style,
215
+ });
216
+ };
217
+
218
  return (
219
  <li className="sheet-rules-card">
220
  <div className="sheet-rules-row">
 
224
  <input
225
  className="sheet-rules-input"
226
  type="text"
227
+ value={rangeText(rule.range)}
228
  aria-labelledby={`${ids}-range`}
229
  placeholder="B2:D40"
230
  onChange={(e) => onPatch(rule.id, { range: e.target.value })}
 
264
  </div>
265
 
266
  <div className="sheet-rules-row">
267
+ {/* ⭐⭐ W54-T05 β€” THE KIND IS ON THE CARD, NOT HIDDEN BEHIND THE MENU THAT MADE IT. A
268
+ colour scale and a data bar are created from the ribbon's Conditional formatting
269
+ gallery, and an editor that could not represent them would have listed a rule it
270
+ could not describe, or worse, quietly rewritten it into a condition nobody chose. */}
271
  <label className="sheet-rules-field">
272
+ <span className="sheet-rules-label" id={`${ids}-kind`}>Rule</span>
273
  <select
274
  className="sheet-rules-select"
275
+ value={kind}
276
+ aria-labelledby={`${ids}-kind`}
277
+ onChange={(e) => setKind(e.target.value as SheetRuleKind)}
278
  >
279
+ {SHEET_RULE_KINDS.map((entry) => (
280
+ <option key={entry} value={entry}>{RULE_KIND_LABEL[entry]}</option>
281
  ))}
282
  </select>
283
  </label>
284
+ {kind === "cell" ? (
285
+ <label className="sheet-rules-field">
286
+ <span className="sheet-rules-label" id={`${ids}-op`}>Condition</span>
287
+ <select
288
+ className="sheet-rules-select"
289
+ value={rule.op}
290
+ aria-labelledby={`${ids}-op`}
291
+ onChange={(e) => onPatch(rule.id, { op: e.target.value as SheetRuleOp })}
292
+ >
293
+ {RULE_OPS.map((op) => (
294
+ <option key={op} value={op}>{RULE_OP_LABEL[op]}</option>
295
+ ))}
296
+ </select>
297
+ </label>
298
+ ) : null}
299
  {arity >= 1 ? (
300
  <label className="sheet-rules-field">
301
  <span className="sheet-rules-label" id={`${ids}-value`}>
 
327
  {/* β›” THE PALETTE IS TOKEN NAMES (`rules.ts::RULE_FILLS` / `RULE_INKS`), the ribbon's own,
328
  so a palette change repaints every rule ever written. `var(--lp-*)` in the swatch is a
329
  token reference and never a hue (DESIGN.md 3). */}
330
+ {/* ⭐ A SCALE CHOOSES A RAMP, NOT A COLOUR. Its two ends are what the document stores
331
+ (`scale: {low, high}`) and the bands between them are looked up from those two names, so
332
+ a person picks the ramp whole rather than assembling one end at a time and being left
333
+ with a scale that runs from red to red. */}
334
+ {kind === "scale" ? (
335
+ <div className="sheet-rules-row sheet-rules-paint">
336
+ <span className="sheet-rules-label">Scale</span>
337
+ <div className="sheet-rules-swatches" role="group" aria-label="Colour scale">
338
+ {RULE_SCALES.map((ramp) => {
339
+ const on = rule.scale?.low === ramp.low && rule.scale?.high === ramp.high;
340
+ return (
341
+ <button
342
+ key={ramp.id}
343
+ type="button"
344
+ className={"sheet-rules-swatch" + (on ? " is-on" : "")}
345
+ style={{ background: rampBackground(ramp.bands) }}
346
+ aria-label={ramp.label}
347
+ aria-pressed={on}
348
+ title={ramp.label}
349
+ onClick={() => onPatch(rule.id, { scale: { low: ramp.low, high: ramp.high } })}
350
+ />
351
+ );
352
+ })}
353
+ </div>
354
+ </div>
355
+ ) : null}
356
+
357
+ {/* ⚠ A SCALE PAINTS FROM ITS RAMP AND FROM NOTHING ELSE, so it is offered no flat fill,
358
+ no ink and no weight: a control that wrote a key `ruleStyleAt` never reads for that kind
359
+ is the fake affordance the ribbon's own contract refuses by name. A BAR keeps the fills,
360
+ because a bar's colour IS its rule's fill, and loses the ink and the weight for the same
361
+ reason. */}
362
+ {kind === "scale" ? null : (
363
  <div className="sheet-rules-row sheet-rules-paint">
364
+ <span className="sheet-rules-label">{kind === "bar" ? "Bar" : "Paint"}</span>
365
  <div className="sheet-rules-swatches" role="group" aria-label="Fill colour">
366
  {RULE_FILLS.map((entry) => (
367
  <button
 
381
  />
382
  ))}
383
  </div>
384
+ {kind === "cell" ? (
385
  <div className="sheet-rules-swatches" role="group" aria-label="Text colour">
386
  {RULE_INKS.map((entry) => (
387
  <button
 
404
  </button>
405
  ))}
406
  </div>
407
+ ) : null}
408
+ {kind === "cell" ? (
409
  <button
410
  type="button"
411
  className={"sheet-rules-bold" + (rule.style?.bold ? " is-on" : "")}
 
418
  >
419
  B
420
  </button>
421
+ ) : null}
422
  </div>
423
+ )}
424
  </li>
425
  );
426
  }
web/src/sheet/SheetChart.tsx CHANGED
@@ -1,4 +1,5 @@
1
- // sheet/SheetChart.tsx β€” a chart that OCCUPIES a rectangle of cells (wave 49, W49-T08, R9/R15).
 
2
  //
3
  // ⭐⭐ R9: A CHART IS A CAPABILITY, NOT A VIEW TYPE. It occupies a rectangle of cells and reads
4
  // those cells; it has no binding, no database and no query of its own. If this file ever calls
@@ -21,23 +22,71 @@
21
  // sized container and letting the viewBox scale, which is what an SVG viewBox is for. Adding size
22
  // props would have meant editing a file outside the fence, which is a ROOT question and not a
23
  // lane's to answer.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
- import { useMemo } from "react";
26
  import { SeriesChart } from "../viz/SeriesChart";
27
  import type { ChartSpec } from "../viz/chartData";
28
  import type { WireField } from "../viz/seriesData";
29
  import type { Row } from "../viz/types";
30
- import type { CellMap } from "./types";
 
31
  import { addressOf } from "./sheetState";
32
 
33
  export interface SheetChartProps {
34
  /** Zero-based inclusive rectangle: the cells this chart occupies AND reads (R9, R15). */
35
  range: { col0: number; row0: number; col1: number; row1: number };
36
  cells: CellMap;
37
- kind?: ChartSpec["kind"];
38
  /** Rendered size in px. The SVG scales to it; the renderer is not resized. */
39
  width: number;
40
  height: number;
 
 
 
 
 
 
 
 
 
 
41
  }
42
 
43
  /** A cell's text, however it is stored. A chart reads what the sheet SHOWS. */
@@ -61,7 +110,547 @@ const columnType = (values: string[]): string => {
61
  return filled.every((v) => Number.isFinite(Number(v))) ? "int" : "text";
62
  };
63
 
64
- export default function SheetChart({ range, cells, kind = "bar", width, height }: SheetChartProps) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  const { fields, rows, series } = useMemo(() => {
66
  const { col0, row0, col1, row1 } = range;
67
  const loCol = Math.min(col0, col1);
@@ -107,24 +696,189 @@ export default function SheetChart({ range, cells, kind = "bar", width, height }
107
  };
108
  }, [range, cells]);
109
 
 
 
 
 
 
110
  const spec: ChartSpec = useMemo(
111
  () => ({
112
  id: "sheet-chart",
113
- kind,
114
  x: fields[0]?.key,
115
  y: series[0]?.y,
116
  agg: "sum",
117
  }),
118
- [kind, fields, series],
119
  );
120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  if (!series.length) {
122
  // Named rather than drawn empty: a chart frame with no series reads as "the data is zero",
123
  // which is a different and wrong statement.
124
  return (
125
- <div className="sheet-chart is-empty" style={{ width, height }} role="img"
126
  aria-label="This range has no numeric column to chart">
127
  <p>This range has no numeric column to chart.</p>
 
128
  </div>
129
  );
130
  }
@@ -132,9 +886,17 @@ export default function SheetChart({ range, cells, kind = "bar", width, height }
132
  return (
133
  // ⭐ THE WRAPPER IS THE SIZING MECHANISM. `SeriesChart` draws into a fixed 720x230 viewBox, so
134
  // scaling it to an arbitrary cell rectangle is the wrapper's job and the renderer stays
135
- // untouched. `viz/**` belongs to no lane in this wave.
136
- <div className="sheet-chart" style={{ width, height }}>
137
- <SeriesChart spec={spec} series={series} fields={fields} rows={rows} />
 
 
 
 
 
 
 
 
138
  </div>
139
  );
140
  }
 
1
+ // sheet/SheetChart.tsx β€” a chart that OCCUPIES a rectangle of cells (wave 49, W49-T08, R9/R15;
2
+ // widened to the eight kinds and given its move/resize gesture by wave 54, W54-T12, ruling R5).
3
  //
4
  // ⭐⭐ R9: A CHART IS A CAPABILITY, NOT A VIEW TYPE. It occupies a rectangle of cells and reads
5
  // those cells; it has no binding, no database and no query of its own. If this file ever calls
 
22
  // sized container and letting the viewBox scale, which is what an SVG viewBox is for. Adding size
23
  // props would have meant editing a file outside the fence, which is a ROOT question and not a
24
  // lane's to answer.
25
+ //
26
+ // ══════════════════════════════════════════════════════════════════════════════════════════════
27
+ // ⭐⭐ W54-T12 β€” WHAT `viz/SeriesChart` ACTUALLY DRAWS, MEASURED RATHER THAN ASSUMED, BECAUSE THE
28
+ // WHOLE KIND MAPPING TURNS ON IT.
29
+ //
30
+ // β›”β›” `viz/SeriesChart` IS A BARS-ONLY RENDERER. Its only mark is `<rect className="pg-bar">`
31
+ // growing UP from a baseline; it never reads `spec.kind` at all, so it draws GROUPED VERTICAL
32
+ // BARS for every one of the six names its own union carries. There is no polyline, no filled
33
+ // region and no arc anywhere in that file. (The Dashboard reaches for `viz/vega` when it wants
34
+ // those pictures; `SeriesChart` is the Y1 chart block's bar renderer and nothing else.)
35
+ //
36
+ // β›” SO DELEGATION IS NOT "THE APP'S EXISTING ANSWER" FOR SIX OF THOSE NAMES, IT IS A WRONG
37
+ // PICTURE. Handing `line` to it paints a bar chart under the word Line, which is the same defect
38
+ // as the `kind={isDrawnChartKind(chart.kind) ? chart.kind : "bar"}` narrowing this ticket removed
39
+ // from `SheetGrid.tsx`: a kind that is named on screen and not honoured in the drawing.
40
+ //
41
+ // β›” AND THE EXCEL NAMES DO NOT LINE UP WITH THE VIZ NAMES. Excel's naming is this ticket's
42
+ // contract: a COLUMN chart has vertical bars, a BAR chart has horizontal ones. Vertical bars is
43
+ // exactly the ONE picture `SeriesChart` draws correctly, and its name for it is `"bar"`. So:
44
+ //
45
+ // sheet `column` -> DELEGATED to `SeriesChart` as its `"bar"`: vertical bars, Excel's column
46
+ // chart, and the only kind the shared renderer genuinely draws.
47
+ // the other SEVEN (`bar` horizontal, `line`, `area`, `pie`, `donut`, `scatter`, `combo`)
48
+ // -> DRAWN HERE by {@link DrawnChart}, on the same 720x230 viewBox, from the
49
+ // same `fields` / `rows` / `series`, wearing the same `pg-*` palette.
50
+ //
51
+ // β›” `types.ts::isDrawnChartKind` IS STILL THE SWITCH, applied to the VIZ NAME rather than to the
52
+ // sheet's own. That is what makes the predicate honest again: before this ticket its branch could
53
+ // only ever go one way, and the narrowing at `SheetGrid.tsx`'s call site silently turned a pie
54
+ // into a bar chart. One kind is delegated, so both branches are live.
55
+ //
56
+ // β›” THE OWN-DRAWN MARKS BORROW `viz`'s PALETTE CLASSES (`pg-ser-0..3`, `pg-ax`, `pg-ax-lab`,
57
+ // `pg-legend*`), never a second set of colours. A palette declared twice is two answers to one
58
+ // question, and DESIGN.md 3 puts strokes on the DEEP companion while fills take the pastel, which
59
+ // is why the line and dot marks carry their own stroke rules in `styles/wave54/ribbon-insert.css`
60
+ // rather than reusing a fill class for a stroke.
61
+ // ══════════════════════════════════════════════════════════════════════════════════════════════
62
 
63
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
64
  import { SeriesChart } from "../viz/SeriesChart";
65
  import type { ChartSpec } from "../viz/chartData";
66
  import type { WireField } from "../viz/seriesData";
67
  import type { Row } from "../viz/types";
68
+ import type { CellMap, SheetChartDrawnKind, SheetChartSpec } from "./types";
69
+ import { isDrawnChartKind } from "./types";
70
  import { addressOf } from "./sheetState";
71
 
72
  export interface SheetChartProps {
73
  /** Zero-based inclusive rectangle: the cells this chart occupies AND reads (R9, R15). */
74
  range: { col0: number; row0: number; col1: number; row1: number };
75
  cells: CellMap;
76
+ kind?: SheetChartSpec["kind"];
77
  /** Rendered size in px. The SVG scales to it; the renderer is not resized. */
78
  width: number;
79
  height: number;
80
+ /**
81
+ * The gesture's PIXEL delta, handed up on release. A chart anchors to a cell RANGE, so this
82
+ * component cannot decide what a drag MEANS: only the grid knows how wide each column is and
83
+ * which rows are hidden. It reports pixels; `SheetGrid.tsx` turns them into a new `range`.
84
+ *
85
+ * ⚠ BOTH ARE OPTIONAL, so the component still renders wherever nothing has wired them, and the
86
+ * handles simply do not appear rather than moving something nobody will save.
87
+ */
88
+ onMove?: (dx: number, dy: number) => void;
89
+ onResize?: (dx: number, dy: number) => void;
90
  }
91
 
92
  /** A cell's text, however it is stored. A chart reads what the sheet SHOWS. */
 
110
  return filled.every((v) => Number.isFinite(Number(v))) ? "int" : "text";
111
  };
112
 
113
+ /**
114
+ * The sheet's kind said in the viz engine's vocabulary, or `null` for a picture the shared
115
+ * renderer does not have. See this file's header for why `column` and `bar` cross over.
116
+ */
117
+ const VIZ_KIND: Record<SheetChartSpec["kind"], SheetChartSpec["kind"] | null> = {
118
+ column: "bar",
119
+ bar: null,
120
+ line: null,
121
+ area: null,
122
+ donut: null,
123
+ pie: null,
124
+ scatter: null,
125
+ combo: null,
126
+ };
127
+
128
+ // ── the own-drawn frame ────────────────────────────────────────────────────────────────────────
129
+ // The same viewBox `SeriesChart` bakes in, deliberately: two charts of different kinds sitting on
130
+ // one sheet have to share a plot area, an axis inset and a label size, or the sheet reads as two
131
+ // products. The wrapper is still what sizes them (see the note above).
132
+ const W = 720;
133
+ const H = 230;
134
+ const PAD_L = 52;
135
+ const PAD_R = 10;
136
+ const PAD_T = 12;
137
+ const PAD_B = 34;
138
+
139
+ const SERIES_SLOTS = 4;
140
+
141
+ /** Axis furniture only, and short: an axis that needs six characters is a table. */
142
+ const axisText = (v: number): string => {
143
+ if (!Number.isFinite(v)) return "";
144
+ const abs = Math.abs(v);
145
+ if (abs >= 1e9) return `${(v / 1e9).toFixed(1)}B`;
146
+ if (abs >= 1e6) return `${(v / 1e6).toFixed(1)}M`;
147
+ if (abs >= 1e3) return `${(v / 1e3).toFixed(1)}k`;
148
+ return Number.isInteger(v) ? v.toLocaleString() : v.toFixed(2);
149
+ };
150
+
151
+ const readNumber = (row: Row, key: string): number => {
152
+ const v = (row as unknown as Record<string, unknown>)[key];
153
+ return typeof v === "number" && Number.isFinite(v) ? v : 0;
154
+ };
155
+
156
+ const readText = (row: Row, key: string): string => {
157
+ const v = (row as unknown as Record<string, unknown>)[key];
158
+ return v == null ? "" : String(v);
159
+ };
160
+
161
+ interface DrawnProps {
162
+ kind: SheetChartSpec["kind"];
163
+ fields: WireField[];
164
+ rows: Row[];
165
+ series: { y: string; label: string }[];
166
+ }
167
+
168
+ /** The legend DESIGN.md 3 makes binding at two series or more. One shape for all seven drawings. */
169
+ function Legend({ series }: { series: { y: string; label: string }[] }) {
170
+ if (series.length < 2) return null;
171
+ return (
172
+ <div className="pg-legend">
173
+ {series.map((s, i) => (
174
+ <span key={s.y} className="pg-legend-key">
175
+ <span className={`pg-legend-swatch pg-ser-${i % SERIES_SLOTS}`} />
176
+ {s.label}
177
+ </span>
178
+ ))}
179
+ </div>
180
+ );
181
+ }
182
+
183
+ /**
184
+ * The point marks on a plotted series. ONE definition, shared by `line`, `area` and `combo`'s
185
+ * line half, because three copies of a circle is three places for a hover title to drift.
186
+ */
187
+ function SeriesDots(
188
+ { slot, points, label, labels }: {
189
+ slot: number;
190
+ points: { x: number; y: number; v: number }[];
191
+ label: string;
192
+ labels: string[];
193
+ },
194
+ ) {
195
+ return (
196
+ <>
197
+ {points.map((p, i) => (
198
+ <circle
199
+ key={i}
200
+ className={`sheet-chart-dot pg-ser-${slot % SERIES_SLOTS}`}
201
+ cx={p.x}
202
+ cy={p.y}
203
+ r={3}
204
+ >
205
+ <title>{`${labels[i] || "(blank)"} and ${label}: ${axisText(p.v)}`}</title>
206
+ </circle>
207
+ ))}
208
+ </>
209
+ );
210
+ }
211
+
212
+ /**
213
+ * ONE slice, for BOTH ring kinds. `inner` of 0 is a pie wedge and a positive radius is a donut
214
+ * segment, which is the whole of the difference between the two kinds: writing the arcs twice
215
+ * would have been two chances to get a sweep flag wrong and one picture to notice it in.
216
+ *
217
+ * ⚠ THE FULL CIRCLE IS ITS OWN CASE. An SVG arc of exactly 360 degrees has identical endpoints
218
+ * and draws NOTHING, so a single-category ring would vanish. It is stated as two half turns; the
219
+ * donut's inner circle is swept the other way so the default winding rule leaves the hole open.
220
+ */
221
+ const slicePath = (
222
+ cx: number, cy: number, r: number, inner: number, from: number, sweep: number,
223
+ ): string => {
224
+ const to = from + sweep;
225
+ const big = sweep > Math.PI ? 1 : 0;
226
+ const full = sweep >= Math.PI * 2 - 1e-9;
227
+ const x0 = cx + r * Math.cos(from);
228
+ const y0 = cy + r * Math.sin(from);
229
+ const x1 = cx + r * Math.cos(to);
230
+ const y1 = cy + r * Math.sin(to);
231
+ if (inner <= 0) {
232
+ if (full) {
233
+ return `M ${cx} ${cy - r} A ${r} ${r} 0 1 1 ${cx} ${cy + r} `
234
+ + `A ${r} ${r} 0 1 1 ${cx} ${cy - r} Z`;
235
+ }
236
+ return `M ${cx} ${cy} L ${x0} ${y0} A ${r} ${r} 0 ${big} 1 ${x1} ${y1} Z`;
237
+ }
238
+ if (full) {
239
+ return `M ${cx} ${cy - r} A ${r} ${r} 0 1 1 ${cx} ${cy + r} `
240
+ + `A ${r} ${r} 0 1 1 ${cx} ${cy - r} Z `
241
+ + `M ${cx} ${cy - inner} A ${inner} ${inner} 0 1 0 ${cx} ${cy + inner} `
242
+ + `A ${inner} ${inner} 0 1 0 ${cx} ${cy - inner} Z`;
243
+ }
244
+ return `M ${x0} ${y0} A ${r} ${r} 0 ${big} 1 ${x1} ${y1} `
245
+ + `L ${cx + inner * Math.cos(to)} ${cy + inner * Math.sin(to)} `
246
+ + `A ${inner} ${inner} 0 ${big} 0 `
247
+ + `${cx + inner * Math.cos(from)} ${cy + inner * Math.sin(from)} Z`;
248
+ };
249
+
250
+ /**
251
+ * The seven pictures the shared renderer does not have. Every one of them reads the SAME `fields`
252
+ * / `rows` / `series` the memo below already built, so no kind gets its own idea of what a row is,
253
+ * and every one draws into the same 720x230 viewBox, so two charts of different kinds sitting on
254
+ * one sheet share a plot area, an axis inset and a label size rather than reading as two products.
255
+ */
256
+ function DrawnChart({ kind, fields, rows, series }: DrawnProps) {
257
+ const xKey = fields[0]?.key ?? "c0";
258
+ const xIsNumeric = fields[0]?.type === "int";
259
+ const labels = rows.map((row) => readText(row, xKey));
260
+ const plotW = W - PAD_L - PAD_R;
261
+ const plotH = H - PAD_T - PAD_B;
262
+ const base = H - PAD_B;
263
+ // One label every nth slot: enough to read, never so many they collide.
264
+ const labelEvery = Math.max(1, Math.ceil(rows.length / 12));
265
+ const footer = (
266
+ <p className="sheet-chart-foot">
267
+ {`${rows.length} categor${rows.length === 1 ? "y" : "ies"} plotted`}
268
+ </p>
269
+ );
270
+
271
+ if (kind === "pie" || kind === "donut") {
272
+ // A ring divided by the FIRST numeric series. Arc length encodes a share of a positive whole,
273
+ // so a negative value has no truthful geometry here and is left out of the total rather than
274
+ // drawn as a slice pointing the other way.
275
+ const key = series[0]?.y ?? "";
276
+ const seriesLabel = series[0]?.label ?? "the first numeric column";
277
+ const values = rows.map((row) => Math.max(0, readNumber(row, key)));
278
+ const total = values.reduce((a, b) => a + b, 0);
279
+ const cx = PAD_L + plotW / 2;
280
+ const cy = PAD_T + plotH / 2;
281
+ const r = Math.max(8, Math.min(plotW, plotH) / 2 - 4);
282
+ const inner = kind === "donut" ? r * 0.55 : 0;
283
+ const labelR = kind === "donut" ? (r + inner) / 2 : r * 0.62;
284
+ let angle = -Math.PI / 2;
285
+ return (
286
+ <>
287
+ <svg
288
+ className="pg-chart-svg"
289
+ viewBox={`0 0 ${W} ${H}`}
290
+ role="img"
291
+ aria-label={`${kind === "donut" ? "Donut" : "Pie"} chart of ${seriesLabel}`}
292
+ >
293
+ {total <= 0 ? (
294
+ <circle className="sheet-chart-ring" cx={cx} cy={cy} r={r} />
295
+ ) : (
296
+ values.map((v, i) => {
297
+ const sweep = (v / total) * Math.PI * 2;
298
+ const from = angle;
299
+ angle += sweep;
300
+ const mid = from + sweep / 2;
301
+ const share = v / total;
302
+ return (
303
+ <g key={`${labels[i]}-${i}`}>
304
+ <path
305
+ className={`sheet-chart-slice pg-ser-${i % SERIES_SLOTS}`}
306
+ d={slicePath(cx, cy, r, inner, from, sweep)}
307
+ >
308
+ <title>{`${labels[i] || "(blank)"}: ${axisText(v)}`}</title>
309
+ </path>
310
+ {share >= 0.08 ? (
311
+ <text
312
+ className="pg-ax-lab"
313
+ x={cx + labelR * Math.cos(mid)}
314
+ y={cy + labelR * Math.sin(mid) + 3}
315
+ textAnchor="middle"
316
+ >
317
+ {`${Math.round(share * 100)}%`}
318
+ </text>
319
+ ) : null}
320
+ </g>
321
+ );
322
+ })
323
+ )}
324
+ </svg>
325
+ <p className="sheet-chart-foot">
326
+ {`${rows.length} slice${rows.length === 1 ? "" : "s"} of ${seriesLabel}`}
327
+ </p>
328
+ </>
329
+ );
330
+ }
331
+
332
+ if (kind === "scatter") {
333
+ // x comes from the first column when it is numeric, and from the row index when it is not:
334
+ // a category axis with no order of its own is still a position, and pretending otherwise
335
+ // would drop every row of a chart whose first column is a name.
336
+ const xs = xIsNumeric
337
+ ? rows.map((row) => readNumber(row, xKey))
338
+ : rows.map((_row, i) => i);
339
+ const xMin = Math.min(0, ...xs);
340
+ const xMax = Math.max(1, ...xs);
341
+ const xSpan = xMax - xMin || 1;
342
+ const yMax = Math.max(
343
+ 1,
344
+ ...series.flatMap((s) => rows.map((row) => readNumber(row, s.y))),
345
+ );
346
+ return (
347
+ <>
348
+ <Legend series={series} />
349
+ <svg
350
+ className="pg-chart-svg"
351
+ viewBox={`0 0 ${W} ${H}`}
352
+ role="img"
353
+ aria-label="Scatter chart"
354
+ >
355
+ <line className="pg-ax" x1={PAD_L} y1={base} x2={W - PAD_R} y2={base} />
356
+ <line className="pg-ax" x1={PAD_L} y1={PAD_T} x2={PAD_L} y2={base} />
357
+ <text className="pg-ax-lab" x={PAD_L - 6} y={PAD_T + 4} textAnchor="end">
358
+ {axisText(yMax)}
359
+ </text>
360
+ <text className="pg-ax-lab" x={PAD_L - 6} y={base} textAnchor="end">
361
+ 0
362
+ </text>
363
+ {series.map((s, si) => (
364
+ <SeriesDots
365
+ key={s.y}
366
+ slot={si}
367
+ label={s.label}
368
+ labels={labels}
369
+ points={rows.map((row, i) => {
370
+ const v = readNumber(row, s.y);
371
+ return {
372
+ x: PAD_L + ((xs[i] - xMin) / xSpan) * plotW,
373
+ y: base - (v / yMax) * plotH,
374
+ v,
375
+ };
376
+ })}
377
+ />
378
+ ))}
379
+ {rows.map((_row, i) =>
380
+ i % labelEvery === 0 ? (
381
+ <text
382
+ key={`xl-${i}`}
383
+ className="pg-ax-lab"
384
+ x={PAD_L + ((xs[i] - xMin) / xSpan) * plotW}
385
+ y={base + 14}
386
+ textAnchor="middle"
387
+ >
388
+ {xIsNumeric ? axisText(xs[i]) : labels[i]}
389
+ </text>
390
+ ) : null,
391
+ )}
392
+ </svg>
393
+ <p className="sheet-chart-foot">
394
+ {`${rows.length} point${rows.length === 1 ? "" : "s"} plotted`}
395
+ </p>
396
+ </>
397
+ );
398
+ }
399
+
400
+ if (kind === "line" || kind === "area") {
401
+ // ⭐ ONE BRANCH FOR BOTH, because an area IS a line with the region under it filled. The
402
+ // stroke is drawn AFTER every fill so a series still reads as a series where two of them
403
+ // overlap, and the fills are transparent enough that the lower one is not erased.
404
+ const max = Math.max(
405
+ 1,
406
+ ...series.flatMap((s) => rows.map((row) => readNumber(row, s.y))),
407
+ );
408
+ // Edge to edge rather than slot centres: nothing is occupying a slot here, so inset points
409
+ // would leave a margin at each end that reads as missing data.
410
+ const at = (i: number) =>
411
+ (rows.length > 1 ? PAD_L + (i * plotW) / (rows.length - 1) : PAD_L + plotW / 2);
412
+ const yOf = (v: number) => base - (v / max) * plotH;
413
+ const plotted = series.map((s) => rows.map((row, i) => {
414
+ const v = readNumber(row, s.y);
415
+ return { x: at(i), y: yOf(v), v };
416
+ }));
417
+ const lineOf = (points: { x: number; y: number }[]) =>
418
+ points.map((p, i) => `${i === 0 ? "M" : "L"} ${p.x.toFixed(2)} ${p.y.toFixed(2)}`).join(" ");
419
+ return (
420
+ <>
421
+ <Legend series={series} />
422
+ <svg
423
+ className="pg-chart-svg"
424
+ viewBox={`0 0 ${W} ${H}`}
425
+ role="img"
426
+ aria-label={kind === "area" ? "Area chart" : "Line chart"}
427
+ >
428
+ <line className="pg-ax" x1={PAD_L} y1={base} x2={W - PAD_R} y2={base} />
429
+ <line className="pg-ax pg-ax-soft" x1={PAD_L} y1={PAD_T} x2={W - PAD_R} y2={PAD_T} />
430
+ <text className="pg-ax-lab" x={PAD_L - 6} y={PAD_T + 4} textAnchor="end">
431
+ {axisText(max)}
432
+ </text>
433
+ <text className="pg-ax-lab" x={PAD_L - 6} y={base} textAnchor="end">
434
+ 0
435
+ </text>
436
+ {kind === "area"
437
+ ? plotted.map((points, si) => (
438
+ points.length ? (
439
+ <path
440
+ key={`a-${series[si].y}`}
441
+ className={`sheet-chart-area pg-ser-${si % SERIES_SLOTS}`}
442
+ d={`${lineOf(points)} L ${points[points.length - 1].x.toFixed(2)} ${base} `
443
+ + `L ${points[0].x.toFixed(2)} ${base} Z`}
444
+ />
445
+ ) : null
446
+ ))
447
+ : null}
448
+ {plotted.map((points, si) => (
449
+ points.length ? (
450
+ <path
451
+ key={`l-${series[si].y}`}
452
+ className={`sheet-chart-line sheet-chart-ink-${si % SERIES_SLOTS}`}
453
+ d={lineOf(points)}
454
+ />
455
+ ) : null
456
+ ))}
457
+ {plotted.map((points, si) => (
458
+ <SeriesDots
459
+ key={`d-${series[si].y}`}
460
+ slot={si}
461
+ label={series[si].label}
462
+ labels={labels}
463
+ points={points}
464
+ />
465
+ ))}
466
+ {rows.map((_row, i) =>
467
+ i % labelEvery === 0 ? (
468
+ <text
469
+ key={`xl-${i}`}
470
+ className="pg-ax-lab"
471
+ x={at(i)}
472
+ y={base + 14}
473
+ textAnchor="middle"
474
+ >
475
+ {labels[i]}
476
+ </text>
477
+ ) : null,
478
+ )}
479
+ </svg>
480
+ {footer}
481
+ </>
482
+ );
483
+ }
484
+
485
+ if (kind === "combo") {
486
+ // The first numeric series as bars, the second as a line over them. With only one numeric
487
+ // series it draws that one as bars and says nothing extra: a line with no second measure
488
+ // would be the same values drawn twice, which reads as agreement between two sources.
489
+ const barKey = series[0]?.y ?? "";
490
+ const lineDef = series[1];
491
+ const barVals = rows.map((row) => readNumber(row, barKey));
492
+ const lineVals = lineDef ? rows.map((row) => readNumber(row, lineDef.y)) : [];
493
+ const max = Math.max(1, ...barVals, ...lineVals);
494
+ const slotW = plotW / Math.max(1, rows.length);
495
+ const barW = Math.max(2, slotW * 0.6);
496
+ const at = (i: number) => PAD_L + i * slotW + slotW / 2;
497
+ const yOf = (v: number) => base - (v / max) * plotH;
498
+ const points = lineVals.map((v, i) => ({ x: at(i), y: yOf(v), v }));
499
+ const path = points
500
+ .map((p, i) => `${i === 0 ? "M" : "L"} ${p.x.toFixed(2)} ${p.y.toFixed(2)}`)
501
+ .join(" ");
502
+ return (
503
+ <>
504
+ <Legend series={lineDef ? [series[0], lineDef] : series.slice(0, 1)} />
505
+ <svg
506
+ className="pg-chart-svg"
507
+ viewBox={`0 0 ${W} ${H}`}
508
+ role="img"
509
+ aria-label={lineDef
510
+ ? `Combination chart of ${series[0]?.label ?? ""} and ${lineDef.label}`
511
+ : `Combination chart of ${series[0]?.label ?? ""}`}
512
+ >
513
+ <line className="pg-ax" x1={PAD_L} y1={base} x2={W - PAD_R} y2={base} />
514
+ <line className="pg-ax pg-ax-soft" x1={PAD_L} y1={PAD_T} x2={W - PAD_R} y2={PAD_T} />
515
+ <text className="pg-ax-lab" x={PAD_L - 6} y={PAD_T + 4} textAnchor="end">
516
+ {axisText(max)}
517
+ </text>
518
+ <text className="pg-ax-lab" x={PAD_L - 6} y={base} textAnchor="end">
519
+ 0
520
+ </text>
521
+ {barVals.map((v, i) => (
522
+ <rect
523
+ key={`b-${i}`}
524
+ className="pg-bar pg-ser-0"
525
+ x={at(i) - barW / 2}
526
+ y={yOf(v)}
527
+ width={barW}
528
+ height={Math.max(v > 0 ? 1 : 0, base - yOf(v))}
529
+ >
530
+ <title>{`${labels[i] || "(blank)"}: ${axisText(v)}`}</title>
531
+ </rect>
532
+ ))}
533
+ {lineDef && path ? (
534
+ <path className="sheet-chart-line sheet-chart-ink-1" d={path} />
535
+ ) : null}
536
+ {lineDef ? (
537
+ <SeriesDots slot={1} label={lineDef.label} labels={labels} points={points} />
538
+ ) : null}
539
+ {rows.map((_row, i) =>
540
+ i % labelEvery === 0 ? (
541
+ <text
542
+ key={`xl-${i}`}
543
+ className="pg-ax-lab"
544
+ x={at(i)}
545
+ y={base + 14}
546
+ textAnchor="middle"
547
+ >
548
+ {labels[i]}
549
+ </text>
550
+ ) : null,
551
+ )}
552
+ </svg>
553
+ {footer}
554
+ </>
555
+ );
556
+ }
557
+
558
+ // `bar`: Excel's HORIZONTAL orientation, which is the one the shared renderer does not have.
559
+ const groupH = plotH / Math.max(1, rows.length);
560
+ const barH = Math.max(2, (groupH * 0.72) / Math.max(1, series.length));
561
+ const max = Math.max(
562
+ 1,
563
+ ...series.flatMap((s) => rows.map((row) => readNumber(row, s.y))),
564
+ );
565
+ return (
566
+ <>
567
+ <Legend series={series} />
568
+ <svg
569
+ className="pg-chart-svg"
570
+ viewBox={`0 0 ${W} ${H}`}
571
+ role="img"
572
+ aria-label="Bar chart, drawn horizontally"
573
+ >
574
+ <line className="pg-ax" x1={PAD_L} y1={PAD_T} x2={PAD_L} y2={base} />
575
+ <line className="pg-ax pg-ax-soft" x1={W - PAD_R} y1={PAD_T} x2={W - PAD_R} y2={base} />
576
+ <text className="pg-ax-lab" x={PAD_L} y={base + 14} textAnchor="start">
577
+ 0
578
+ </text>
579
+ <text className="pg-ax-lab" x={W - PAD_R} y={base + 14} textAnchor="end">
580
+ {axisText(max)}
581
+ </text>
582
+ {rows.map((row, i) => {
583
+ const top = PAD_T + i * groupH + (groupH - barH * series.length) / 2;
584
+ return (
585
+ <g key={`g-${i}`}>
586
+ {series.map((s, si) => {
587
+ const v = readNumber(row, s.y);
588
+ return (
589
+ <rect
590
+ key={s.y}
591
+ className={`pg-bar pg-ser-${si % SERIES_SLOTS}`}
592
+ x={PAD_L}
593
+ y={top + si * barH}
594
+ width={Math.max(v > 0 ? 1 : 0, (v / max) * plotW)}
595
+ height={Math.max(1, barH - 1.5)}
596
+ >
597
+ <title>{`${labels[i] || "(blank)"} and ${s.label}: ${axisText(v)}`}</title>
598
+ </rect>
599
+ );
600
+ })}
601
+ {i % labelEvery === 0 ? (
602
+ <text
603
+ className="pg-ax-lab sheet-chart-cat"
604
+ x={PAD_L - 6}
605
+ y={top + (barH * series.length) / 2 + 3}
606
+ textAnchor="end"
607
+ >
608
+ {labels[i]}
609
+ </text>
610
+ ) : null}
611
+ </g>
612
+ );
613
+ })}
614
+ </svg>
615
+ {footer}
616
+ </>
617
+ );
618
+ }
619
+
620
+ // ── the gesture ───────────────────────────────────────────────────────────────────────────────
621
+ //
622
+ // ⭐ DESIGN.md, quoted, because it is this ticket's own rule: "track pointer movement 1:1 with
623
+ // pointer capture, preserve the grab offset, allow reversal, and use a critically damped spring
624
+ // from the presentation value on release". Bounce is only for a momentum-bearing gesture and this
625
+ // is not one, so the spring is critically damped: it returns without ever crossing zero.
626
+ //
627
+ // β›” WHY THE PRESENTATION VALUE SETTLES AT ALL. The document is the truth and the grid re-anchors
628
+ // the chart the instant the new `range` lands, so the transform this component held during the
629
+ // drag has to come off. Snapping it off is a jump; releasing it through the spring is the same
630
+ // arrival, taken in 150 to 250 ms, from wherever the finger actually let go.
631
+
632
+ type Nudge = { dx: number; dy: number; dw: number; dh: number };
633
+ const ZERO: Nudge = { dx: 0, dy: 0, dw: 0, dh: 0 };
634
+ const NUDGE_KEYS: (keyof Nudge)[] = ["dx", "dy", "dw", "dh"];
635
+ /** rad/s. Higher is a shorter settle; at zeta = 1 there is no overshoot at any speed. */
636
+ const OMEGA = 22;
637
+ /** Below half a pixel and half a pixel per second, the spring has arrived. */
638
+ const AT_REST = 0.5;
639
+
640
+ const prefersReducedMotion = (): boolean =>
641
+ typeof window !== "undefined"
642
+ && typeof window.matchMedia === "function"
643
+ && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
644
+
645
+ export default function SheetChart({
646
+ range,
647
+ cells,
648
+ kind = "bar",
649
+ width,
650
+ height,
651
+ onMove,
652
+ onResize,
653
+ }: SheetChartProps) {
654
  const { fields, rows, series } = useMemo(() => {
655
  const { col0, row0, col1, row1 } = range;
656
  const loCol = Math.min(col0, col1);
 
696
  };
697
  }, [range, cells]);
698
 
699
+ const delegated = useMemo<SheetChartDrawnKind | null>(() => {
700
+ const viz = VIZ_KIND[kind];
701
+ return viz !== null && isDrawnChartKind(viz) ? viz : null;
702
+ }, [kind]);
703
+
704
  const spec: ChartSpec = useMemo(
705
  () => ({
706
  id: "sheet-chart",
707
+ kind: delegated ?? "bar",
708
  x: fields[0]?.key,
709
  y: series[0]?.y,
710
  agg: "sum",
711
  }),
712
+ [delegated, fields, series],
713
  );
714
 
715
+ const [nudge, setNudge] = useState<Nudge>(ZERO);
716
+ const [flash, setFlash] = useState(false);
717
+ const grab = useRef<{ x: number; y: number; mode: "move" | "resize" } | null>(null);
718
+ const frame = useRef<number | null>(null);
719
+
720
+ const stopSettle = useCallback(() => {
721
+ if (frame.current !== null && typeof cancelAnimationFrame === "function") {
722
+ cancelAnimationFrame(frame.current);
723
+ }
724
+ frame.current = null;
725
+ }, []);
726
+
727
+ useEffect(() => stopSettle, [stopSettle]);
728
+
729
+ /** The critically damped return, integrated from the value the finger let go at. */
730
+ const settle = useCallback((from: Nudge) => {
731
+ if (prefersReducedMotion() || typeof requestAnimationFrame !== "function") {
732
+ // β›” Reduced motion replaces the spring with a short opacity change, never with a slide
733
+ // taken faster: the whole point is that nothing travels across the screen.
734
+ setNudge(ZERO);
735
+ setFlash(true);
736
+ window.setTimeout(() => setFlash(false), 140);
737
+ return;
738
+ }
739
+ let value: Nudge = { ...from };
740
+ let velocity: Nudge = { ...ZERO };
741
+ let last = performance.now();
742
+ const step = (now: number) => {
743
+ const dt = Math.min(0.032, Math.max(0.001, (now - last) / 1000));
744
+ last = now;
745
+ let moving = false;
746
+ const nextValue: Nudge = { ...ZERO };
747
+ const nextVelocity: Nudge = { ...ZERO };
748
+ for (const key of NUDGE_KEYS) {
749
+ const accel = -2 * OMEGA * velocity[key] - OMEGA * OMEGA * value[key];
750
+ nextVelocity[key] = velocity[key] + accel * dt;
751
+ nextValue[key] = value[key] + nextVelocity[key] * dt;
752
+ if (Math.abs(nextValue[key]) > AT_REST || Math.abs(nextVelocity[key]) > AT_REST) {
753
+ moving = true;
754
+ }
755
+ }
756
+ value = nextValue;
757
+ velocity = nextVelocity;
758
+ if (!moving) {
759
+ setNudge(ZERO);
760
+ frame.current = null;
761
+ return;
762
+ }
763
+ setNudge(value);
764
+ frame.current = requestAnimationFrame(step);
765
+ };
766
+ frame.current = requestAnimationFrame(step);
767
+ }, []);
768
+
769
+ const beginDrag = useCallback((mode: "move" | "resize") =>
770
+ (event: React.PointerEvent<HTMLButtonElement>) => {
771
+ if (event.button !== 0) return;
772
+ event.preventDefault();
773
+ event.stopPropagation();
774
+ stopSettle();
775
+ grab.current = { x: event.clientX, y: event.clientY, mode };
776
+ event.currentTarget.setPointerCapture(event.pointerId);
777
+ setNudge(ZERO);
778
+ }, [stopSettle]);
779
+
780
+ const duringDrag = useCallback((event: React.PointerEvent<HTMLButtonElement>) => {
781
+ const held = grab.current;
782
+ if (!held) return;
783
+ // 1:1 with the pointer, from the offset it was grabbed at, so pushing back the way it came
784
+ // undoes the drag exactly rather than starting a new one.
785
+ const dx = event.clientX - held.x;
786
+ const dy = event.clientY - held.y;
787
+ setNudge(held.mode === "move"
788
+ ? { dx, dy, dw: 0, dh: 0 }
789
+ : { dx: 0, dy: 0, dw: dx, dh: dy });
790
+ }, []);
791
+
792
+ const endDrag = useCallback((event: React.PointerEvent<HTMLButtonElement>) => {
793
+ const held = grab.current;
794
+ if (!held) return;
795
+ grab.current = null;
796
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {
797
+ event.currentTarget.releasePointerCapture(event.pointerId);
798
+ }
799
+ const dx = event.clientX - held.x;
800
+ const dy = event.clientY - held.y;
801
+ if (held.mode === "move") onMove?.(dx, dy);
802
+ else onResize?.(dx, dy);
803
+ settle(held.mode === "move"
804
+ ? { dx, dy, dw: 0, dh: 0 }
805
+ : { dx: 0, dy: 0, dw: dx, dh: dy });
806
+ }, [onMove, onResize, settle]);
807
+
808
+ // ⭐ THE DRAG IS NOT THE ONLY WAY, which DESIGN.md requires: the arrow keys walk the anchor one
809
+ // cell at a time from the same two controls, and the Insert tab's own dialog sets a range
810
+ // outright. A step is this chart's own width over the columns it spans, which IS one column on
811
+ // the grid it is sitting on.
812
+ const stepX = Math.max(8, width / Math.max(1, Math.abs(range.col1 - range.col0) + 1));
813
+ const stepY = Math.max(8, height / Math.max(1, Math.abs(range.row1 - range.row0) + 1));
814
+
815
+ const arrowKeys = useCallback((mode: "move" | "resize") =>
816
+ (event: React.KeyboardEvent<HTMLButtonElement>) => {
817
+ const send = mode === "move" ? onMove : onResize;
818
+ if (!send) return;
819
+ if (event.key === "ArrowLeft") send(-stepX, 0);
820
+ else if (event.key === "ArrowRight") send(stepX, 0);
821
+ else if (event.key === "ArrowUp") send(0, -stepY);
822
+ else if (event.key === "ArrowDown") send(0, stepY);
823
+ else return;
824
+ event.preventDefault();
825
+ }, [onMove, onResize, stepX, stepY]);
826
+
827
+ const tools = (onMove || onResize) ? (
828
+ <div className="sheet-chart-tools">
829
+ {onMove ? (
830
+ <button
831
+ type="button"
832
+ className="sheet-chart-tool sheet-chart-grip"
833
+ aria-label="Move this chart. Drag it, or use the arrow keys."
834
+ onPointerDown={beginDrag("move")}
835
+ onPointerMove={duringDrag}
836
+ onPointerUp={endDrag}
837
+ onPointerCancel={endDrag}
838
+ onKeyDown={arrowKeys("move")}
839
+ >
840
+ {/* Four arrows from one centre: the existing set's stroke weight and round caps. */}
841
+ <svg className="sheet-chart-tool-icon" viewBox="0 0 16 16" aria-hidden="true">
842
+ <path d="M8 2.5v11M2.5 8h11M8 2.5 6 4.5M8 2.5l2 2M8 13.5l-2-2M8 13.5l2-2
843
+ M2.5 8l2-2M2.5 8l2 2M13.5 8l-2-2M13.5 8l-2 2" />
844
+ </svg>
845
+ </button>
846
+ ) : null}
847
+ {onResize ? (
848
+ <button
849
+ type="button"
850
+ className="sheet-chart-tool sheet-chart-corner"
851
+ aria-label="Resize this chart. Drag it, or use the arrow keys."
852
+ onPointerDown={beginDrag("resize")}
853
+ onPointerMove={duringDrag}
854
+ onPointerUp={endDrag}
855
+ onPointerCancel={endDrag}
856
+ onKeyDown={arrowKeys("resize")}
857
+ >
858
+ {/* The corner angle, the same two-stroke glyph the grid's own edge affordances use. */}
859
+ <svg className="sheet-chart-tool-icon" viewBox="0 0 16 16" aria-hidden="true">
860
+ <path d="M13.5 6.5v7h-7M13.5 10.5v3h-3" />
861
+ </svg>
862
+ </button>
863
+ ) : null}
864
+ </div>
865
+ ) : null;
866
+
867
+ const shell: React.CSSProperties = {
868
+ width: Math.max(24, width + nudge.dw),
869
+ height: Math.max(24, height + nudge.dh),
870
+ transform: nudge.dx || nudge.dy ? `translate(${nudge.dx}px, ${nudge.dy}px)` : undefined,
871
+ opacity: flash ? 0.72 : undefined,
872
+ };
873
+
874
  if (!series.length) {
875
  // Named rather than drawn empty: a chart frame with no series reads as "the data is zero",
876
  // which is a different and wrong statement.
877
  return (
878
+ <div className="sheet-chart is-empty" style={shell} role="img"
879
  aria-label="This range has no numeric column to chart">
880
  <p>This range has no numeric column to chart.</p>
881
+ {tools}
882
  </div>
883
  );
884
  }
 
886
  return (
887
  // ⭐ THE WRAPPER IS THE SIZING MECHANISM. `SeriesChart` draws into a fixed 720x230 viewBox, so
888
  // scaling it to an arbitrary cell rectangle is the wrapper's job and the renderer stays
889
+ // untouched. `viz/**` belongs to no lane in this wave, and the own-drawn kinds use the same
890
+ // viewBox for the same reason.
891
+ <div className="sheet-chart" style={shell}>
892
+ {delegated
893
+ ? <SeriesChart spec={spec} series={series} fields={fields} rows={rows} />
894
+ : (
895
+ <div className="sheet-chart-plot">
896
+ <DrawnChart kind={kind} fields={fields} rows={rows} series={series} />
897
+ </div>
898
+ )}
899
+ {tools}
900
  </div>
901
  );
902
  }
web/src/sheet/SheetGrid.tsx CHANGED
The diff for this file is too large to render. See raw diff
 
web/src/sheet/SheetPage.tsx CHANGED
@@ -51,14 +51,15 @@ import "../customer-grid/chatDock.css";
51
  import { SHEET_VIEW_KIND } from "./index";
52
  import BindingEditor from "./BindingEditor";
53
  import DrillModal from "./DrillModal";
 
54
  import FormulaBar from "./FormulaBar";
55
  import SheetGridBase from "./SheetGrid";
56
  import type { SheetGridProps } from "./SheetGrid";
57
  import SheetRail from "./SheetRail";
58
  import type { RailStrata } from "./SheetRail";
59
  import {
60
- createWorkbook, deleteWorkbook, patchTabCells, readIndex, readTab, readTabMeta, readWorkbook,
61
- refreshWorkbook, writeIndex, writeWorkbook,
62
  } from "./sheetApi";
63
  import type { SheetIndex } from "./sheetApi";
64
  // β›”β›” W51-T10 / R6 β€” THE ONE CONFIRM DIALOG (contract C8). The sheet-delete prompt below used to
@@ -76,7 +77,7 @@ import type { GridChatAnswer, GridChatField } from "../customer-grid/gridChat";
76
  import { fetchTableWindow, fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge";
77
  import type { SurfaceScope } from "../customer-grid/apiBridge";
78
  import { CUSTOMER_TOPIC, PRODUCT_TOPIC } from "../customer-grid/types";
79
- import type { TopicConfig } from "../customer-grid/types";
80
  import {
81
  addTab, applyStructure, bandBoundLabel, boundCellsInBand, cellAt,
82
  drillAffordance, emptyHistory, growSheet, moveTab, pushHistory, redoHistory, removeTab,
@@ -85,7 +86,7 @@ import {
85
  } from "./sheetState";
86
  import type { SheetHistory, StructureOp } from "./sheetState";
87
  import { emptyIndex } from "./types";
88
- import type { Cell, IndexRepair, SheetTab, Workbook } from "./types";
89
 
90
  /**
91
  * ⭐⭐ W51-T08 / CONTRACT C1 β€” THE FOUR SEAM PROPS, TYPED HERE BECAUSE `SheetGrid.tsx` IS LANE E'S.
@@ -295,6 +296,21 @@ export default function SheetPage() {
295
  const [index, setIndex] = useState<SheetIndex>(emptyIndex);
296
  /** The address whose rows are open, or "" for none. R11: the popup belongs to ONE cell. */
297
  const [drillAt, setDrillAt] = useState("");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
  /** The address whose binding is being edited, or "" for none (W49-T06). */
299
  const [editAt, setEditAt] = useState("");
300
  /**
@@ -369,6 +385,29 @@ export default function SheetPage() {
369
  const tabLoadedRef = useRef<Set<string>>(new Set());
370
  /** The pending debounce, or null when nothing is waiting. */
371
  const saveTimerRef = useRef<number | null>(null);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372
  /** The current drain, so the unmount flush can call it without re-arming its own effect. */
373
  const drainRef = useRef<() => void>(() => {});
374
 
@@ -690,6 +729,7 @@ export default function SheetPage() {
690
  if (live && sent.value.rev) applyLocal({ ...live, rev: sent.value.rev });
691
  const refused = sent.value.refused ?? [];
692
  if (refused.length > 0) {
 
693
  const head = refused[0];
694
  setNotice(refused.length === 1
695
  ? (head.sentence || `${head.addr} was not saved.`)
@@ -756,6 +796,7 @@ export default function SheetPage() {
756
  // moved, against a server still holding the row that was inserted. The insert would never
757
  // be sent and the cells that were would describe a grid the server does not have.
758
  structureDirtyRef.current = true;
 
759
  setNotice("Some sheets in this workbook could not be read, so nothing was saved. "
760
  + "Reload the page and try again.");
761
  return;
@@ -781,6 +822,7 @@ export default function SheetPage() {
781
  // ⚠ AND HERE THE FLAG STAYS OFF, deliberately. The re-read REPLACED the tree the
782
  // structure change was made in, so there is nothing left to re-send; the sentence above
783
  // is what tells the reader their change did not land.
 
784
  setNotice("This workbook changed somewhere else, so that edit was not saved. "
785
  + "The sheet has been reloaded with the other change.");
786
  return;
@@ -788,6 +830,7 @@ export default function SheetPage() {
788
  // A refusal that is not a revision conflict leaves the local tree intact, so the pending
789
  // structure change is still pending and the next drain must still carry it.
790
  structureDirtyRef.current = true;
 
791
  setNotice(saved.message);
792
  return;
793
  }
@@ -809,11 +852,13 @@ export default function SheetPage() {
809
  const drainSave = useCallback(() => {
810
  saveChainRef.current = saveChainRef.current.then(async () => {
811
  if (!bookRef.current) return;
 
812
  const structural = structureDirtyRef.current;
813
  structureDirtyRef.current = false;
814
  if (!structural && patchModeRef.current !== "put") {
815
  if (dirtyRef.current.size === 0) return;
816
  const outcome = await sendDirtyCells();
 
817
  // β›” ONLY AN ABSENT ROUTE FALLS THROUGH TO THE PUT, and it falls through in THIS drain so
818
  // the edit that discovered it still lands. A 409, a 413 and an unreachable server have
819
  // each been answered already; re-sending the whole document after one of them would
@@ -995,6 +1040,65 @@ export default function SheetPage() {
995
  if (base) commitSheets(setColumnWidth(base, openTabId(base), colIndex, width));
996
  }, [commitSheets, openTabId]);
997
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
998
  // ── the tab bar (wave-49 R7) ───────────────────────────────────────────────────────────────
999
 
1000
  const onAddTab = useCallback(() => {
@@ -1093,21 +1197,126 @@ export default function SheetPage() {
1093
  queueSave();
1094
  }, [applyLocal, queueSave]);
1095
 
1096
- /** Persist one cell's binding, then let the ordinary Refresh compute it (R10: a snapshot). */
1097
- const onSaveBinding = useCallback((binding: Record<string, unknown>) => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1098
  // ⚠ IT GOES THROUGH `commitCells` LIKE EVERY OTHER WRITE (W50-T18). It used to build its
1099
  // own `sheets` array and PUT directly, which was correct while it was the only writer; now
1100
  // that a keystroke also saves, two writers each sending the `rev` they last read is exactly
1101
  // the race `put_workbook` refuses. One door, one queue, one rev.
1102
- const addr = editAt;
1103
- if (!addr) return;
1104
- setEditAt("");
 
1105
  // A newly bound cell is STALE, never fresh: nothing has been computed yet, and marking it
1106
- // fresh would show an empty value wearing the mark that means "this number is current".
 
1107
  commitCells({
1108
  [addr]: { kind: "bound" as const, state: "stale" as const, binding, value: null },
1109
  });
1110
- }, [commitCells, editAt]);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1111
 
1112
  // ⭐ R17 is enforced BEFORE the popup opens, not inside it. `drillAffordance` already disables
1113
  // the control for a formula or a literal and names the reason; this guard is the second half of
@@ -1120,6 +1329,9 @@ export default function SheetPage() {
1120
  return;
1121
  }
1122
  setNotice("");
 
 
 
1123
  setDrillAt(addr);
1124
  }, []);
1125
 
@@ -1504,12 +1716,50 @@ export default function SheetPage() {
1504
 
1505
  const tab = book?.sheets.find((t) => t.id === tabId) ?? book?.sheets[0] ?? null;
1506
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1507
  return (
1508
  // β›” `data-view-kind` STAYS IN THIS FILE. `verify_wiring.py`'s W49-W1 row asserts
1509
  // `data-view-kind={SHEET_VIEW_KIND}` inside `sheet/SheetPage.tsx` by path, so moving the rail
1510
  // out without moving this attribute up would have turned a green wiring row red for a reason
1511
  // that has nothing to do with what it guards. R2's one view kind is a property of the PAGE.
1512
- <div className="sheet-page" data-view-kind={SHEET_VIEW_KIND}>
 
 
 
 
 
 
 
1513
  <SheetRail
1514
  importRequest={importRequest}
1515
  loading={loading}
@@ -1599,7 +1849,10 @@ export default function SheetPage() {
1599
  <SheetGrid
1600
  workbook={book}
1601
  tab={tab}
1602
- busy={busy}
 
 
 
1603
  onEdit={onEdit}
1604
  onViewRows={onViewRows}
1605
  onRefresh={onRefresh}
@@ -1614,6 +1867,15 @@ export default function SheetPage() {
1614
  onGrow={onGrow}
1615
  onFreeze={onFreeze}
1616
  onColumnWidth={onColumnWidth}
 
 
 
 
 
 
 
 
 
1617
  // ⭐⭐ W51-T08 / CONTRACT C1 β€” THE FOUR SEAM PROPS THE RIBBON IS FED THROUGH.
1618
  //
1619
  // ⚠ THEY SIT AFTER `onCommit` AND THAT IS LOAD BEARING, not tidiness. `verify_wiring`'s
@@ -1854,7 +2116,14 @@ export default function SheetPage() {
1854
  workbookId={book.id}
1855
  addr={drillAt}
1856
  label={drillAt}
1857
- onClose={() => setDrillAt("")}
 
 
 
 
 
 
 
1858
  />
1859
  )}
1860
  </div>
 
51
  import { SHEET_VIEW_KIND } from "./index";
52
  import BindingEditor from "./BindingEditor";
53
  import DrillModal from "./DrillModal";
54
+ import type { DrillCellScope } from "./DrillModal";
55
  import FormulaBar from "./FormulaBar";
56
  import SheetGridBase from "./SheetGrid";
57
  import type { SheetGridProps } from "./SheetGrid";
58
  import SheetRail from "./SheetRail";
59
  import type { RailStrata } from "./SheetRail";
60
  import {
61
+ computeCell, createWorkbook, deleteWorkbook, patchTabCells, readIndex, readTab, readTabMeta,
62
+ readWorkbook, refreshWorkbook, writeIndex, writeWorkbook,
63
  } from "./sheetApi";
64
  import type { SheetIndex } from "./sheetApi";
65
  // β›”β›” W51-T10 / R6 β€” THE ONE CONFIRM DIALOG (contract C8). The sheet-delete prompt below used to
 
77
  import { fetchTableWindow, fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge";
78
  import type { SurfaceScope } from "../customer-grid/apiBridge";
79
  import { CUSTOMER_TOPIC, PRODUCT_TOPIC } from "../customer-grid/types";
80
+ import type { FilterTree, TopicConfig } from "../customer-grid/types";
81
  import {
82
  addTab, applyStructure, bandBoundLabel, boundCellsInBand, cellAt,
83
  drillAffordance, emptyHistory, growSheet, moveTab, pushHistory, redoHistory, removeTab,
 
86
  } from "./sheetState";
87
  import type { SheetHistory, StructureOp } from "./sheetState";
88
  import { emptyIndex } from "./types";
89
+ import type { Cell, IndexRepair, SheetChartSpec, SheetRule, SheetTab, Workbook } from "./types";
90
 
91
  /**
92
  * ⭐⭐ W51-T08 / CONTRACT C1 β€” THE FOUR SEAM PROPS, TYPED HERE BECAUSE `SheetGrid.tsx` IS LANE E'S.
 
296
  const [index, setIndex] = useState<SheetIndex>(emptyIndex);
297
  /** The address whose rows are open, or "" for none. R11: the popup belongs to ONE cell. */
298
  const [drillAt, setDrillAt] = useState("");
299
+ /**
300
+ * ⭐⭐ W54-T34 (owner instruction 10) β€” THE CONTROL HALF OF "I HEARD YOU".
301
+ *
302
+ * Owner: *"Clicking View rows still takes a long time; if it must, we need a loading button so
303
+ * the user knows their click worked."* The button itself lives in `sheet/CellActionBar.tsx`,
304
+ * which this ticket may not edit, so the busy state is driven through the ONE prop that already
305
+ * crosses that fence: `busy`, which the bar spends on `disabled`. This flag is folded into it
306
+ * below rather than being a second prop nobody forwards.
307
+ *
308
+ * β›” IT IS ITS OWN FLAG AND NOT `busy` REUSED, for the reason the CSS needs: `busy` is also a
309
+ * refresh in flight, and the two want different words on the same control. `data-drill` on the
310
+ * page root is what lets `styles/wave49/sheet.css` say "this control is working" rather than
311
+ * "this control is unavailable", which is all `:disabled` can say on its own.
312
+ */
313
+ const [drillLoading, setDrillLoading] = useState(false);
314
  /** The address whose binding is being edited, or "" for none (W49-T06). */
315
  const [editAt, setEditAt] = useState("");
316
  /**
 
385
  const tabLoadedRef = useRef<Set<string>>(new Set());
386
  /** The pending debounce, or null when nothing is waiting. */
387
  const saveTimerRef = useRef<number | null>(null);
388
+ /**
389
+ * ⭐⭐ W54-T32 β€” DID THE DRAIN THAT JUST FINISHED ACTUALLY PERSIST WHAT IT CARRIED?
390
+ *
391
+ * β›”β›” THE ONE READER IS `onSaveBinding`, AND IT EXISTS BECAUSE A SECOND SENTENCE OVERWROTE A
392
+ * TRUE ONE. Observed in the running app on a read-only tenant: the cell PATCH was refused
393
+ * `503 store_write_refused` and `sendDirtyCells` said so, correctly; the recompute that follows
394
+ * a binding save then asked the server about a cell that had never reached it, was correctly
395
+ * answered `404 cell_missing`, and painted "Cell A1 is not filled in." over the real cause. The
396
+ * reader was told the wrong thing about their own workbook. A refusal names its cause or it is
397
+ * worse than silence.
398
+ *
399
+ * ⚠ WHY NOT THE DIRTY SET, WHICH IS THE OBVIOUS SIGNAL. It answers only the case that was
400
+ * observed. `sendDirtyCells` RE-ARMS the addresses on a plain refusal (the 503 above), so the
401
+ * set does distinguish that one, but four other non-landings leave it EMPTY by design and would
402
+ * read as success: a 409 re-reads the tab instead, a 413 must never re-send an oversized
403
+ * payload, `sendWholeWorkbook` clears the set before its PUT and does not restore it, and a
404
+ * `refused[]` entry on an otherwise accepted PATCH is a cell that did not land inside a request
405
+ * that did. This flag is set at each of those exits instead, which is the same list as "the
406
+ * places that already write a notice of their own".
407
+ *
408
+ * ⚠ TRUE IS THE RESTING VALUE. A drain with nothing to send has lost nothing.
409
+ */
410
+ const savedCleanRef = useRef(true);
411
  /** The current drain, so the unmount flush can call it without re-arming its own effect. */
412
  const drainRef = useRef<() => void>(() => {});
413
 
 
729
  if (live && sent.value.rev) applyLocal({ ...live, rev: sent.value.rev });
730
  const refused = sent.value.refused ?? [];
731
  if (refused.length > 0) {
732
+ savedCleanRef.current = false;
733
  const head = refused[0];
734
  setNotice(refused.length === 1
735
  ? (head.sentence || `${head.addr} was not saved.`)
 
796
  // moved, against a server still holding the row that was inserted. The insert would never
797
  // be sent and the cells that were would describe a grid the server does not have.
798
  structureDirtyRef.current = true;
799
+ savedCleanRef.current = false;
800
  setNotice("Some sheets in this workbook could not be read, so nothing was saved. "
801
  + "Reload the page and try again.");
802
  return;
 
822
  // ⚠ AND HERE THE FLAG STAYS OFF, deliberately. The re-read REPLACED the tree the
823
  // structure change was made in, so there is nothing left to re-send; the sentence above
824
  // is what tells the reader their change did not land.
825
+ savedCleanRef.current = false;
826
  setNotice("This workbook changed somewhere else, so that edit was not saved. "
827
  + "The sheet has been reloaded with the other change.");
828
  return;
 
830
  // A refusal that is not a revision conflict leaves the local tree intact, so the pending
831
  // structure change is still pending and the next drain must still carry it.
832
  structureDirtyRef.current = true;
833
+ savedCleanRef.current = false;
834
  setNotice(saved.message);
835
  return;
836
  }
 
852
  const drainSave = useCallback(() => {
853
  saveChainRef.current = saveChainRef.current.then(async () => {
854
  if (!bookRef.current) return;
855
+ savedCleanRef.current = true;
856
  const structural = structureDirtyRef.current;
857
  structureDirtyRef.current = false;
858
  if (!structural && patchModeRef.current !== "put") {
859
  if (dirtyRef.current.size === 0) return;
860
  const outcome = await sendDirtyCells();
861
+ if (outcome === "stopped") savedCleanRef.current = false;
862
  // β›” ONLY AN ABSENT ROUTE FALLS THROUGH TO THE PUT, and it falls through in THIS drain so
863
  // the edit that discovered it still lands. A 409, a 413 and an unreachable server have
864
  // each been answered already; re-sending the whole document after one of them would
 
1040
  if (base) commitSheets(setColumnWidth(base, openTabId(base), colIndex, width));
1041
  }, [commitSheets, openTabId]);
1042
 
1043
+ /**
1044
+ * ⭐ W54-T10 / LANE B β€” THE INSERT TAB'S CHARTS, THROUGH THE SAME DOOR EVERY OTHER TAB-LEVEL
1045
+ * WRITE TAKES. `charts` is a key ON the tab (never a cell), so replacing the open tab's list and
1046
+ * handing the result to `commitSheets` is one history step, one PUT and one `rev`, which is what
1047
+ * makes an inserted chart survive a reload and Ctrl+Z remove it. Same shape as `onGrow`,
1048
+ * `onFreeze` and `onColumnWidth` above; the only difference is that the transform is a one line
1049
+ * replace rather than a named helper in `sheetState.ts`, a file this lane does not own.
1050
+ */
1051
+ const onCharts = useCallback((charts: SheetChartSpec[]) => {
1052
+ const base = bookRef.current;
1053
+ if (!base) return;
1054
+ const target = openTabId(base);
1055
+ if (!target) return;
1056
+ commitSheets(base.sheets.map((t) => (t.id === target ? { ...t, charts } : t)));
1057
+ }, [commitSheets, openTabId]);
1058
+
1059
+ /**
1060
+ * ⭐⭐ W54-T05's HANDOVER, COMPLETED AT THE COMBINE. Lane A built colour scales, data bars and
1061
+ * Cell styles and could not wire them: `SheetPage.tsx` is lane E's file and carried four live
1062
+ * lane-E tickets, so the declaration named this edit `integration: combine-owned` rather than
1063
+ * reaching across a lane.
1064
+ *
1065
+ * β›” WITHOUT IT THE FEATURE SAVES NOTHING AND SAYS SO. `SheetGrid.tsx` reads
1066
+ * `const rules = (onRules ? tab.rules : localRules) ?? []`, so an unwired page falls back to a
1067
+ * per-session list and the sheet tells the user its rules last only as long as the tab stays
1068
+ * open. Both halves this depends on were already proven on the lane: the server keeps the rule
1069
+ * (`_clean_sheet` round-trips `kind` and `scale`) and `rules.ts::parseRange` reads the
1070
+ * `{col0,row0,col1,row1}` rect the server normalises a range into.
1071
+ *
1072
+ * ⭐ SAME DOOR AS `onCharts`. `rules` and the hidden bands are keys ON the tab, never cells, so
1073
+ * replacing the open tab and handing the result to `commitSheets` is one history step, one PUT
1074
+ * and one `rev` -- which is what makes a colour scale survive a reload and Ctrl+Z remove it.
1075
+ */
1076
+ const onRules = useCallback((rules: SheetRule[]) => {
1077
+ const base = bookRef.current;
1078
+ if (!base) return;
1079
+ const target = openTabId(base);
1080
+ if (!target) return;
1081
+ commitSheets(base.sheets.map((t) => (t.id === target ? { ...t, rules } : t)));
1082
+ }, [commitSheets, openTabId]);
1083
+
1084
+ /**
1085
+ * ⭐ AND `onHideBands` BESIDE IT, which lane A's declaration asked for in the same breath and for
1086
+ * the same reason: W51-T18 left hidden rows and columns on a session-local fallback for want of
1087
+ * this one wire. The patch is a partial, so a call that hides only rows must not erase the
1088
+ * hidden columns -- hence the two `??` guards rather than a spread of `patch`.
1089
+ */
1090
+ const onHideBands = useCallback((patch: { hiddenRows?: number[]; hiddenCols?: number[] }) => {
1091
+ const base = bookRef.current;
1092
+ if (!base) return;
1093
+ const target = openTabId(base);
1094
+ if (!target) return;
1095
+ commitSheets(base.sheets.map((t) => (t.id === target
1096
+ ? { ...t,
1097
+ hiddenRows: patch.hiddenRows ?? t.hiddenRows,
1098
+ hiddenCols: patch.hiddenCols ?? t.hiddenCols }
1099
+ : t)));
1100
+ }, [commitSheets, openTabId]);
1101
+
1102
  // ── the tab bar (wave-49 R7) ───────────────────────────────────────────────────────────────
1103
 
1104
  const onAddTab = useCallback(() => {
 
1197
  queueSave();
1198
  }, [applyLocal, queueSave]);
1199
 
1200
+ /**
1201
+ * Persist ONE NAMED CELL's binding AND recompute that one cell, so a save shows the number.
1202
+ *
1203
+ * ⭐⭐ W54-T35 β€” IT TAKES THE ADDRESS AS AN ARGUMENT NOW, AND THAT IS THE WHOLE REFACTOR. It
1204
+ * used to read `editAt`, which is the binding panel's own state and is empty while the drill is
1205
+ * open, so the drill's filter edit had no way through this door and would have had to build a
1206
+ * second writer: another `commitCells`, another `flushSave`, another recompute, and two places
1207
+ * to keep the save-then-compute ordering right. `onSaveBinding` below is now a two-line wrapper
1208
+ * that supplies `editAt`, so the panel's behaviour is byte-identical and there is still exactly
1209
+ * one writer of a cell binding on this page.
1210
+ *
1211
+ * ⚠ IT RETURNS A PROMISE THAT SETTLES WHEN THE RECOMPUTE IS DONE. The panel ignores it, as it
1212
+ * always has; the drill awaits it, because it has to re-read the rows AFTER the server holds the
1213
+ * new binding. Nothing about the panel's path changed to make that true.
1214
+ *
1215
+ * ⭐⭐ W54-T32 (owner instruction 9) β€” THE SHIMMER USED TO RUN UNTIL SOMEBODY PRESSED REFRESH.
1216
+ * Owner: *"When I Save a database cell in Sheet, it shows the loading animation but never loads
1217
+ * until I press Refresh."* The comment that stood here recorded W53's R10 as the reason ("a
1218
+ * snapshot"), and it was an accurate description of a defect: the cell was committed `stale`,
1219
+ * `stale` is exactly what `SheetGrid.tsx` paints the moving band for, and nothing on any path
1220
+ * afterwards ever resolved it. R10 says a bound cell stores its value as LAST COMPUTED; it does
1221
+ * not say the save must decline to compute one.
1222
+ *
1223
+ * β›” AND IT IS NOT A WHOLE-WORKBOOK REFRESH. `refreshWorkbook` would answer, and it is the wrong
1224
+ * answer: it recomputes every bound cell and every formula in the document, drops the undo
1225
+ * stack and the dirty set, and repaints every tab, to deliver the one number this person asked
1226
+ * for. `computeCell` is the one-cell door.
1227
+ *
1228
+ * β›”β›” `flushSave` FIRST, AND IT IS THE WHOLE ORDERING. `commitCells` queues a DEBOUNCED save,
1229
+ * so the binding is not on the server when this function would otherwise call for it; the
1230
+ * server reads the STORED cell, so it would compute the cell as it was BEFORE the edit, or
1231
+ * refuse `cell_missing` on a cell that has never been saved at all.
1232
+ *
1233
+ * ⚠ THE ANSWER IS DROPPED IF THE CELL MOVED WHILE THE ROUND TRIP WAS OUT. The binding object
1234
+ * committed below is compared by IDENTITY against what the cell now holds, so an undo, a retype
1235
+ * or a second binding save during those few tens of milliseconds wins over an answer that
1236
+ * describes a cell that no longer exists.
1237
+ */
1238
+ const saveBindingAt = useCallback((addr: string, binding: Record<string, unknown>) => {
1239
  // ⚠ IT GOES THROUGH `commitCells` LIKE EVERY OTHER WRITE (W50-T18). It used to build its
1240
  // own `sheets` array and PUT directly, which was correct while it was the only writer; now
1241
  // that a keystroke also saves, two writers each sending the `rev` they last read is exactly
1242
  // the race `put_workbook` refuses. One door, one queue, one rev.
1243
+ if (!addr) return Promise.resolve();
1244
+ const base = bookRef.current;
1245
+ const target = base?.sheets.find((t) => t.id === tabIdRef.current)?.id
1246
+ ?? base?.sheets[0]?.id ?? "";
1247
  // A newly bound cell is STALE, never fresh: nothing has been computed yet, and marking it
1248
+ // fresh would show an empty value wearing the mark that means "this number is current". The
1249
+ // recompute below is what takes it out of that state, in one round trip.
1250
  commitCells({
1251
  [addr]: { kind: "bound" as const, state: "stale" as const, binding, value: null },
1252
  });
1253
+ if (!base || !target) return Promise.resolve();
1254
+ const wid = base.id;
1255
+ return (async () => {
1256
+ await flushSave();
1257
+ const settled = bookRef.current;
1258
+ if (!settled || settled.id !== wid) return;
1259
+ // β›”β›” THE SAVE HAS TO HAVE LANDED BEFORE THE RECOMPUTE MAY SPEAK. If it did not, the cell
1260
+ // is not on the server, so the compute below would be answered `cell_missing` truthfully
1261
+ // and that sentence would then paint over the save path's own, which is the one that names
1262
+ // what actually went wrong. So this returns SILENTLY: the drain already wrote the accurate
1263
+ // notice, and a second sentence for one failure is worse than none.
1264
+ if (!savedCleanRef.current) return;
1265
+ const got = await computeCell(wid, addr, target);
1266
+ const live = bookRef.current;
1267
+ if (!live || live.id !== wid) return;
1268
+ if (!got.ok) {
1269
+ // ⚠ A COMPUTE THAT FAILS ON ITS OWN MERITS AFTER A SAVE THAT DID LAND still speaks, and
1270
+ // this is the case the line was written for: an unreadable database, a scope that cannot
1271
+ // be compiled, a mirror still syncing. Nothing else has written a sentence about it.
1272
+ setNotice(got.message);
1273
+ return;
1274
+ }
1275
+ const held = live.sheets.find((t) => t.id === target)?.cells?.[addr];
1276
+ if (!held || held.binding !== binding) return;
1277
+ applyLocal({
1278
+ ...withCells(live, target, { [addr]: got.value.cell }),
1279
+ rev: got.value.rev || live.rev,
1280
+ });
1281
+ })();
1282
+ }, [applyLocal, commitCells, flushSave]);
1283
+
1284
+ /** The binding panel's Save. It names the cell the panel is editing, and nothing else. */
1285
+ const onSaveBinding = useCallback((binding: Record<string, unknown>) => {
1286
+ const addr = editAt;
1287
+ if (!addr) return;
1288
+ setEditAt("");
1289
+ void saveBindingAt(addr, binding);
1290
+ }, [editAt, saveBindingAt]);
1291
+
1292
+ /**
1293
+ * ⭐⭐ W54-T35 (owner instruction 8, ruling R8) β€” A FILTER CHANGED INSIDE THE DRILL.
1294
+ *
1295
+ * Owner: *"they should be able to change the filter there too."* The only thing that changes is
1296
+ * `scope.filter`; everything else the binding says about the cell (its database, its aggregate,
1297
+ * its period, its drag behaviour) is carried over verbatim, because the reader edited a filter
1298
+ * and not a cell.
1299
+ *
1300
+ * β›” `scope` IS SPREAD RATHER THAN REBUILT, WHICH IS WHAT KEEPS R11's `adoptedFrom` ALIVE. A
1301
+ * filter adopted from a purged view carries that provenance in its scope and the binding panel
1302
+ * is careful to re-save it; a scope rebuilt here as `{ filter }` would erase it, and the
1303
+ * sentence in the panel that explains where the filter came from would silently disappear the
1304
+ * first time somebody edited the filter from the drill.
1305
+ *
1306
+ * β›” AND A VIEW-BOUND CELL IS REFUSED HERE AS WELL AS IN THE DRILL. R8: a saved view already
1307
+ * fixes the rows. The drill offers no editor for one, and this is the second half of that rule,
1308
+ * so a caller reaching the handler another way cannot fork a cell off its view.
1309
+ */
1310
+ const onDrillFilterChange = useCallback((addr: string, tree: FilterTree) => {
1311
+ const base = bookRef.current;
1312
+ const target = base?.sheets.find((t) => t.id === tabIdRef.current) ?? base?.sheets[0] ?? null;
1313
+ const held = target?.cells?.[addr];
1314
+ const binding = held?.binding as Record<string, unknown> | undefined;
1315
+ if (!binding) return Promise.resolve();
1316
+ const scope = (binding.scope ?? {}) as Record<string, unknown>;
1317
+ if (typeof scope.view_id === "string" && scope.view_id.trim()) return Promise.resolve();
1318
+ return saveBindingAt(addr, { ...binding, scope: { ...scope, filter: tree } });
1319
+ }, [saveBindingAt]);
1320
 
1321
  // ⭐ R17 is enforced BEFORE the popup opens, not inside it. `drillAffordance` already disables
1322
  // the control for a formula or a literal and names the reason; this guard is the second half of
 
1329
  return;
1330
  }
1331
  setNotice("");
1332
+ // ⭐ W54-T34: the busy state goes on in the SAME act as the open, so the control changes in the
1333
+ // same frame the surface appears. `DrillModal` takes it off again through `onSettled`.
1334
+ setDrillLoading(true);
1335
  setDrillAt(addr);
1336
  }, []);
1337
 
 
1716
 
1717
  const tab = book?.sheets.find((t) => t.id === tabId) ?? book?.sheets[0] ?? null;
1718
 
1719
+ /**
1720
+ * ⭐⭐ W54-T35 β€” WHICH ROWS THE DRILLED CELL ASKED FOR, read off the LOCAL workbook.
1721
+ *
1722
+ * ⚠ THE LOCAL COPY RATHER THAN THE DRILL ANSWER, AND THE DIFFERENCE IS THE POINT. The answer
1723
+ * describes what the server used for the rows on screen; this describes what the cell holds
1724
+ * now, so the sentence in the drill moves the instant an edit is committed here and does not
1725
+ * wait on a round trip to say what the reader just did.
1726
+ *
1727
+ * ⚠ NOT MEMOISED, ON PURPOSE. `DrillModal` depends on the KIND and on the tree's identity, not
1728
+ * on this object's, precisely so that a page re-rendering for an unrelated reason cannot churn
1729
+ * the drill's callbacks. The tree itself is the one held on the binding, so its identity is
1730
+ * stable until the cell is rewritten.
1731
+ */
1732
+ const drillBinding = (drillAt ? tab?.cells?.[drillAt]?.binding : null) as
1733
+ Record<string, unknown> | null | undefined;
1734
+ const drillBindingScope = (drillBinding?.scope ?? null) as Record<string, unknown> | null;
1735
+ const drillViewId = typeof drillBindingScope?.view_id === "string"
1736
+ ? drillBindingScope.view_id.trim() : "";
1737
+ const drillScope: DrillCellScope | null = !drillBindingScope
1738
+ ? null
1739
+ : drillViewId
1740
+ ? {
1741
+ kind: "view",
1742
+ name: typeof drillBindingScope.view_name === "string" ? drillBindingScope.view_name : "",
1743
+ }
1744
+ : {
1745
+ kind: "filter",
1746
+ tree: (drillBindingScope.filter as FilterTree | null | undefined)
1747
+ ?? { conj: "and", nodes: [] },
1748
+ };
1749
+
1750
  return (
1751
  // β›” `data-view-kind` STAYS IN THIS FILE. `verify_wiring.py`'s W49-W1 row asserts
1752
  // `data-view-kind={SHEET_VIEW_KIND}` inside `sheet/SheetPage.tsx` by path, so moving the rail
1753
  // out without moving this attribute up would have turned a green wiring row red for a reason
1754
  // that has nothing to do with what it guards. R2's one view kind is a property of the PAGE.
1755
+ // ⭐ W54-T34: `data-drill` is the ONE hook the stylesheet needs to reach a button in a file
1756
+ // this ticket does not own. The action bar is a plain descendant of this element (it is not
1757
+ // portalled), so `.sheet-page[data-drill="loading"] .sheet-action-bar .sheet-action` matches.
1758
+ <div
1759
+ className="sheet-page"
1760
+ data-view-kind={SHEET_VIEW_KIND}
1761
+ data-drill={drillLoading ? "loading" : undefined}
1762
+ >
1763
  <SheetRail
1764
  importRequest={importRequest}
1765
  loading={loading}
 
1849
  <SheetGrid
1850
  workbook={book}
1851
  tab={tab}
1852
+ // ⭐ W54-T34: a drill in flight is a round trip like a refresh, and the cell action bar
1853
+ // reads exactly one prop for "a round trip is in flight". The page root's `data-drill`
1854
+ // is what tells the two apart in the stylesheet.
1855
+ busy={busy || drillLoading}
1856
  onEdit={onEdit}
1857
  onViewRows={onViewRows}
1858
  onRefresh={onRefresh}
 
1867
  onGrow={onGrow}
1868
  onFreeze={onFreeze}
1869
  onColumnWidth={onColumnWidth}
1870
+ // ⭐ W54-T10 / lane B β€” the Insert tab's chart door. It sits AFTER
1871
+ // `onCommit={commitCells}` on purpose: `verify_wiring`'s W50-T17 row scans forward
1872
+ // from `<SheetGrid` to that prop and refuses an intervening self-closing tag.
1873
+ onCharts={onCharts}
1874
+ // ⭐⭐ W54-T05's combine-owned handover. Same slot rule as `onCharts` above: after
1875
+ // `onCommit={commitCells}`, with no self-closing tag in between, or `verify_wiring`'s
1876
+ // W50-T17 row reds a ticket this does not own.
1877
+ onRules={onRules}
1878
+ onHideBands={onHideBands}
1879
  // ⭐⭐ W51-T08 / CONTRACT C1 β€” THE FOUR SEAM PROPS THE RIBBON IS FED THROUGH.
1880
  //
1881
  // ⚠ THEY SIT AFTER `onCommit` AND THAT IS LOAD BEARING, not tidiness. `verify_wiring`'s
 
2116
  workbookId={book.id}
2117
  addr={drillAt}
2118
  label={drillAt}
2119
+ onClose={() => { setDrillAt(""); setDrillLoading(false); }}
2120
+ // β›” AFTER `onClose`, AND THAT IS LOAD BEARING. `verify_wiring`'s W50-W1 row matches
2121
+ // `<DrillModal` forward to `onClose={` and refuses an intervening `/>`; a prop placed
2122
+ // before it would red a row this ticket does not own.
2123
+ onSettled={() => setDrillLoading(false)}
2124
+ // ⭐ W54-T35, and both props sit after `onClose` for the reason the note above gives.
2125
+ cellScope={drillScope}
2126
+ onFilterChange={onDrillFilterChange}
2127
  />
2128
  )}
2129
  </div>
web/src/sheet/bindingRefs.ts ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // sheet/bindingRefs.ts β€” WHERE A BINDING KEEPS CELL REFERENCES, AND HOW THEY MOVE (wave 54,
2
+ // W54-T18, contract C3, ruling R6).
3
+ //
4
+ // ⭐⭐ THIS FILE EXISTS SO THERE IS EXACTLY ONE ANSWER TO "WHICH PARTS OF A BINDING ARE CELL
5
+ // REFERENCES". Today the answer is one slot, `period.ref`. C3 promises a second one β€” a filter
6
+ // value read out of a cell β€” and the moment that lands, a codebase that answered the question
7
+ // inline inside `dragBoundCell` would grow a SECOND answer somewhere else, and the two would
8
+ // agree until the day they did not. Adding that slot here is ONE ENTRY in `REF_SLOTS` and no edit
9
+ // anywhere else: every door that copies, fills or pastes a bound cell already comes through
10
+ // `shiftBindingRefs`.
11
+ //
12
+ // β›”β›” THE `$` IN THE STORED STRING **IS** THE PER-AXIS ABSOLUTE FLAG, AND NO SECOND
13
+ // REPRESENTATION OF IT IS ADDED HERE. C3 is worded "stored with explicit absolute/relative flags
14
+ // per axis", which reads like an invitation to add `colAbs` / `rowAbs` booleans to the stored
15
+ // binding. It was considered and it is REFUSED. Excel already encodes those two flags, per axis,
16
+ // in the `$` characters of the text; `a1.ts::CellRef` already parses them into real booleans;
17
+ // `core/sheets.py` already stores and round-trips the string. Storing the flags a second time
18
+ // would create two records of one fact, which drift the first time anything writes one without
19
+ // the other β€” and the thing most likely to write only one is a hand edit in the binding editor.
20
+ // So the flags are EXPOSED through the API, on the parsed shape every slot carries, and stored
21
+ // once, in the character the reader typed.
22
+ //
23
+ // β›” ANCHORING IS NEVER RE-DERIVED HERE. `a1.ts` owns what a `$` pins, the clamp at row 1 and
24
+ // column A, and the quoted sheet name. A second opinion about which of `LOG10(`, `'Q1 plan'!A1`
25
+ // and `$B$5` is a reference is precisely the failure this file is built to make impossible.
26
+ //
27
+ // β›” NOTHING HERE MAY IMPORT OUTSIDE `src/sheet/`. tsc's emitted ROOT moves with the import graph,
28
+ // so one import of `../../ui` would drop every emitted module a level down and break every
29
+ // `require` path the battery's Sheet proofs use. `./a1` only.
30
+
31
+ import { formatRef, parseRef, shiftRef } from "./a1";
32
+ import type { CellRef } from "./a1";
33
+
34
+ /**
35
+ * ⭐ THE ONE-REFERENCE RULE. Shift one reference's TEXT by a row and column delta, `$` honoured
36
+ * per axis, by handing the whole question to `a1.ts`.
37
+ *
38
+ * ⚠ Text that is not a reference comes back untouched rather than mangled or emptied. A drag is
39
+ * not the place to discover that a stored pointer was malformed, and blanking it would lose the
40
+ * only copy of what the reader actually wrote.
41
+ */
42
+ export const shiftRefText = (text: string, dRow: number, dCol: number): string => {
43
+ const src = String(text ?? "").trim();
44
+ if (!src || (!dRow && !dCol)) return src;
45
+ const parsed = parseRef(src);
46
+ if (!parsed) return src;
47
+ return formatRef(shiftRef(parsed, dRow, dCol));
48
+ };
49
+
50
+ /**
51
+ * One place inside a binding where a cell reference is allowed to live.
52
+ *
53
+ * ⚠ `pinnedAt` IS A LOCK, NOT A VALIDITY TEST. R9's locked period copies verbatim through every
54
+ * door, so a pinned slot is enumerated (the reader can still see what it points at) and simply
55
+ * never shifted.
56
+ */
57
+ interface RefSlotSpec {
58
+ /** The dotted name, for anything that has to SAY which slot it means. */
59
+ readonly key: string;
60
+ /** The path from the binding root to the reference's own string. */
61
+ readonly path: readonly string[];
62
+ /** A path to a truthy value that freezes this slot. Absent means nothing freezes it. */
63
+ readonly pinnedAt?: readonly string[];
64
+ }
65
+
66
+ /**
67
+ * ⭐⭐ THE REGISTRY. Everything this module knows about binding references is these entries.
68
+ *
69
+ * C3's filter-value-from-a-cell is a future entry here, not a future edit to `dragBoundCell`:
70
+ * give it a `path` and, if a lock governs it, a `pinnedAt`, and every copy, fill, Ctrl+D, Ctrl+R
71
+ * and paste door starts shifting it correctly on the same commit.
72
+ */
73
+ const REF_SLOTS: readonly RefSlotSpec[] = [
74
+ { key: "period.ref", path: ["period", "ref"], pinnedAt: ["period", "locked"] },
75
+ ];
76
+
77
+ /** What one occupied slot IS, right now, with its anchoring already parsed out per axis. */
78
+ export interface BindingRefSlot {
79
+ readonly key: string;
80
+ readonly path: readonly string[];
81
+ /** The stored text, trimmed exactly as `types.ts::bindingPeriod` trims it. */
82
+ readonly text: string;
83
+ /**
84
+ * The parsed shape, or `null` when the text is not a reference at all. ⭐ THIS IS WHERE THE
85
+ * PER-AXIS ABSOLUTE FLAGS ARE EXPOSED: `colAbs` and `rowAbs` are real booleans here, read out
86
+ * of the `$` characters that store them.
87
+ */
88
+ readonly parsed: CellRef | null;
89
+ /** True when a lock holds this slot still, whatever the delta (R9). */
90
+ readonly pinned: boolean;
91
+ }
92
+
93
+ const asRecord = (value: unknown): Record<string, unknown> | null =>
94
+ value && typeof value === "object" && !Array.isArray(value)
95
+ ? (value as Record<string, unknown>)
96
+ : null;
97
+
98
+ /** Read the string at a path, trimmed. Empty when any step of the path is missing. */
99
+ const readAt = (root: Record<string, unknown>, path: readonly string[]): string => {
100
+ let node: Record<string, unknown> | null = root;
101
+ for (let i = 0; i < path.length - 1; i += 1) {
102
+ node = node ? asRecord(node[path[i]]) : null;
103
+ }
104
+ const leaf = node ? node[path[path.length - 1]] : undefined;
105
+ return typeof leaf === "string" ? leaf.trim() : "";
106
+ };
107
+
108
+ /**
109
+ * Whether the flag at a path is set.
110
+ *
111
+ * β›” IT IS STRICT `=== true`, WHICH IS `types.ts::bindingPeriod`'s OWN TEST AND NOT AN ACCIDENT.
112
+ * A missing key reads FALSE, the permissive answer: a period stored before the lock toggle
113
+ * existed must not start refusing to shift with nothing on screen saying why.
114
+ */
115
+ const flagAt = (root: Record<string, unknown>, path: readonly string[] | undefined): boolean => {
116
+ if (!path || path.length === 0) return false;
117
+ let node: Record<string, unknown> | null = root;
118
+ for (let i = 0; i < path.length - 1; i += 1) {
119
+ node = node ? asRecord(node[path[i]]) : null;
120
+ }
121
+ return (node ? node[path[path.length - 1]] : false) === true;
122
+ };
123
+
124
+ /**
125
+ * Write a value at a path, COPYING every record along the way.
126
+ *
127
+ * β›” NOTHING IS MUTATED. `dragBoundCell` is a pure function over a workbook and the cell it is
128
+ * handed is still on the sheet; writing through would edit the SOURCE cell while copying it.
129
+ */
130
+ const writeAt = (
131
+ root: Record<string, unknown>, path: readonly string[], value: string,
132
+ ): Record<string, unknown> => {
133
+ if (path.length === 1) return { ...root, [path[0]]: value };
134
+ const head = path[0];
135
+ const inner = asRecord(root[head]) ?? {};
136
+ return { ...root, [head]: writeAt(inner, path.slice(1), value) };
137
+ };
138
+
139
+ /**
140
+ * Every slot in this binding that actually HOLDS a reference, in registry order.
141
+ *
142
+ * ⚠ An empty slot is not reported. "The slots that exist" means the ones the binding carries, not
143
+ * the ones the registry knows how to carry β€” a caller counting them is asking about this binding.
144
+ */
145
+ export const bindingRefSlots = (binding: unknown): BindingRefSlot[] => {
146
+ const record = asRecord(binding);
147
+ if (!record) return [];
148
+ const out: BindingRefSlot[] = [];
149
+ for (const spec of REF_SLOTS) {
150
+ const text = readAt(record, spec.path);
151
+ if (!text) continue;
152
+ out.push({
153
+ key: spec.key,
154
+ path: spec.path,
155
+ text,
156
+ parsed: parseRef(text),
157
+ pinned: flagAt(record, spec.pinnedAt),
158
+ });
159
+ }
160
+ return out;
161
+ };
162
+
163
+ /** What `shiftBindingRefs` did, so a caller can say whether the binding is the one it copied. */
164
+ export interface BindingRefShift {
165
+ /** The binding, rewritten. The SAME object when nothing moved, so `===` is a valid check. */
166
+ binding: Record<string, unknown>;
167
+ /** At least one slot's text is different from the one it was copied from. */
168
+ changed: boolean;
169
+ /** The `key` of each slot that actually moved. */
170
+ moved: string[];
171
+ }
172
+
173
+ /**
174
+ * ⭐⭐ THE DOOR. Shift every reference this binding holds by one delta, `$` honoured per axis,
175
+ * locked slots left verbatim.
176
+ *
177
+ * ⚠ `changed` IS LOAD-BEARING FOR THE CALLER AND NOT MERELY INFORMATIONAL. A bound cell whose
178
+ * binding CHANGED drops its last computed value, because showing the source's number under a
179
+ * different reference is a wrong number wearing a plausible mark; a verbatim copy keeps it. So a
180
+ * slot whose shifted text equals its stored text does NOT count as moved, and neither does a
181
+ * pinned one, an empty one or an unparseable one.
182
+ */
183
+ export const shiftBindingRefs = (
184
+ binding: Record<string, unknown>, dRow: number, dCol: number,
185
+ ): BindingRefShift => {
186
+ let out = binding;
187
+ const moved: string[] = [];
188
+ if (!asRecord(binding)) return { binding, changed: false, moved };
189
+ for (const slot of bindingRefSlots(binding)) {
190
+ if (slot.pinned) continue;
191
+ const next = shiftRefText(slot.text, dRow, dCol);
192
+ if (next === slot.text) continue;
193
+ out = writeAt(out, slot.path, next);
194
+ moved.push(slot.key);
195
+ }
196
+ return { binding: out, changed: moved.length > 0, moved };
197
+ };
web/src/sheet/cellBorders.ts ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------------------------
2
+ // sheet/cellBorders.ts β€” THE PER-CELL BORDER PAINT, LIFTED OUT OF `SheetGrid.tsx`.
3
+ //
4
+ // ⭐ WAVE 54 BASE KIT β€” this is a SEAM, not a redesign. Every line below was moved verbatim out of
5
+ // `SheetGrid.tsx::paintCell` step 4 so that the border work and the rest of the hub file can be
6
+ // edited by two different lanes at once. The move itself changed nothing; W54-T01 then changed the
7
+ // LEFT and TOP geometry here, for the reason written on `paintCellBorders` below. Order of sides,
8
+ // stroke colour, line width, the single stroke and the save/restore pair are all still the ones
9
+ // that came over.
10
+ //
11
+ // β›” `tokenColour` CAME ALONG, AND THAT IS A FENCE DECISION RATHER THAN A DESIGN ONE. The stroke
12
+ // setup reads `--lp-line-strong` through `SheetGrid.tsx`'s own memoised token resolver, which was
13
+ // a module-local `const` there and is not exported. The three ways out were: import it back from
14
+ // `SheetGrid.tsx` (a cycle, and a NEW export on the file this split exists to shrink), copy it
15
+ // (two caches for one palette), or move the definition here and let `SheetGrid.tsx` import it.
16
+ // The third is the only one that is a pure move, so it is the one taken. `sheet/colors.ts` is the
17
+ // tidier home and this file's editing fence does not reach it β€” recorded here rather than done
18
+ // behind the fence, the same way `sheet/index.ts` records W49-T01's route constant.
19
+ // ---------------------------------------------------------------------------------------------
20
+
21
+ import type { CellBorder } from "./types";
22
+
23
+ /**
24
+ * A `--lp-*` token name resolved to the hue the document currently gives it.
25
+ *
26
+ * ⭐ MEMOISED, BECAUSE `drawCell` RUNS PER CELL PER FRAME. `getComputedStyle` forces a style
27
+ * recalculation on every call, and a 26 by 40 viewport of styled cells would ask for it a
28
+ * thousand times a frame. The tokens are declared once on `:root` and nothing in this app swaps
29
+ * a palette at runtime, so one read each is the whole of it.
30
+ *
31
+ * ⚠ THE FALLBACK IS THE INK, NOT BLACK. A token that has been renamed out of the palette must
32
+ * still leave a readable cell rather than an invisible one.
33
+ */
34
+ const TOKEN_CACHE = new Map<string, string>();
35
+ export const tokenColour = (token: string, fallback: string): string => {
36
+ if (!token) return fallback;
37
+ if (token.startsWith("#")) return token;
38
+ const cached = TOKEN_CACHE.get(token);
39
+ if (cached !== undefined) return cached || fallback;
40
+ const value = getComputedStyle(document.documentElement).getPropertyValue(token).trim();
41
+ TOKEN_CACHE.set(token, value);
42
+ return value || fallback;
43
+ };
44
+
45
+ /**
46
+ * THE CELL'S OWN BORDERS, painted onto `rect`.
47
+ *
48
+ * β›”β›” THE INSET IS ASYMMETRIC ON PURPOSE: LEFT AND TOP SIT A PIXEL FURTHER IN THAN RIGHT AND
49
+ * BOTTOM, AND TIDYING ALL FOUR BACK TO A SYMMETRIC HALF PIXEL RE-BREAKS THE FEATURE. Before
50
+ * W54-T01 all four sides were laid on the cell's own edge at a half pixel, and "All sides" then
51
+ * painted a visible right and bottom with NO left and NO top. Two independent mechanisms of the
52
+ * grid library eat those two strokes, and both of them are escaped by the same one pixel move
53
+ * inward:
54
+ * 1. THE DAMAGE CLIP. `data-grid-render.cells` clips each cell to a box that starts at
55
+ * `cellX + 1` and `drawY + 1` while running flush to the right and bottom edges, so
56
+ * anything we draw left of `cellX + 1` or above `drawY + 1` is discarded outright. A nested
57
+ * clip can only ever intersect that one, so it cannot be widened from in here.
58
+ * 2. THE LIBRARY'S OWN GRID LINES. `data-grid-render` draws its light grid AFTER the cells, on
59
+ * the same context, at exactly `cellX + 0.5` and `drawY + 0.5` in the theme's border
60
+ * colour. Those are the very device pixels our left and top strokes used to occupy, so even
61
+ * an unclipped stroke there would be painted over on every frame. The right stroke at
62
+ * `width - 0.5` and the bottom at `height - 0.5` land a pixel inside and are never touched,
63
+ * which is exactly why the bug looked like "only two sides work".
64
+ *
65
+ * ⚠ THE OFFSET IS 1.5 AND NOT 1.0. At 1.5 the stroke covers one whole device pixel column or row
66
+ * inside the clip and clear of the library's line, at full intensity. At 1.0 a one pixel wide
67
+ * stroke straddles the clip boundary: half of it is clipped away and the other half is overpainted
68
+ * by the library's grid line, giving a faint smear rather than a border.
69
+ *
70
+ * ⚠ A STROKE POSITION IS NOT A RUN EXTENT, and conflating the two is what hid this for two waves.
71
+ * `strokeX*` / `strokeY*` say WHERE a line lies along its own thin axis. `runFrom*` / `runTo*` say
72
+ * how far it travels along the other axis. The runs start at the cell's own half pixel edge and
73
+ * let the damage clip trim them, which is what makes all four corners meet on a fully covered
74
+ * pixel with no antialiased gap.
75
+ *
76
+ * ⚠ THE CALLER PAINTS THIS OUTSIDE ITS TEXT CLIP, so a side lands on the cell edge rather than
77
+ * deep inside it. That is the caller's business and the reason the call sits where it does in
78
+ * `paintCell`; this function only assumes it is free to save and restore the context. The frozen
79
+ * band needs no separate handling: `paintFrozenCell` delegates to `paintCell`, so it is the same
80
+ * paint.
81
+ *
82
+ * ⚠ AN ABSENT `border` IS NOT AN ERROR, it is the ordinary case: {@link CellBorder} carries only
83
+ * the sides that are ON, and a cell with no border at all has no `border` key. The early return
84
+ * is the `if (border)` guard the call site used to hold, said one scope down.
85
+ */
86
+ export function paintCellBorders(
87
+ ctx: CanvasRenderingContext2D,
88
+ rect: { x: number; y: number; width: number; height: number },
89
+ border: CellBorder | undefined,
90
+ ): void {
91
+ if (!border) return;
92
+ ctx.save();
93
+ ctx.strokeStyle = tokenColour("--lp-line-strong", "#c9ced8");
94
+ ctx.lineWidth = 1;
95
+ ctx.beginPath();
96
+ // Where each side's thin line lies. Left and top are inset a further pixel to clear the damage
97
+ // clip and the library's own grid line; right and bottom already sit inside both.
98
+ const strokeXLeft = rect.x + 1.5;
99
+ const strokeYTop = rect.y + 1.5;
100
+ const strokeXRight = rect.x + rect.width - 0.5;
101
+ const strokeYBottom = rect.y + rect.height - 0.5;
102
+ // How far each side travels. Starts on the cell's own edge so the clip trims it to a whole
103
+ // pixel and the corners meet the perpendicular stroke exactly.
104
+ const runFromX = rect.x + 0.5;
105
+ const runToX = strokeXRight;
106
+ const runFromY = rect.y + 0.5;
107
+ const runToY = strokeYBottom;
108
+ if (border.top) { ctx.moveTo(runFromX, strokeYTop); ctx.lineTo(runToX, strokeYTop); }
109
+ if (border.bottom) { ctx.moveTo(runFromX, strokeYBottom); ctx.lineTo(runToX, strokeYBottom); }
110
+ if (border.left) { ctx.moveTo(strokeXLeft, runFromY); ctx.lineTo(strokeXLeft, runToY); }
111
+ if (border.right) { ctx.moveTo(strokeXRight, runFromY); ctx.lineTo(strokeXRight, runToY); }
112
+ ctx.stroke();
113
+ ctx.restore();
114
+ }
web/src/sheet/cellStyleOps.ts ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------------------------
2
+ // sheet/cellStyleOps.ts β€” THE STYLE WRITERS, LIFTED OUT OF `sheetState.ts`.
3
+ //
4
+ // ⭐ WAVE 54 BASE KIT β€” a SEAM, not a redesign. Every function below was moved verbatim out of
5
+ // `sheetState.ts`, comments and all, so that the lanes that write styles and the lanes that write
6
+ // values stop meeting in one 2,100 line file. `sheetState.ts` imports them straight back and
7
+ // re-exports them under their own names, so no consumer's import line changed and no behaviour did.
8
+ //
9
+ // β›” `pasteCells` DID NOT COME WITH THEM, ON PURPOSE. It writes VALUES, and it happens to carry a
10
+ // style along with each one; a paste is not a style act. It stays in `sheetState.ts` beside the
11
+ // other bulk value doors, which is where every reader already looks for it.
12
+ //
13
+ // ⚠ THE IMPORT OF `cellAt` POINTS BACK AT `sheetState.ts`, WHICH IS A CYCLE, AND IT IS SAFE FOR
14
+ // ONE REASON WORTH WRITING DOWN. Nothing here reads that module at LOAD time: `cellAt` is called
15
+ // from inside a function body, so by the time anybody calls `styleCells` both modules are fully
16
+ // evaluated. `verify_api.py` compiles this file to CommonJS beside `sheetState.js` and RUNS it,
17
+ // which is where a load-time cycle would show up as `undefined is not a function`.
18
+ //
19
+ // ⚠ AND THAT RUN HAS NOT HAPPENED YET, SO SAY SO RATHER THAN IMPLY IT. The wave-54 base worktree
20
+ // carries no `web/node_modules`, so the compile-and-run half of that gate could not execute on
21
+ // the change that created this file. The cycle is safe by CONSTRUCTION, which is an argument;
22
+ // the first tree with dependencies installed is where it becomes evidence.
23
+ //
24
+ // β›” AND NOTHING HERE MAY IMPORT OUTSIDE `src/sheet/`. tsc's emitted ROOT moves with the import
25
+ // graph, so one `../ui/*` import would drop every emitted module a level down and break every
26
+ // `require` path the battery's Sheet proofs use. [[tsc-outdir-root-moves-with-the-import-graph]]
27
+ // ---------------------------------------------------------------------------------------------
28
+
29
+ import type { Cell, CellStyle, CellStylePatch, SheetTab } from "./types";
30
+ import { applyStylePatch } from "./types";
31
+ import { cellAt } from "./sheetState";
32
+ import type { BulkEdit } from "./sheetState";
33
+
34
+ // ═════════════════════════════════════════════════════════════════════════════════════════════
35
+ // W51-T16 β€” THE STYLE ENGINE AND THE RIBBON'S ACTS, ALL OF THEM PURE (contract C2, D-641).
36
+ //
37
+ // ⭐⭐ WHY THE PURE HALF IS HERE AND NOT IN THE COMPONENT. `SheetGrid.tsx` imports glide, which
38
+ // cannot be loaded under node, so anything living there can only ever be GREPPED by a gate. Every
39
+ // function below is executed by `verify_api.py`'s compile-and-run harness instead, which is what
40
+ // lets the battery prove that AutoSum picks the right range and that styling a blank block leaves
41
+ // `handTypedCount` alone, rather than proving that the words appear in a file.
42
+ //
43
+ // β›”β›” THE ONE NUMBER THIS SECTION MUST NOT MOVE. The sheet PRINTS its hand typed count on the
44
+ // screen (`handTypedLabel`, `.sheet-grid-literals`), and `handTypedCount` counts every
45
+ // `kind: "literal"` cell. So a styled blank is `kind: "empty"` and nothing here may take a
46
+ // shortcut through `literal`: bolding twenty blank cells and claiming twenty typed values would
47
+ // be a lie the owner reads straight off the header.
48
+ // ═════════════════════════════════════════════════════════════════════════════════════════════
49
+
50
+ /**
51
+ * ⭐⭐ D-641, AND IT IS THE WHOLE TICKET: FORMATTING APPLIES TO EMPTY CELLS.
52
+ *
53
+ * W50-T19's `applyStyle` carried `if (!cell) continue`, so selecting three blank cells and
54
+ * pressing Borders painted nothing. It could not do otherwise at the time: creating a cell would
55
+ * have meant `kind: "literal"`, and the count on the header would have risen by three. C2's
56
+ * `empty` kind is what removes that trade.
57
+ *
58
+ * β›” IT PRUNES ITS OWN CREATIONS. A patch that leaves an empty cell with no style at all removes
59
+ * the cell rather than storing `{kind: "empty", state: "fresh"}`, which is a document the server
60
+ * would keep forever and which means exactly what an absence means.
61
+ *
62
+ * ⚠ R19 / R20, DECIDED IN W50-T19 AND UNCHANGED: styling a BOUND cell is allowed and is NOT a
63
+ * conversion. A colour changes nothing about where the value comes from, so a cell's KIND is
64
+ * deliberately not consulted here at all β€” the opposite of what R5 (W52-T09) made every EDIT
65
+ * door do, which is write a bound cell exactly as it writes any other one.
66
+ */
67
+ export const styleCells = (
68
+ tab: SheetTab | null | undefined,
69
+ addrs: readonly string[],
70
+ patch: CellStylePatch,
71
+ ): BulkEdit => {
72
+ const edits: Record<string, Cell | null> = {};
73
+ for (const addr of addrs) {
74
+ const cell = cellAt(tab, addr);
75
+ const style = applyStylePatch(cell?.style, patch);
76
+ if (!cell) {
77
+ // THE LINE D-641 ASKED FOR. A blank address becomes a style-only cell, and only when the
78
+ // patch actually left a style on it.
79
+ if (style) edits[addr] = { kind: "empty", state: "fresh", style };
80
+ continue;
81
+ }
82
+ if (cell.kind === "empty" && !style && !cell.validation) {
83
+ edits[addr] = null;
84
+ continue;
85
+ }
86
+ const next: Cell = { ...cell };
87
+ if (style) next.style = style;
88
+ else delete next.style;
89
+ edits[addr] = next;
90
+ }
91
+ return { edits };
92
+ };
93
+
94
+ /**
95
+ * CLEAR FORMATS: the value stays, the styling goes. A cell that was ONLY styling disappears with
96
+ * it, because a `kind: "empty"` cell carrying no style is an absence written down.
97
+ */
98
+ export const clearFormats = (
99
+ tab: SheetTab | null | undefined,
100
+ addrs: readonly string[],
101
+ ): BulkEdit => {
102
+ const edits: Record<string, Cell | null> = {};
103
+ for (const addr of addrs) {
104
+ const cell = cellAt(tab, addr);
105
+ if (!cell || !cell.style) continue;
106
+ if (cell.kind === "empty" && !cell.validation) {
107
+ edits[addr] = null;
108
+ continue;
109
+ }
110
+ const next: Cell = { ...cell };
111
+ delete next.style;
112
+ edits[addr] = next;
113
+ }
114
+ return { edits };
115
+ };
116
+
117
+ /**
118
+ * CLEAR ALL: the value AND the styling. This is the only one of the three that empties the map.
119
+ *
120
+ * ⭐⭐ R5 (W52-T09): NO WALL HERE EITHER, ANY MORE. A bound cell clears exactly like any other:
121
+ * its whole record is removed, value and binding together. {@link clearFormats} never needed a
122
+ * wall in the first place, since removing a colour from a bound cell leaves it reading from
123
+ * exactly the database it read before.
124
+ */
125
+ export const clearAll = (
126
+ tab: SheetTab | null | undefined,
127
+ addrs: readonly string[],
128
+ ): BulkEdit => {
129
+ const edits: Record<string, Cell | null> = {};
130
+ for (const addr of addrs) {
131
+ const cell = cellAt(tab, addr);
132
+ if (!cell) continue;
133
+ edits[addr] = null;
134
+ }
135
+ return { edits };
136
+ };
137
+
138
+ /** The style a Format painter picked up. `null` when the cell it was picked from carries none. */
139
+ export const styleOf = (cell: Cell | null | undefined): CellStyle | null =>
140
+ cell?.style ? { ...cell.style } : null;
141
+
142
+ /**
143
+ * β›”β›” EVERY KEY `CellStyle` CARRIES, AND A MISSING ONE IS A SILENT HALF-PAINT. The Format painter
144
+ * REPLACES a style rather than merging into it, so it has to say `null` for the keys the picked
145
+ * up style does not have. A key absent from this list is a key the painter leaves behind: paint a
146
+ * plain cell's format onto a bold one and the target stays bold, which reads as the painter
147
+ * having half worked and is the harder defect to notice.
148
+ */
149
+ export const STYLE_KEYS = [
150
+ "bold", "italic", "underline", "color", "fill", "align", "format", "border",
151
+ // ⭐ W54-T03 / R10 ADDS `font`, AND IT HAD TO BE ADDED HERE IN THE SAME CHANGE THAT FIRST
152
+ // WROTE IT. `types.ts`'s own note on `textRotation` states the rule this obeys: the lane that
153
+ // first writes a style key names it here, or the painter leaves that key behind on every cell
154
+ // it paints over. Paint a Georgia cell's style onto an Arial one and the target would have
155
+ // stayed Arial, which reads as the painter having half worked.
156
+ // ⭐⭐ W54-T06 ADDS `textRotation`, AND IT IS THE KEY THIS LIST'S OWN NOTE WAS WRITTEN ABOUT.
157
+ // The base kit declared the slot and left it out of here on purpose, because nothing wrote it
158
+ // yet; this lane's Orientation gallery is the first writer, so the name lands in the SAME
159
+ // change. Paint a horizontal cell's style onto a cell turned 45 degrees and, without this, the
160
+ // target would have stayed turned while every other key was replaced.
161
+ "valign", "wrap", "indent", "size", "font", "textRotation",
162
+ ] as const;
163
+
164
+ /** The patch that makes a cell's style EQUAL to `style`, clearing everything `style` omits. */
165
+ export const paintPatch = (style: CellStyle | null | undefined): CellStylePatch => {
166
+ const source = (style ?? {}) as Record<string, unknown>;
167
+ const patch: Record<string, unknown> = {};
168
+ for (const key of STYLE_KEYS) patch[key] = source[key] ?? null;
169
+ return patch as CellStylePatch;
170
+ };
web/src/sheet/clipboardOps.ts ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------------------------
2
+ // sheet/clipboardOps.ts β€” WHAT A COPY OUT OF THE SHEET IS MADE OF, LIFTED OUT OF `SheetGrid.tsx`.
3
+ //
4
+ // ⭐ WAVE 54 BASE KIT β€” a SEAM, not a redesign. The body below was moved verbatim out of
5
+ // `SheetGrid.tsx::heldFor`; the component keeps a one-line `useCallback` around it so both copy
6
+ // doors (the ribbon's button and glide's own native Ctrl+C) still share ONE builder and both
7
+ // dependency arrays are unchanged.
8
+ //
9
+ // ⭐⭐ AND `copySelection` HAS NOW FOLLOWED IT, WHICH THE NOTE ABOVE THIS ONE USED TO REFUSE. The
10
+ // refusal was right at the time and is worth keeping, because it names the trap: it closes over
11
+ // six pieces of component state (`viewRange`, `onNotice`, `heldFor`, `copiedRef`, `setCopyMarquee`
12
+ // and `clearSelection`), and `verify_grid_ux.py`'s copy-marquee leg asserted its marquee literal
13
+ // INSIDE `SheetGrid.tsx`, so moving it under a no-behaviour-change brief would have reddened a
14
+ // gate about a claim that was still true. Wave 54 re-aimed that leg to read THIS file instead: it
15
+ // asserts where the marquee is set FROM, which is a claim about the code, and the code moved. The
16
+ // six values are ARGUMENTS now, and the component keeps a `useCallback` whose dependency array is
17
+ // unchanged, exactly as it already does for `heldFor`.
18
+ //
19
+ // β›” AND `pasteCells` IS NOT HERE EITHER. It already lives in `sheetState.ts` and is imported from
20
+ // there by both paste doors; a second home for it would be a second answer to the same question.
21
+ // ---------------------------------------------------------------------------------------------
22
+
23
+ import type { CellRange } from "./sheetState";
24
+ // ⭐⭐ W54-T15: `rememberCopy` is the IN APP CLIPBOARD, and it lives in `sheetState.ts` beside
25
+ // the one paste engine that reads it. The import direction is this file -> `sheetState.ts`, which
26
+ // is the direction that already existed for `displayText`; the reverse would be a cycle.
27
+ import { editableText, rawDisplayText, rememberCopy, rememberCut } from "./sheetState";
28
+ import type { Cell, CellMap } from "./types";
29
+ import { formatCellText } from "./types";
30
+
31
+ /**
32
+ * WHAT A COPY OF `range` PUTS ON THE CLIPBOARD, AND WHAT THE COMPONENT REMEMBERS ABOUT IT.
33
+ *
34
+ * ⭐ IT WRITES WHAT THE CELL READS, not what it stores: `formatCellText` over `displayText`, so
35
+ * a currency cell arrives in Excel as the currency somebody chose. That is the same string
36
+ * `displayData` carries, which is what makes glide's own Ctrl+C agree with the ribbon's button
37
+ * β€” and it is why the two copy doors can share one builder at all.
38
+ *
39
+ * ⚠ THE FOUR DEPENDENCIES ARE ARGUMENTS RATHER THAN A CLOSURE, which is the whole of what this
40
+ * extraction did. `cells` is the tab's map, `addrAt` is the ONE door from a view coordinate to an
41
+ * A1 address, and `realCol`/`realRow` translate a VIEW index back to the sheet's own coordinates
42
+ * β€” a hidden column would otherwise move the recorded top-left one column left with no error.
43
+ *
44
+ * ⭐⭐ W54-T15 β€” AND IT IS WHERE THE COPY IS REGISTERED, because it is the ONE builder BOTH copy
45
+ * doors share. The ribbon's button goes through `runCopySelection`, but a NATIVE Ctrl+C is
46
+ * answered by glide and reaches this component only as a DOM `copy` event, whose handler calls
47
+ * this function and nothing else. Registering in `runCopySelection` therefore covered the button
48
+ * alone, and a native copy pasted back with the destination's own formatting still on it.
49
+ *
50
+ * ⭐⭐ TWO KEYS, ONE BLOCK, AND BOTH ARE NEEDED. What goes on the OS clipboard is the FORMATTED
51
+ * grid, because Excel must receive the currency somebody chose; but glide round trips its own
52
+ * copy through a `text/html` payload carrying `getCellContent`'s `data`, which is
53
+ * `editableText`. So the very same copy comes back as `1234.5` where it left as `$1,234.50`, and
54
+ * a registry findable under only one of those two strings misses on exactly one of the two
55
+ * doors. The EDITABLE grid is built here beside the formatted one, joined with the same tabs and
56
+ * newlines, and {@link rememberCopy} files the block under both.
57
+ *
58
+ * ⚠ REGISTERING HERE MEANS A COPY IS REGISTERED EVEN IF THE CLIPBOARD WRITE LATER REFUSES. That
59
+ * is deliberate and it is the native door's requirement: glide's own Ctrl+C hands this component
60
+ * no promise to observe, so there is no later moment at which to register. The cost of being
61
+ * wrong is one stale entry in a two entry registry that is only ever consulted by an exact text
62
+ * match, which no other clipboard content can produce.
63
+ */
64
+ export function buildCopyPayload(
65
+ range: CellRange,
66
+ cells: CellMap,
67
+ addrAt: (col: number, row: number) => string,
68
+ realCol: (view: number) => number,
69
+ realRow: (view: number) => number,
70
+ ): CopyPayload {
71
+ const lines: string[] = [];
72
+ // ⭐ W54-T15: the second key. `editableText` is what glide's own `data` round trip hands back.
73
+ const editableLines: string[] = [];
74
+ // ⭐ W51-T19: the CELLS are kept beside the text, so a bound cell pasted back into the sheet
75
+ // can take its drag rules. See `copiedRef` for why the text alone cannot carry a binding.
76
+ const block: (Cell | null)[][] = [];
77
+ for (let r = Math.min(range.row0, range.row1); r <= Math.max(range.row0, range.row1); r += 1) {
78
+ const line: string[] = [];
79
+ const editLine: string[] = [];
80
+ const row: (Cell | null)[] = [];
81
+ for (let c = Math.min(range.col0, range.col1); c <= Math.max(range.col0, range.col1);
82
+ c += 1) {
83
+ const cell = cells[addrAt(c, r)] ?? null;
84
+ // β›”β›” W54-T17: `rawDisplayText`, NEVER `displayText`. The IMPLICIT default number
85
+ // format is a reading convenience on the canvas, not a value: a plain 1234.5 copied out
86
+ // to Excel must arrive as 1234.5 and not as the rounded, grouped string a screen shows.
87
+ // A format somebody EXPLICITLY chose still travels, because `formatCellText` applies it
88
+ // here exactly as it always has.
89
+ line.push(formatCellText(cell, rawDisplayText(cell)));
90
+ editLine.push(editableText(cell));
91
+ row.push(cell);
92
+ }
93
+ lines.push(line.join("\t"));
94
+ editableLines.push(editLine.join("\t"));
95
+ block.push(row);
96
+ }
97
+ const payload: CopyPayload = {
98
+ text: lines.join("\n"),
99
+ col: realCol(Math.min(range.col0, range.col1)),
100
+ row: realRow(Math.min(range.row0, range.row1)),
101
+ cells: block,
102
+ editable: editableLines.join("\n"),
103
+ };
104
+ rememberCopy(payload);
105
+ return payload;
106
+ }
107
+
108
+ /** What one copy out of the sheet is made of. `buildCopyPayload` returns exactly this shape. */
109
+ export interface CopyPayload {
110
+ text: string;
111
+ col: number;
112
+ row: number;
113
+ cells: (Cell | null)[][];
114
+ /**
115
+ * β›” W54-T15 β€” THE SECOND LOOKUP KEY, NEVER THE CLIPBOARD STRING. `text` stays the FORMATTED
116
+ * grid: it is what is written to the OS clipboard for Excel, and it is what
117
+ * `SheetGrid.tsx::copiedBlock` and `::isRecognizedCopy` compare against verbatim. This is the
118
+ * same block rendered as `editableText`, which is the string glide's own `text/html` round trip
119
+ * gives back to the paste door. Optional because only {@link buildCopyPayload} can build it.
120
+ */
121
+ editable?: string;
122
+ }
123
+
124
+ /** The copied rectangle, in the sheet's REAL coordinates: top left plus how many of each. */
125
+ export interface CopyMarquee {
126
+ col: number;
127
+ row: number;
128
+ cols: number;
129
+ rows: number;
130
+ }
131
+
132
+ /**
133
+ * COPY, and CUT, which is a copy whose source goes away WHEN THE PASTE LANDS.
134
+ *
135
+ * β›” THE CLEAR ONLY HAPPENS IF THE COPY SUCCEEDED. A browser that refuses clipboard access on a
136
+ * cut would otherwise delete a person's cells with nothing on the clipboard to paste back.
137
+ *
138
+ * ⭐⭐ W54-T16 β€” AND IT NO LONGER HAPPENS HERE AT ALL. Clearing at CUT time is the defect the
139
+ * owner reported from both ends: the source cell was emptied of its value but kept its fill
140
+ * colour, its borders and its database binding, so it still looked occupied; and a cut abandoned
141
+ * with Escape had already destroyed the value with nothing pasted anywhere. The successful write
142
+ * now ARMS the cut through `sheetState.ts::rememberCut`, and `sheetState.ts::pasteCells` removes
143
+ * the source in the SAME edit set as the paste that completes it - one undo step, one save, and
144
+ * an identity check on every source cell before a single one is removed.
145
+ *
146
+ * ⭐ WHAT IT PUTS ON THE CLIPBOARD IS `heldFor`'s, which glide's own Ctrl+C now records
147
+ * through the same builder.
148
+ *
149
+ * ⚠ THE SIX DEPENDENCIES ARE ARGUMENTS RATHER THAN A CLOSURE, which is the whole of what the
150
+ * wave-54 extraction did. `viewRange` is the selection as VIEW coordinates, `heldFor` is the one
151
+ * copy builder both doors share, `copiedRef` is the component's memory of its own last copy,
152
+ * `setCopyMarquee` paints it, `_clearSelection` used to be the cut's second half, and `onNotice`
153
+ * is the one door every refusal in this feature speaks through.
154
+ *
155
+ * β›”β›” W54-T16 KEEPS THE SIXTH PARAMETER AND STOPS USING IT, WHICH IS DELIBERATE AND NOT A
156
+ * LEFTOVER. `verify_grid_ux.py` pins the CALL SITE in `SheetGrid.tsx` as an exact string, and
157
+ * that file belongs to another ticket this wave, so dropping the argument would redden a gate leg
158
+ * from inside a file this one may not touch. `noUnusedParameters` is on, so the name carries a
159
+ * leading underscore instead; the component keeps handing its selection clearer over, and the
160
+ * next lane to touch that call site may retire both halves in one move.
161
+ */
162
+ export function runCopySelection(
163
+ cut: boolean,
164
+ viewRange: () => CellRange | null,
165
+ heldFor: (range: CellRange) => CopyPayload,
166
+ copiedRef: { current: CopyPayload | null },
167
+ setCopyMarquee: (rect: CopyMarquee | null) => void,
168
+ _clearSelection: () => void,
169
+ onNotice: (message: string) => void,
170
+ ): void {
171
+ const range = viewRange();
172
+ if (!range) {
173
+ onNotice(cut ? "Select a cell first, then cut it." : "Select a cell first, then copy it.");
174
+ return;
175
+ }
176
+ // ⭐ W53-T03: the block and its text are built by `heldFor`, the ONE builder both copy doors
177
+ // share, so a native Ctrl+C and this button can never record different things about the same
178
+ // selection.
179
+ const held = heldFor(range);
180
+ const block = held.cells;
181
+ const text = held.text;
182
+ // β›” RECORDED ONLY ON A SUCCESSFUL WRITE, so the sheet never believes it holds a block the
183
+ // clipboard does not. It is a SEPARATE `then` so that the cut stays the one line a
184
+ // W51-T17 gate leg pins: a cut takes effect only after the copy landed, and folding
185
+ // the two together would have moved that leg's anchor for no reason at all.
186
+ navigator.clipboard.writeText(text)
187
+ .then(() => {
188
+ copiedRef.current = held;
189
+ // ⭐⭐ W54-T15 / C2 β€” THE IN APP CLIPBOARD IS NOT REGISTERED HERE, AND THAT IS THE FIX
190
+ // RATHER THAN AN OMISSION. `heldFor` is `buildCopyPayload`, which registers the block
191
+ // itself under both of its keys, so this door is already covered; a second registration
192
+ // from here would file the same block again through a parameter typed as the narrower
193
+ // `CopyPayload`, and the de-duplication would then REPLACE the entry that carries the
194
+ // editable key with one that may not. One registration, at the one shared builder.
195
+ //
196
+ // ⭐ W52-T07: a NEW copy/cut is the closest thing to "the clipboard changed" this app can
197
+ // observe, so it replaces the marquee rather than requiring an Escape first.
198
+ setCopyMarquee({ col: held.col, row: held.row, cols: block[0]?.length ?? 0,
199
+ rows: block.length });
200
+ })
201
+ // ⭐⭐ W54-T16: the cut is ARMED here and performed by the paste that completes it. On a
202
+ // browser that refuses the write this `then` never runs, so nothing is armed, nothing is
203
+ // deleted, and the catch below says so out loud.
204
+ .then(() => { if (cut) rememberCut(held); })
205
+ .catch(() => onNotice("This browser did not let the sheet write to the clipboard. "
206
+ + "Press Ctrl+C instead."));
207
+ }
web/src/sheet/formulaEval.ts CHANGED
@@ -3,8 +3,9 @@
3
  // ⭐⭐ RULING R2: a formula that references only OTHER CELLS evaluates HERE, the instant it is
4
  // committed, and never touches the network. `evaluateFormula` is the whole of that: a small,
5
  // self-contained engine over numeric literals, A1 cell references (with Excel's `$` tolerated),
6
- // the four operators, parentheses, and C1's five aggregate functions (SUM/COUNT/AVG/MIN/MAX) run
7
- // over one simple range. It is NOT a reimplementation of the server's full grammar
 
8
  // (`api/formula_runtime.py::evaluate_sheet`) β€” no cross-sheet references, no function catalogue
9
  // beyond the five aggregates.
10
  //
@@ -42,7 +43,7 @@ export type CellValue =
42
  | { kind: "empty" }
43
  | { kind: "pending" }
44
  | { kind: "unsupported"; reason: string }
45
- | { kind: "error"; message: string };
46
 
47
  /**
48
  * β›” C1's parity list, spelled in the evaluator's own (Excel-flavoured) names.
@@ -53,7 +54,25 @@ export type CellValue =
53
  export const AGGREGATE_FUNCTIONS = ["SUM", "COUNT", "AVG", "MIN", "MAX"] as const;
54
  export type AggregateFunction = (typeof AGGREGATE_FUNCTIONS)[number];
55
 
56
- const AGGREGATE_SET: ReadonlySet<string> = new Set<string>(AGGREGATE_FUNCTIONS);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
  /**
59
  * ⭐⭐ THE ONE SENTENCE A CYCLE STATES, DECLARED HERE SO ONE FILE OWNS IT. `sheetState.ts`
@@ -63,7 +82,87 @@ const AGGREGATE_SET: ReadonlySet<string> = new Set<string>(AGGREGATE_FUNCTIONS);
63
  */
64
  export const CYCLE_REFUSAL = "This formula refers back to itself.";
65
 
66
- /** A stated wrong: the reader sees this sentence in the cell instead of a number. */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  class FormulaError extends Error {}
68
  /** Not wrong, just not ours: the cell keeps its old behaviour and the server answers it. */
69
  class Unsupported extends Error {}
@@ -78,6 +177,8 @@ type Token =
78
  | { t: "num"; v: number }
79
  | { t: "ref"; v: string }
80
  | { t: "fn"; v: string }
 
 
81
  | { t: "op"; v: "+" | "-" | "*" | "/" | "(" | ")" | ":" };
82
 
83
  const OPS = "+-*/():";
@@ -132,7 +233,28 @@ const tokenize = (src: string): Token[] => {
132
  i = j;
133
  continue;
134
  }
135
- // A quote, a comma, a `!`, a `%`, a `^`: every one of them is a formula the SERVER can read
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  // and this file cannot. See the header: that is `unsupported`, never an error.
137
  throw new Unsupported("token");
138
  }
@@ -234,6 +356,158 @@ export const referencedAddresses = (src: string): string[] => {
234
  return out;
235
  };
236
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  /** The formula graph, indexed both ways, with every address upper cased exactly once. */
238
  const graphOf = (formulas: Record<string, string>) => {
239
  const reads = new Map<string, string[]>();
@@ -375,26 +649,65 @@ const isOp = (tk: Token | undefined, v: string): boolean => !!tk && tk.t === "op
375
 
376
  type Getter = (addr: string) => CellValue;
377
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
378
  const evalAggregate = (name: string, addrs: string[], get: Getter): Num => {
379
  const nums: number[] = [];
380
  let pending = false;
381
- let counted = 0;
 
382
  for (const addr of addrs) {
383
  const cv = get(addr);
384
  if (cv.kind === "empty") continue;
385
  if (cv.kind === "pending") { pending = true; continue; }
386
  if (cv.kind === "unsupported") throw new Unsupported(cv.reason);
387
- if (cv.kind === "error") throw new FormulaError(cv.message);
388
- if (cv.kind === "text" && cv.value.trim() === "") continue;
389
- const num = toNum(cv);
390
- pending = pending || num.pending;
391
- nums.push(num.n);
392
- counted += 1;
 
 
 
 
 
 
 
 
 
 
 
393
  }
394
  const sum = nums.reduce((a, b) => a + b, 0);
395
  switch (name) {
396
  case "SUM": return { n: sum, pending };
397
- case "COUNT": return { n: counted, pending };
 
398
  case "AVG": return { n: nums.length ? sum / nums.length : 0, pending };
399
  case "MIN": return { n: nums.length ? Math.min(...nums) : 0, pending };
400
  case "MAX": return { n: nums.length ? Math.max(...nums) : 0, pending };
@@ -402,26 +715,50 @@ const evalAggregate = (name: string, addrs: string[], get: Getter): Num => {
402
  }
403
  };
404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
405
  const parseAtom = (c: Cursor, get: Getter): Num => {
406
  const tk = take(c);
407
  if (tk.t === "num") return { n: tk.v, pending: false };
408
  if (tk.t === "ref") return toNum(get(tk.v));
 
 
 
 
 
 
 
409
  if (tk.t === "fn") {
410
  const name = tk.v;
 
 
 
 
411
  // ⭐ EVERY OTHER FUNCTION IN THE CATALOGUE IS THE SERVER'S. `IF`, `ROUND`, `TEXT` and the
412
  // rest are real formulas this file does not speak, so they take the `unsupported` road home
413
  // and keep working exactly as they did before this ticket (see the header).
 
 
414
  if (!AGGREGATE_SET.has(name)) throw new Unsupported(name);
415
- if (!isOp(peekTok(c), "(")) throw new Unsupported(name);
416
  take(c);
417
- const from = take(c);
418
- if (from.t !== "ref" || !isOp(peekTok(c), ":")) throw new Unsupported(name);
419
  take(c);
420
- const to = take(c);
421
- if (to.t !== "ref") throw new Unsupported(name);
422
  if (!isOp(peekTok(c), ")")) throw new Unsupported(name);
423
  take(c);
424
- return evalAggregate(name, rangeAddresses(from.v, to.v), get);
425
  }
426
  if (tk.t === "op" && tk.v === "(") {
427
  const inner = parseExpr(c, get);
@@ -501,6 +838,11 @@ export const evaluateFormula = (src: string, get: Getter): CellValue => {
501
  try {
502
  const tokens = tokenize(src);
503
  if (tokens.length === 0) return { kind: "empty" };
 
 
 
 
 
504
  if (tokens.length === 1 && tokens[0].t === "ref") {
505
  const one = tokens[0];
506
  return one.t === "ref" ? get(one.v) : { kind: "empty" };
@@ -516,7 +858,8 @@ export const evaluateFormula = (src: string, get: Getter): CellValue => {
516
  } catch (err) {
517
  if (err instanceof PendingInput) return { kind: "pending" };
518
  if (err instanceof Unsupported) return { kind: "unsupported", reason: err.message };
519
- if (err instanceof FormulaError) return { kind: "error", message: err.message };
 
520
  return { kind: "error", message: "This formula could not be calculated." };
521
  }
522
  };
 
3
  // ⭐⭐ RULING R2: a formula that references only OTHER CELLS evaluates HERE, the instant it is
4
  // committed, and never touches the network. `evaluateFormula` is the whole of that: a small,
5
  // self-contained engine over numeric literals, A1 cell references (with Excel's `$` tolerated),
6
+ // the four operators, parentheses, and C1's five aggregate functions (SUM/COUNT/AVG/MIN/MAX) plus
7
+ // COUNTA (W54-T27), each run over one simple range. It is NOT a reimplementation of the server's
8
+ // full grammar
9
  // (`api/formula_runtime.py::evaluate_sheet`) β€” no cross-sheet references, no function catalogue
10
  // beyond the five aggregates.
11
  //
 
43
  | { kind: "empty" }
44
  | { kind: "pending" }
45
  | { kind: "unsupported"; reason: string }
46
+ | { kind: "error"; message: string; code?: FormulaErrorCode };
47
 
48
  /**
49
  * β›” C1's parity list, spelled in the evaluator's own (Excel-flavoured) names.
 
54
  export const AGGREGATE_FUNCTIONS = ["SUM", "COUNT", "AVG", "MIN", "MAX"] as const;
55
  export type AggregateFunction = (typeof AGGREGATE_FUNCTIONS)[number];
56
 
57
+ /**
58
+ * ⭐⭐ W54-T27 / RULING R9(iii): `COUNTA` IS THE SIXTH RANGE FUNCTION, AND IT IS DELIBERATELY NOT
59
+ * A MEMBER OF THE LIST ABOVE. {@link AGGREGATE_FUNCTIONS} is C1's PARITY list, asserted name for
60
+ * name against `platform/modules/sheet.py::AGGREGATE_FNS`, which is the set a BOUND cell may roll
61
+ * a database column up with. Adding a sixth name there would red that parity leg over a function
62
+ * that has nothing to do with bindings, and the only honest way to make it green again would be
63
+ * to teach the rollup planner a function nobody asked it for.
64
+ *
65
+ * ⭐ IT IS SAFE TO TYPE BECAUSE THE SERVER ALREADY SPEAKS IT. `api/formula_runtime.py` carries
66
+ * `COUNTA` in both `FN_ARITY` and `FN_CATALOGUE`, and `functionCatalog.ts` already offers it in
67
+ * the suggestion list, so a `COUNTA` a person types survives the save and comes back with the
68
+ * same answer this file computes. This is the one place the two engines had to agree first.
69
+ */
70
+ export const COUNTA_FUNCTION = "COUNTA";
71
+
72
+ /** Every function name this engine reads ahead of one simple range: the five, plus `COUNTA`. */
73
+ export const RANGE_FUNCTIONS = [...AGGREGATE_FUNCTIONS, COUNTA_FUNCTION] as const;
74
+
75
+ const AGGREGATE_SET: ReadonlySet<string> = new Set<string>(RANGE_FUNCTIONS);
76
 
77
  /**
78
  * ⭐⭐ THE ONE SENTENCE A CYCLE STATES, DECLARED HERE SO ONE FILE OWNS IT. `sheetState.ts`
 
82
  */
83
  export const CYCLE_REFUSAL = "This formula refers back to itself.";
84
 
85
+ // ── W54-T26 / RULING R9(ii): AN ERROR IS A VALUE, AND A VALUE HAS A CODE ──────────────────────
86
+ //
87
+ // ⭐⭐ WHAT WAS WRONG, MEASURED IN A BROWSER BEFORE THIS TICKET. `=1/0` painted the ENGLISH
88
+ // SENTENCE "This formula divid..." across the cell, clipped by the column, and `=FOO(1)` painted
89
+ // its own SOURCE TEXT back at the reader. Two different wrongs with one cause: an error had no
90
+ // VALUE to be, so a cell had nothing to show but prose or the formula it could not compute.
91
+ //
92
+ // β›” DESIGN.md 4, "refusals: never over-explain". A cell states a CODE. The sentence is still
93
+ // carried, first token after the code, so a disclosure can state the diagnosis without the grid
94
+ // having to; nothing about that sentence reaches the cell face.
95
+ //
96
+ // ⚠ THE CODES ARE EXCEL'S OWN TOKENS AND ARE SPELLED EXACTLY. They are not ours to prettify,
97
+ // translate or shorten: a reader who knows spreadsheets already knows what each one means, and a
98
+ // near miss (`#DIV0!`, `#NAME!`) reads as a bug in us rather than a fault in their formula.
99
+
100
+ export const ERROR_DIV0 = "#DIV/0!";
101
+ export const ERROR_REF = "#REF!";
102
+ export const ERROR_NAME = "#NAME?";
103
+ export const ERROR_VALUE = "#VALUE!";
104
+
105
+ /**
106
+ * β›” THE CLOSED VOCABULARY. `types.ts` declares the SAME four for the renderer, and the gate
107
+ * family asserts one set across the two files, exactly as {@link AGGREGATE_FUNCTIONS} is asserted
108
+ * against the server's own list. This file imports nothing from the project (see the header), so
109
+ * a second declaration is the price of that rule and a parity leg is what keeps the price honest.
110
+ */
111
+ export const FORMULA_ERROR_CODES = [ERROR_DIV0, ERROR_REF, ERROR_NAME, ERROR_VALUE] as const;
112
+ export type FormulaErrorCode = (typeof FORMULA_ERROR_CODES)[number];
113
+
114
+ /**
115
+ * ⭐⭐ THE SENTENCE IS THE IDENTITY OF THE WRONG; THE CODE IS HOW IT READS. This table is the one
116
+ * place the two are paired, so a sentence cannot reach a cell without a code and a code cannot be
117
+ * invented at a throw site.
118
+ *
119
+ * β›” IT IS KEYED ON THE MESSAGE RATHER THAN PASSED AT THE THROW, AND THAT IS DELIBERATE. Every
120
+ * `throw new FormulaError(...)` statement in this file is a NEEDLE in `verify_formula_engine.py`'s
121
+ * compiled-artifact mutation table, which requires each to occur exactly once and drives a
122
+ * negative control by replacing it whole. Adding an argument to those statements would leave that
123
+ * gate's targets unfindable and red a wave-53 leg that has nothing to do with error values.
124
+ */
125
+ const ERROR_CODE_BY_MESSAGE: Readonly<Record<string, FormulaErrorCode>> = {
126
+ "This formula divides by zero.": ERROR_DIV0,
127
+ "This formula expects a number here.": ERROR_VALUE,
128
+ "This formula uses a name nothing here answers to.": ERROR_NAME,
129
+ };
130
+
131
+ /** β›” Said once, so the throw site and the table above cannot drift apart. */
132
+ const NAME_NOT_FOUND = "This formula uses a name nothing here answers to.";
133
+
134
+ /** A code sitting at the head of a message, matched loosely so a near miss is NOT accepted. */
135
+ const LEADING_ERROR_CODE = /^(#[A-Z0-9/]{2,6}[!?])(?:\s|$)/;
136
+
137
+ /**
138
+ * ⭐⭐ THE CODE A MESSAGE ALREADY STATES, WHICH IS THE WHOLE OF PROPAGATION. Excel passes an error
139
+ * through every formula that reads it unchanged: `=A1+1` over a `#DIV/0!` is `#DIV/0!`, not a new
140
+ * complaint about A1. A referenced cell arrives here as its stored message, so reading the code
141
+ * back off the front of it is what makes a dependent formula answer with the ORIGINAL fault.
142
+ */
143
+ export const errorCodeOf = (message: string): FormulaErrorCode | null => {
144
+ const found = LEADING_ERROR_CODE.exec(String(message ?? "").trim());
145
+ const code = found ? found[1] : "";
146
+ return (FORMULA_ERROR_CODES as readonly string[]).includes(code)
147
+ ? (code as FormulaErrorCode)
148
+ : null;
149
+ };
150
+
151
+ /**
152
+ * One stated wrong, as a VALUE. A message that already carries a code keeps it (propagation); a
153
+ * message this file knows gains one; anything else stays a bare message rather than being forced
154
+ * into a code that would name the wrong fault.
155
+ */
156
+ const errorValue = (message: string): CellValue => {
157
+ const said = String(message ?? "").trim();
158
+ const carried = errorCodeOf(said);
159
+ if (carried) return { kind: "error", code: carried, message: said };
160
+ const code = ERROR_CODE_BY_MESSAGE[said];
161
+ if (!code) return { kind: "error", message: said };
162
+ return { kind: "error", code, message: code + " " + said };
163
+ };
164
+
165
+ /** A stated wrong: the reader sees this error's CODE in the cell instead of a number. */
166
  class FormulaError extends Error {}
167
  /** Not wrong, just not ours: the cell keeps its old behaviour and the server answers it. */
168
  class Unsupported extends Error {}
 
177
  | { t: "num"; v: number }
178
  | { t: "ref"; v: string }
179
  | { t: "fn"; v: string }
180
+ | { t: "str"; v: string }
181
+ | { t: "err"; v: FormulaErrorCode }
182
  | { t: "op"; v: "+" | "-" | "*" | "/" | "(" | ")" | ":" };
183
 
184
  const OPS = "+-*/():";
 
233
  i = j;
234
  continue;
235
  }
236
+ // ⭐⭐ W54-T26: AN ERROR LITERAL IS A TOKEN, because Excel writes one INTO a formula. A
237
+ // structural delete that invalidates a reference leaves `#REF!` in the text, and a workbook
238
+ // imported from Excel carries whatever codes it was saved with, so an engine that cannot read
239
+ // one back answers about a formula nobody typed.
240
+ if (ch === "#") {
241
+ const literal = FORMULA_ERROR_CODES.find((code) => text.startsWith(code, i));
242
+ if (!literal) throw new Unsupported("token");
243
+ tokens.push({ t: "err", v: literal });
244
+ i += literal.length;
245
+ continue;
246
+ }
247
+ // ⭐ W54-T26: A QUOTED RUN IS A TEXT LITERAL, so `=1+"x"` can say `#VALUE!` about the thing
248
+ // that is actually wrong with it. It is still only a literal: a comma, a `&` and a comparison
249
+ // all remain unreadable here, so every function call carrying one is still the server's.
250
+ if (ch === '"' || ch === "'") {
251
+ const close = text.indexOf(ch, i + 1);
252
+ if (close < 0) throw new Unsupported("token");
253
+ tokens.push({ t: "str", v: text.slice(i + 1, close) });
254
+ i = close + 1;
255
+ continue;
256
+ }
257
+ // A comma, a `!`, a `%`, a `^`: every one of them is a formula the SERVER can read
258
  // and this file cannot. See the header: that is `unsupported`, never an error.
259
  throw new Unsupported("token");
260
  }
 
356
  return out;
357
  };
358
 
359
+ // ── W54-T25 / RULING R9(i): the two pure string rules formula ENTRY needs ─────────────────────
360
+ //
361
+ // ⭐⭐ THEY LIVE HERE BECAUSE THIS FILE IS PURE AND DRIVEN UNDER NODE. Both are string
362
+ // arithmetic with no React, no DOM and no project import, so `verify_formula_engine.py` can
363
+ // compile this one module and EXECUTE the claims rather than grep for them. `SheetGrid.tsx` is
364
+ // the only caller: it closes the draft at COMMIT and cycles the anchors on F4.
365
+
366
+ /**
367
+ * ⭐⭐ AUTO-CLOSE ON COMMIT: `=SUM(A1:A2` becomes `=SUM(A1:A2)`, and it is the STORED string that
368
+ * changes, never a display of it. `SheetGrid.tsx::commitFormulaEditor` runs the draft through
369
+ * this before `commitTyped`, so the stored formula, the formula bar's readback and the evaluator
370
+ * all read one identical closed text. Auto-closing only what is painted would leave a cell that
371
+ * LOOKS balanced and is stored broken, which is worse than never closing it at all.
372
+ *
373
+ * β›” IT ONLY EVER APPENDS. An extra `)` the person actually typed (`=A1)`) is their text and is
374
+ * left exactly as it is: this rule finishes an unfinished formula, it does not edit a wrong one.
375
+ *
376
+ * β›” A QUOTED RUN IS NOT COUNTED, and an UNTERMINATED one refuses the whole repair. `="a("` has
377
+ * no open bracket, and `=SUM("a` is a string somebody is still in the middle of typing, where a
378
+ * closing bracket would land inside their label.
379
+ *
380
+ * ⚠ NOT A FORMULA, NOT OUR BUSINESS. Text that does not start with `=` comes back untouched, so
381
+ * a literal cell reading `Total (net` keeps the shape its author typed.
382
+ */
383
+ export const autoCloseFormula = (src: string): string => {
384
+ const text = String(src ?? "");
385
+ if (!text.startsWith("=")) return text;
386
+ let depth = 0;
387
+ let quote: string | null = null;
388
+ for (let i = 0; i < text.length; i += 1) {
389
+ const ch = text[i];
390
+ if (quote !== null) {
391
+ if (ch === quote) quote = null;
392
+ continue;
393
+ }
394
+ if (ch === '"' || ch === "'") { quote = ch; continue; }
395
+ if (ch === "(") depth += 1;
396
+ else if (ch === ")") depth = depth > 0 ? depth - 1 : 0;
397
+ }
398
+ if (quote !== null) return text;
399
+ if (depth <= 0) return text;
400
+ return text + ")".repeat(depth);
401
+ };
402
+
403
+ /**
404
+ * One reference OCCURRENCE with its offsets and its two dollar flags, so a caller can rewrite
405
+ * exactly that occurrence and leave every other character of the formula alone.
406
+ */
407
+ interface RefSpan {
408
+ start: number;
409
+ end: number;
410
+ colAbs: boolean;
411
+ rowAbs: boolean;
412
+ col: string;
413
+ row: string;
414
+ }
415
+
416
+ const REF_SPAN_SCAN = /(\$?)([A-Za-z]{1,3})(\$?)([0-9]{1,7})/g;
417
+
418
+ /**
419
+ * Every A1 occurrence in `src` WITH ITS OFFSETS, quoted runs blanked and the same two boundary
420
+ * guards `referencedAddresses` uses: a run inside a longer name is not a reference, and neither
421
+ * is one followed by `(` (a function call) or by a sheet-qualified name part.
422
+ *
423
+ * ⚠ `withoutQuotes` replaces a quoted run with SPACES OF THE SAME LENGTH, which is what makes the
424
+ * offsets returned here valid against the ORIGINAL string.
425
+ */
426
+ const refSpans = (src: string): RefSpan[] => {
427
+ const text = withoutQuotes(src);
428
+ const out: RefSpan[] = [];
429
+ REF_SPAN_SCAN.lastIndex = 0;
430
+ let m = REF_SPAN_SCAN.exec(text);
431
+ while (m) {
432
+ const start = m.index;
433
+ const end = start + m[0].length;
434
+ const before = start > 0 ? text[start - 1] : "";
435
+ const after = end < text.length ? text[end] : "";
436
+ const namePart = /[A-Za-z0-9_$!'.]/.test(before);
437
+ const callOrName = after === "(" || /[A-Za-z0-9_.]/.test(after);
438
+ // β›” THE TEST IS NAMED RATHER THAN INLINED, and that is not a style choice. `verify_formula_
439
+ // engine.py`'s W53-T01 family drives a negative control by replacing the COMPILED text of
440
+ // `referencedAddresses`'s own guard, `if (!namePart && !callOrName)`, and requires it to
441
+ // occur exactly once in the emitted module. A second copy of that line here would make the
442
+ // control ambiguous and red a leg that has nothing to do with this ticket.
443
+ const standalone = !namePart && !callOrName;
444
+ if (standalone) {
445
+ out.push({ start, end, colAbs: m[1] === "$", rowAbs: m[3] === "$", col: m[2], row: m[4] });
446
+ }
447
+ m = REF_SPAN_SCAN.exec(text);
448
+ }
449
+ return out;
450
+ };
451
+
452
+ /**
453
+ * β›” EXCEL'S FOUR STATES IN EXCEL'S ORDER: `A1`, `$A$1`, `A$1`, `$A1`, and the fourth press is
454
+ * back where it started. `sheetState.ts::ANCHOR_CYCLE` states the same four for the WHOLE-FORMULA
455
+ * F4 that a selected (not open) cell gets; this one is per reference, so the two must not drift.
456
+ */
457
+ const ANCHOR_STATES: readonly { colAbs: boolean; rowAbs: boolean }[] = [
458
+ { colAbs: false, rowAbs: false },
459
+ { colAbs: true, rowAbs: true },
460
+ { colAbs: false, rowAbs: true },
461
+ { colAbs: true, rowAbs: false },
462
+ ];
463
+
464
+ export interface AnchorCycleResult {
465
+ /** The whole formula text with ONE reference rewritten. */
466
+ text: string;
467
+ /** Where the caret goes: the END of the rewritten reference. */
468
+ caret: number;
469
+ }
470
+
471
+ /**
472
+ * ⭐⭐ F4 IN THE OPEN EDITOR: the reference UNDER THE CARET walks one step of the cycle, and
473
+ * nothing else in the formula moves. `=SUM(A1:A2` with the caret at the end cycles `A2`, leaving
474
+ * `A1` exactly as it was, which is the whole difference from the whole-formula F4 a closed cell
475
+ * gets.
476
+ *
477
+ * β›”β›” NO REFERENCE UNDER THE CARET MEANS NOTHING HAPPENS, AND THAT IS A DECISION. `null` comes
478
+ * back for a caret in `=1+2`, for a caret before the leading `=`, and for a caret sitting in a
479
+ * quoted label that merely LOOKS like an address. The alternatives were cycling the first
480
+ * reference in the formula, which moves a character the person was not looking at, or cycling all
481
+ * of them, which is the other F4 and would make one key mean two things. A key that does nothing
482
+ * is honest; a key that edits somewhere else is not.
483
+ *
484
+ * ⭐ THE CARET LANDS AT THE END OF THE REWRITTEN REFERENCE, so a second press finds the SAME
485
+ * reference and four presses restore the text. Adding a `$` shifts every later character, so a
486
+ * caret left where it was would drift out of the reference it is cycling.
487
+ *
488
+ * ⚠ ADJACENT COUNTS, both sides. `start <= caret <= end`, so a caret resting immediately before
489
+ * or immediately after a reference cycles it; the spans are disjoint, so at most one qualifies.
490
+ */
491
+ export const cycleAnchorAtCaret = (src: string, caret: number): AnchorCycleResult | null => {
492
+ const text = String(src ?? "");
493
+ const raw = Number.isFinite(caret) ? Math.trunc(caret) : 0;
494
+ const at = Math.max(0, Math.min(raw, text.length));
495
+ let hit: RefSpan | null = null;
496
+ for (const span of refSpans(text)) {
497
+ if (span.start <= at && at <= span.end) hit = span;
498
+ }
499
+ if (!hit) return null;
500
+ const current = ANCHOR_STATES.findIndex(
501
+ (s) => s.colAbs === hit?.colAbs && s.rowAbs === hit?.rowAbs,
502
+ );
503
+ const next = ANCHOR_STATES[((current < 0 ? 0 : current) + 1) % ANCHOR_STATES.length];
504
+ const replacement = (next.colAbs ? "$" : "") + hit.col + (next.rowAbs ? "$" : "") + hit.row;
505
+ return {
506
+ text: text.slice(0, hit.start) + replacement + text.slice(hit.end),
507
+ caret: hit.start + replacement.length,
508
+ };
509
+ };
510
+
511
  /** The formula graph, indexed both ways, with every address upper cased exactly once. */
512
  const graphOf = (formulas: Record<string, string>) => {
513
  const reads = new Map<string, string[]>();
 
649
 
650
  type Getter = (addr: string) => CellValue;
651
 
652
+ // ── W54-T27 / RULING R9(iii): AN AGGREGATE IGNORES TEXT, AND `COUNT` IS NOT `COUNTA` ──────────
653
+ //
654
+ // ⭐⭐ WHAT WAS WRONG, MEASURED IN A BROWSER BEFORE THIS TICKET. A column with a HEADER in it,
655
+ // which is the single most common shape a spreadsheet has, broke every aggregate below it: with
656
+ // a label in A1 and two numbers under it, all five of `SUM`, `COUNT`, `AVG`, `MIN` and `MAX`
657
+ // answered a refusal rather than a number. The cause was one line: a non blank, non numeric cell
658
+ // went through the same numeric coercion an operand does, and that coercion states a wrong.
659
+ //
660
+ // β›” SO A RANGE IS FILTERED, NOT COERCED. An aggregate reads a REGION, and a region is expected
661
+ // to hold labels beside its numbers. An operand is a single value somebody wrote INTO the
662
+ // formula, and a label there really is a mistake, so `=A1+1` over a label is still a stated
663
+ // wrong. That asymmetry is Excel's and it is the whole distinction this file now draws.
664
+ //
665
+ // β›” AND AN ERROR IS NOT A LABEL, SO THE FOUR THAT COMPUTE PROPAGATE IT. `SUM`, `AVG`, `MIN` and
666
+ // `MAX` answer with the ORIGINAL fault of any cell in their range, because a total that quietly
667
+ // skipped a broken cell would be a confidently wrong number, which is worse than a refusal. The
668
+ // two that COUNT never adopt it: they are measuring how full a region is, not computing with it,
669
+ // so `COUNT` ignores an error (it is not a number) and `COUNTA` counts it (it is not empty).
670
+ // Excel answers all six of those exactly this way.
671
+
672
+ /**
673
+ * ⭐ THE TWO THAT MEASURE A REGION RATHER THAN COMPUTING OVER IT, said once so the error rule and
674
+ * the switch below cannot drift apart.
675
+ */
676
+ const COUNTING_FUNCTIONS: ReadonlySet<string> = new Set<string>(["COUNT", COUNTA_FUNCTION]);
677
+
678
  const evalAggregate = (name: string, addrs: string[], get: Getter): Num => {
679
  const nums: number[] = [];
680
  let pending = false;
681
+ let filled = 0;
682
+ const counting = COUNTING_FUNCTIONS.has(name);
683
  for (const addr of addrs) {
684
  const cv = get(addr);
685
  if (cv.kind === "empty") continue;
686
  if (cv.kind === "pending") { pending = true; continue; }
687
  if (cv.kind === "unsupported") throw new Unsupported(cv.reason);
688
+ if (cv.kind === "error") {
689
+ if (!counting) throw new FormulaError(cv.message);
690
+ filled += 1;
691
+ continue;
692
+ }
693
+ if (cv.kind === "text") {
694
+ // ⭐⭐ THE OWNER'S SENTENCE, IN ONE BRANCH: a blank is nothing at all and a label is
695
+ // something that is not a number. Neither reaches the arithmetic; only the second is a
696
+ // non empty cell, so only the second is counted by `COUNTA`.
697
+ if (cv.value.trim() === "") continue;
698
+ pending = pending || cv.pending === true;
699
+ filled += 1;
700
+ continue;
701
+ }
702
+ pending = pending || cv.pending === true;
703
+ filled += 1;
704
+ nums.push(cv.value);
705
  }
706
  const sum = nums.reduce((a, b) => a + b, 0);
707
  switch (name) {
708
  case "SUM": return { n: sum, pending };
709
+ case "COUNT": return { n: nums.length, pending };
710
+ case "COUNTA": return { n: filled, pending };
711
  case "AVG": return { n: nums.length ? sum / nums.length : 0, pending };
712
  case "MIN": return { n: nums.length ? Math.min(...nums) : 0, pending };
713
  case "MAX": return { n: nums.length ? Math.max(...nums) : 0, pending };
 
715
  }
716
  };
717
 
718
+ /**
719
+ * ⭐⭐ W54-T27 / D-678: A RANGE ENDPOINT MAY BE AN ERROR LITERAL, AND THEN THE CALL IS THAT ERROR.
720
+ * A structural delete leaves `#REF!` written into the formula text, so `=SUM(#REF!)` is a real
721
+ * thing a workbook holds. Demanding a `ref : ref` pair answered `unsupported` for it, which sent
722
+ * a formula the server cannot mend any further off on a round trip to be told the same thing.
723
+ * Excel answers `#REF!`, and so does this now.
724
+ */
725
+ const rangeEndpoint = (tok: Token, name: string): string => {
726
+ if (tok.t === "err") throw new FormulaError(tok.v);
727
+ if (tok.t !== "ref") throw new Unsupported(name);
728
+ return tok.v;
729
+ };
730
+
731
  const parseAtom = (c: Cursor, get: Getter): Num => {
732
  const tk = take(c);
733
  if (tk.t === "num") return { n: tk.v, pending: false };
734
  if (tk.t === "ref") return toNum(get(tk.v));
735
+ // ⭐⭐ W54-T26: AN ERROR PROPAGATES THROUGH ARITHMETIC, EXACTLY AS EXCEL DOES. Reading one is
736
+ // the same as reading a cell that holds one, so it takes the same road out: a thrown
737
+ // `FormulaError` whose message already states the code, which `errorValue` passes through.
738
+ if (tk.t === "err") throw new FormulaError(tk.v);
739
+ // ⭐ W54-T26: a text literal coerces the way a text CELL does, so `=1+"1"` is 2 and `=1+"x"`
740
+ // is `#VALUE!`, which is Excel's own answer to both.
741
+ if (tk.t === "str") return toNum({ kind: "text", value: tk.v });
742
  if (tk.t === "fn") {
743
  const name = tk.v;
744
+ // ⭐⭐ W54-T26: A BARE NAME IS NOT A CALL AND NOTHING CAN RESOLVE IT. `=FOO` names a thing,
745
+ // and NEITHER engine has named ranges, so no round trip to the server can turn it into a
746
+ // value. That makes it the one name this file may refuse on its own: `#NAME?`.
747
+ if (!isOp(peekTok(c), "(")) throw new FormulaError(NAME_NOT_FOUND);
748
  // ⭐ EVERY OTHER FUNCTION IN THE CATALOGUE IS THE SERVER'S. `IF`, `ROUND`, `TEXT` and the
749
  // rest are real formulas this file does not speak, so they take the `unsupported` road home
750
  // and keep working exactly as they did before this ticket (see the header).
751
+ // β›” WHICH IS WHY AN UNKNOWN CALL IS NOT `#NAME?` HERE. The server owns the catalogue; it
752
+ // answers `bad_formula` for a name no catalogue has, and `types.ts` reads THAT as `#NAME?`.
753
  if (!AGGREGATE_SET.has(name)) throw new Unsupported(name);
 
754
  take(c);
755
+ const from = rangeEndpoint(take(c), name);
756
+ if (!isOp(peekTok(c), ":")) throw new Unsupported(name);
757
  take(c);
758
+ const to = rangeEndpoint(take(c), name);
 
759
  if (!isOp(peekTok(c), ")")) throw new Unsupported(name);
760
  take(c);
761
+ return evalAggregate(name, rangeAddresses(from, to), get);
762
  }
763
  if (tk.t === "op" && tk.v === "(") {
764
  const inner = parseExpr(c, get);
 
838
  try {
839
  const tokens = tokenize(src);
840
  if (tokens.length === 0) return { kind: "empty" };
841
+ // ⭐ W54-T26: `="hello"` IS ITS OWN TEXT, not a wrong-typed argument. Only once an operator
842
+ // or a function is involved does a literal coerce, which is the same distinction the bare
843
+ // reference below already draws.
844
+ const only = tokens.length === 1 ? tokens[0] : null;
845
+ if (only && only.t === "str") return { kind: "text", value: only.v };
846
  if (tokens.length === 1 && tokens[0].t === "ref") {
847
  const one = tokens[0];
848
  return one.t === "ref" ? get(one.v) : { kind: "empty" };
 
858
  } catch (err) {
859
  if (err instanceof PendingInput) return { kind: "pending" };
860
  if (err instanceof Unsupported) return { kind: "unsupported", reason: err.message };
861
+ // ⭐⭐ W54-T26: THE ONE DOOR AN ERROR LEAVES BY, AND IT LEAVES AS A VALUE WITH A CODE.
862
+ if (err instanceof FormulaError) return errorValue(err.message);
863
  return { kind: "error", message: "This formula could not be calculated." };
864
  }
865
  };
web/src/sheet/ribbonHome.tsx ADDED
@@ -0,0 +1,1226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // sheet/ribbonHome.tsx β€” the HOME TAB of the Sheet's ribbon (wave 54, base kit part 2a).
2
+ //
3
+ // ⭐⭐ WHY THIS FILE EXISTS. `Ribbon.tsx` was one file carrying both the SHELL (the tab strip, the
4
+ // four action buttons, the roving-focus handler) and every Home group, and two wave-54 lanes both
5
+ // needed to extend it: one adds groups here, one adds a whole Insert tab. Two lanes cannot share a
6
+ // file, so the shell kept the frame and each TAB now owns its own module. Nothing was rewritten in
7
+ // the move: every group below, and every comment on it, is the byte the shell carried before.
8
+ //
9
+ // ⭐ WHAT A TAB MODULE OWES THE SHELL. Three exports, and the shell reads only these:
10
+ // `HOME_KEYS` the control keys this tab renders, IN ROVING ORDER (the shell's `ControlKey`
11
+ // union is derived from them, so a control rendered under a name that is not here
12
+ // is a TYPE ERROR, exactly as it was when the arrays lived in the shell).
13
+ // `homeGroups` the groups themselves, as a function of the shell's `RibbonTabContext`. The
14
+ // context carries the shared control vocabulary (`control`, `group`, `word`,
15
+ // `item`) plus the state a group reads (`style`, `open`, `anchorEl`) and the two
16
+ // emissions (`apply`, `act`). β›” A TAB HOLDS NO STATE OF ITS OWN. The whole reason
17
+ // the shell is stateless toward the document survives the split: the selection,
18
+ // the cells and the commit still live in `SheetGrid.tsx`.
19
+ // `HOME_TAB` the descriptor the shell registers in `TABS`: its id, the `data-ribbon` key and
20
+ // key-tip of its tab button, its label, the class and the accessible name of the
21
+ // toolbar row it paints.
22
+ //
23
+ // ⚠ DESIGN CONTRACT (DESIGN.md 2 through 5) β€” unchanged and still binding here: icons are inline
24
+ // SVG on `currentColor` and never emoji, a colour swatch is a token-styled span, colour and type
25
+ // are token only, sentence case labels, no em dash or en dash in any string that reaches a screen.
26
+
27
+ import {
28
+ CELL_FONTS, CELL_FORMAT_KINDS, DEFAULT_CELL_FONT, FONT_SIZE_STEPS, FONT_STACKS,
29
+ clampFontPt, fontPt, isCellFormatKind, stepFontPt,
30
+ } from "./types";
31
+ import type { CSSProperties } from "react";
32
+ import type { CellFormatKind, CellStyle, CellStylePatch } from "./types";
33
+ // ⭐⭐ W54-T05 β€” THE PRESETS ARE WRITTEN THROUGH `paintPatch`, WHICH IS THE WHOLE OF WHY THIS
34
+ // IMPORT EXISTS. A cell style has to be a complete STYLE and not a name the renderer resolves
35
+ // later, so applying one must also CLEAR every key the preset does not want; `paintPatch` walks
36
+ // `STYLE_KEYS` and says `null` for each of them, which is exactly that shape. Hand listing the
37
+ // keys here would be a second key list to keep in step, and that list's own note calls a missing
38
+ // key a silent half paint.
39
+ import { paintPatch } from "./cellStyleOps";
40
+ // ⭐ The shell's own contract, TYPE ONLY. `import type` is erased at compile time, so the shell
41
+ // imports this module's values while this module imports only the shell's types: there is no
42
+ // import cycle at runtime at all.
43
+ import type { RibbonTabContext } from "./Ribbon";
44
+ // ⭐ W52-T16 (instruction 18, ruling R4) β€” the new Clipboard/Editing/Cells/Styles icons live in
45
+ // their own file (`ribbonIcons.tsx`) rather than growing this one further; the icons already in
46
+ // THIS file (IconAlign, IconVAlign, ...) stay here β€” see that file's own header for why.
47
+ import {
48
+ IconAutoSum, IconCellFormat, IconClear, IconConditional, IconCopy, IconCut, IconDelete,
49
+ IconFillDown, IconFillRight, IconFormatPainter, IconInsert, IconPaste,
50
+ } from "./ribbonIcons";
51
+ import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
52
+ // ⭐ W54 base kit 2a β€” this tab's OWN stylesheet, a component-owned side-effect import for the
53
+ // same reason `styles/wave52/ribbon.css`'s header sets out. The shell keeps the shell rules; the
54
+ // Clipboard and Alignment layouts are Home layouts and travel with the Home groups.
55
+ import "../styles/wave54/ribbon-home.css";
56
+
57
+ const CLIPBOARD = ["paste", "cut", "copy", "painter"] as const;
58
+ // ⭐⭐ W54-T03 (instruction 4, rulings R10 + R11) β€” THE FONT GROUP IS TWO ROWS NOW, AND THE
59
+ // ARRAY IS RE-SEQUENCED TO THE READING ORDER, exactly as W53-T05 did for Alignment. Excel's top
60
+ // row is the family combo, the size box and the two size steppers; its bottom row is bold,
61
+ // italic, underline and then the border, fill and text colour. β›” THE ARRAY IS THE ROVING SOURCE
62
+ // AND THE JSX IS NOT: a key here with no `control(...)` rendering it makes ArrowRight land on
63
+ // nothing with every gate still green, and a `control(...)` under a key that is not here is a
64
+ // type error, so the two are changed together or not at all.
65
+ const FONT = [
66
+ "font", "size", "grow", "shrink",
67
+ "bold", "italic", "underline", "border", "fill", "color",
68
+ ] as const;
69
+ // ⭐⭐ W53-T05 (instruction 16) β€” TWO VISUAL ROWS, ONE ROVING ORDER, AND THE ORDER IS THE READING
70
+ // ORDER. Excel lays Alignment out as two rows, so this array is re-sequenced to match what the eye
71
+ // walks: top row (vertical align, then Wrap text), then bottom row (horizontal align, then the two
72
+ // indents). β›” THE ARRAY IS THE ROVING SOURCE AND THE JSX IS NOT: a key listed here with no
73
+ // `control(...)` call rendering it makes ArrowRight land on nothing, with every gate still green,
74
+ // so the two are changed together or not at all.
75
+ // ⭐⭐ W54-T06 (instruction 5, ruling R2) ADDS `orientation` TO THE TOP ROW, after Wrap text.
76
+ // The top row carried four controls against the bottom row's five, so the group takes no extra
77
+ // width at all: measured at 1440x900 the strip's group edges are unchanged by this ticket.
78
+ const ALIGNMENT = [
79
+ "top", "middle", "bottom", "wrap", "orientation",
80
+ "left", "center", "right", "outdent", "indent",
81
+ ] as const;
82
+ const NUMBER = ["format", "currency", "percent", "comma", "decless", "decmore"] as const;
83
+ // ⭐⭐ W54-T05 (instruction 5, ruling R2) β€” STYLES IS TWO CONTROLS AND TWO ROWS. Excel's own
84
+ // Styles group stacks Conditional Formatting over Format as Table over Cell Styles; R2 removes the
85
+ // middle one outright (owner: the table function IS the data module), so what is left is the pair.
86
+ // β›” THE ARRAY IS THE ROVING SOURCE AND THE JSX IS NOT: a key here with no `control(...)` call
87
+ // makes ArrowRight land on nothing with every gate green, and a `control(...)` under a key that is
88
+ // not here is a type error, so the two are changed together or not at all.
89
+ const STYLES = ["conditional", "cellstyles"] as const;
90
+ const CELLS = ["insert", "delete", "cellformat"] as const;
91
+ // ⭐⭐ W54-T07 (instruction 5, ruling R2) β€” EDITING IS TWO ROWS AND GAINS FIND AND SELECT.
92
+ // Top row: AutoSum, Fill down, Fill right. Bottom row: Clear, then the new Find and select
93
+ // gallery. β›” THE STACK IS A WIDTH DECISION, NOT A TIDY (D-663): Editing is the LAST group in the
94
+ // strip and measured at 1440x900 it ended at 1385 of a 1440 viewport, so a fifth control laid
95
+ // beside the other four would have taken most of the 55px that was left. Stacked, the group is
96
+ // three controls wide instead of five, so the strip is NARROWER after this ticket than before it.
97
+ // β›” THE ARRAY IS THE ROVING SOURCE AND THE JSX IS NOT: a key here with no `control(...)` makes
98
+ // ArrowRight land on nothing with every gate still green, and a `control(...)` under a key that is
99
+ // not here is a type error, so the two are changed together or not at all. The order below is the
100
+ // READING order, top row first, exactly as Alignment and Font sequence theirs.
101
+ const EDITING = ["autosum", "filldown", "fillright", "clear", "findselect"] as const;
102
+
103
+ /**
104
+ * ⭐⭐ THE HOME TAB'S ROVING ORDER, WHICH IS ALSO ITS TYPE. The shell spreads this into the union
105
+ * every `control(...)` key is checked against, so the arrays above stay the single source of both
106
+ * the reading order and the vocabulary.
107
+ * β›” THE ARRAY IS THE ROVING SOURCE AND THE JSX IS NOT: a key listed here with no `control(...)`
108
+ * call rendering it makes ArrowRight land on nothing, with every gate still green, so the two are
109
+ * changed together or not at all.
110
+ */
111
+ export const HOME_KEYS = [
112
+ ...CLIPBOARD, ...FONT, ...ALIGNMENT, ...NUMBER, ...STYLES, ...CELLS, ...EDITING,
113
+ ] as const;
114
+
115
+ /**
116
+ * The ink a person may choose, as TOKEN NAMES.
117
+ *
118
+ * β›” A HEX HERE WOULD OUTLIVE THE PALETTE. What is stored in the workbook is this string, and
119
+ * `SheetGrid.tsx` resolves it against the document at paint time, so a palette change repaints
120
+ * every sheet ever written. The `*-deep` tones are the text safe end of each hue (DESIGN.md 3);
121
+ * the pale ones are fills and are never offered as ink.
122
+ */
123
+ const INKS: { token: string; label: string }[] = [
124
+ { token: "--lp-ink", label: "Default" },
125
+ { token: "--lp-muted", label: "Muted" },
126
+ { token: "--lp-blue-deep", label: "Blue" },
127
+ { token: "--lp-green-deep", label: "Green" },
128
+ { token: "--lp-yellow-deep", label: "Amber" },
129
+ { token: "--lp-red-deep", label: "Red" },
130
+ { token: "--lp-purple-deep", label: "Purple" },
131
+ ];
132
+
133
+ /**
134
+ * ⭐ W54-T06 β€” THE FIVE TURNS EXCEL OFFERS, in Excel's own order and its own words.
135
+ *
136
+ * β›” THE DEGREES ARE THE DOCUMENT'S, NOT THE CANVAS'S. A positive degree is counterclockwise, the
137
+ * way a protractor reads and the way `platform/core/sheets.py::_clean_style` clamps
138
+ * ({@link MIN_TEXT_ROTATION} through {@link MAX_TEXT_ROTATION}); `SheetGrid.tsx::paintCell`
139
+ * negates it once when it turns the context, because a canvas y grows downward.
140
+ *
141
+ * ⚠ ZERO IS THE CLEAR, and it is written as `null` where it is applied so the key is REMOVED.
142
+ */
143
+ const ORIENTATIONS: { label: string; degrees: number }[] = [
144
+ { label: "Angle counterclockwise", degrees: 45 },
145
+ { label: "Angle clockwise", degrees: -45 },
146
+ { label: "Rotate text up", degrees: 90 },
147
+ { label: "Rotate text down", degrees: -90 },
148
+ { label: "Horizontal", degrees: 0 },
149
+ ];
150
+
151
+ /** The fills, which are the tint end of the same hues, so ink stays readable on every one. */
152
+ const FILLS: { token: string; label: string }[] = [
153
+ { token: "--lp-surface-2", label: "Grey" },
154
+ { token: "--lp-blue-tint", label: "Blue" },
155
+ { token: "--lp-green-tint", label: "Green" },
156
+ { token: "--lp-yellow-tint", label: "Amber" },
157
+ { token: "--lp-red-tint", label: "Red" },
158
+ { token: "--lp-purple-tint", label: "Purple" },
159
+ ];
160
+
161
+ /**
162
+ * ⭐⭐ W54-T05 (instruction 5) β€” THE NAMED CELL STYLES, AS REAL VALUES AND NEVER AS A NAME.
163
+ *
164
+ * β›”β›” THE DOCUMENT NEVER LEARNS THAT A PRESET EXISTED. What is written is `{bold: true,
165
+ * size: 15, color: "--lp-blue-deep"}`, so nothing downstream has to resolve a style NAME: not the
166
+ * painter, not `core/sheets.py`, not an export, not a second workbook that never heard of this
167
+ * table. That is the done-when's own clause, and it is also what makes a preset safe to rename or
168
+ * retire later without touching a single stored sheet.
169
+ *
170
+ * ⭐ NORMAL IS THE ONE THAT CLEARS, and it clears by being EMPTY rather than by listing what to
171
+ * remove: `paintPatch({})` says `null` for every key in `STYLE_KEYS`, so Normal stays correct on
172
+ * the day a new style key is added and every other preset does too.
173
+ *
174
+ * ⚠ NO PRESET SETS A `size` EXCEPT HEADING, and Heading's is a POINT size (R11's widened slot),
175
+ * not a step name. A preset that quietly resized everything it touched would be the one thing a
176
+ * person cannot undo by pressing the preset they had before.
177
+ */
178
+ const CELL_STYLES: { id: string; label: string; style: CellStyle }[] = [
179
+ { id: "normal", label: "Normal", style: {} },
180
+ { id: "heading", label: "Heading", style: { bold: true, size: 15, color: "--lp-blue-deep" } },
181
+ { id: "total", label: "Total", style: { bold: true, border: { top: true, bottom: true } } },
182
+ {
183
+ id: "currency", label: "Currency",
184
+ style: { align: "right", format: { kind: "currency", decimals: 2 } },
185
+ },
186
+ { id: "good", label: "Good", style: { fill: "--lp-green-tint", color: "--lp-green-deep" } },
187
+ { id: "bad", label: "Bad", style: { fill: "--lp-red-tint", color: "--lp-red-deep" } },
188
+ {
189
+ id: "neutral", label: "Neutral",
190
+ style: { fill: "--lp-yellow-tint", color: "--lp-yellow-deep" },
191
+ },
192
+ ];
193
+
194
+ /**
195
+ * Each preset's own name, shown IN the preset, which is what makes the list a gallery rather than
196
+ * a menu of words.
197
+ *
198
+ * β›” IT PREVIEWS THE WEIGHT, THE SLANT AND THE TWO COLOURS, AND NEVER THE SIZE. This is the same
199
+ * carve-out the font family gallery above takes and it stops at the same line: an inline
200
+ * `fontSize` would be type in a place the token scale does not reach (DESIGN.md 2), and a 15pt row
201
+ * in a 26px menu would resize the menu rather than describe the style. The colours are `var(...)`
202
+ * TOKEN references, never hues.
203
+ */
204
+ const previewStyle = (style: CellStyle): CSSProperties => ({
205
+ fontWeight: style.bold ? 600 : undefined,
206
+ fontStyle: style.italic ? "italic" : undefined,
207
+ color: style.color ? `var(${style.color})` : undefined,
208
+ background: style.fill ? `var(${style.fill})` : undefined,
209
+ });
210
+
211
+ /**
212
+ * β›” THE FIVE THE DOCUMENT MODEL CARRIES, AND ONLY THOSE. `CELL_FORMAT_KINDS` is mirrored in
213
+ * `platform/core/sheets.py` and a sixth spelling is REFUSED by name on the way in, so R8's
214
+ * Accounting and Custom code are offered as ACTS (`format-accounting`, `format-custom`) rather
215
+ * than smuggled in here as a kind the server would reject.
216
+ */
217
+ const FORMAT_LABEL: Record<CellFormatKind, string> = {
218
+ general: "General",
219
+ number: "Number",
220
+ currency: "Currency",
221
+ percent: "Percent",
222
+ date: "Date",
223
+ };
224
+
225
+ // ⭐ W52-T17 β€” each entry carries its own ONE-LETTER key-tip badge, painted fresh once `Alt, H, B`
226
+ // opens this gallery (KT-11). Non-colliding within the gallery's own scope, which is all KT-11
227
+ // requires: a two-letter code from a DIFFERENT depth (Home's own "B" for this same control, or
228
+ // Styles' "L") means nothing here, because depth scopes the badge set entirely.
229
+ const BORDERS: { id: string; label: string; sides: Record<string, boolean>; kt: string }[] = [
230
+ { id: "all", label: "All sides", sides: { top: true, right: true, bottom: true, left: true }, kt: "A" },
231
+ { id: "top", label: "Top", sides: { top: true }, kt: "T" },
232
+ { id: "right", label: "Right", sides: { right: true }, kt: "R" },
233
+ { id: "bottom", label: "Bottom", sides: { bottom: true }, kt: "B" },
234
+ { id: "left", label: "Left", sides: { left: true }, kt: "L" },
235
+ ];
236
+
237
+ /**
238
+ * ⭐⭐ W54-T03: THE TWO A GLYPHS, DRAWN. Excel's Increase Font Size is a large A beside an up
239
+ * arrow and its Decrease is a small A beside a down arrow, and the whole of the difference the
240
+ * eye reads is the size of the letter. Both are inline SVG on `currentColor` from this file's own
241
+ * vocabulary (DESIGN.md 2): never an icon pack, and never a real letter scaled by a `font-size`,
242
+ * which would be type in a place the token scale does not reach.
243
+ */
244
+ function IconFontStep({ up }: { up: boolean }) {
245
+ const letter = up ? "M1.9 12.8L6.1 3.3l4.2 9.5" : "M3.2 12.8L6.1 6.4l2.9 6.4";
246
+ const bar = up ? "M3.5 10.2h5.2" : "M4.4 10.9h3.4";
247
+ const stem = up ? "M13.3 12.4V4.3" : "M13.3 4.3v8.1";
248
+ const head = up ? "M11.5 6.1l1.8-1.8 1.8 1.8" : "M11.5 10.6l1.8 1.8 1.8-1.8";
249
+ return (
250
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
251
+ <path d={letter} />
252
+ <path d={bar} />
253
+ <path d={stem} />
254
+ <path d={head} />
255
+ </svg>
256
+ );
257
+ }
258
+
259
+ function IconAlign({ to }: { to: "left" | "center" | "right" }) {
260
+ // Four rules; the short ones move, which is what says left, centre or right without a word.
261
+ const short = to === "left" ? "M2.5 8h6M2.5 12h7"
262
+ : to === "center" ? "M4.5 8h7M3.5 12h9"
263
+ : "M7.5 8h6M6.5 12h7";
264
+ return (
265
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
266
+ <path d="M2.5 4h11" />
267
+ <path d={short} />
268
+ </svg>
269
+ );
270
+ }
271
+
272
+ /** The vertical three: a cell box, with the text rule sitting where the value would land. */
273
+ function IconVAlign({ to }: { to: "top" | "middle" | "bottom" }) {
274
+ const y = to === "top" ? 5 : to === "middle" ? 8 : 11;
275
+ return (
276
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
277
+ <rect x="2.6" y="2.6" width="10.8" height="10.8" rx="1" />
278
+ <path d={`M5 ${y}h6`} />
279
+ </svg>
280
+ );
281
+ }
282
+
283
+ function IconWrap() {
284
+ return (
285
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
286
+ <path d="M2.5 4.5h11" />
287
+ <path d="M2.5 8h8.5a2 2 0 0 1 0 4H7" />
288
+ <path d="M8.6 10.4L7 12l1.6 1.6" />
289
+ </svg>
290
+ );
291
+ }
292
+
293
+ /**
294
+ * ⭐ W54-T06 β€” ORIENTATION: a letter STANDING ON A SLOPE, with the turn shown as a small arc.
295
+ * Drawn as paths on `currentColor` like every other icon here (DESIGN.md 3): the letter is two
296
+ * strokes and a crossbar inside a rotated group, never a glyph in a font and never an icon pack,
297
+ * so it inherits the button's ink and needs no second colour of its own.
298
+ */
299
+ function IconOrientation() {
300
+ return (
301
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
302
+ <g transform="rotate(-45 7.2 8.6)">
303
+ <path d="M4.4 11.6L7.2 4.8l2.8 6.8" />
304
+ <path d="M5.4 9.4h3.6" />
305
+ </g>
306
+ <path d="M11.2 13.2a4.4 4.4 0 0 0 1.8-3.4" />
307
+ <path d="M11.9 8.7l1.1 1.1 1.1-1.1" />
308
+ </svg>
309
+ );
310
+ }
311
+
312
+ function IconIndent({ out }: { out: boolean }) {
313
+ const arrow = out ? "M6.6 6.4L4.6 8l2 1.6" : "M4.6 6.4L6.6 8l-2 1.6";
314
+ return (
315
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
316
+ <path d="M2.5 3.5h11" />
317
+ <path d="M8.5 6.5h5M8.5 9.5h5" />
318
+ <path d="M2.5 12.5h11" />
319
+ <path d={arrow} />
320
+ </svg>
321
+ );
322
+ }
323
+
324
+ function IconInk() {
325
+ return (
326
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
327
+ <path d="M4.5 11.5L8 3.2l3.5 8.3" />
328
+ <path d="M5.9 9.1h4.2" />
329
+ </svg>
330
+ );
331
+ }
332
+
333
+ function IconFill() {
334
+ return (
335
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
336
+ <path d="M3.4 8.2l4.4-4.4 4.5 4.4-4.5 4.5z" />
337
+ <path d="M13.4 10.4c.7 1 .7 2.2-.4 2.2s-1.1-1.2-.4-2.2z" />
338
+ </svg>
339
+ );
340
+ }
341
+
342
+ function IconBorder() {
343
+ return (
344
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
345
+ <rect x="2.6" y="2.6" width="10.8" height="10.8" rx="1" />
346
+ <path d="M8 2.6v10.8M2.6 8h10.8" />
347
+ </svg>
348
+ );
349
+ }
350
+
351
+ /** Two decimal dots and the direction the count moves. Never a glyph, never a dash. */
352
+ function IconDecimals({ more }: { more: boolean }) {
353
+ const arrow = more ? "M9.4 6.2L11.4 8l-2 1.8" : "M11.4 6.2L9.4 8l2 1.8";
354
+ return (
355
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
356
+ <path d="M3 11.6h.01M6 11.6h.01" />
357
+ <path d="M3 5.5v3.4M6 5.5v3.4" />
358
+ <path d={arrow} />
359
+ </svg>
360
+ );
361
+ }
362
+
363
+ /**
364
+ * ⭐ W54-T05 β€” CELL STYLES: a cell with a heading band across its top and two rules of body text
365
+ * under it, which is a styled cell rather than a letter. Drawn here rather than in
366
+ * `ribbonIcons.tsx` because that file belongs to another ticket's fence this wave; same
367
+ * vocabulary either way (16 by 16, `currentColor`, `.sheet-ribbon-icon`, no icon pack, no emoji).
368
+ */
369
+ function IconCellStyles() {
370
+ return (
371
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
372
+ <rect x="2.4" y="2.6" width="11.2" height="10.8" rx="1" />
373
+ <path d="M2.4 6.2h11.2" />
374
+ <path d="M4.8 9h6.4M4.8 11.2h4.2" />
375
+ </svg>
376
+ );
377
+ }
378
+
379
+ /**
380
+ * ⭐ W54-T07 β€” FIND AND SELECT: a magnifier over a ruled page, which is Excel's own reading of the
381
+ * control (it searches the sheet and it JUMPS the selection somewhere). Drawn here rather than in
382
+ * `ribbonIcons.tsx` because that file belongs to another ticket's fence this wave; same vocabulary
383
+ * either way (16 by 16, `currentColor`, `.sheet-ribbon-icon`, no icon pack, no emoji).
384
+ */
385
+ function IconFindSelect() {
386
+ return (
387
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
388
+ <circle cx="7" cy="7" r="4.1" />
389
+ <path d="M10.1 10.1l3.3 3.3" />
390
+ <path d="M2.6 13.4h4" />
391
+ </svg>
392
+ );
393
+ }
394
+
395
+ export function IconCaret() {
396
+ return (
397
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-caret">
398
+ <path d="M5 6.5L8 9.5l3-3" />
399
+ </svg>
400
+ );
401
+ }
402
+
403
+ /**
404
+ * ⭐⭐ EVERY HOME GROUP, IN R8's ORDER. Moved here whole from `Ribbon.tsx`; the shell renders the
405
+ * result inside the one `role="toolbar"` row it still owns, so the DOM this paints is the DOM it
406
+ * painted before, to the pixel.
407
+ */
408
+ export const homeGroups = (ctx: RibbonTabContext) => {
409
+ const {
410
+ style, frozen, open, anchorEl, onApply, apply, act, openPop, closePop,
411
+ control, group, word, item,
412
+ } = ctx;
413
+
414
+ const swatches = (
415
+ which: "color" | "fill",
416
+ list: { token: string; label: string }[],
417
+ ) => (
418
+ <AnchoredOverlay
419
+ anchor={anchorEl}
420
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
421
+ onDismiss={closePop}
422
+ role="menu"
423
+ ariaLabel={which === "color" ? "Text colour" : "Fill colour"}
424
+ initialFocus="none"
425
+ >
426
+ <div className="sheet-ribbon-swatches">
427
+ {list.map((entry) => (
428
+ <button
429
+ key={entry.token}
430
+ type="button"
431
+ role="menuitem"
432
+ className="sheet-ribbon-swatch"
433
+ aria-label={entry.label}
434
+ title={entry.label}
435
+ onMouseDown={(e) => e.preventDefault()}
436
+ onClick={() => apply({ [which]: entry.token } as CellStylePatch)}
437
+ >
438
+ <span className="sheet-ribbon-chip" style={{ background: `var(${entry.token})` }} />
439
+ </button>
440
+ ))}
441
+ </div>
442
+ <button
443
+ type="button"
444
+ role="menuitem"
445
+ className="sheet-ribbon-item"
446
+ onMouseDown={(e) => e.preventDefault()}
447
+ onClick={() => apply({ [which]: null } as CellStylePatch)}
448
+ >
449
+ {which === "color" ? "Reset the text colour" : "No fill"}
450
+ </button>
451
+ </AnchoredOverlay>
452
+ );
453
+
454
+ // ── W54-T03 (instruction 4, R10 + R11): what the Font group READS off the anchor cell ──────
455
+ //
456
+ // ⭐⭐ NO NEW ACT AND NO SHELL EDIT. `apply()` already takes a `CellStylePatch` and `style` is
457
+ // already the anchor cell's own style, so the family picker is a patch, the size box is a patch
458
+ // and each stepper is a patch computed from the size that is there. `RibbonActionKind` gains no
459
+ // member and `SheetGrid.tsx::onRibbonAction` gains no case, which is what keeps this ticket
460
+ // inside one lane's files.
461
+ //
462
+ // ⚠ THE GRID'S `case "font-size":` ARM SURVIVES AND IS SIMPLY NO LONGER SPOKEN TO. It maps the
463
+ // retired Small/Normal/Large/Heading menu onto the four step names; nothing in this file emits
464
+ // that act any more, and the arm is in a file this lane does not own.
465
+ const points = fontPt(style?.size);
466
+ const family = style?.font ?? DEFAULT_CELL_FONT;
467
+
468
+ /**
469
+ * Read the size box and write what it asked for, NORMALIZING the box either way.
470
+ *
471
+ * ⚠ IT CLAMPS RATHER THAN REFUSES, exactly as the rotation and the indent do: 400 is somebody
472
+ * asking for the largest there is, not an entry that has to be rejected. Text that is not a
473
+ * number at all snaps back to the size the cell already had, so the box can never be left
474
+ * showing something the document does not say.
475
+ */
476
+ const commitPoints = (input: HTMLInputElement) => {
477
+ const asked = Number.parseInt(input.value.trim(), 10);
478
+ const next = Number.isFinite(asked) ? clampFontPt(asked) : points;
479
+ input.value = String(next);
480
+ if (next !== points) apply({ size: next });
481
+ };
482
+
483
+ // ── W54-T06 (instruction 5, R2): what the Alignment group READS off the anchor cell ──────
484
+ //
485
+ // ⚠ UPRIGHT IS AN ABSENCE, so the readback normalizes it to zero rather than to `undefined`:
486
+ // the gallery's Horizontal entry has to be able to show as the one that is ON, and a cell that
487
+ // was never turned is exactly as horizontal as one that was turned back.
488
+ const rotation = typeof style?.textRotation === "number" ? style.textRotation : 0;
489
+ const turned = rotation !== 0;
490
+
491
+ const format = style?.format;
492
+ const kind: CellFormatKind = format?.kind ?? "general";
493
+ const decimals = format?.decimals ?? (kind === "currency" ? 2 : 0);
494
+ /** Stepping decimals on a date or on an unformatted cell means the cell becomes a number. */
495
+ const numeric: CellFormatKind =
496
+ kind === "currency" || kind === "percent" ? kind : "number";
497
+
498
+ const stepDecimals = (delta: number) => onApply({
499
+ format: {
500
+ ...format,
501
+ kind: numeric,
502
+ decimals: Math.min(10, Math.max(0, decimals + delta)),
503
+ },
504
+ });
505
+
506
+ return (
507
+ <>
508
+ {/* ⭐⭐ W52-T16 (instruction 18, ruling R4) β€” THE ARRANGEMENT INSTRUCTION 18 NAMES
509
+ EXPLICITLY: a large split Paste on the left (icon above, caption below) with Cut,
510
+ Copy and Format painter stacked as three small icon+label rows to its right,
511
+ exactly like Excel's own Clipboard group.
512
+ ⚠ DOCUMENTED DEVIATION (contract C4) β€” real Excel's Paste is a SPLIT button: a
513
+ direct click pastes, and a separate caret opens Paste Special and friends. This
514
+ app's `RibbonActionKind` union (`SheetGrid.tsx`'s exhaustive switch, OUTSIDE this
515
+ ticket's file fence) has no act for those sub-options, and adding one is lane B's
516
+ surface, not this ticket's. So Paste stays a SINGLE button here β€” same tall
517
+ left-slot layout Excel uses, still firing `act("paste")` directly on click, with
518
+ `data-kt="V"` and no `data-kt-opens` (it does not actually open a menu in this
519
+ codebase). The LAYOUT is what instruction 18 and R4 ask for; the backend act stays
520
+ exactly what W51-T16 already built. */}
521
+ {group("Clipboard", (
522
+ <div className="sheet-ribbon-clip">
523
+ <span className="sheet-ribbon-paste-large">
524
+ {control("paste", "Paste", <>{<IconPaste />}{word("Paste")}</>,
525
+ () => act("paste"), false, undefined, "V")}
526
+ </span>
527
+ {/* ⭐⭐ W53-T06 (owner instruction 17) β€” CUT, COPY AND FORMAT PAINTER ARE ICONS,
528
+ WITH NO WORD BESIDE THEM. Excel's Clipboard group is one large captioned Paste
529
+ and three small icon-only controls; a caption beside a 26px button is the one
530
+ thing its Home ribbon never does. Paste KEEPS its caption, and that is the
531
+ faithful reading rather than an inconsistency: the researched convention is
532
+ that only a wide combo box or a TALL two-row-spanning button carries text, and
533
+ the large Paste is exactly that.
534
+ β›” THE LABEL IS NOT DELETED, ONLY THE PAINTED WORD. `control()` writes its
535
+ `label` argument into BOTH `aria-label` and `title`, so a screen reader still
536
+ announces "Format painter" and a hover still says it. That matters twice over:
537
+ `verify_api.py`'s `_RIBBON_GROUPS` pins the literals `"Cut"`, `"Copy"` and
538
+ `"Format painter"` as the proof this group still offers what R8 names, and an
539
+ icon-only control with no accessible name is a regression no gate in this repo
540
+ would catch. */}
541
+ <div className="sheet-ribbon-clip-stack">
542
+ {control("cut", "Cut", <IconCut />, () => act("cut"),
543
+ false, undefined, "X")}
544
+ {control("copy", "Copy", <IconCopy />, () => act("copy"),
545
+ false, undefined, "C")}
546
+ {control("painter", "Format painter", <IconFormatPainter />,
547
+ () => act("format-painter"), false, undefined, "FP")}
548
+ </div>
549
+ </div>
550
+ ))}
551
+
552
+ {/* ⭐⭐ W54-T03 (owner instruction 4, rulings R10 + R11) β€” THE FONT GROUP IS EXCEL'S OWN
553
+ TWO ROWS. Top row: the font FAMILY combo, then the editable font SIZE box with its own
554
+ gallery caret, then Increase and Decrease font size. Bottom row: bold, italic, underline,
555
+ then borders, fill colour and text colour, which is exactly what this group carried
556
+ before. The mechanism is the one Clipboard and Alignment already established: a COLUMN
557
+ wrapper inside `.sheet-ribbon-group-controls`, each row a plain row flex of the SAME
558
+ `.sheet-ribbon-btn` buttons, no new control shape and no new button size.
559
+
560
+ β›”β›” TWO ROWS IS NOT MERELY FAITHFUL, IT IS THE CONSTRAINT (D-663). The strip already
561
+ overflows: measured on this tree at 1440x900, Cells and Editing are past the right edge
562
+ already, and a family combo added to a single-line Font group would have pushed Number off
563
+ too. Two 26px rows fill `--sheet-ribbon-band` exactly, so the ribbon does not grow by a
564
+ pixel in either direction; the group is in fact NARROWER than the one line it replaces.
565
+
566
+ ⭐ R10 IN ONE SENTENCE: the family control styles CELL CONTENT and nothing else. The
567
+ shell, this ribbon and every label stay Inter; what a person sets a cell in is that cell's
568
+ data, exactly as its fill colour is, and `types.ts`'s note on `CELL_SIZES` was rewritten
569
+ in this same change to say so rather than to say the opposite.
570
+ ⭐ R11 IN ONE SENTENCE: the size box widens the EXISTING `size` slot to a point size on
571
+ both halves of the document. There is no second `fontSize` field to disagree with it. */}
572
+ {group("Font", (
573
+ <div className="sheet-ribbon-font">
574
+ <div className="sheet-ribbon-font-row">
575
+ {/* ⚠ THE COMBO SHOWS THE FACE THE ANCHOR CELL IS IN, and it names the default rather
576
+ than going blank when the cell carries none: a blank combo reads as "no answer"
577
+ where the truth is "the default one". */}
578
+ <span className="sheet-ribbon-slot sheet-ribbon-fontname">
579
+ {control("font", "Font", <>{word(family)}<IconCaret /></>,
580
+ openPop("font"), !!style?.font, open === "font",
581
+ "FF", "gallery")}
582
+ {open === "font" && (
583
+ <AnchoredOverlay
584
+ anchor={anchorEl}
585
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
586
+ onDismiss={closePop}
587
+ role="menu"
588
+ ariaLabel="Font"
589
+ initialFocus="none"
590
+ >
591
+ {/* β›” EACH NAME IS PREVIEWED IN ITS OWN FACE, which is why these are written out
592
+ rather than passed through `item()`. The inline `fontFamily` is the SAME
593
+ carve-out the colour swatches above take for their inline `background`: what
594
+ is being shown is the DATA a person is choosing, not app chrome, so the token
595
+ scale has nothing to say about it. No size is set here, and none may be. */}
596
+ {CELL_FONTS.map((name) => (
597
+ <button
598
+ key={name}
599
+ type="button"
600
+ role="menuitemradio"
601
+ aria-checked={name === family}
602
+ className={"sheet-ribbon-item" + (name === family ? " is-on" : "")}
603
+ style={{ fontFamily: FONT_STACKS[name] }}
604
+ onMouseDown={(e) => e.preventDefault()}
605
+ onClick={() => apply({ font: name })}
606
+ >
607
+ {name}
608
+ </button>
609
+ ))}
610
+ </AnchoredOverlay>
611
+ )}
612
+ </span>
613
+
614
+ {/* β›”β›” THE BOX COMES BEFORE THE CARET INSIDE THE SLOT, AND THAT ORDER IS LOAD BEARING
615
+ TWICE OVER. It is Excel's own arrangement, and `verify_ui.py::_RIBBON_KEYTIPS` pins
616
+ `control("size", ...)` to the sequence "FS" by scanning forward from that call, so
617
+ nothing may sit between the call and its own key-tip argument.
618
+ ⚠ THE INPUT IS THE ONE RIBBON CONTROL THAT MUST TAKE FOCUS. Every button here
619
+ cancels its own mousedown so the canvas keeps the keyboard; a box a person types a
620
+ number into cannot do that. The selection is React state in `SheetGrid.tsx` and is
621
+ not glide's to drop, so the patch still lands on the cells that were selected. */}
622
+ <span className="sheet-ribbon-slot sheet-ribbon-fontsize">
623
+ <input
624
+ // Remounting on the anchor cell's own size is what keeps an UNCONTROLLED box
625
+ // honest: a tab module holds no state, so the document is the only thing that can
626
+ // say what this box reads, and a new key is how it says it.
627
+ key={points}
628
+ type="text"
629
+ inputMode="numeric"
630
+ className="sheet-ribbon-size-box"
631
+ aria-label="Font size in points"
632
+ title="Font size in points"
633
+ defaultValue={String(points)}
634
+ onKeyDown={(e) => {
635
+ // The toolbar's arrows belong to the toolbar only outside a text box. Inside one
636
+ // they belong to the caret, so this handler keeps them.
637
+ e.stopPropagation();
638
+ if (e.key === "Enter") e.currentTarget.blur();
639
+ if (e.key === "Escape") {
640
+ e.currentTarget.value = String(points);
641
+ e.currentTarget.blur();
642
+ }
643
+ }}
644
+ onBlur={(e) => commitPoints(e.currentTarget)}
645
+ />
646
+ {control("size", "Font size", <IconCaret />,
647
+ openPop("size"), false, open === "size",
648
+ "FS", "gallery")}
649
+ {open === "size" && (
650
+ <AnchoredOverlay
651
+ anchor={anchorEl}
652
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
653
+ onDismiss={closePop}
654
+ role="menu"
655
+ ariaLabel="Font size"
656
+ initialFocus="none"
657
+ >
658
+ {FONT_SIZE_STEPS.map((step) => item(
659
+ String(step), () => apply({ size: step }), step === points, "menuitemradio",
660
+ ))}
661
+ </AnchoredOverlay>
662
+ )}
663
+ </span>
664
+
665
+ {/* ⭐ THE TWO STEPPERS WALK THE GALLERY'S OWN LIST AND STOP AT ITS ENDS. `stepFontPt`
666
+ returns the size it was given when there is no next entry, so the largest and the
667
+ smallest are quiet no-ops rather than an error or a wrap around. From a size that is
668
+ not on the list at all, it walks to the nearest entry in the direction asked for. */}
669
+ {control("grow", "Increase font size", <IconFontStep up />,
670
+ () => apply({ size: stepFontPt(points, 1) }), false, undefined, "FG")}
671
+ {control("shrink", "Decrease font size", <IconFontStep up={false} />,
672
+ () => apply({ size: stepFontPt(points, -1) }), false, undefined, "FK")}
673
+ </div>
674
+
675
+ <div className="sheet-ribbon-font-row">
676
+ {control("bold", "Bold", <span className="sheet-ribbon-glyph is-bold">B</span>,
677
+ () => apply({ bold: !style?.bold }), style?.bold === true, undefined, "1")}
678
+ {control("italic", "Italic",
679
+ <span className="sheet-ribbon-glyph is-italic">I</span>,
680
+ () => apply({ italic: !style?.italic }), style?.italic === true, undefined, "2")}
681
+ {control("underline", "Underline",
682
+ <span className="sheet-ribbon-glyph is-underline">U</span>,
683
+ () => apply({ underline: !style?.underline }), style?.underline === true,
684
+ undefined, "3")}
685
+
686
+ <span className="sheet-ribbon-slot">
687
+ {control("border", "Borders", <><IconBorder /><IconCaret /></>,
688
+ openPop("border"),
689
+ Object.values(style?.border ?? {}).some(Boolean), open === "border",
690
+ "B", "gallery")}
691
+ {open === "border" && (
692
+ <AnchoredOverlay
693
+ anchor={anchorEl}
694
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
695
+ onDismiss={closePop}
696
+ role="menu"
697
+ ariaLabel="Borders"
698
+ initialFocus="none"
699
+ >
700
+ {BORDERS.map((entry) => item(
701
+ entry.label, () => apply({ border: entry.sides }), false, "menuitem", entry.kt,
702
+ ))}
703
+ {item("No border", () => apply({ border: null }), false, "menuitem", "N")}
704
+ </AnchoredOverlay>
705
+ )}
706
+ </span>
707
+
708
+ {/* ⚠ FILL COLOUR AND TEXT COLOUR BOTH OPEN A SWATCH POPOVER IN THIS CODEBASE
709
+ (`open === "fill"` / `open === "color"`), so both carry `data-kt-opens`
710
+ per the general C4 rule even though the ticket's own inline example list did
711
+ not annotate Fill colour with "/opens" β€” a judgment call, documented here and
712
+ in the HANDOFF, resolved in favour of matching the code's real behaviour. */}
713
+ <span className="sheet-ribbon-slot">
714
+ {control("fill", "Fill colour",
715
+ <><IconFill /><IconCaret /></>,
716
+ openPop("fill"), !!style?.fill, open === "fill",
717
+ "H", "gallery")}
718
+ {open === "fill" && swatches("fill", FILLS)}
719
+ </span>
720
+ <span className="sheet-ribbon-slot">
721
+ {control("color", "Text colour",
722
+ <><IconInk /><IconCaret /></>,
723
+ openPop("color"), !!style?.color,
724
+ open === "color", "FC", "gallery")}
725
+ {open === "color" && swatches("color", INKS)}
726
+ </span>
727
+ </div>
728
+ </div>
729
+ ))}
730
+
731
+ {/* ⭐⭐ W53-T05 (instruction 16) β€” ALIGNMENT IS TWO ROWS, NOT ONE LINE. Excel stacks
732
+ the vertical three over the horizontal three and hangs the rest to their right;
733
+ one long line was this group's only real departure from it. The mechanism is the
734
+ one `.sheet-ribbon-clip-stack` already established for Clipboard: a COLUMN wrapper
735
+ inside `.sheet-ribbon-group-controls`, which is itself a row flex, with each row a
736
+ plain row flex of the SAME `control()` buttons. No new control shape, no new
737
+ button size, and the two rows total 52px, which is exactly the height Clipboard's
738
+ large Paste already sets, so the ribbon does not grow by a pixel.
739
+ ⚠ THE SIX ALIGNMENT BUTTONS STAY ICON ONLY, and so does Wrap text: the researched
740
+ Excel convention is that only a WIDE combo box or a TALL two-row-spanning button
741
+ carries a caption, and none of these is either. `control()` writes the label into
742
+ both `aria-label` and `title`, so every one of them keeps its accessible name.
743
+ ⭐⭐ W54-T06 LANDED ORIENTATION, and the reason W53-T05 could not is worth keeping:
744
+ it assumed a new control meant a new `RibbonActionKind`, and the shell's switch
745
+ closes on `const _exhaustive: never = action.kind`, which no single lane could
746
+ extend. The base kit changed that answer by declaring `CellStyle.textRotation`, so
747
+ the turn is a STYLE PATCH through the `apply()` door every colour already uses and
748
+ no act was needed at all.
749
+ β›” MERGE AND CENTER IS STILL NOT HERE, and its reason has not changed: it needs a
750
+ merged-cell model `sheet/types.ts` does not have, so a control rendered anyway
751
+ would be the fake affordance `RibbonProps` refuses by name. Raised in the HANDOFF
752
+ as a PRD amendment instead. */}
753
+ {group("Alignment", (
754
+ <div className="sheet-ribbon-align">
755
+ <div className="sheet-ribbon-align-row">
756
+ {/* ⚠ TOP/MIDDLE/BOTTOM VERTICAL ALIGN HAS NO ROW IN THE TICKET'S OWN INLINE
757
+ KeyTip LIST (it names align top/middle/bottom as one of the examples with no
758
+ row to copy). `AT`/`AM`/`AB` follows the same two-letter shape the spec's
759
+ real Excel sequences use for the horizontal three (`AL`/`AC`/`AR`). */}
760
+ {control("top", "Align top", <IconVAlign to="top" />, () => act("align-top"),
761
+ false, undefined, "AT")}
762
+ {control("middle", "Align middle", <IconVAlign to="middle" />,
763
+ () => act("align-middle"), false, undefined, "AM")}
764
+ {control("bottom", "Align bottom", <IconVAlign to="bottom" />,
765
+ () => act("align-bottom"), false, undefined, "AB")}
766
+ {control("wrap", "Wrap text", <IconWrap />, () => act("wrap-text"),
767
+ false, undefined, "W")}
768
+
769
+ {/* ⭐⭐ W54-T06 (instruction 5, ruling R2) β€” TEXT ORIENTATION, AND IT NEEDED NO NEW
770
+ ACT. The base kit had already declared `CellStyle.textRotation` and
771
+ `core/sheets.py::_clean_style` already clamped and kept it, so `CellStylePatch`
772
+ carries the key and `apply({ textRotation: n })` writes it directly. That is why
773
+ this control could land inside one lane's files: `RibbonActionKind` gains no
774
+ member, so the shell's exhaustive switch in `SheetGrid.tsx` gains no arm and
775
+ `Ribbon.tsx` is untouched. The lane's OTHER three obligations were paid in the same
776
+ change - `stylePaints` counts the key, `paintCell` turns the canvas, and
777
+ `cellStyleOps.ts::STYLE_KEYS` names it so the Format painter clears it.
778
+ ⚠ FIVE ENTRIES, WHICH IS EXCEL'S OWN LIST MINUS THE ONE THIS SLOT CANNOT SAY.
779
+ Vertical stacked text is not a rotation at all (it is a per character layout), and
780
+ the slot is a signed degree between -90 and 90, so offering it would be a control
781
+ that writes nothing.
782
+ β›” HORIZONTAL WRITES `null`, NOT ZERO. `applyStylePatch` removes a null key, so a
783
+ cell turned and set back upright is byte for byte the cell it was; a stored zero
784
+ would leave an undo comparing unequal to the thing it undid. */}
785
+ <span className="sheet-ribbon-slot">
786
+ {control("orientation", "Orientation", <><IconOrientation /><IconCaret /></>,
787
+ openPop("orientation"), turned, open === "orientation",
788
+ "FQ", "gallery")}
789
+ {open === "orientation" && (
790
+ <AnchoredOverlay
791
+ anchor={anchorEl}
792
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
793
+ onDismiss={closePop}
794
+ role="menu"
795
+ ariaLabel="Orientation"
796
+ initialFocus="none"
797
+ >
798
+ {ORIENTATIONS.map((entry) => item(
799
+ entry.label,
800
+ () => apply({ textRotation: entry.degrees === 0 ? null : entry.degrees }),
801
+ rotation === entry.degrees,
802
+ "menuitemradio",
803
+ ))}
804
+ </AnchoredOverlay>
805
+ )}
806
+ </span>
807
+ </div>
808
+ <div className="sheet-ribbon-align-row">
809
+ {/* β›” THIS `.map` STAYS A MAP. Unrolling it into three literal `control("left",
810
+ ...)` calls would delete the `to === "left" ? "AL" : ...` ternary that
811
+ `verify_ui.py::_RIBBON_ALIGN_H_TERNARY` pins byte for byte β€” the horizontal
812
+ three are the one trio whose key is a variable, which is why their key-tips
813
+ are checked as that one expression rather than per call. */}
814
+ {(["left", "center", "right"] as const).map((to) => control(
815
+ to,
816
+ to === "left" ? "Align left" : to === "center" ? "Align centre" : "Align right",
817
+ <IconAlign to={to} />,
818
+ () => apply({ align: style?.align === to ? null : to }),
819
+ style?.align === to,
820
+ undefined,
821
+ to === "left" ? "AL" : to === "center" ? "AC" : "AR",
822
+ ))}
823
+ {control("outdent", "Decrease indent", <IconIndent out />,
824
+ () => act("indent-decrease"), false, undefined, "5")}
825
+ {control("indent", "Increase indent", <IconIndent out={false} />,
826
+ () => act("indent-increase"), false, undefined, "6")}
827
+ </div>
828
+ </div>
829
+ ))}
830
+
831
+ {group("Number", (
832
+ <>
833
+ <span className="sheet-ribbon-slot">
834
+ {control("format", "Number format",
835
+ <><span className="sheet-ribbon-label">{FORMAT_LABEL[kind]}</span><IconCaret /></>,
836
+ openPop("format"), kind !== "general",
837
+ open === "format", "N", "gallery")}
838
+ {open === "format" && (
839
+ <AnchoredOverlay
840
+ anchor={anchorEl}
841
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
842
+ onDismiss={closePop}
843
+ role="menu"
844
+ ariaLabel="Number format"
845
+ initialFocus="none"
846
+ >
847
+ {/* ⚠ FILTERED, AND D-671 IS WHY. Wave 54's base kit widened `CELL_FORMAT_KINDS`
848
+ to the server's six so the parity leg stops reading a drift, and `code` is the
849
+ sixth. `CellFormatKind` still EXCLUDES it, `types.ts` says in terms that the
850
+ ribbon's code item stays an ACT until W51-T20 lands the painter, and
851
+ `isCellFormatKind` is the predicate that file names for exactly this call. So
852
+ the menu offers the same five kinds it offered before, and the map is type
853
+ correct again rather than indexing a label table with a name that has no row. */}
854
+ {CELL_FORMAT_KINDS.filter(isCellFormatKind).map((entry) => (
855
+ <button
856
+ key={entry}
857
+ type="button"
858
+ role="menuitemradio"
859
+ aria-checked={entry === kind}
860
+ className={"sheet-ribbon-item" + (entry === kind ? " is-on" : "")}
861
+ onMouseDown={(e) => e.preventDefault()}
862
+ onClick={() => onApply(
863
+ entry === "general"
864
+ ? { format: null }
865
+ : {
866
+ format: {
867
+ kind: entry,
868
+ decimals: entry === "currency" ? 2 : entry === "date" ? undefined : 0,
869
+ thousands: format?.thousands,
870
+ },
871
+ },
872
+ )}
873
+ >
874
+ {FORMAT_LABEL[entry]}
875
+ </button>
876
+ ))}
877
+ {/* ⚠ THE TWO R8 NAMES THE DOCUMENT MODEL DOES NOT CARRY YET. They are acts,
878
+ not kinds: `clean_cell` refuses an unknown `format.kind` BY NAME, so
879
+ writing `accounting` here would refuse the whole cell. */}
880
+ {item("Accounting", () => act("format-accounting"))}
881
+ {item("Custom code", () => act("format-custom"))}
882
+ {/* ⚠ THE TWO OPTIONS A1 NAMES BY NAME: decimals, and thousands. They are
883
+ shown only where they mean something; a date has neither and a percent
884
+ groups by locale. */}
885
+ {(kind === "number" || kind === "currency" || kind === "percent") && (
886
+ <div className="sheet-ribbon-row">
887
+ <span className="sheet-ribbon-row-label">Decimal places</span>
888
+ <button
889
+ type="button"
890
+ className="sheet-ribbon-step"
891
+ aria-label="Fewer decimal places"
892
+ onMouseDown={(e) => e.preventDefault()}
893
+ onClick={() => stepDecimals(-1)}
894
+ >
895
+ Fewer
896
+ </button>
897
+ <span className="sheet-ribbon-count">{decimals}</span>
898
+ <button
899
+ type="button"
900
+ className="sheet-ribbon-step"
901
+ aria-label="More decimal places"
902
+ onMouseDown={(e) => e.preventDefault()}
903
+ onClick={() => stepDecimals(1)}
904
+ >
905
+ More
906
+ </button>
907
+ </div>
908
+ )}
909
+ {kind === "number" && (
910
+ <button
911
+ type="button"
912
+ role="menuitemcheckbox"
913
+ aria-checked={format?.thousands === true}
914
+ className={"sheet-ribbon-item" + (format?.thousands ? " is-on" : "")}
915
+ onMouseDown={(e) => e.preventDefault()}
916
+ onClick={() => onApply({
917
+ format: { ...format, kind, thousands: !format?.thousands },
918
+ })}
919
+ >
920
+ Thousands separator
921
+ </button>
922
+ )}
923
+ </AnchoredOverlay>
924
+ )}
925
+ </span>
926
+
927
+ {/* ⚠ CURRENCY HAS NO ROW IN THE TICKET'S OWN INLINE KeyTip LIST (named as one of
928
+ the examples with no row to copy). `CU` is invented, non-colliding. */}
929
+ {control("currency", "Currency",
930
+ <span className="sheet-ribbon-glyph">$</span>,
931
+ () => apply({ format: { kind: "currency", decimals: 2 } }),
932
+ kind === "currency", undefined, "CU")}
933
+ {control("percent", "Percent",
934
+ <span className="sheet-ribbon-glyph">%</span>,
935
+ () => apply({ format: { kind: "percent", decimals: 0 } }),
936
+ kind === "percent", undefined, "P")}
937
+ {control("comma", "Comma",
938
+ <span className="sheet-ribbon-glyph">,</span>,
939
+ () => apply({ format: { kind: "number", decimals: 2, thousands: true } }),
940
+ kind === "number" && format?.thousands === true, undefined, "K")}
941
+ {/* ⭐ THE TICKET'S OWN MAPPING: Increase decimal is the DIGIT `0`, decrease is `9`
942
+ (spec KT-T1 β€” Corporate Finance Institute's "Alt+H+O" for Increase Decimal is
943
+ almost certainly the digit rendered as a letter, since Decrease Decimal is
944
+ `9`). `decless` is this file's DECREASE control, `decmore` is INCREASE. */}
945
+ {control("decless", "Decrease decimals", <IconDecimals more={false} />,
946
+ () => stepDecimals(-1), false, undefined, "9")}
947
+ {control("decmore", "Increase decimals", <IconDecimals more />,
948
+ () => stepDecimals(1), false, undefined, "0")}
949
+ </>
950
+ ))}
951
+
952
+ {/* ⭐⭐ W53-T05 (D-663) β€” STYLES, CELLS AND EDITING ARE ICON ONLY FROM HERE. Measured
953
+ at the contract viewport, the seven groups wanted about 1,680px of the 864px the
954
+ ribbon actually has, so Styles, Cells and Editing were off the right edge entirely
955
+ and the owner could not see that AutoSum, Insert, Delete and Clear already exist.
956
+ A caption beside a small same-size button is also the one thing Excel's Home ribbon
957
+ never does: only a wide combo box or a tall two-row-spanning button carries text.
958
+ β›” THE LABEL IS NOT DELETED, ONLY THE PAINTED WORD. `control()` passes its `label`
959
+ into BOTH `aria-label` and `title`, so a screen reader still announces "Conditional
960
+ formatting" and a hover still says it. `verify_api.py`'s `_RIBBON_GROUPS` pins each
961
+ of those label literals, and they are all still right there in the call. */}
962
+ {/* ⭐⭐ W54-T05 (owner instruction 5, ruling R2) β€” STYLES IS TWO STACKED ROWS NOW.
963
+
964
+ Conditional formatting became a GALLERY: highlight-cells rules still open the editor
965
+ W51-T18 built, and the two new items build a rule FROM THE SELECTION and route it through
966
+ the same `saveRules` door rather than opening a second one. Cell styles is a gallery of
967
+ named presets that write real `CellStyle` values.
968
+
969
+ β›” FORMAT AS TABLE AND SORT AND FILTER ARE OUT, BY RULING R2, and that is a decision rather
970
+ than an omission. Owner, verbatim: the table function IS basically the data module itself,
971
+ so we do not need it.
972
+
973
+ ⭐ THE TWO ROWS ARE A WIDTH DECISION, NOT A TIDY (D-663). The strip already overflows at
974
+ 1440x900, and a second control laid beside the first would have pushed Editing further
975
+ past the right edge. Stacked, the group is 26px wide plus its carets instead of twice
976
+ that, and two 26px rows come to exactly `--sheet-ribbon-band`, so the ribbon does not grow
977
+ by a pixel in either direction. Same mechanism Clipboard, Alignment and Font already use.
978
+
979
+ β›” THE LABEL "Conditional formatting" IS BYTE-PINNED in `verify_api.py`'s `_RIBBON_GROUPS`
980
+ Styles tuple and its key-tip "L" in `verify_ui.py::_RIBBON_KEYTIPS`, so both stay exactly
981
+ where they were even though the control now opens a menu instead of firing an act. */}
982
+ {group("Styles", (
983
+ <div className="sheet-ribbon-styles">
984
+ <span className="sheet-ribbon-slot">
985
+ {control("conditional", "Conditional formatting",
986
+ <><IconConditional /><IconCaret /></>,
987
+ openPop("conditional"), false, open === "conditional", "L", "gallery")}
988
+ {open === "conditional" && (
989
+ <AnchoredOverlay
990
+ anchor={anchorEl}
991
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
992
+ onDismiss={closePop}
993
+ role="menu"
994
+ ariaLabel="Conditional formatting"
995
+ initialFocus="none"
996
+ >
997
+ {item("Highlight cells rules", () => act("conditional-formatting"))}
998
+ {item("Colour scales", () => act("colour-scale"))}
999
+ {item("Data bars", () => act("data-bars"))}
1000
+ {item("Manage rules", () => act("conditional-formatting"))}
1001
+ </AnchoredOverlay>
1002
+ )}
1003
+ </span>
1004
+ <span className="sheet-ribbon-slot">
1005
+ {control("cellstyles", "Cell styles",
1006
+ <><IconCellStyles /><IconCaret /></>,
1007
+ openPop("cellstyles"), false, open === "cellstyles", "J", "gallery")}
1008
+ {open === "cellstyles" && (
1009
+ <AnchoredOverlay
1010
+ anchor={anchorEl}
1011
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1012
+ onDismiss={closePop}
1013
+ role="menu"
1014
+ ariaLabel="Cell styles"
1015
+ initialFocus="none"
1016
+ >
1017
+ {/* β›” WRITTEN OUT RATHER THAN PASSED THROUGH `item()` FOR ONE REASON: each row
1018
+ previews itself in the style it applies, which `item()` has no slot for. It is
1019
+ the same carve-out the font family gallery above takes, and the click still
1020
+ goes through the SAME `apply(...)` door every other control in this file uses,
1021
+ with no act and no new plumbing at all. */}
1022
+ {CELL_STYLES.map((preset) => (
1023
+ <button
1024
+ key={preset.id}
1025
+ type="button"
1026
+ role="menuitem"
1027
+ className="sheet-ribbon-item"
1028
+ style={previewStyle(preset.style)}
1029
+ onMouseDown={(e) => e.preventDefault()}
1030
+ onClick={() => apply(paintPatch(preset.style))}
1031
+ >
1032
+ {preset.label}
1033
+ </button>
1034
+ ))}
1035
+ </AnchoredOverlay>
1036
+ )}
1037
+ </span>
1038
+ </div>
1039
+ ))}
1040
+
1041
+ {/* ⭐⭐ THE CELLS GROUP IS WHERE THE OLD "Rows and columns" STRIP WENT. Every act it
1042
+ carried is still here and still reaches the same page callback; what is gone is a
1043
+ second toolbar of its own. */}
1044
+ {group("Cells", (
1045
+ <>
1046
+ <span className="sheet-ribbon-slot">
1047
+ {control("insert", "Insert", <>{<IconInsert />}<IconCaret /></>,
1048
+ openPop("insert"), false, open === "insert",
1049
+ "I", "gallery")}
1050
+ {open === "insert" && (
1051
+ <AnchoredOverlay
1052
+ anchor={anchorEl}
1053
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1054
+ onDismiss={closePop}
1055
+ role="menu"
1056
+ ariaLabel="Insert"
1057
+ initialFocus="none"
1058
+ >
1059
+ {item("Insert row above", () => act("insert-row"))}
1060
+ {item("Insert column left", () => act("insert-column"))}
1061
+ {item("Add rows", () => act("add-rows"))}
1062
+ {item("Add columns", () => act("add-columns"))}
1063
+ </AnchoredOverlay>
1064
+ )}
1065
+ </span>
1066
+ <span className="sheet-ribbon-slot">
1067
+ {control("delete", "Delete", <>{<IconDelete />}<IconCaret /></>,
1068
+ openPop("delete"), false, open === "delete",
1069
+ "D", "gallery")}
1070
+ {open === "delete" && (
1071
+ <AnchoredOverlay
1072
+ anchor={anchorEl}
1073
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1074
+ onDismiss={closePop}
1075
+ role="menu"
1076
+ ariaLabel="Delete"
1077
+ initialFocus="none"
1078
+ >
1079
+ {item("Delete row", () => act("delete-row"))}
1080
+ {item("Delete column", () => act("delete-column"))}
1081
+ </AnchoredOverlay>
1082
+ )}
1083
+ </span>
1084
+ <span className="sheet-ribbon-slot">
1085
+ {control("cellformat", "Format",
1086
+ <>{<IconCellFormat />}<IconCaret /></>,
1087
+ openPop("cellformat"), false,
1088
+ open === "cellformat", "O", "gallery")}
1089
+ {open === "cellformat" && (
1090
+ <AnchoredOverlay
1091
+ anchor={anchorEl}
1092
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1093
+ onDismiss={closePop}
1094
+ role="menu"
1095
+ ariaLabel="Format"
1096
+ initialFocus="none"
1097
+ >
1098
+ {item("Row height", () => act("row-height"))}
1099
+ {item("Column width", () => act("column-width"))}
1100
+ {/* ⭐⭐ W54-T07 β€” THE TWO AUTOFITS SIT BESIDE THE TWO MANUAL SIZES, which is
1101
+ Excel's own arrangement and also the honest one: each pair is the same
1102
+ question asked once by hand and once from the content. Both act on the
1103
+ SELECTION, and the asymmetry between them is real rather than a shortcut,
1104
+ so `SheetGrid.tsx` states it where it is implemented: the document stores a
1105
+ width PER COLUMN and one shared row height, so a column fits itself and a
1106
+ row moves the base. */}
1107
+ {item("AutoFit row height", () => act("autofit-rows"))}
1108
+ {item("AutoFit column width", () => act("autofit-columns"))}
1109
+ {item("Hide rows", () => act("hide-rows"))}
1110
+ {item("Hide columns", () => act("hide-columns"))}
1111
+ {item("Unhide", () => act("unhide"))}
1112
+ {/* ⭐ W51-T34 LANDED, so this OPENS a Freeze panes panel offering rows and
1113
+ columns rather than toggling one column. The label had to move with the
1114
+ behaviour: a control that says "Freeze first column" and opens a
1115
+ two-axis panel is the kind of small lie an owner finds in the first
1116
+ minute. `aria-checked` still reports whether ANYTHING is frozen, which
1117
+ is the useful state for a person scanning the menu.
1118
+ ⚠ THE LABEL IS BYTE-PINNED in `verify_api.py`'s `_RIBBON_GROUPS` Cells
1119
+ tuple, so the two move in ONE commit or the rename reds a leg in a
1120
+ ticket that never touched this file. */}
1121
+ {item("Freeze panes", () => act("freeze"), frozen,
1122
+ "menuitemcheckbox")}
1123
+ </AnchoredOverlay>
1124
+ )}
1125
+ </span>
1126
+ </>
1127
+ ))}
1128
+
1129
+ {/* ⭐⭐ W54-T07 (owner instruction 5, ruling R2) β€” EDITING IS TWO ROWS AND FINISHES THE GROUP.
1130
+ Excel's Editing group is AutoSum, Fill, Clear, Sort & Filter and Find & Select; R2 removes
1131
+ Sort & Filter outright (owner, verbatim: the table function IS basically the data module
1132
+ itself), so what completes the group is Find and select and nothing else.
1133
+
1134
+ β›” THE STACK IS A WIDTH DECISION (D-663), and this is the group where it bites hardest:
1135
+ Editing is the LAST of the seven, so everything the six before it spend comes out of its
1136
+ own right edge. Two 26px rows come to exactly `--sheet-ribbon-band`, so the ribbon does not
1137
+ grow by a pixel in height, and three controls wide instead of five is a group NARROWER than
1138
+ the one it replaces. Same mechanism Clipboard, Alignment, Font and Styles already use.
1139
+
1140
+ ⭐ FIND AND SELECT OPENS THE FIND BOX THAT ALREADY EXISTS. `SheetGrid.tsx` has carried a
1141
+ `role="search"` panel since W51-T17 and Ctrl+F already reaches it; all three items here
1142
+ speak to that one surface, so there is no second find box in this app and no second place
1143
+ for the two to disagree about what a match is.
1144
+ β›” ITS KEY-TIP IS `SL`, NOT EXCEL'S `FD`. Excel's own Find & Select sequence collides here
1145
+ with Fill down, whose `FD` is byte-pinned in `verify_ui.py::_RIBBON_KEYTIPS`; a duplicate
1146
+ badge would make one of the two unreachable from the keyboard, so the newcomer takes the
1147
+ free sequence rather than the incumbent giving up a pinned one. */}
1148
+ {group("Editing", (
1149
+ <div className="sheet-ribbon-editing">
1150
+ <div className="sheet-ribbon-editing-row">
1151
+ {control("autosum", "AutoSum", <IconAutoSum />,
1152
+ () => act("autosum"), false, undefined, "U")}
1153
+ {/* ⚠ FILL DOWN AND FILL RIGHT HAVE NO ROW IN THE TICKET'S OWN INLINE KeyTip LIST.
1154
+ `FD`/`FR` are invented, non-colliding with `FP` (Format painter), `FS` (Font
1155
+ size) or `FC` (Font colour). */}
1156
+ {control("filldown", "Fill down", <IconFillDown />,
1157
+ () => act("fill-down"), false, undefined, "FD")}
1158
+ {control("fillright", "Fill right", <IconFillRight />,
1159
+ () => act("fill-right"), false, undefined, "FR")}
1160
+ </div>
1161
+ <div className="sheet-ribbon-editing-row">
1162
+ <span className="sheet-ribbon-slot">
1163
+ {control("clear", "Clear", <>{<IconClear />}<IconCaret /></>,
1164
+ openPop("clear"), false, open === "clear",
1165
+ "E", "gallery")}
1166
+ {open === "clear" && (
1167
+ <AnchoredOverlay
1168
+ anchor={anchorEl}
1169
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1170
+ onDismiss={closePop}
1171
+ role="menu"
1172
+ ariaLabel="Clear"
1173
+ initialFocus="none"
1174
+ >
1175
+ {item("Clear contents", () => act("clear-contents"))}
1176
+ {item("Clear formats", () => act("clear-formats"))}
1177
+ {item("Clear all", () => act("clear-all"))}
1178
+ </AnchoredOverlay>
1179
+ )}
1180
+ </span>
1181
+ <span className="sheet-ribbon-slot">
1182
+ {control("findselect", "Find and select", <><IconFindSelect /><IconCaret /></>,
1183
+ openPop("findselect"), false, open === "findselect",
1184
+ "SL", "gallery")}
1185
+ {open === "findselect" && (
1186
+ <AnchoredOverlay
1187
+ anchor={anchorEl}
1188
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal"
1189
+ onDismiss={closePop}
1190
+ role="menu"
1191
+ ariaLabel="Find and select"
1192
+ initialFocus="none"
1193
+ >
1194
+ {item("Find", () => act("find"))}
1195
+ {item("Replace", () => act("replace"))}
1196
+ {/* ⭐ GO TO ADDS NO SURFACE OF ITS OWN. Excel's Name Box is already in this app,
1197
+ as the formula bar's cell address input, and it already jumps to whatever
1198
+ address is typed into it; what a Go to item owes a person is therefore the
1199
+ focus, not a second dialog asking the same question. */}
1200
+ {item("Go to", () => act("go-to"))}
1201
+ </AnchoredOverlay>
1202
+ )}
1203
+ </span>
1204
+ </div>
1205
+ </div>
1206
+ ))}
1207
+ </>
1208
+ );
1209
+ };
1210
+
1211
+ /**
1212
+ * ⭐ THE DESCRIPTOR THE SHELL REGISTERS. `bodyClass` and `toolbarLabel` are here rather than in
1213
+ * the shell because a tab-agnostic frame cannot know that the Home row is the Formatting toolbar;
1214
+ * a second tab paints its own row under its own name through the same two fields.
1215
+ */
1216
+ export const HOME_TAB = {
1217
+ id: "home",
1218
+ /** The tab button's own `data-ribbon` key, and its first-level key-tip badge (KT-4/KT-8). */
1219
+ key: "tab-home",
1220
+ kt: "H",
1221
+ label: "Home",
1222
+ bodyClass: "sheet-ribbon-home",
1223
+ toolbarLabel: "Formatting",
1224
+ keys: HOME_KEYS,
1225
+ groups: homeGroups,
1226
+ } as const;
web/src/sheet/ribbonInsert.tsx ADDED
@@ -0,0 +1,649 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // sheet/ribbonInsert.tsx β€” the INSERT TAB of the Sheet's ribbon (wave 54, base kit part 2a;
2
+ // filled and REGISTERED by W54-T10, owner instruction 5, ruling R3).
3
+ //
4
+ // ⭐⭐ REGISTERED NOW, AND IT WAS NOT BEFORE ON PURPOSE. The base kit shipped this module exporting
5
+ // its descriptor with an EMPTY group list, and `Ribbon.tsx`'s `TABS` carried Home alone, because a
6
+ // registered empty tab paints a clickable tab that opens a blank toolbar row. W54-T10 gives the tab
7
+ // its four groups and adds its descriptor to that array in the same change, which is the whole of
8
+ // the wiring this module owes: the shell reads `keys` for the roving order, `groups` for the row,
9
+ // and the rest of the descriptor for the tab button.
10
+ //
11
+ // ⭐ WHAT A TAB MODULE OWES THE SHELL is set out in `ribbonHome.tsx`'s header, and this file is the
12
+ // same three exports:
13
+ // `INSERT_KEYS` the control keys this tab renders, IN ROVING ORDER. Every key here joins the
14
+ // shell's `ControlKey` union automatically, which is what makes a control rendered
15
+ // under an unlisted name a TYPE ERROR.
16
+ // `insertGroups` the groups, as a function of the shell's `RibbonTabContext`.
17
+ // `INSERT_TAB` the descriptor.
18
+ //
19
+ // β›”β›” RULING R3 β€” FOUR GROUPS, AND THE ABSENCES ARE THE RULING. Excel's own Insert tab in
20
+ // `reference/EXCEL 2.png` also carries Tables, PivotTable, Recommended PivotTables, Illustrations,
21
+ // Slicer, Timeline, Text and Symbols. NONE of them is here and none of them is coming: the DATA
22
+ // module exists exactly for tables and pivots, and R3 names the rest out. Ours is Charts,
23
+ // Sparklines, Links and Comments.
24
+ //
25
+ // β›”β›” THESE CONTROLS DO NOT ADD A NAMED ACT, AND THAT IS DELIBERATE. `RibbonActionKind` is closed
26
+ // by an exhaustive switch in `SheetGrid.tsx`, a file this lane does not own, so a new member would
27
+ // be a compile error in every lane at once. A chart, a sparkline, a link and a note are DOCUMENT
28
+ // WRITES rather than named acts, and they take the document's own doors instead, handed over as
29
+ // `ctx.insert` (`Ribbon.tsx::RibbonInsertDoor`): a chart is a TAB level key and takes the
30
+ // replace-the-list door, and the other three are CELL keys and take the same one commit door a
31
+ // style patch takes.
32
+ // ⚠ W54-T11 ADDS ONE CALL TO `act`, AND IT NAMES AN ACT THAT ALREADY EXISTED. The chart dialog's
33
+ // database tab writes bound cells, and a bound cell is `stale` until the workbook refreshes, so
34
+ // the block would sit empty without `refresh`. The union is untouched.
35
+ //
36
+ // β›” NO FAKE AFFORDANCE. `RibbonProps.canImport`'s own comment is the precedent: a control is
37
+ // offered only where a door for it exists. When `ctx.insert` is undefined every control below
38
+ // renders DISABLED, through a native `<fieldset disabled>` rather than a per-button flag, because
39
+ // the shell's shared `control(...)` helper takes no disabled argument and this lane may not widen
40
+ // it. In the app after `SheetGrid.tsx` wires the door it is never undefined; the fence is what
41
+ // keeps this module honest if the prop is ever dropped.
42
+ //
43
+ // ⚠ A TAB MODULE IS A FUNCTION, NOT A COMPONENT. `Ribbon.tsx` CALLS `activeTab.groups(ctx)` during
44
+ // its own render, so a hook here would attach to the shell and its order would change the moment
45
+ // somebody switched tabs. That is why the two small forms below are UNCONTROLLED: they read their
46
+ // value out of the submitted form rather than out of a `useState` this file cannot have.
47
+ //
48
+ // ⚠ DESIGN CONTRACT (DESIGN.md 2 through 5): inline SVG on `currentColor` and never emoji, token
49
+ // only colour and type, sentence case labels, no em dash or en dash in a string that reaches a
50
+ // screen, and the two overlay shapes kept apart: POPOVERS originate at their trigger through
51
+ // `AnchoredOverlay` (the link and comment forms) while MODALS REMAIN CENTRED (the chart dialog,
52
+ // through `useOverlayLayer` and `BodyPortal`). Never a local keydown listener in either case.
53
+
54
+ import { useState } from "react";
55
+ import type { FormEvent } from "react";
56
+ import type { RibbonTabContext } from "./Ribbon";
57
+ // ⭐⭐ W54-T11 (ruling R5) β€” THE CHART GALLERY IS GONE AND A DIALOG STANDS WHERE IT STOOD. R5 reads
58
+ // "A chart reads BOTH. A cell range, exactly like Excel, is the primary path; a database source is
59
+ // a second tab in the same dialog. Ship both." A gallery of eight kinds cannot carry a second
60
+ // source, so the eight kinds moved INTO the dialog and this tab keeps ONE Charts control that
61
+ // opens ONE surface. DESIGN.md 4: modals remain centred, which is what makes this a dialog rather
62
+ // than a wider popover.
63
+ // ⚠ THE HOOKS LIVE IN THE DIALOG, WHICH IS A REAL COMPONENT. `insertGroups` is a function the
64
+ // shell calls during its own render, so it still may not hold state of its own; `ChartDialog` may
65
+ // hold all it likes, and the shell's popover state is what mounts it.
66
+ import ChartDialog from "./ChartDialog";
67
+ import type { ChartRange } from "./ChartDialog";
68
+ // ⭐⭐ W54-T14 β€” THE LINK FORM MOVED OUT AND GREW THE OTHER TWO KINDS. W54-T10 shipped an
69
+ // uncontrolled one-field form here that could only write `kind: "url"`; a kind picker whose
70
+ // refusal has to survive a keystroke needs state, and `insertGroups` is a function the ribbon
71
+ // shell calls during its own render and may not hold one. So the Links group mounts a real
72
+ // component, exactly as the Charts group mounts `ChartDialog`, and that component owns its own
73
+ // anchored overlay. The Comments group's form stays uncontrolled: it has one field and no refusal.
74
+ import LinkDialog from "./LinkDialog";
75
+ import type { CellLink } from "./LinkDialog";
76
+ import { MAX_CELL_NOTE } from "./types";
77
+ import type { Cell, SheetChartSpec, SparklineKind } from "./types";
78
+ // ⭐ THE DOCUMENT'S OWN ADDRESSER, in SHEET coordinates. The door hands over a sheet-coordinate
79
+ // rectangle and a sheet-coordinate reader, so the address a cell edit is keyed by is built with
80
+ // the same function `SheetGrid.tsx` builds every other one with. A second spelling of A1 in this
81
+ // file would be a second answer to a question the document already answers.
82
+ import { addressOf } from "./sheetState";
83
+ // ⭐ THE DOCUMENT'S OWN A1 PARSER, and the reason this ticket does not write a second one. A rule's
84
+ // range, a chart's range and a sparkline's range are all the same rectangle spelled the same way,
85
+ // so `D40:B2` normalises here exactly as it does in the conditional-format dialog.
86
+ import { parseRange } from "./rules";
87
+ import type { RuleRect } from "./rules";
88
+ import { AnchoredOverlay } from "../customer-grid/OverlaySurface";
89
+ // ⭐ This tab's own stylesheet, a component-owned side-effect import, exactly as `ribbonHome.tsx`
90
+ // imports its own. See the stylesheet's header for what it restates and why.
91
+ import "../styles/wave54/ribbon-insert.css";
92
+
93
+ const CHARTS = ["chart"] as const;
94
+ const SPARKLINES = ["sparkline-line", "sparkline-column", "sparkline-winloss"] as const;
95
+ const LINKS = ["link"] as const;
96
+ const COMMENTS = ["comment"] as const;
97
+
98
+ /**
99
+ * ⭐⭐ THE INSERT TAB'S ROVING ORDER, WHICH IS ALSO ITS TYPE. The shell spreads this into the union
100
+ * every `control(...)` key is checked against, so the arrays above are the single source of both
101
+ * the reading order and the vocabulary.
102
+ * β›” THE ARRAY IS THE ROVING SOURCE AND THE JSX IS NOT: a key listed here with no `control(...)`
103
+ * call rendering it makes ArrowRight land on nothing, with every gate still green, so the two are
104
+ * changed together or not at all.
105
+ */
106
+ export const INSERT_KEYS = [...CHARTS, ...SPARKLINES, ...LINKS, ...COMMENTS] as const;
107
+
108
+ /**
109
+ * ⭐ THE EIGHT KINDS AND THE FALLBACK RECTANGLE BOTH MOVED TO `ChartDialog.tsx` (W54-T11), which
110
+ * is where they are now chosen and computed. The dialog also SAYS which rectangle it will cover,
111
+ * which is what the retired gallery could not do: the range was grown silently, because
112
+ * `RibbonTabContext` carries no notice path and there was nowhere honest to say so.
113
+ */
114
+
115
+ /** A short unique id. No uuid library, and none is needed: this is a key within one document. */
116
+ const chartId = (): string =>
117
+ `ch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`;
118
+
119
+ function IconChart() {
120
+ return (
121
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
122
+ <path d="M2.5 13.5h11" />
123
+ <path d="M4.5 11.5V7M8 11.5V3.5M11.5 11.5V6" />
124
+ </svg>
125
+ );
126
+ }
127
+
128
+ function IconSparkLine() {
129
+ return (
130
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
131
+ <path d="M2.5 11L5.5 6.5L8.5 9L13.5 4" />
132
+ </svg>
133
+ );
134
+ }
135
+
136
+ function IconSparkColumn() {
137
+ return (
138
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
139
+ <path d="M3 12V9M6.5 12V5M10 12V7.5M13.5 12V3.5" />
140
+ </svg>
141
+ );
142
+ }
143
+
144
+ function IconSparkWinLoss() {
145
+ return (
146
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
147
+ <path d="M2 8h12" />
148
+ <path d="M4 8V5M7.5 8v3M11 8V5" />
149
+ </svg>
150
+ );
151
+ }
152
+
153
+ function IconLink() {
154
+ return (
155
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
156
+ <path d="M6.8 9.2a2.6 2.6 0 0 0 3.7 0l2-2a2.6 2.6 0 0 0-3.7-3.7l-1 1" />
157
+ <path d="M9.2 6.8a2.6 2.6 0 0 0-3.7 0l-2 2a2.6 2.6 0 0 0 3.7 3.7l1-1" />
158
+ </svg>
159
+ );
160
+ }
161
+
162
+ function IconComment() {
163
+ return (
164
+ <svg viewBox="0 0 16 16" aria-hidden="true" className="sheet-ribbon-icon">
165
+ <path d="M2.5 3.5h11v7h-6l-3 2.5v-2.5h-2z" />
166
+ </svg>
167
+ );
168
+ }
169
+
170
+ /**
171
+ * ⚠ `IconCaret` IS GONE WITH THE GALLERY (W54-T11). A caret says "a menu opens under this button",
172
+ * and the Charts control now opens a centred modal instead; wearing the caret would have promised
173
+ * the wrong surface. The two form popovers below never wore one.
174
+ */
175
+
176
+ // ═════════════════════════════════════════════════════════════════════════════════════════════
177
+ // ⭐⭐ W54-T13 β€” THE TWO RANGES EXCEL ASKS FOR, AND WHY THE SECOND ONE IS NOT A FIELD ON THE SPEC.
178
+ //
179
+ // Excel's "Create Sparklines" asks for a DATA range and a LOCATION range, and W54-T10 shipped
180
+ // neither: it wrote one sparkline onto the cell the selection started on. That was the honest
181
+ // minimum for a tab that had to exist; a location range is what makes the group useful, because
182
+ // the ordinary case is one sparkline PER ROW of a block, not one sparkline for a block.
183
+ //
184
+ // β›” THE LOCATION IS THE CELL THE SPEC IS STORED ON. `CellSparkline` carries a DATA range and
185
+ // nothing else, deliberately: a location range of six cells is six cells each carrying their own
186
+ // spec over their own slice, which is what makes one of them movable, deletable and undoable on
187
+ // its own. Adding a `location` field would have given the document two answers to "where is this
188
+ // drawn" and let them disagree.
189
+ //
190
+ // β›” THE MAPPING IS STATED ON SCREEN, in one sentence, because it is the one thing a person cannot
191
+ // guess: N location cells split the data range into N slices ALONG THE OTHER AXIS. When the counts
192
+ // do not divide the form REFUSES rather than truncating, because a silently shortened range is a
193
+ // picture of data nobody chose.
194
+ // ═════════════════════════════════════════════════════════════════════════════════════════════
195
+
196
+ /** Where one sparkline goes, and the slice of the data range it draws. */
197
+ interface SparkPlacement {
198
+ col: number;
199
+ row: number;
200
+ range: RuleRect;
201
+ }
202
+
203
+ /** `B2` for one cell, `B2:E7` for a rectangle. The corners are normalised on the way in. */
204
+ const rangeText = (r: RuleRect): string => {
205
+ const a = addressOf(Math.min(r.col0, r.col1), Math.min(r.row0, r.row1));
206
+ const b = addressOf(Math.max(r.col0, r.col1), Math.max(r.row0, r.row1));
207
+ return a === b ? a : `${a}:${b}`;
208
+ };
209
+
210
+ const many = (n: number, word: string): string => `${n} ${word}${n === 1 ? "" : "s"}`;
211
+
212
+ const KIND_LABEL: Record<SparklineKind, string> = {
213
+ line: "Line sparkline",
214
+ column: "Column sparkline",
215
+ winloss: "Win loss sparkline",
216
+ };
217
+
218
+ /**
219
+ * ⭐ A SENSIBLE NEIGHBOUR, RATHER THAN AN EMPTY BOX. Excel leaves the location blank and makes the
220
+ * person work it out; the two shapes people actually select have an obvious answer, so it is
221
+ * offered and stays editable:
222
+ * β€’ a single COLUMN of readings gets ONE cell directly under it, because slicing a column of
223
+ * numbers into one sparkline per number would draw a picture of one value;
224
+ * β€’ anything else gets a COLUMN of cells directly to the right, one per row, which is the
225
+ * one sparkline per row that the group exists for. A single row is that same rule with one
226
+ * row in it, so it lands on the single cell to the right.
227
+ */
228
+ const defaultLocation = (r: RuleRect): RuleRect => {
229
+ const c0 = Math.min(r.col0, r.col1);
230
+ const c1 = Math.max(r.col0, r.col1);
231
+ const r0 = Math.min(r.row0, r.row1);
232
+ const r1 = Math.max(r.row0, r.row1);
233
+ if (c0 === c1 && r1 > r0) return { col0: c0, row0: r1 + 1, col1: c0, row1: r1 + 1 };
234
+ return { col0: c1 + 1, row0: r0, col1: c1 + 1, row1: r1 };
235
+ };
236
+
237
+ /**
238
+ * THE MAPPING RULE, IN CODE. One cell takes the whole data range; a location COLUMN of N cells
239
+ * takes the rows of the data range in N equal slices; a location ROW of N cells takes its columns
240
+ * the same way. Anything that does not divide comes back as a refusal in one sentence.
241
+ */
242
+ const planSparklines = (
243
+ data: RuleRect,
244
+ loc: RuleRect,
245
+ ): { items: SparkPlacement[] } | { why: string } => {
246
+ const dc0 = Math.min(data.col0, data.col1);
247
+ const dc1 = Math.max(data.col0, data.col1);
248
+ const dr0 = Math.min(data.row0, data.row1);
249
+ const dr1 = Math.max(data.row0, data.row1);
250
+ const lc0 = Math.min(loc.col0, loc.col1);
251
+ const lc1 = Math.max(loc.col0, loc.col1);
252
+ const lr0 = Math.min(loc.row0, loc.row1);
253
+ const lr1 = Math.max(loc.row0, loc.row1);
254
+ const lCols = lc1 - lc0 + 1;
255
+ const lRows = lr1 - lr0 + 1;
256
+ const n = lCols * lRows;
257
+
258
+ if (n === 1) {
259
+ return { items: [{ col: lc0, row: lr0, range: { col0: dc0, row0: dr0, col1: dc1, row1: dr1 } }] };
260
+ }
261
+ if (lCols > 1 && lRows > 1) {
262
+ return { why: "A location range of more than one cell has to be a single row or a single column." };
263
+ }
264
+
265
+ const items: SparkPlacement[] = [];
266
+ if (lCols === 1) {
267
+ const rows = dr1 - dr0 + 1;
268
+ if (rows % n !== 0) {
269
+ return { why: `Those counts do not divide: ${many(rows, "row")} into ${many(n, "cell")}.` };
270
+ }
271
+ const step = rows / n;
272
+ for (let i = 0; i < n; i += 1) {
273
+ items.push({
274
+ col: lc0,
275
+ row: lr0 + i,
276
+ range: { col0: dc0, col1: dc1, row0: dr0 + i * step, row1: dr0 + i * step + step - 1 },
277
+ });
278
+ }
279
+ return { items };
280
+ }
281
+
282
+ const cols = dc1 - dc0 + 1;
283
+ if (cols % n !== 0) {
284
+ return { why: `Those counts do not divide: ${many(cols, "column")} into ${many(n, "cell")}.` };
285
+ }
286
+ const step = cols / n;
287
+ for (let i = 0; i < n; i += 1) {
288
+ items.push({
289
+ col: lc0 + i,
290
+ row: lr0,
291
+ range: { row0: dr0, row1: dr1, col0: dc0 + i * step, col1: dc0 + i * step + step - 1 },
292
+ });
293
+ }
294
+ return { items };
295
+ };
296
+
297
+ /**
298
+ * ⭐⭐ A REAL COMPONENT, AND THAT IS WHAT BUYS THE STATE. `insertGroups` is a FUNCTION the shell
299
+ * calls during its own render, so a `useState` written there would attach to the shell and its
300
+ * hook order would change the moment somebody switched tabs. The two older forms in this file
301
+ * dodged that by staying uncontrolled; a refusal has to survive a keystroke, so this one is
302
+ * mounted as a component instead. The shell's popover state is what mounts and unmounts it, which
303
+ * is also what re-seeds the two fields from the current selection each time it opens.
304
+ *
305
+ * ⚠ NO LOCAL KEYDOWN LISTENER. Escape comes from `AnchoredOverlay` and from nowhere else.
306
+ */
307
+ function SparklineForm({
308
+ kind,
309
+ selection,
310
+ onCreate,
311
+ }: {
312
+ kind: SparklineKind;
313
+ selection: RuleRect | null;
314
+ onCreate: (kind: SparklineKind, items: SparkPlacement[]) => void;
315
+ }) {
316
+ const seed: RuleRect = selection ?? { col0: 0, row0: 0, col1: 0, row1: 0 };
317
+ const [data, setData] = useState(() => rangeText(seed));
318
+ const [location, setLocation] = useState(() => rangeText(defaultLocation(seed)));
319
+ const [why, setWhy] = useState("");
320
+
321
+ const submit = (event: FormEvent<HTMLFormElement>) => {
322
+ event.preventDefault();
323
+ const d = parseRange(data);
324
+ if (!d) {
325
+ setWhy("That data range is not an address like B2:E2.");
326
+ return;
327
+ }
328
+ const l = parseRange(location);
329
+ if (!l) {
330
+ setWhy("That location range is not an address like F2.");
331
+ return;
332
+ }
333
+ const plan = planSparklines(d, l);
334
+ if ("why" in plan) {
335
+ setWhy(plan.why);
336
+ return;
337
+ }
338
+ onCreate(kind, plan.items);
339
+ };
340
+
341
+ return (
342
+ <form className="sheet-ribbon-insert-fields" onSubmit={submit}>
343
+ <p className="sheet-ribbon-insert-title">{KIND_LABEL[kind]}</p>
344
+
345
+ <label className="sheet-ribbon-insert-caption" htmlFor="sheet-insert-spark-data">
346
+ Data range
347
+ </label>
348
+ <input
349
+ id="sheet-insert-spark-data"
350
+ name="data"
351
+ type="text"
352
+ className="sheet-ribbon-insert-input"
353
+ value={data}
354
+ placeholder="B2:E2"
355
+ onChange={(event) => { setData(event.target.value); setWhy(""); }}
356
+ />
357
+
358
+ <label className="sheet-ribbon-insert-caption" htmlFor="sheet-insert-spark-location">
359
+ Location range
360
+ </label>
361
+ <input
362
+ id="sheet-insert-spark-location"
363
+ name="location"
364
+ type="text"
365
+ className="sheet-ribbon-insert-input"
366
+ value={location}
367
+ placeholder="F2"
368
+ onChange={(event) => { setLocation(event.target.value); setWhy(""); }}
369
+ />
370
+
371
+ <p className="sheet-ribbon-insert-hint">
372
+ A location column of N cells takes N rows of the data range, a location row of N cells
373
+ takes N columns, and one cell takes the whole range.
374
+ </p>
375
+
376
+ {why && <p className="sheet-ribbon-insert-refusal" role="alert">{why}</p>}
377
+
378
+ <button type="submit" className="sheet-ribbon-item">Add sparkline</button>
379
+ </form>
380
+ );
381
+ }
382
+
383
+ export const insertGroups = (ctx: RibbonTabContext) => {
384
+ // ⚠ `item` IS NO LONGER TAKEN OFF THE CONTEXT, and that is W54-T11's doing rather than an
385
+ // oversight: the only menu this tab ever painted was the chart gallery, and the eight kinds are
386
+ // buttons inside `ChartDialog` now. The shell still offers the helper to every tab.
387
+ const { open, anchorEl, openPop, closePop, control, group, word, insert, act } = ctx;
388
+
389
+ /**
390
+ * ⭐ THE ANCHOR CELL, IN SHEET COORDINATES. The door hands the selection over already translated
391
+ * (`SheetGrid.tsx` maps every view index through `realCol` / `realRow` before it gets here), so
392
+ * nothing in this file has to know that a hidden row moves what glide calls row 3.
393
+ */
394
+ const anchorAt = (): { col: number; row: number } => {
395
+ const sel = insert?.selection;
396
+ if (!sel) return { col: 0, row: 0 };
397
+ return { col: Math.min(sel.col0, sel.col1), row: Math.min(sel.row0, sel.row1) };
398
+ };
399
+
400
+ /**
401
+ * ⭐⭐ THE ONE DOOR OUT OF THE DIALOG, AND BOTH TABS COME THROUGH IT (W54-T11, R5).
402
+ *
403
+ * The cell-range tab hands over a kind and a rectangle and nothing else, which is exactly what
404
+ * the retired gallery did. The database tab ALSO hands over the cells it wants written, and this
405
+ * is where the ordering matters:
406
+ * 1. the cells go in ONE call, so the block is ONE history step and ONE save;
407
+ * 2. the chart is anchored over the rectangle those cells occupy;
408
+ * 3. a refresh runs, because a `stale` cell holds no value until the workbook refreshes.
409
+ *
410
+ * β›” RULING R9 SURVIVES THIS INTACT. The chart still READS CELLS: it is handed a rectangle and
411
+ * never a database, a binding or a query, so there is still exactly one way to fetch a number in
412
+ * this document and it is the binding path a bound cell already uses.
413
+ *
414
+ * β›” `refresh` IS AN EXISTING `RibbonActionKind`. Nothing new joins that union here: adding a
415
+ * member would be a compile error in `SheetGrid.tsx`'s exhaustive switch, in every lane at once.
416
+ */
417
+ const createChart = (
418
+ kind: SheetChartSpec["kind"],
419
+ range: ChartRange,
420
+ cells?: Record<string, Cell>,
421
+ ) => {
422
+ if (!insert) return;
423
+ if (cells) insert.onCells(cells);
424
+ insert.onCharts([...insert.charts, { id: chartId(), range, kind }]);
425
+ closePop();
426
+ if (cells) act("refresh");
427
+ };
428
+
429
+ /**
430
+ * ⭐⭐ EVERY LOCATION CELL IN ONE CALL, WHICH IS ONE HISTORY STEP AND ONE SAVE. `insert.onCells`
431
+ * takes many cells at a time for exactly this: six sparklines written one call each would be six
432
+ * undos to take back and six writes to the store for one gesture.
433
+ *
434
+ * ⚠ A CELL WITH NO RECORD BECOMES `empty` / `typed` CARRYING ONLY THE SPARKLINE. That is the
435
+ * shape W54-T09 provisioned server side (`platform/core/sheets.py::_clean_sparkline` keeps the
436
+ * slot on an empty cell), and it is the ordinary case: a sparkline cell usually holds no text.
437
+ * A cell that DOES have a record is amended rather than replaced, so a sparkline never eats a
438
+ * formula, a style or a binding, and the renderer draws it as an underlay under that cell's own
439
+ * value (`sheet/sparkline.ts`).
440
+ */
441
+ const addSparklines = (kind: SparklineKind, items: SparkPlacement[]) => {
442
+ if (!insert) return;
443
+ const edits: Record<string, Cell> = {};
444
+ for (const item of items) {
445
+ const held = insert.cellAt(item.col, item.row);
446
+ const sparkline = { kind, range: item.range };
447
+ edits[addressOf(item.col, item.row)] = held
448
+ ? { ...held, sparkline }
449
+ : { kind: "empty", state: "typed", sparkline };
450
+ }
451
+ insert.onCells(edits);
452
+ closePop();
453
+ };
454
+
455
+ /**
456
+ * Which of the three sparkline triggers is showing its form, or `null` when none is.
457
+ * β›” THE KIND IS THE TRIGGER, NOT A CONTROL INSIDE THE FORM. Three buttons stay three
458
+ * affordances (the group is Excel's own three, and a menu over three items costs a press without
459
+ * buying anything); putting a fourth kind picker in the popover would also let `aria-expanded` on
460
+ * the Line button describe a Column form.
461
+ */
462
+ const openKind: SparklineKind | null =
463
+ open === "sparkline-line" ? "line"
464
+ : open === "sparkline-column" ? "column"
465
+ : open === "sparkline-winloss" ? "winloss"
466
+ : null;
467
+
468
+ /**
469
+ * ⭐ W54-T14 β€” ALL THREE KINDS THROUGH ONE WRITER. The dialog has already decided which kind it
470
+ * is and validated the target for that kind; this only amends the anchor cell, so a link never
471
+ * eats a value, a formula, a style or a binding.
472
+ */
473
+ const addLink = (link: CellLink) => {
474
+ if (!insert) return;
475
+ const { col, row } = anchorAt();
476
+ const held = insert.cellAt(col, row);
477
+ const next: Cell = held ? { ...held, link } : { kind: "empty", state: "typed", link };
478
+ insert.onCells({ [addressOf(col, row)]: next });
479
+ };
480
+
481
+ const addNote = (note: string) => {
482
+ if (!insert) return;
483
+ const { col, row } = anchorAt();
484
+ const held = insert.cellAt(col, row);
485
+ const next: Cell = held
486
+ ? { ...held, note }
487
+ : { kind: "empty", state: "typed", note };
488
+ insert.onCells({ [addressOf(col, row)]: next });
489
+ };
490
+
491
+ /** What the anchor cell already carries, so the two forms open on it rather than on blank. */
492
+ const heldAt = (): Cell | null => {
493
+ if (!insert) return null;
494
+ const { col, row } = anchorAt();
495
+ return insert.cellAt(col, row);
496
+ };
497
+
498
+ return (
499
+ /* β›” THE FENCE IS THE DISABLED STATE, AND IT IS NATIVE RATHER THAN PER BUTTON. A
500
+ `<fieldset disabled>` disables every descendant form control the browser knows about, so one
501
+ attribute covers the six controls and both forms without the shell's `control(...)` helper
502
+ growing a ninth argument this lane may not give it. The rules that strip its own box live in
503
+ `styles/wave54/ribbon-insert.css`. */
504
+ <fieldset className="sheet-ribbon-insert-fence" disabled={!insert}>
505
+ {group("Charts", (
506
+ <span className="sheet-ribbon-slot">
507
+ {control("chart", "Chart", <><IconChart />{word("Chart")}</>,
508
+ openPop("chart"), false, open === "chart", "C", "gallery")}
509
+ {/* ⚠ MOUNTED CONDITIONALLY, never rendered behind an `open` prop: `useOverlayLayer`
510
+ claims Escape the moment it runs, so a hidden dialog would hold the key. The
511
+ `insert` guard is belt and braces, and it is not the fieldset's job here: the
512
+ dialog portals to the body and is therefore OUTSIDE the disabled fence. */}
513
+ {open === "chart" && insert && (
514
+ <ChartDialog
515
+ selection={insert.selection}
516
+ onClose={closePop}
517
+ onCreate={createChart}
518
+ />
519
+ )}
520
+ </span>
521
+ ))}
522
+
523
+ {/* ⭐ THREE CONTROLS RATHER THAN ONE WITH A GALLERY. Excel's Sparklines group is exactly
524
+ three buttons, the choice is small and closed, and a menu over three items costs a press
525
+ without buying anything. Each one opens the SAME authoring form, already knowing its kind.
526
+ ⚠ `data-kt-opens="gallery"` IS WHAT MAKES THE ALT LAYER OPEN THEM. `KeyTips.tsx` fires a
527
+ badge with no such attribute as a plain command and never descends; these three now open
528
+ a popover, so they have to say so or the key tip would flash and land nowhere. */}
529
+ {group("Sparklines", (
530
+ <span className="sheet-ribbon-slot">
531
+ {control("sparkline-line", "Line sparkline", <IconSparkLine />,
532
+ openPop("sparkline-line"), false, open === "sparkline-line", "SL", "gallery")}
533
+ {control("sparkline-column", "Column sparkline", <IconSparkColumn />,
534
+ openPop("sparkline-column"), false, open === "sparkline-column", "SC", "gallery")}
535
+ {control("sparkline-winloss", "Win loss sparkline", <IconSparkWinLoss />,
536
+ openPop("sparkline-winloss"), false, open === "sparkline-winloss", "SW", "gallery")}
537
+ {openKind && insert && (
538
+ /* ⚠ `role="dialog"` RATHER THAN `role="menu"`, for the reason the Link form states
539
+ one group down: a form is not a list of commands.
540
+ ⭐ `key` FORCES A REMOUNT PER KIND, which is what re-seeds the two fields from the
541
+ current selection when the person moves from Line to Column without closing. */
542
+ <AnchoredOverlay
543
+ anchor={anchorEl}
544
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal sheet-ribbon-insert-form"
545
+ onDismiss={closePop}
546
+ role="dialog"
547
+ ariaLabel={KIND_LABEL[openKind]}
548
+ >
549
+ <SparklineForm
550
+ key={openKind}
551
+ kind={openKind}
552
+ selection={insert.selection}
553
+ onCreate={addSparklines}
554
+ />
555
+ </AnchoredOverlay>
556
+ )}
557
+ </span>
558
+ ))}
559
+
560
+ {group("Links", (
561
+ <span className="sheet-ribbon-slot">
562
+ {control("link", "Link", <><IconLink />{word("Link")}</>,
563
+ openPop("link"), false, open === "link", "I", "gallery")}
564
+ {/* ⚠ MOUNTED CONDITIONALLY AND OUTSIDE THE FIELDSET, for the two reasons the Charts
565
+ group states: an overlay claims Escape the moment it runs, so a hidden one would
566
+ hold the key; and it portals to the body, which puts it outside the disabled fence,
567
+ so the `insert` guard is written here rather than inherited.
568
+ ⚠ `role="dialog"` RATHER THAN `role="menu"` (the component says so): a form is not a
569
+ list of commands, and a menu role would promise arrow-key item navigation that is
570
+ not there. The shell's `control(...)` still writes `aria-haspopup="menu"` on the
571
+ trigger, which it hardcodes for every expandable control; widening that helper is
572
+ outside this lane's fence, so the mismatch is recorded here rather than papered
573
+ over. */}
574
+ {open === "link" && insert && (
575
+ <LinkDialog
576
+ anchor={anchorEl}
577
+ held={heldAt()?.link}
578
+ onClose={closePop}
579
+ onSubmit={(link) => { addLink(link); closePop(); }}
580
+ />
581
+ )}
582
+ </span>
583
+ ))}
584
+
585
+ {group("Comments", (
586
+ <span className="sheet-ribbon-slot">
587
+ {control("comment", "Comment", <><IconComment />{word("Comment")}</>,
588
+ openPop("comment"), false, open === "comment", "M", "gallery")}
589
+ {open === "comment" && (
590
+ <AnchoredOverlay
591
+ anchor={anchorEl}
592
+ className="sheet-ribbon-pop sheet-ribbon-pop-portal sheet-ribbon-insert-form"
593
+ onDismiss={closePop}
594
+ role="dialog"
595
+ ariaLabel="Comment"
596
+ >
597
+ <form
598
+ className="sheet-ribbon-insert-fields"
599
+ onSubmit={(event) => {
600
+ event.preventDefault();
601
+ const field = event.currentTarget.elements.namedItem("note");
602
+ const note = field instanceof HTMLTextAreaElement ? field.value.trim() : "";
603
+ if (note) addNote(note.slice(0, MAX_CELL_NOTE));
604
+ closePop();
605
+ }}
606
+ >
607
+ <label className="sheet-ribbon-insert-caption" htmlFor="sheet-insert-comment">
608
+ Comment
609
+ </label>
610
+ <textarea
611
+ id="sheet-insert-comment"
612
+ name="note"
613
+ className="sheet-ribbon-insert-area"
614
+ rows={3}
615
+ maxLength={MAX_CELL_NOTE}
616
+ defaultValue={heldAt()?.note ?? ""}
617
+ />
618
+ {/* ⭐ W54-T14 β€” IT EDITS RATHER THAN REPLACES, and the label is what says so. The
619
+ field is already seeded from the cell's own note above, so a second Insert >
620
+ Comment on the same cell opens what is there; the wording is the only part a
621
+ person can see before they have typed anything. */}
622
+ <button type="submit" className="sheet-ribbon-item">
623
+ {heldAt()?.note ? "Update comment" : "Add comment"}
624
+ </button>
625
+ </form>
626
+ </AnchoredOverlay>
627
+ )}
628
+ </span>
629
+ ))}
630
+ </fieldset>
631
+ );
632
+ };
633
+
634
+ /**
635
+ * ⭐ THE DESCRIPTOR, REGISTERED IN `Ribbon.tsx::TABS` SINCE W54-T10.
636
+ * ⚠ `kt` IS THE TAB'S OWN FIRST-LEVEL KEY-TIP BADGE and `N` is what Excel uses for Insert. Tab
637
+ * badges are scoped to the tab depth by `KeyTips.tsx`, so this does not collide with the Number
638
+ * format control's own `N` one depth down.
639
+ */
640
+ export const INSERT_TAB = {
641
+ id: "insert",
642
+ key: "tab-insert",
643
+ kt: "N",
644
+ label: "Insert",
645
+ bodyClass: "sheet-ribbon-insert",
646
+ toolbarLabel: "Insert",
647
+ keys: INSERT_KEYS,
648
+ groups: insertGroups,
649
+ } as const;
web/src/sheet/rules.ts CHANGED
@@ -24,9 +24,27 @@
24
  // never lands.
25
  // ---------------------------------------------------------------------------------------------
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  import { colToIndex, parseRef } from "./a1";
28
  import { MAX_SHEET_RULES, SHEET_RULE_OPS } from "./types";
29
- import type { Cell, SheetRule, SheetRuleOp } from "./types";
30
 
31
  /**
32
  * β›” C2's WIRE VOCABULARY AND THE DONE-WHEN's LABELS ARE TWO DIFFERENT LISTS, mapped here and
@@ -87,6 +105,58 @@ export const RULE_INKS: readonly { token: string; label: string }[] = [
87
  { token: "--lp-purple-deep", label: "Purple" },
88
  ];
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  /** What a rule may paint. A subset of `CellStyle` on purpose: nothing here moves a pixel of
91
  * geometry, because a rule that changed a row's height would repaint the sheet as data arrived. */
92
  export type RuleStyle = SheetRule["style"];
@@ -212,8 +282,25 @@ export interface RuleRect {
212
  * ⚠ THE CORNERS ARE NORMALISED. `D40:B2` is the same rectangle a person dragged the other way,
213
  * and a rule that only matched when the anchor happened to be top left would be a rule that works
214
  * for whoever wrote it and for nobody who edits it.
 
 
 
 
 
 
 
215
  */
216
- export const parseRange = (range: string): RuleRect | null => {
 
 
 
 
 
 
 
 
 
 
217
  const text = String(range ?? "").trim();
218
  if (!text) return null;
219
  const parts = text.split(":");
@@ -231,19 +318,124 @@ export const parseRange = (range: string): RuleRect | null => {
231
  };
232
  };
233
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
234
  /** Does a rule's range cover this zero-based cell? `false` for a range that does not parse. */
235
- export const rangeCovers = (range: string, col: number, row: number): boolean => {
236
  const rect = parseRange(range);
237
  if (!rect) return false;
238
  return col >= rect.col0 && col <= rect.col1 && row >= rect.row0 && row <= rect.row1;
239
  };
240
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
241
  /**
242
  * ⭐⭐ THE ONE QUESTION THIS MODULE ANSWERS: which style does this address get?
243
  *
244
  * `null` means no rule applies, which is what lets `drawCell` keep handing an unstyled cell back
245
  * to glide. THE FIRST MATCHING RULE WINS, WHOLESALE (see the head note), so the walk stops at the
246
  * first hit rather than folding the rest in.
 
 
 
 
 
 
 
247
  */
248
  export const ruleStyleAt = (
249
  rules: readonly SheetRule[] | null | undefined,
@@ -252,14 +444,44 @@ export const ruleStyleAt = (
252
  subject: RuleSubject,
253
  ): RuleStyle | null => {
254
  for (const rule of rules ?? []) {
255
- if (!rule || !rule.style) continue;
256
- if (!rangeCovers(rule.range, col, row)) continue;
257
- if (!matchesRule(rule, subject)) continue;
 
 
 
 
 
258
  return rule.style;
259
  }
260
  return null;
261
  };
262
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263
  /**
264
  * A rule's style laid OVER the cell's own, as `drawCell` paints it.
265
  *
@@ -317,6 +539,68 @@ export const blankRule = (range: string): SheetRule => ({
317
  style: { fill: "--lp-yellow-tint" },
318
  });
319
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  /** Append a rule, or REFUSE at the cap. */
321
  export const addRule = (rules: readonly SheetRule[], rule: SheetRule): RulesEdit => {
322
  const current = rules ?? [];
@@ -364,7 +648,23 @@ export const moveRule = (
364
  */
365
  export const ruleRefusal = (rule: SheetRule): string | null => {
366
  if (!parseRange(rule.range)) {
367
- return `The range "${rule.range}" is not a cell or a block of cells. Write it as B2 or B2:D40.`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
  }
369
  const arity = ruleArity(rule.op);
370
  const first = String(rule.value ?? "").trim();
@@ -392,9 +692,20 @@ export const rulesRefusal = (rules: readonly SheetRule[]): string | null => {
392
 
393
  /** How the dialog reads one rule back, so a person can check the list without opening each row. */
394
  export const ruleSummary = (rule: SheetRule): string => {
 
 
 
 
395
  const label = RULE_OP_LABEL[rule.op] ?? rule.op;
396
  const arity = ruleArity(rule.op);
397
- if (arity === 0) return `${rule.range}, ${label.toLowerCase()}`;
398
- if (arity === 2) return `${rule.range}, between ${rule.value} and ${rule.value2}`;
399
- return `${rule.range}, ${label.toLowerCase()} ${rule.value}`;
 
 
 
 
 
 
 
400
  };
 
24
  // never lands.
25
  // ---------------------------------------------------------------------------------------------
26
 
27
+ // ⭐⭐ W54-T05 β€” THREE KINDS OF RULE NOW, AND ONLY ONE OF THEM PAINTS A FLAT STYLE. A `cell` rule
28
+ // is what this module has always done: an operator, up to two operands, one style. A `scale` rule
29
+ // bands its value across a low..high range and answers with the band's FILL TOKEN, so it flows
30
+ // through the very same `ruleStyleAt` door and needs no new paint code. A `bar` rule cannot be
31
+ // said as a style at all (a proportional width is not a fill), so it has a SECOND door of its own,
32
+ // `ruleBarAt`, and the grid draws the rectangle. Both doors walk the list themselves and ask ONE
33
+ // shared predicate, `ruleOwns`, so first-match-wins stays one answer rather than two that can
34
+ // disagree. ⚠ The WALK is duplicated on purpose and `ruleOwns`'s own note says why: a gate mutates
35
+ // the compiled tail of `ruleStyleAt`'s loop to prove that rule can still be broken.
36
+ //
37
+ // ⚠ A SCALE'S BOUNDS ARE STORED, NOT DERIVED, AND THAT IS A REAL LIMITATION SAID OUT LOUD. The
38
+ // low and the high ride `op: "between"` in `value` and `value2`, which the server already
39
+ // persists, so a scale survives a save with no new persistence whatsoever. The cost is that the
40
+ // scale does NOT re-normalise when the data later changes: add a bigger number to the column and
41
+ // it takes the top band rather than moving every other cell down. Excel offers both a stored and
42
+ // a derived variant; this is the stored one, and the way to re-normalise is to make the rule
43
+ // again over the selection.
44
+
45
  import { colToIndex, parseRef } from "./a1";
46
  import { MAX_SHEET_RULES, SHEET_RULE_OPS } from "./types";
47
+ import type { Cell, SheetRule, SheetRuleKind, SheetRuleRect, SheetRuleOp } from "./types";
48
 
49
  /**
50
  * β›” C2's WIRE VOCABULARY AND THE DONE-WHEN's LABELS ARE TWO DIFFERENT LISTS, mapped here and
 
105
  { token: "--lp-purple-deep", label: "Purple" },
106
  ];
107
 
108
+ /**
109
+ * ⭐⭐ W54-T05 β€” THE COLOUR SCALES, AS RAMPS OF THE FILL TOKENS ABOVE.
110
+ *
111
+ * β›” A RAMP IS NAMED BY ITS TWO ENDS AND NOTHING ELSE. A rule stores `scale: {low, high}`, which
112
+ * is two token names, and this table is what turns that pair back into the BANDS between them.
113
+ * The alternative was storing the whole band list on every rule, which would freeze a palette
114
+ * decision into every document ever written; the alternative after that was interpolating two
115
+ * colours at paint time, which cannot be done here at all, because a token is a name and this
116
+ * module is compiled and run under node with no stylesheet to resolve it against.
117
+ *
118
+ * ⚠ A PAIR THIS TABLE DOES NOT CARRY STILL WORKS. {@link scaleBands} falls back to the two ends
119
+ * as a two band ramp, so a rule written by a later editor offering more pairs degrades to a
120
+ * coarser scale rather than to nothing at all.
121
+ */
122
+ export const RULE_SCALES: readonly {
123
+ id: string; label: string; low: string; high: string; bands: readonly string[];
124
+ }[] = [
125
+ {
126
+ id: "green-red", label: "Green to red",
127
+ low: "--lp-green-tint", high: "--lp-red-tint",
128
+ bands: ["--lp-green-tint", "--lp-yellow-tint", "--lp-red-tint"],
129
+ },
130
+ {
131
+ id: "red-green", label: "Red to green",
132
+ low: "--lp-red-tint", high: "--lp-green-tint",
133
+ bands: ["--lp-red-tint", "--lp-yellow-tint", "--lp-green-tint"],
134
+ },
135
+ {
136
+ id: "grey-purple", label: "Grey to purple",
137
+ low: "--lp-surface-2", high: "--lp-purple-tint",
138
+ bands: ["--lp-surface-2", "--lp-blue-tint", "--lp-purple-tint"],
139
+ },
140
+ ];
141
+
142
+ /** The scale a new colour scale opens with, and the fill a new data bar is drawn in. */
143
+ export const DEFAULT_RULE_SCALE = RULE_SCALES[0];
144
+ export const DEFAULT_BAR_FILL = "--lp-blue-tint";
145
+
146
+ /**
147
+ * A ramp drawn as one CSS background, so a swatch showing a scale needs NO new class and no new
148
+ * stylesheet rule: it is the same inline `background` carve-out the colour swatches already take,
149
+ * and what it names are still `var(--lp-*)` TOKENS rather than hues (DESIGN.md 3).
150
+ */
151
+ export const rampBackground = (bands: readonly string[]): string => {
152
+ const stops = bands.map((token, index) => {
153
+ const from = Math.round((index / bands.length) * 100);
154
+ const to = Math.round(((index + 1) / bands.length) * 100);
155
+ return `var(${token}) ${from}% ${to}%`;
156
+ });
157
+ return `linear-gradient(90deg, ${stops.join(", ")})`;
158
+ };
159
+
160
  /** What a rule may paint. A subset of `CellStyle` on purpose: nothing here moves a pixel of
161
  * geometry, because a rule that changed a row's height would repaint the sheet as data arrived. */
162
  export type RuleStyle = SheetRule["style"];
 
282
  * ⚠ THE CORNERS ARE NORMALISED. `D40:B2` is the same rectangle a person dragged the other way,
283
  * and a rule that only matched when the anchor happened to be top left would be a rule that works
284
  * for whoever wrote it and for nobody who edits it.
285
+ *
286
+ * β›”β›” W54-T05: IT ALSO TAKES THE RECTANGLE THE SERVER STORES, and that is not a convenience.
287
+ * `core/sheets.py::_clean_range` normalizes `"B2:D40"` to `{col0,row0,col1,row1}` on the way in,
288
+ * so a rule read back off a saved workbook arrives as an OBJECT. A string-only parser turned that
289
+ * object into `"[object Object]"`, failed, and covered nothing: every rule would have survived
290
+ * the save and painted nothing after a reload, which is the worst of the three possible outcomes
291
+ * because the dialog still lists it.
292
  */
293
+ export const parseRange = (range: string | SheetRuleRect): RuleRect | null => {
294
+ if (range && typeof range === "object") {
295
+ const { col0, row0, col1, row1 } = range;
296
+ if (![col0, row0, col1, row1].every((n) => typeof n === "number" && Number.isFinite(n))) {
297
+ return null;
298
+ }
299
+ return {
300
+ col0: Math.min(col0, col1), col1: Math.max(col0, col1),
301
+ row0: Math.min(row0, row1), row1: Math.max(row0, row1),
302
+ };
303
+ }
304
  const text = String(range ?? "").trim();
305
  if (!text) return null;
306
  const parts = text.split(":");
 
318
  };
319
  };
320
 
321
+ /**
322
+ * A range as a person reads and edits it, whichever of the two shapes it arrived in.
323
+ *
324
+ * ⚠ IT NEVER INVENTS ONE. Text that is not a range at all comes straight back out, because the
325
+ * editor has to show a person the thing they typed in order for them to fix it, and a refusal
326
+ * that quotes a normalised guess quotes something nobody wrote.
327
+ */
328
+ export const rangeText = (range: string | SheetRuleRect): string => {
329
+ if (!range || typeof range !== "object") return String(range ?? "");
330
+ const rect = parseRange(range);
331
+ if (!rect) return "";
332
+ const letters = (index: number): string => {
333
+ let out = "";
334
+ let n = index + 1;
335
+ while (n > 0) {
336
+ const rem = (n - 1) % 26;
337
+ out = String.fromCharCode(65 + rem) + out;
338
+ n = Math.floor((n - 1) / 26);
339
+ }
340
+ return out;
341
+ };
342
+ const first = `${letters(rect.col0)}${rect.row0 + 1}`;
343
+ const last = `${letters(rect.col1)}${rect.row1 + 1}`;
344
+ return first === last ? first : `${first}:${last}`;
345
+ };
346
+
347
  /** Does a rule's range cover this zero-based cell? `false` for a range that does not parse. */
348
+ export const rangeCovers = (range: string | SheetRuleRect, col: number, row: number): boolean => {
349
  const rect = parseRange(range);
350
  if (!rect) return false;
351
  return col >= rect.col0 && col <= rect.col1 && row >= rect.row0 && row <= rect.row1;
352
  };
353
 
354
+ /** A rule's kind, with `cell` read out of an ABSENCE (see `types.ts::SHEET_RULE_KINDS`). */
355
+ export const ruleKind = (rule: SheetRule): SheetRuleKind => rule.kind ?? "cell";
356
+
357
+ /** The number a scale or a bar measures, or `null` when the subject is not a number at all. */
358
+ export const ruleNumber = (subject: RuleSubject): number | null =>
359
+ asNumeric(subject.value != null ? subject.value : subject.text);
360
+
361
+ /**
362
+ * Where this subject sits between a scale or bar rule's two stored bounds, `0` through `1`.
363
+ *
364
+ * ⚠ IT CLAMPS RATHER THAN REFUSING AT EITHER END, which is what the stored bounds require: a
365
+ * value below the low bound takes the low band and one above takes the high band. A rule whose
366
+ * bounds are equal answers `0`, because dividing by that span is the one arithmetic this cannot
367
+ * do and painting everything the low band is the honest reading of "no spread at all".
368
+ */
369
+ const rangeFraction = (rule: SheetRule, subject: RuleSubject): number | null => {
370
+ const value = ruleNumber(subject);
371
+ if (value === null) return null;
372
+ const a = asNumeric(rule.value);
373
+ const b = asNumeric(rule.value2);
374
+ if (a === null || b === null) return null;
375
+ const low = Math.min(a, b);
376
+ const high = Math.max(a, b);
377
+ if (high <= low) return 0;
378
+ return Math.max(0, Math.min(1, (value - low) / (high - low)));
379
+ };
380
+
381
+ /** The bands a scale rule paints, low end first. See {@link RULE_SCALES} for the fallback. */
382
+ export const scaleBands = (rule: SheetRule): readonly string[] => {
383
+ const low = rule.scale?.low;
384
+ const high = rule.scale?.high;
385
+ const ramp = RULE_SCALES.find((entry) => entry.low === low && entry.high === high);
386
+ if (ramp) return ramp.bands;
387
+ if (low && high) return [low, high];
388
+ return DEFAULT_RULE_SCALE.bands;
389
+ };
390
+
391
+ /**
392
+ * Does this rule own this subject at all? The three kinds answer it differently and that is the
393
+ * whole of the difference between them: a `cell` rule asks its operator, and a `scale` or a `bar`
394
+ * asks only whether there is a number and two bounds to measure it against. A text cell inside a
395
+ * scale's range is therefore NOT owned, and the rules below it still get their turn.
396
+ */
397
+ const ruleApplies = (rule: SheetRule, subject: RuleSubject): boolean =>
398
+ ruleKind(rule) === "cell"
399
+ ? matchesRule(rule, subject)
400
+ : rangeFraction(rule, subject) !== null;
401
+
402
+ /**
403
+ * ⭐⭐ DOES THIS RULE OWN THIS ADDRESS? BOTH PAINT DOORS ASK THIS ONE PREDICATE.
404
+ *
405
+ * β›” THAT IS NOT A TIDY. `ruleStyleAt` and `ruleBarAt` are called on the same cell in the same
406
+ * paint, so two hand written tests could disagree about which rule won: the fill of one rule under
407
+ * the bar of another, with the dialog listing an order neither of them obeyed.
408
+ *
409
+ * ⚠ THE WALK ITSELF STAYS INSIDE EACH DOOR RATHER THAN MOVING HERE, and that is deliberate:
410
+ * `verify_api.py`'s W51-T18 negative control mutates the compiled tail of `ruleStyleAt`'s own loop
411
+ * to prove the first-match rule can still be broken, so hoisting the loop out of this function
412
+ * would leave that control unable to bite with every leg still green.
413
+ */
414
+ const ruleOwns = (
415
+ rule: SheetRule | null | undefined,
416
+ col: number,
417
+ row: number,
418
+ subject: RuleSubject,
419
+ ): boolean => {
420
+ if (!rule) return false;
421
+ if (ruleKind(rule) === "cell" && !rule.style) return false;
422
+ if (!rangeCovers(rule.range, col, row)) return false;
423
+ return ruleApplies(rule, subject);
424
+ };
425
+
426
  /**
427
  * ⭐⭐ THE ONE QUESTION THIS MODULE ANSWERS: which style does this address get?
428
  *
429
  * `null` means no rule applies, which is what lets `drawCell` keep handing an unstyled cell back
430
  * to glide. THE FIRST MATCHING RULE WINS, WHOLESALE (see the head note), so the walk stops at the
431
  * first hit rather than folding the rest in.
432
+ *
433
+ * ⭐ A `scale` ANSWERS WITH ITS BAND'S FILL, which is why a colour scale needed no new paint code
434
+ * anywhere: it is a fill like any other fill, chosen per cell instead of once.
435
+ * ⚠ A `bar` ANSWERS WITH AN EMPTY STYLE, and the empty object is load bearing rather than lazy.
436
+ * It is not `null`, because `null` would let the rules below it paint the cell the bar has
437
+ * already claimed; and it carries no `fill`, because a bar's colour is a RECTANGLE inside the
438
+ * cell and filling the whole background with it would hide the very proportion it draws.
439
  */
440
  export const ruleStyleAt = (
441
  rules: readonly SheetRule[] | null | undefined,
 
444
  subject: RuleSubject,
445
  ): RuleStyle | null => {
446
  for (const rule of rules ?? []) {
447
+ if (!ruleOwns(rule, col, row, subject)) continue;
448
+ const kind = ruleKind(rule);
449
+ if (kind === "bar") return {};
450
+ if (kind === "scale") {
451
+ const bands = scaleBands(rule);
452
+ const at = Math.floor((rangeFraction(rule, subject) ?? 0) * bands.length);
453
+ return { fill: bands[Math.max(0, Math.min(bands.length - 1, at))] };
454
+ }
455
  return rule.style;
456
  }
457
  return null;
458
  };
459
 
460
+ /**
461
+ * ⭐⭐ THE SECOND DOOR, AND IT EXISTS BECAUSE A PROPORTION IS NOT A STYLE. `RuleStyle` can say a
462
+ * fill, an ink and a weight; it cannot say "three fifths of the way across this cell", so the bar
463
+ * is answered separately and `SheetGrid.tsx::paintCell` draws the rectangle itself.
464
+ *
465
+ * β›” IT STOPS AT THE FIRST OWNER TOO, AND ANSWERS `null` WHEN THAT OWNER IS NOT A BAR. Walking on
466
+ * past it would let a bar three rules down paint a cell an earlier rule had already won, which is
467
+ * the per-aspect merge this module's head note refuses in the style door.
468
+ */
469
+ export const ruleBarAt = (
470
+ rules: readonly SheetRule[] | null | undefined,
471
+ col: number,
472
+ row: number,
473
+ subject: RuleSubject,
474
+ ): { fraction: number; fill: string } | null => {
475
+ for (const rule of rules ?? []) {
476
+ if (!ruleOwns(rule, col, row, subject)) continue;
477
+ if (ruleKind(rule) !== "bar") return null;
478
+ const fraction = rangeFraction(rule, subject);
479
+ if (fraction === null) return null;
480
+ return { fraction, fill: rule.style?.fill || DEFAULT_BAR_FILL };
481
+ }
482
+ return null;
483
+ };
484
+
485
  /**
486
  * A rule's style laid OVER the cell's own, as `drawCell` paints it.
487
  *
 
539
  style: { fill: "--lp-yellow-tint" },
540
  });
541
 
542
+ /**
543
+ * The lowest and the highest number in a block of subjects, or `null` when none of them is one.
544
+ *
545
+ * ⚠ IT IS A LOOP RATHER THAN `Math.min` OVER A SPREAD, because a selection is allowed to be tens
546
+ * of thousands of cells and a spread of that size is an argument list the engine can refuse.
547
+ */
548
+ export const numericBounds = (
549
+ subjects: readonly RuleSubject[],
550
+ ): { low: number; high: number } | null => {
551
+ let low = Number.POSITIVE_INFINITY;
552
+ let high = Number.NEGATIVE_INFINITY;
553
+ let seen = false;
554
+ for (const subject of subjects) {
555
+ const value = ruleNumber(subject);
556
+ if (value === null) continue;
557
+ seen = true;
558
+ if (value < low) low = value;
559
+ if (value > high) high = value;
560
+ }
561
+ return seen ? { low, high } : null;
562
+ };
563
+
564
+ /**
565
+ * A COLOUR SCALE over a range, with the bounds MEASURED FROM THE DATA AT CREATION TIME.
566
+ *
567
+ * ⚠ AND THEY STAY WHERE THEY WERE PUT. `value` and `value2` are what the server persists, so this
568
+ * is what makes a scale survive a save with no new field at all; the price is that the scale does
569
+ * not re-normalise as the numbers change afterwards. That trade is stated in this module's head
570
+ * note and in the ticket's handoff rather than left for a reader to discover from behaviour.
571
+ */
572
+ export const scaleRule = (
573
+ range: string,
574
+ low: number,
575
+ high: number,
576
+ ramp = DEFAULT_RULE_SCALE,
577
+ ): SheetRule => ({
578
+ id: newRuleId(),
579
+ range: range || "A1",
580
+ kind: "scale",
581
+ op: "between",
582
+ value: low,
583
+ value2: high,
584
+ scale: { low: ramp.low, high: ramp.high },
585
+ style: {},
586
+ });
587
+
588
+ /** A DATA BAR over a range, on the same measured bounds. The bar's colour is the rule's fill. */
589
+ export const barRule = (
590
+ range: string,
591
+ low: number,
592
+ high: number,
593
+ fill = DEFAULT_BAR_FILL,
594
+ ): SheetRule => ({
595
+ id: newRuleId(),
596
+ range: range || "A1",
597
+ kind: "bar",
598
+ op: "between",
599
+ value: low,
600
+ value2: high,
601
+ style: { fill },
602
+ });
603
+
604
  /** Append a rule, or REFUSE at the cap. */
605
  export const addRule = (rules: readonly SheetRule[], rule: SheetRule): RulesEdit => {
606
  const current = rules ?? [];
 
648
  */
649
  export const ruleRefusal = (rule: SheetRule): string | null => {
650
  if (!parseRange(rule.range)) {
651
+ return `The range "${rangeText(rule.range)}" is not a cell or a block of cells. `
652
+ + "Write it as B2 or B2:D40.";
653
+ }
654
+ // ⭐ W54-T05: A SCALE AND A BAR ARE COMPLETE ON DIFFERENT TERMS. Neither carries an operator a
655
+ // person chose, so the operand sentences below would name a condition the editor never offered;
656
+ // what each one genuinely needs is two numbers to spread between, and a bar needs its colour.
657
+ const kind = ruleKind(rule);
658
+ if (kind !== "cell") {
659
+ if (asNumeric(rule.value) === null || asNumeric(rule.value2) === null) {
660
+ return kind === "scale"
661
+ ? "A colour scale needs the lowest and the highest number to spread between."
662
+ : "A data bar needs the lowest and the highest number to measure against.";
663
+ }
664
+ if (kind === "bar" && !rule.style?.fill) {
665
+ return "Choose a fill for the data bar, or it would paint nothing.";
666
+ }
667
+ return null;
668
  }
669
  const arity = ruleArity(rule.op);
670
  const first = String(rule.value ?? "").trim();
 
692
 
693
  /** How the dialog reads one rule back, so a person can check the list without opening each row. */
694
  export const ruleSummary = (rule: SheetRule): string => {
695
+ const where = rangeText(rule.range);
696
+ const kind = ruleKind(rule);
697
+ if (kind === "scale") return `${where}, colour scale from ${rule.value} to ${rule.value2}`;
698
+ if (kind === "bar") return `${where}, data bars from ${rule.value} to ${rule.value2}`;
699
  const label = RULE_OP_LABEL[rule.op] ?? rule.op;
700
  const arity = ruleArity(rule.op);
701
+ if (arity === 0) return `${where}, ${label.toLowerCase()}`;
702
+ if (arity === 2) return `${where}, between ${rule.value} and ${rule.value2}`;
703
+ return `${where}, ${label.toLowerCase()} ${rule.value}`;
704
+ };
705
+
706
+ /** How a person reads a rule's KIND in the editor. Sentence case, no dash (standing rule 2). */
707
+ export const RULE_KIND_LABEL: Record<SheetRuleKind, string> = {
708
+ cell: "Highlight cells",
709
+ scale: "Colour scale",
710
+ bar: "Data bars",
711
  };
web/src/sheet/sheetApi.ts CHANGED
@@ -312,6 +312,51 @@ export const previewCell = (
312
  (body) => body as { value: unknown; display: string },
313
  );
314
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  export interface CellDrill {
316
  database: string;
317
  view_id?: string;
 
312
  (body) => body as { value: unknown; display: string },
313
  );
314
 
315
+ /**
316
+ * W54-T32 (instruction 9): what `POST /sheets/{id}/cells/{addr}/compute` answers.
317
+ *
318
+ * ⭐⭐ ONE CELL, NOT THE WORKBOOK, AND THAT IS THE WHOLE POINT OF A SECOND DOOR. Saving a binding
319
+ * used to leave the cell `stale` with nothing on any path to resolve it, so the shimmer ran until
320
+ * somebody pressed Refresh; {@link refreshWorkbook} does answer, but it recomputes every bound
321
+ * cell and every formula in the document to deliver the one number the person just asked for.
322
+ *
323
+ * ⚠ `rev` IS LOAD BEARING AND MUST BE ADOPTED. This door PERSISTS the cell it computed, so the
324
+ * workbook's revision has moved; a caller that keeps the revision it held would have its next
325
+ * PATCH refused as stale by a conflict it caused itself.
326
+ *
327
+ * ⚠ THE CELL CAN COME BACK `refused` WITH A 200. A binding that cannot resolve is a cell carrying
328
+ * its own reason, exactly as Refresh writes one, and never a cell left waiting forever.
329
+ */
330
+ export interface CellRecomputed {
331
+ /** The stored cell as it now stands: `fresh` with a value, or `refused` with a reason. */
332
+ cell: Cell;
333
+ /** The workbook revision after the write. Send this with the next PATCH. */
334
+ rev: number;
335
+ /** The tab the cell was found on, as the server addresses it. */
336
+ tab: string;
337
+ /** The address, normalized the way the server stores it. */
338
+ addr: string;
339
+ }
340
+
341
+ export const computeCell = (
342
+ id: string,
343
+ addr: string,
344
+ tab?: string,
345
+ ): Promise<Result<CellRecomputed>> =>
346
+ call(
347
+ `/sheets/${encodeURIComponent(id)}/cells/${encodeURIComponent(addr)}/compute`,
348
+ sends("POST", tab ? { tab } : {}),
349
+ (body) => {
350
+ const raw = (body as Partial<CellRecomputed> | null) ?? {};
351
+ return {
352
+ cell: (raw.cell ?? null) as Cell,
353
+ rev: typeof raw.rev === "number" ? raw.rev : 0,
354
+ tab: typeof raw.tab === "string" ? raw.tab : "",
355
+ addr: typeof raw.addr === "string" ? raw.addr : "",
356
+ };
357
+ },
358
+ );
359
+
360
  export interface CellDrill {
361
  database: string;
362
  view_id?: string;
web/src/sheet/sheetState.ts CHANGED
@@ -11,21 +11,26 @@
11
  // paints as bound.
12
 
13
  import type {
14
- BindingOnDrag, BindingPeriod, Cell, CellMap, CellState, CellStyle, CellStylePatch,
15
  PeriodUnit, Workbook, SheetTab,
16
  } from "./types";
17
  import {
18
- applyStylePatch, asNumber, bindingOnDrag, bindingPeriod,
19
  DEFAULT_COL_WIDTH, MAX_COL_WIDTH, MAX_SHEET_COLS, MAX_SHEET_ROWS, MIN_COL_WIDTH, sheetExtent,
20
  } from "./types";
21
  // ⭐ THE ONLY THING THIS FILE BORROWS. `a1.ts` owns Excel's `$` anchoring rule, the quoted-text
22
  // guard and the one reference scanner; `fillCells` and the structural doors below call it rather
23
  // than rewriting references themselves.
24
  import {
25
- colToIndex, fillFormula, formatRef, indexToCol, parseRef, renameSheetRefs, rewriteRefs,
26
- shiftForStructure, shiftRef,
27
  } from "./a1";
28
  import type { StructuralShift } from "./a1";
 
 
 
 
 
 
29
  // ⭐⭐ W53-T01 / CONTRACT C1 β€” THE ONE IMPORT THAT MAKES A COMMITTED FORMULA COMPUTE LOCALLY.
30
  // `formulaEval.ts` imports nothing back from this file (see its own header): it takes a plain
31
  // `get(addr) => CellValue` callback and knows nothing about a `Cell`. `cellToValue`, below, is the
@@ -474,8 +479,38 @@ export const editableText = (cell: Cell | null | undefined): string => {
474
  return cell.value == null ? "" : String(cell.value);
475
  };
476
 
477
- /** What a cell PAINTS. A refusal states its reason and never shows a blank (R16). */
478
- export const displayText = (cell: Cell | null | undefined): string => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
479
  if (!cell) return "";
480
  if (cell.state === "refused") {
481
  return cell.refusal?.message ?? "This cell could not be calculated.";
@@ -483,6 +518,42 @@ export const displayText = (cell: Cell | null | undefined): string => {
483
  return cell.display ?? (cell.value == null ? "" : String(cell.value));
484
  };
485
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
486
  /**
487
  * Replace or REMOVE several cells at once, returning a NEW workbook. `null` removes.
488
  *
@@ -717,9 +788,9 @@ export const shiftPeriodStart = (
717
  /**
718
  * Shift a period's `ref` the way a dragged formula reference shifts, `$` anchors honoured.
719
  *
720
- * ⭐ IT IS `a1.ts`'s RULE AND NOT A SECOND ONE. `parseRef`, `shiftRef` and `formatRef` already
721
- * own Excel's anchoring, the clamp at row 1 and column A, and the quoted sheet name; a hand
722
- * written shift here would be a second opinion about the same question.
723
  *
724
  * ⚠ THE REF SHIFTS ON BOTH AXES, WHILE THE PERIOD'S `start` SHIFTS ONLY ACROSS COLUMNS. They are
725
  * different things: a `start` is a period, and R9 says a period moves across and holds down; a
@@ -727,13 +798,8 @@ export const shiftPeriodStart = (
727
  * same cell from forty different places. A reader who wants it fixed writes `$B$1`, which is the
728
  * control Excel already taught them, or locks the period.
729
  */
730
- export const shiftPeriodRef = (ref: string, dRow: number, dCol: number): string => {
731
- const text = String(ref ?? "").trim();
732
- if (!text || (!dRow && !dCol)) return text;
733
- const parsed = parseRef(text);
734
- if (!parsed) return text;
735
- return formatRef(shiftRef(parsed, dRow, dCol));
736
- };
737
 
738
  /** Where a value sits in an option order, or -1. An unset value walks into the FIRST option. */
739
  const optionIndex = (options: readonly string[], value: string): number =>
@@ -828,30 +894,26 @@ export const dragBoundCell = (
828
  let changed = false;
829
 
830
  // ── ACROSS COLUMNS (R9, R10): the period, and only ever the COLUMN delta ──────────────────
831
- if (period && !period.locked && rules.across === "period" && dCol !== 0) {
832
- const moved: Record<string, unknown> = { ...(binding.period as Record<string, unknown>) };
833
  const start = shiftPeriodStart(period.start, period.unit, dCol);
834
- if (period.start && start !== period.start) {
835
- moved.start = start;
836
- changed = true;
837
- }
838
- if (period.ref) {
839
- const ref = shiftPeriodRef(period.ref, dRow, dCol);
840
- if (ref !== period.ref) {
841
- moved.ref = ref;
842
- changed = true;
843
- }
844
- }
845
- if (changed) next.period = moved;
846
- } else if (period && !period.locked && period.ref && (dRow !== 0 || dCol !== 0)) {
847
- // A pointer follows the drag even where the period itself holds: see `shiftPeriodRef`.
848
- const ref = shiftPeriodRef(period.ref, dRow, dCol);
849
- if (ref !== period.ref) {
850
- next.period = { ...(binding.period as Record<string, unknown>), ref };
851
  changed = true;
852
  }
853
  }
854
 
 
 
 
 
 
 
 
 
 
 
 
 
855
  // ── DOWN ROWS (R10): the chosen filter's value, and only ever the ROW delta ───────────────
856
  let noCatalogue = false;
857
  let noField = false;
@@ -949,6 +1011,230 @@ export const clearCells = (tab: SheetTab | null | undefined, addrs: string[]): B
949
  return { edits };
950
  };
951
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
952
  /**
953
  * A TSV paste, landed with its top left corner at the target cell.
954
  *
@@ -990,6 +1276,23 @@ export const pasteCells = (
990
  const source = values.length === 0 || values.every((row) => row.length === 0)
991
  ? ([[""]] as readonly (readonly string[])[])
992
  : values;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
993
  /**
994
  * Land the copied block ONCE, with its top left corner at `originCol` / `originRow`.
995
  *
@@ -1022,18 +1325,52 @@ export const pasteCells = (
1022
  // `c`s cancel. Writing `col - from.col` instead adds the block's own width back in and
1023
  // gives the second column of a two column paste a period one month further out than the
1024
  // first, which reads as a working feature until somebody checks the numbers.
1025
- const copied = drag?.cells?.[r]?.[c] ?? null;
1026
- if (copied && copied.kind === "bound" && drag?.from) {
1027
- const out = dragBoundCell(copied, originCol - drag.from.col,
1028
- originRow - drag.from.row, drag.catalogue);
1029
- edits[addr] = out.cell;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1030
  tally.dragged += 1;
1031
  if (out.noCatalogue) tally.noCatalogue += 1;
1032
  if (out.noField) tally.noField += 1;
1033
  if (out.atEnd) tally.atEnd += 1;
1034
  continue;
1035
  }
1036
- edits[addr] = commitTyped(cell, String(row[c] ?? ""), read);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1037
  }
1038
  }
1039
  };
@@ -1048,6 +1385,8 @@ export const pasteCells = (
1048
  if (!rect || srcRows === 0 || srcCols === 0 || (wide === 1 && tall === 1)) {
1049
  // No drag, or one target cell: the block lands anchored where it was dropped, as it always has.
1050
  writeBlock(targetCol, targetRow);
 
 
1051
  return { edits, ...tally };
1052
  }
1053
  if (wide % srcCols !== 0 || tall % srcRows !== 0) {
@@ -1061,6 +1400,10 @@ export const pasteCells = (
1061
  writeBlock(rect.col0 + tx * srcCols, rect.row0 + ty * srcRows);
1062
  }
1063
  }
 
 
 
 
1064
  return { edits, ...tally };
1065
  };
1066
 
@@ -1122,9 +1465,14 @@ export const fillCells = (
1122
  // "bound"` directly: that predicate and its whole CONVERSION concept are retired, and this
1123
  // is the one remaining place that ever asked what a cell's OWN kind is, for drag-routing
1124
  // rather than for a confirmation.
 
 
 
 
 
1125
  if (pattern.kind === "bound") {
1126
  const dragged = dragBoundCell(pattern, col - srcCol, row - srcRow, drag?.catalogue);
1127
- edits[addr] = dragged.cell;
1128
  tally.dragged += 1;
1129
  if (dragged.noCatalogue) tally.noCatalogue += 1;
1130
  if (dragged.noField) tally.noField += 1;
@@ -1132,14 +1480,14 @@ export const fillCells = (
1132
  continue;
1133
  }
1134
  if (pattern.kind === "formula") {
1135
- edits[addr] = setFormula(
1136
  target,
1137
  fillFormula(pattern.formula ?? "", row - srcRow, col - srcCol),
1138
  read,
1139
- );
1140
  continue;
1141
  }
1142
- edits[addr] = commitTyped(target, editableText(pattern));
1143
  }
1144
  }
1145
  return { edits, ...tally };
@@ -1510,133 +1858,20 @@ export const moveTab = (book: Workbook, tabId: string, step: number): SheetTab[]
1510
  return sheets;
1511
  };
1512
 
1513
- // ═════════════════════════════════════════════════════════════════════════════════════════════
1514
- // W51-T16 β€” THE STYLE ENGINE AND THE RIBBON'S ACTS, ALL OF THEM PURE (contract C2, D-641).
1515
- //
1516
- // ⭐⭐ WHY THE PURE HALF IS HERE AND NOT IN THE COMPONENT. `SheetGrid.tsx` imports glide, which
1517
- // cannot be loaded under node, so anything living there can only ever be GREPPED by a gate. Every
1518
- // function below is executed by `verify_api.py`'s compile-and-run harness instead, which is what
1519
- // lets the battery prove that AutoSum picks the right range and that styling a blank block leaves
1520
- // `handTypedCount` alone, rather than proving that the words appear in a file.
1521
  //
1522
- // β›”β›” THE ONE NUMBER THIS SECTION MUST NOT MOVE. The sheet PRINTS its hand typed count on the
1523
- // screen (`handTypedLabel`, `.sheet-grid-literals`), and `handTypedCount` counts every
1524
- // `kind: "literal"` cell. So a styled blank is `kind: "empty"` and nothing here may take a
1525
- // shortcut through `literal`: bolding twenty blank cells and claiming twenty typed values would
1526
- // be a lie the owner reads straight off the header.
1527
- // ═════════════════════════════════════════════════════════════════════════════════════════════
1528
-
1529
- /**
1530
- * ⭐⭐ D-641, AND IT IS THE WHOLE TICKET: FORMATTING APPLIES TO EMPTY CELLS.
1531
- *
1532
- * W50-T19's `applyStyle` carried `if (!cell) continue`, so selecting three blank cells and
1533
- * pressing Borders painted nothing. It could not do otherwise at the time: creating a cell would
1534
- * have meant `kind: "literal"`, and the count on the header would have risen by three. C2's
1535
- * `empty` kind is what removes that trade.
1536
- *
1537
- * β›” IT PRUNES ITS OWN CREATIONS. A patch that leaves an empty cell with no style at all removes
1538
- * the cell rather than storing `{kind: "empty", state: "fresh"}`, which is a document the server
1539
- * would keep forever and which means exactly what an absence means.
1540
- *
1541
- * ⚠ R19 / R20, DECIDED IN W50-T19 AND UNCHANGED: styling a BOUND cell is allowed and is NOT a
1542
- * conversion. A colour changes nothing about where the value comes from, so a cell's KIND is
1543
- * deliberately not consulted here at all β€” the opposite of what R5 (W52-T09) made every EDIT
1544
- * door do, which is write a bound cell exactly as it writes any other one.
1545
- */
1546
- export const styleCells = (
1547
- tab: SheetTab | null | undefined,
1548
- addrs: readonly string[],
1549
- patch: CellStylePatch,
1550
- ): BulkEdit => {
1551
- const edits: Record<string, Cell | null> = {};
1552
- for (const addr of addrs) {
1553
- const cell = cellAt(tab, addr);
1554
- const style = applyStylePatch(cell?.style, patch);
1555
- if (!cell) {
1556
- // THE LINE D-641 ASKED FOR. A blank address becomes a style-only cell, and only when the
1557
- // patch actually left a style on it.
1558
- if (style) edits[addr] = { kind: "empty", state: "fresh", style };
1559
- continue;
1560
- }
1561
- if (cell.kind === "empty" && !style && !cell.validation) {
1562
- edits[addr] = null;
1563
- continue;
1564
- }
1565
- const next: Cell = { ...cell };
1566
- if (style) next.style = style;
1567
- else delete next.style;
1568
- edits[addr] = next;
1569
- }
1570
- return { edits };
1571
- };
1572
-
1573
- /**
1574
- * CLEAR FORMATS: the value stays, the styling goes. A cell that was ONLY styling disappears with
1575
- * it, because a `kind: "empty"` cell carrying no style is an absence written down.
1576
- */
1577
- export const clearFormats = (
1578
- tab: SheetTab | null | undefined,
1579
- addrs: readonly string[],
1580
- ): BulkEdit => {
1581
- const edits: Record<string, Cell | null> = {};
1582
- for (const addr of addrs) {
1583
- const cell = cellAt(tab, addr);
1584
- if (!cell || !cell.style) continue;
1585
- if (cell.kind === "empty" && !cell.validation) {
1586
- edits[addr] = null;
1587
- continue;
1588
- }
1589
- const next: Cell = { ...cell };
1590
- delete next.style;
1591
- edits[addr] = next;
1592
- }
1593
- return { edits };
1594
- };
1595
-
1596
- /**
1597
- * CLEAR ALL: the value AND the styling. This is the only one of the three that empties the map.
1598
- *
1599
- * ⭐⭐ R5 (W52-T09): NO WALL HERE EITHER, ANY MORE. A bound cell clears exactly like any other:
1600
- * its whole record is removed, value and binding together. {@link clearFormats} never needed a
1601
- * wall in the first place, since removing a colour from a bound cell leaves it reading from
1602
- * exactly the database it read before.
1603
- */
1604
- export const clearAll = (
1605
- tab: SheetTab | null | undefined,
1606
- addrs: readonly string[],
1607
- ): BulkEdit => {
1608
- const edits: Record<string, Cell | null> = {};
1609
- for (const addr of addrs) {
1610
- const cell = cellAt(tab, addr);
1611
- if (!cell) continue;
1612
- edits[addr] = null;
1613
- }
1614
- return { edits };
1615
- };
1616
-
1617
- /** The style a Format painter picked up. `null` when the cell it was picked from carries none. */
1618
- export const styleOf = (cell: Cell | null | undefined): CellStyle | null =>
1619
- cell?.style ? { ...cell.style } : null;
1620
-
1621
- /**
1622
- * β›”β›” EVERY KEY `CellStyle` CARRIES, AND A MISSING ONE IS A SILENT HALF-PAINT. The Format painter
1623
- * REPLACES a style rather than merging into it, so it has to say `null` for the keys the picked
1624
- * up style does not have. A key absent from this list is a key the painter leaves behind: paint a
1625
- * plain cell's format onto a bold one and the target stays bold, which reads as the painter
1626
- * having half worked and is the harder defect to notice.
1627
- */
1628
- export const STYLE_KEYS = [
1629
- "bold", "italic", "underline", "color", "fill", "align", "format", "border",
1630
- "valign", "wrap", "indent", "size",
1631
- ] as const;
1632
-
1633
- /** The patch that makes a cell's style EQUAL to `style`, clearing everything `style` omits. */
1634
- export const paintPatch = (style: CellStyle | null | undefined): CellStylePatch => {
1635
- const source = (style ?? {}) as Record<string, unknown>;
1636
- const patch: Record<string, unknown> = {};
1637
- for (const key of STYLE_KEYS) patch[key] = source[key] ?? null;
1638
- return patch as CellStylePatch;
1639
- };
1640
 
1641
  /** One selected rectangle, in the sheet's own zero based coordinates, inclusive of both corners. */
1642
  export interface CellRange {
 
11
  // paints as bound.
12
 
13
  import type {
14
+ BindingOnDrag, BindingPeriod, Cell, CellFormat, CellMap, CellState,
15
  PeriodUnit, Workbook, SheetTab,
16
  } from "./types";
17
  import {
18
+ asNumber, bindingOnDrag, bindingPeriod, formatCellText,
19
  DEFAULT_COL_WIDTH, MAX_COL_WIDTH, MAX_SHEET_COLS, MAX_SHEET_ROWS, MIN_COL_WIDTH, sheetExtent,
20
  } from "./types";
21
  // ⭐ THE ONLY THING THIS FILE BORROWS. `a1.ts` owns Excel's `$` anchoring rule, the quoted-text
22
  // guard and the one reference scanner; `fillCells` and the structural doors below call it rather
23
  // than rewriting references themselves.
24
  import {
25
+ colToIndex, fillFormula, indexToCol, renameSheetRefs, rewriteRefs, shiftForStructure,
 
26
  } from "./a1";
27
  import type { StructuralShift } from "./a1";
28
+ // ⭐⭐ W54-T18 / CONTRACT C3 β€” THE ONE DOOR THAT KNOWS WHERE A BINDING KEEPS CELL REFERENCES.
29
+ // `bindingRefs.ts` owns both halves of that question: WHICH parts of a binding are references
30
+ // (its registry) and HOW one moves (delegated straight to `a1.ts`, never re-derived). This file
31
+ // used to answer the first half inline, in two branches of `dragBoundCell`, which meant C3's
32
+ // second reference slot would have had to be added here as well as wherever it was declared.
33
+ import { shiftBindingRefs, shiftRefText } from "./bindingRefs";
34
  // ⭐⭐ W53-T01 / CONTRACT C1 β€” THE ONE IMPORT THAT MAKES A COMMITTED FORMULA COMPUTE LOCALLY.
35
  // `formulaEval.ts` imports nothing back from this file (see its own header): it takes a plain
36
  // `get(addr) => CellValue` callback and knows nothing about a `Cell`. `cellToValue`, below, is the
 
479
  return cell.value == null ? "" : String(cell.value);
480
  };
481
 
482
+ /**
483
+ * ⭐⭐ W54-T17 / CONTRACT C2 β€” THE DEFAULT NUMBER FORMAT, AND IT IS A NAMED CONSTANT BECAUSE THE
484
+ * ABSENCE OF A STYLE OBJECT IS NOT A DEFAULT.
485
+ *
486
+ * The owner's words are `0,000`: a comma group separator, no decimals. `types.ts::applyStylePatch`
487
+ * DELETES a format whose kind is `general`, so "General" is stored as an ABSENCE β€” which means an
488
+ * unformatted cell has nowhere for a default to live unless one is written down. This is that one
489
+ * place. A reader who wants to know what a fresh number looks like reads this line and no other.
490
+ *
491
+ * β›” IT IS PRESENTATION ONLY. Nothing writes it into a document, nothing patches a stored cell,
492
+ * and a cell that has never been styled still has `style === undefined` after {@link displayText}
493
+ * has painted it. Restyling on READ would queue a save for a workbook nobody edited and would
494
+ * make merely opening a sheet a revision of it.
495
+ */
496
+ export const DEFAULT_NUMBER_FORMAT: CellFormat = {
497
+ kind: "number",
498
+ thousands: true,
499
+ decimals: 0,
500
+ };
501
+
502
+ /**
503
+ * What a cell paints BEFORE the default number format is applied: the cell's own stored string,
504
+ * and a refusal's sentence (R16).
505
+ *
506
+ * β›”β›” THIS EXISTS SO THE CLIPBOARD CANNOT INHERIT THE DEFAULT. `clipboardOps.ts` builds the OS
507
+ * clipboard text, and a copy out to Excel of a plain `1234.5` must arrive as `1234.5` rather than
508
+ * as the rounded, grouped `1,235` a screen shows. A format somebody EXPLICITLY chose has always
509
+ * travelled to the clipboard and still does β€” `formatCellText` applies it there β€” but the
510
+ * IMPLICIT default is a reading convenience and never a value. So the clipboard reads this door
511
+ * and the canvas reads {@link displayText}.
512
+ */
513
+ export const rawDisplayText = (cell: Cell | null | undefined): string => {
514
  if (!cell) return "";
515
  if (cell.state === "refused") {
516
  return cell.refusal?.message ?? "This cell could not be calculated.";
 
518
  return cell.display ?? (cell.value == null ? "" : String(cell.value));
519
  };
520
 
521
+ /**
522
+ * What a cell PAINTS. A refusal states its reason and never shows a blank (R16), and a number
523
+ * that nobody has formatted reads with {@link DEFAULT_NUMBER_FORMAT}.
524
+ *
525
+ * β›” IT REUSES `types.ts::formatCellText` RATHER THAN GROUPING DIGITS ITSELF. A second formatter
526
+ * would be a second opinion about what the Number kind means, and the two would drift the first
527
+ * time one of them learned about locales. The cell handed to it is a THROWAWAY COPY carrying the
528
+ * default in its format slot; the cell this function was given is never touched.
529
+ *
530
+ * β›” FOUR CARVE-OUTS, AND EACH ONE IS A DEFECT IF IT IS DROPPED:
531
+ * 1. AN EXPLICIT FORMAT WINS. The default is what a cell reads when nobody has said otherwise;
532
+ * overriding a chosen format would make the ribbon's Number menu, and its thousands toggle
533
+ * in particular, a control that does something other than what it says.
534
+ * 2. A REFUSED CELL KEEPS ITS SENTENCE. Running a sentence through a number formatter is how
535
+ * the one thing R16 puts on the screen gets replaced by `NaN`.
536
+ * 3. A VALIDATED CELL IS LEFT ALONE. `SheetGrid.tsx` decides which option of a dropdown is
537
+ * selected by comparing this string against the raw option values, so grouping a numeric
538
+ * option would silently stop a list matching its own value.
539
+ * 4. ANYTHING `asNumber` CANNOT READ IS RETURNED UNTOUCHED. Text stays text, a date string
540
+ * stays a date string, and a blank cell stays blank.
541
+ */
542
+ export const displayText = (cell: Cell | null | undefined): string => {
543
+ const raw = rawDisplayText(cell);
544
+ if (!cell) return raw;
545
+ if (cell.state === "refused") return raw;
546
+ if (cell.style?.format) return raw;
547
+ if (cell.validation) return raw;
548
+ // ⚠ THE SAME SOURCE `formatCellText` WILL READ, so the guard and the formatter can never
549
+ // disagree about whether there is a number here at all.
550
+ if (asNumber(cell.value != null ? cell.value : raw) === null) return raw;
551
+ return formatCellText(
552
+ { ...cell, style: { ...(cell.style ?? {}), format: DEFAULT_NUMBER_FORMAT } },
553
+ raw,
554
+ );
555
+ };
556
+
557
  /**
558
  * Replace or REMOVE several cells at once, returning a NEW workbook. `null` removes.
559
  *
 
788
  /**
789
  * Shift a period's `ref` the way a dragged formula reference shifts, `$` anchors honoured.
790
  *
791
+ * ⭐ IT IS `a1.ts`'s RULE AND NOT A SECOND ONE, AND SINCE W54-T18 IT DOES NOT EVEN REACH FOR IT
792
+ * ITSELF: `bindingRefs.ts::shiftRefText` is the one-reference rule now, so this name survives as
793
+ * the door its callers already know while there stays exactly ONE implementation underneath.
794
  *
795
  * ⚠ THE REF SHIFTS ON BOTH AXES, WHILE THE PERIOD'S `start` SHIFTS ONLY ACROSS COLUMNS. They are
796
  * different things: a `start` is a period, and R9 says a period moves across and holds down; a
 
798
  * same cell from forty different places. A reader who wants it fixed writes `$B$1`, which is the
799
  * control Excel already taught them, or locks the period.
800
  */
801
+ export const shiftPeriodRef = (ref: string, dRow: number, dCol: number): string =>
802
+ shiftRefText(ref, dRow, dCol);
 
 
 
 
 
803
 
804
  /** Where a value sits in an option order, or -1. An unset value walks into the FIRST option. */
805
  const optionIndex = (options: readonly string[], value: string): number =>
 
894
  let changed = false;
895
 
896
  // ── ACROSS COLUMNS (R9, R10): the period, and only ever the COLUMN delta ──────────────────
897
+ if (period && !period.locked && rules.across === "period" && dCol !== 0 && period.start) {
 
898
  const start = shiftPeriodStart(period.start, period.unit, dCol);
899
+ if (start !== period.start) {
900
+ next.period = { ...(binding.period as Record<string, unknown>), start };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
901
  changed = true;
902
  }
903
  }
904
 
905
+ // ── THE BINDING'S CELL REFERENCES (C3, R6): both axes, `$` honoured, locks obeyed ─────────
906
+ // ⭐⭐ W54-T18: ONE CALL, AND IT IS THE ONLY PLACE A BINDING'S REFERENCES MOVE. It runs whatever
907
+ // the across rule says, because a `ref` is a POINTER and a pointer follows its cell in every
908
+ // direction even where the period itself holds β€” that was two identical inline branches before
909
+ // this ticket. `bindingRefs.ts` decides WHICH slots those are, so C3's filter-value reference
910
+ // arrives without a second edit here.
911
+ const shifted = shiftBindingRefs(next, dRow, dCol);
912
+ if (shifted.changed) {
913
+ next = shifted.binding;
914
+ changed = true;
915
+ }
916
+
917
  // ── DOWN ROWS (R10): the chosen filter's value, and only ever the ROW delta ───────────────
918
  let noCatalogue = false;
919
  let noField = false;
 
1011
  return { edits };
1012
  };
1013
 
1014
+ // ═════════════════════════════════════════════════════════════════════════════════════════════
1015
+ // W54-T15 / CONTRACT C2 β€” THE IN APP CLIPBOARD, so a copy carries the WHOLE cell style.
1016
+ //
1017
+ // ⭐⭐ IT EXISTS BECAUSE A CLIPBOARD ROUND TRIP CARRIES TEXT AND NOTHING ELSE. The component's
1018
+ // own `copiedRef` already held the copied CELLS, but the door that reads it only hands them on
1019
+ // when the pasted text BYTE MATCHES what was copied, so a trip through another app β€” which
1020
+ // normalises line endings, or appends a trailing newline β€” degraded every paste to a bare value
1021
+ // wearing the DESTINATION's formatting. This module level registry is the second door:
1022
+ // `clipboardOps.ts::buildCopyPayload` records into it, because that is the ONE builder BOTH copy
1023
+ // doors share - the ribbon's button and glide's own native Ctrl+C - and `pasteCells` reads from
1024
+ // it when the door that pasted brought no cells of its own.
1025
+ //
1026
+ // β›” THE TOKEN IS THE KEY, NOT A MARKER IN THE TEXT. Nothing is added to the string a person
1027
+ // pastes into Excel: the clean TSV IS the lookup key, normalised for line endings and a trailing
1028
+ // newline. An external paste simply misses and degrades gracefully.
1029
+ //
1030
+ // β›” AND IT IS BOUNDED. This is a clipboard, not a cache: a couple of entries, newest first.
1031
+ // ═════════════════════════════════════════════════════════════════════════════════════════════
1032
+
1033
+ /** One copy this app made of its own cells. `clipboardOps.ts::buildCopyPayload` builds it. */
1034
+ export interface CopiedBlock {
1035
+ /** The FORMATTED grid, which is what goes to the OS clipboard and on to Excel. */
1036
+ text: string;
1037
+ col: number;
1038
+ row: number;
1039
+ cells: readonly (readonly (Cell | null)[])[];
1040
+ /**
1041
+ * ⭐⭐ THE SECOND KEY FOR THE SAME BLOCK, and one key was not enough. The two copy doors come
1042
+ * back through DIFFERENT strings: the OS clipboard carries the FORMATTED grid, so a currency
1043
+ * cell leaves as `$1,234.50`, while glide round trips its own copy through a `text/html`
1044
+ * payload carrying `editableText`, so the very same cell comes back as `1234.5`. A registry
1045
+ * findable under only one of them misses on exactly one of the doors, which is what left a
1046
+ * native Ctrl+C pasting with the destination's own formatting still on it.
1047
+ */
1048
+ editable?: string;
1049
+ }
1050
+
1051
+ /** How many copies the registry remembers. A clipboard holds one; the spare covers a cut. */
1052
+ export const COPY_REGISTRY_LIMIT = 2;
1053
+
1054
+ const copyRegistry: CopiedBlock[] = [];
1055
+
1056
+ /**
1057
+ * ⭐⭐ W54-T16 β€” THE ONE PENDING CUT, WHICH IS A CUT THAT HAS NOT HAPPENED YET.
1058
+ *
1059
+ * β›”β›” A CUT CLEARS ITS SOURCE WHEN THE PASTE LANDS, NOT WHEN THE SCISSORS ARE PRESSED. Clearing
1060
+ * at cut time is what the owner saw: Ctrl+X emptied nothing an eye could trust (a filled cell
1061
+ * kept its fill, a bound cell kept everything), and Ctrl+X followed by Escape had already thrown
1062
+ * the value away with no paste to put it back. So the cut is RECORDED here and performed by
1063
+ * {@link pasteCells}, in the same edit set as the paste, which is also what makes it one undo
1064
+ * step and one save rather than two racing for the same revision.
1065
+ *
1066
+ * β›” EXACTLY ONE MAY BE PENDING. A newer copy or cut is the person changing their mind, and a
1067
+ * second pending cut would mean a paste could delete cells from a rectangle nobody remembers
1068
+ * cutting. {@link rememberCopy} therefore drops it, and every copy goes through that door.
1069
+ */
1070
+ let pendingCut: CopiedBlock | null = null;
1071
+
1072
+ /**
1073
+ * The lookup key: the clipboard text with its line endings normalised and any trailing newline
1074
+ * dropped. Windows writes `\r\n` and Excel appends a final newline; neither of those changes
1075
+ * which cells were copied, so neither may change which entry is found.
1076
+ */
1077
+ const clipboardKey = (text: string): string =>
1078
+ String(text ?? "").replace(/\r\n?/g, "\n").replace(/\n+$/, "");
1079
+
1080
+ /** Every normalised string one block can be found under. Usually one; two when they differ. */
1081
+ const copyKeys = (block: CopiedBlock): string[] => {
1082
+ const keys = [clipboardKey(block.text)];
1083
+ if (block.editable !== undefined) {
1084
+ const editable = clipboardKey(block.editable);
1085
+ if (editable !== keys[0]) keys.push(editable);
1086
+ }
1087
+ return keys;
1088
+ };
1089
+
1090
+ /**
1091
+ * Record a copy this app just made, so a later paste can find its cells by the text alone.
1092
+ *
1093
+ * ⚠ A BLOCK THAT SHARES ANY KEY WITH AN OLDER ENTRY REPLACES IT. Two entries answering to the
1094
+ * same string would make which cells arrive depend on insertion order, and the newer copy is
1095
+ * always the one somebody just made.
1096
+ */
1097
+ export const rememberCopy = (block: CopiedBlock): void => {
1098
+ // β›” W54-T16: A NEW COPY OR CUT DROPS THE PENDING CUT, and this is the ONE place it can be
1099
+ // done once for both doors, because every copy this app makes is built by
1100
+ // `clipboardOps.ts::buildCopyPayload` and every build registers here. A cut re-arms it
1101
+ // immediately afterwards, from the promise that saw the clipboard accept the write.
1102
+ pendingCut = null;
1103
+ const keys = copyKeys(block);
1104
+ for (let i = copyRegistry.length - 1; i >= 0; i -= 1) {
1105
+ const held = copyRegistry[i];
1106
+ if (held && copyKeys(held).some((key) => keys.includes(key))) copyRegistry.splice(i, 1);
1107
+ }
1108
+ copyRegistry.unshift(block);
1109
+ while (copyRegistry.length > COPY_REGISTRY_LIMIT) copyRegistry.pop();
1110
+ };
1111
+
1112
+ /** The cells behind this clipboard text, when this app is the one that copied them. */
1113
+ export const recallCopy = (text: string): CopiedBlock | null => {
1114
+ const key = clipboardKey(text);
1115
+ return copyRegistry.find((held) => copyKeys(held).includes(key)) ?? null;
1116
+ };
1117
+
1118
+ /** Empty the registry. A proof needs it; nothing in the app has to forget a copy. */
1119
+ export const forgetCopies = (): void => { copyRegistry.length = 0; };
1120
+
1121
+ /**
1122
+ * ⭐⭐ W54-T16 β€” ARM THE CUT. `clipboardOps.ts::runCopySelection` calls this on a cut whose
1123
+ * clipboard write was ACCEPTED, and only then: a browser that refuses the write leaves nothing
1124
+ * armed, so nothing is ever deleted with an empty clipboard to paste back from.
1125
+ */
1126
+ export const rememberCut = (block: CopiedBlock): void => { pendingCut = block; };
1127
+
1128
+ /** The cut waiting for its paste, if there is one. Read by proofs; {@link pasteCells} owns it. */
1129
+ export const recallCut = (): CopiedBlock | null => pendingCut;
1130
+
1131
+ /** Disarm the cut. Called when its paste has landed, and by a proof between cases. */
1132
+ export const forgetCut = (): void => { pendingCut = null; };
1133
+
1134
+ /**
1135
+ * A CHEAP FINGERPRINT OF ONE CELL, which is all the identity guard below needs.
1136
+ *
1137
+ * ⚠ IT IS DELIBERATELY NOT A DEEP EQUAL. The question is "is this still the cell that was cut",
1138
+ * not "is every field identical": kind, typed text, last computed value, display string and
1139
+ * WHETHER there is a binding already separate a cut cell from anything a person is likely to
1140
+ * have put in its place, and a deep comparison would run over every cell of the block on every
1141
+ * paste for no additional safety.
1142
+ */
1143
+ const cutFingerprint = (cell: Cell | null | undefined): string =>
1144
+ cell
1145
+ ? [cell.kind, cell.text ?? "", String(cell.value ?? ""), cell.display ?? "",
1146
+ cell.binding ? "bound" : ""].join("")
1147
+ : "";
1148
+
1149
+ /**
1150
+ * ⭐⭐ W54-T16 β€” THE OTHER HALF OF A CUT, PERFORMED INSIDE THE PASTE THAT COMPLETES IT.
1151
+ *
1152
+ * The pending cut is claimed only when the text being pasted is the text that was cut, matched
1153
+ * through {@link copyKeys} so BOTH clipboard renderings of the same block find it: the OS
1154
+ * clipboard carries the formatted grid and glide's own round trip carries the editable one.
1155
+ *
1156
+ * β›” THE SOURCE IS REMOVED, NOT BLANKED. The record goes away entirely, so the fill colour and
1157
+ * the database binding go with it, which is what "the cell it was cut from is empty" means to
1158
+ * the person looking at it. {@link blankOf} keeps the formatting on purpose and stays the Delete
1159
+ * key's answer; a cut is a MOVE, and what moved is not still sitting there in amber.
1160
+ *
1161
+ * β›”β›” AN ADDRESS THE PASTE ITSELF JUST WROTE IS NEVER CLEARED. A block cut and pasted onto
1162
+ * itself, or onto a rectangle overlapping its own, must keep what landed; the clear runs after
1163
+ * the paste's writes and skips every address already spoken for.
1164
+ *
1165
+ * β›”β›” AND IT FAILS CLOSED ON IDENTITY, WHICH IS THE GUARD THAT STOPS THIS DELETING SOMEBODY'S
1166
+ * DATA. Nothing tells this function which TAB the cut was made on, so a cut on one sheet and a
1167
+ * paste on another would otherwise delete whatever happens to sit at the same addresses. Every
1168
+ * recorded source cell must still match the cell at its address on the tab being pasted into; if
1169
+ * a single one does not, NOTHING is cleared and the cut stays armed for the paste that belongs
1170
+ * to it. A recorded cell that was empty asks for nothing and cannot fail the check.
1171
+ */
1172
+ /**
1173
+ * ⭐⭐ W54-T16 β€” IS THIS PASTE THE OTHER HALF OF THE PENDING CUT? Matched through
1174
+ * {@link copyKeys}, so both clipboard renderings of the same block answer yes.
1175
+ *
1176
+ * β›”β›” THE KEY MATCH ALONE DECIDES IT, AND THE IDENTITY CHECK IS A DIFFERENT QUESTION. This one
1177
+ * asks "is this a MOVE", which governs how the cells that LAND are built; the identity check
1178
+ * asks "may the source be removed", which governs the cells that go away. Welding the two
1179
+ * together would make a paste whose source has since changed silently start shifting periods
1180
+ * again, which is the one failure nobody would see on screen.
1181
+ */
1182
+ const completesCut = (pastedText: string): boolean =>
1183
+ pendingCut !== null && copyKeys(pendingCut).includes(clipboardKey(pastedText));
1184
+
1185
+ const clearCutSource = (
1186
+ tab: SheetTab | null | undefined,
1187
+ edits: Record<string, Cell | null>,
1188
+ pastedText: string,
1189
+ ): void => {
1190
+ const block = pendingCut;
1191
+ if (!block) return;
1192
+ if (!completesCut(pastedText)) return;
1193
+ const addrs: string[] = [];
1194
+ for (let r = 0; r < block.cells.length; r += 1) {
1195
+ const row = block.cells[r] ?? [];
1196
+ for (let c = 0; c < row.length; c += 1) {
1197
+ const cut = row[c] ?? null;
1198
+ if (!cut) continue;
1199
+ const addr = addressOf(block.col + c, block.row + r);
1200
+ if (cutFingerprint(cellAt(tab, addr)) !== cutFingerprint(cut)) return;
1201
+ addrs.push(addr);
1202
+ }
1203
+ }
1204
+ for (const addr of addrs) {
1205
+ if (Object.prototype.hasOwnProperty.call(edits, addr)) continue;
1206
+ edits[addr] = null;
1207
+ }
1208
+ pendingCut = null;
1209
+ };
1210
+
1211
+ /**
1212
+ * ⭐⭐ CONTRACT C2 β€” THE WHOLE `CellStyle` RIDES ACROSS, NEVER A LIST OF KEY NAMES. The style
1213
+ * object is SPREAD as a whole, so a key added to `CellStyle` next wave is carried by this code
1214
+ * without an edit here. A hand maintained copy list is exactly how the next added field silently
1215
+ * stops being copied, and C2 refuses it.
1216
+ *
1217
+ * β›” THE SOURCE REPLACES THE TARGET'S OWN STYLE, it does not merge into it. Excel replaces, and
1218
+ * a merge would leave the destination's old fill showing under a source cell that has none.
1219
+ *
1220
+ * ⚠ NO SOURCE CELL MEANS NO OPINION. An external paste knows nothing about where its text came
1221
+ * from, so it leaves the target's formatting exactly as it was rather than blanking it.
1222
+ *
1223
+ * ⚠ A STYLED BLANK STILL LANDS. Copying an empty cell that carries only a fill and pasting it
1224
+ * paints that fill, which is why this may build a cell where {@link commitTyped} returned none.
1225
+ */
1226
+ const withSourceStyle = (landed: Cell | null, copied: Cell | null): Cell | null => {
1227
+ if (!copied) return landed;
1228
+ if (copied.style) {
1229
+ const base: Cell = landed ?? { kind: "empty", state: "fresh" };
1230
+ return { ...base, style: { ...copied.style } };
1231
+ }
1232
+ if (!landed?.style) return landed;
1233
+ const bare: Cell = { ...landed };
1234
+ delete bare.style;
1235
+ return bare;
1236
+ };
1237
+
1238
  /**
1239
  * A TSV paste, landed with its top left corner at the target cell.
1240
  *
 
1276
  const source = values.length === 0 || values.every((row) => row.length === 0)
1277
  ? ([[""]] as readonly (readonly string[])[])
1278
  : values;
1279
+ // ⭐⭐ W54-T15 β€” WHERE THE SOURCE CELLS COME FROM WHEN THE DOOR THAT PASTED HAS NONE. The
1280
+ // component hands them over only while the pasted text byte matches its own last copy, so a
1281
+ // round trip through another app arrived here with `drag.cells` absent and the source's whole
1282
+ // style on the floor. The registry is asked second, keyed on the pasted text itself, and a
1283
+ // miss changes nothing: the block then lands as the values it really is.
1284
+ //
1285
+ // ⭐ W54-T16: THE SAME STRING ANSWERS THE SECOND QUESTION TOO - "is this paste the other half
1286
+ // of a cut" - so it is built once and handed to both doors rather than rebuilt below.
1287
+ const pastedText = source.map((row) => row.join("\t")).join("\n");
1288
+ // β›”β›” W54-T16 β€” A CUT IS A MOVE, AND A MOVE SHIFTS NOTHING. Answered ONCE, before any cell is
1289
+ // built, because every landing cell in the block has to agree about it.
1290
+ const moving = completesCut(pastedText);
1291
+ const recalled = drag?.cells
1292
+ ? null
1293
+ : recallCopy(pastedText);
1294
+ const held = drag?.cells ?? recalled?.cells ?? null;
1295
+ const heldFrom = drag?.from ?? (recalled ? { col: recalled.col, row: recalled.row } : null);
1296
  /**
1297
  * Land the copied block ONCE, with its top left corner at `originCol` / `originRow`.
1298
  *
 
1325
  // `c`s cancel. Writing `col - from.col` instead adds the block's own width back in and
1326
  // gives the second column of a two column paste a period one month further out than the
1327
  // first, which reads as a working feature until somebody checks the numbers.
1328
+ //
1329
+ // ⭐⭐ W54-T15 / C2 β€” AND THE SOURCE'S WHOLE STYLE LANDS WITH IT. `commitTyped` spreads
1330
+ // the TARGET cell, which is right for a typed edit and wrong for a paste: the
1331
+ // destination kept its own fill, borders and number format while the source's were
1332
+ // dropped. {@link withSourceStyle} carries the style object across as a whole.
1333
+ const copied = held?.[r]?.[c] ?? null;
1334
+ if (copied && copied.kind === "bound" && heldFrom) {
1335
+ // β›”β›” W54-T16 β€” A CUT IS A MOVE, AND A MOVE SHIFTS NOTHING. Excel's rule, and the two
1336
+ // halves of it are different acts: a COPY walks a binding's period and its cell
1337
+ // references by the paste delta (R6, and W54-T18 depends on it), while a CUT carries
1338
+ // the cell to its new address verbatim. Handing the delta to both was measured in a
1339
+ // browser: a bound cell on 2026-08, cut and dropped two columns right, arrived on
1340
+ // 2026-10, and because the binding then counted as CHANGED it also arrived BLANK -
1341
+ // somebody moved a cell reading 41,250 and got an empty one. A zero delta keeps
1342
+ // `dragBoundCell` on its `kept` branch, so the value survives the move.
1343
+ //
1344
+ // ⚠ THE TEST IS THE KEY MATCH ALONE, never whether the source can still be cleared.
1345
+ // Those are two questions: `completesCut` says the person pressed Cut, and
1346
+ // `clearCutSource`'s own identity check decides whether the source may be removed. A
1347
+ // cut whose source has since changed is still a MOVE for reference purposes.
1348
+ const dCol = moving ? 0 : originCol - heldFrom.col;
1349
+ const dRow = moving ? 0 : originRow - heldFrom.row;
1350
+ const out = dragBoundCell(copied, dCol, dRow, drag?.catalogue);
1351
+ edits[addr] = withSourceStyle(out.cell, copied);
1352
  tally.dragged += 1;
1353
  if (out.noCatalogue) tally.noCatalogue += 1;
1354
  if (out.noField) tally.noField += 1;
1355
  if (out.atEnd) tally.atEnd += 1;
1356
  continue;
1357
  }
1358
+ // β›”β›” W54-T15 β€” WHERE THE SOURCE CELL IS KNOWN, THE SOURCE'S OWN VALUE LANDS, NOT THE
1359
+ // CLIPBOARD'S RENDERING OF IT. A currency cell reaches this door as `$1,234.50`, and
1360
+ // committing that string stored a cell that LOOKS right (`formatCellText` falls back to
1361
+ // the raw string) while `types.ts::asNumber` strips only commas and spaces, so the
1362
+ // currency mark left it a number no longer: `SUM` would skip a cell somebody had just
1363
+ // copied from another that summed fine. Excel pastes the VALUE and paints it with the
1364
+ // format, which is exactly what `editableText` plus the carried style give.
1365
+ //
1366
+ // β›” A COPIED FORMULA IS UNCHANGED BY THIS. `editableText` returns the formula for a
1367
+ // formula cell, which is the same string glide's own round trip already delivered, so a
1368
+ // pasted formula still lands verbatim and its references are still not shifted here.
1369
+ //
1370
+ // β›” AND THE NO SOURCE PATH IS UNTOUCHED. An external paste, or a registry miss, has no
1371
+ // cell to ask, so it commits the clipboard string exactly as it always has.
1372
+ const landing = copied ? editableText(copied) : String(row[c] ?? "");
1373
+ edits[addr] = withSourceStyle(commitTyped(cell, landing, read), copied);
1374
  }
1375
  }
1376
  };
 
1385
  if (!rect || srcRows === 0 || srcCols === 0 || (wide === 1 && tall === 1)) {
1386
  // No drag, or one target cell: the block lands anchored where it was dropped, as it always has.
1387
  writeBlock(targetCol, targetRow);
1388
+ // β›” W54-T16: AFTER the paste's own writes, so an overlapping cut keeps what just landed.
1389
+ clearCutSource(tab, edits, pastedText);
1390
  return { edits, ...tally };
1391
  }
1392
  if (wide % srcCols !== 0 || tall % srcRows !== 0) {
 
1400
  writeBlock(rect.col0 + tx * srcCols, rect.row0 + ty * srcRows);
1401
  }
1402
  }
1403
+ // β›” W54-T16: same rule on the tiled path, and after every tile - a cut tiled back over its own
1404
+ // rectangle keeps the copies that landed there. A SIZE REFUSAL above wrote nothing and returned
1405
+ // before this line, so a refused paste also leaves the cut armed for the paste that works.
1406
+ clearCutSource(tab, edits, pastedText);
1407
  return { edits, ...tally };
1408
  };
1409
 
 
1465
  // "bound"` directly: that predicate and its whole CONVERSION concept are retired, and this
1466
  // is the one remaining place that ever asked what a cell's OWN kind is, for drag-routing
1467
  // rather than for a confirmation.
1468
+ //
1469
+ // ⭐ W54-T15 / C2 β€” A FILL CARRIES THE PATTERN'S WHOLE STYLE TOO, exactly as Excel's fill
1470
+ // handle does and exactly as a paste now does one door away. `setFormula` and `commitTyped`
1471
+ // both spread the TARGET, so without {@link withSourceStyle} dragging a formatted cell
1472
+ // across a range copied its value and left every destination wearing its own old format.
1473
  if (pattern.kind === "bound") {
1474
  const dragged = dragBoundCell(pattern, col - srcCol, row - srcRow, drag?.catalogue);
1475
+ edits[addr] = withSourceStyle(dragged.cell, pattern);
1476
  tally.dragged += 1;
1477
  if (dragged.noCatalogue) tally.noCatalogue += 1;
1478
  if (dragged.noField) tally.noField += 1;
 
1480
  continue;
1481
  }
1482
  if (pattern.kind === "formula") {
1483
+ edits[addr] = withSourceStyle(setFormula(
1484
  target,
1485
  fillFormula(pattern.formula ?? "", row - srcRow, col - srcCol),
1486
  read,
1487
+ ), pattern);
1488
  continue;
1489
  }
1490
+ edits[addr] = withSourceStyle(commitTyped(target, editableText(pattern)), pattern);
1491
  }
1492
  }
1493
  return { edits, ...tally };
 
1858
  return sheets;
1859
  };
1860
 
1861
+ // ════════════════════════════════════════════════════════════════════════════════════════
1862
+ // ⭐ WAVE 54 BASE KIT β€” THE STYLE WRITERS NOW LIVE IN `cellStyleOps.ts`, AND THEY ARE STILL
1863
+ // EXPORTED FROM HERE. W51-T16's whole section moved out of this file verbatim, comments and all,
1864
+ // so that a lane writing styles and a lane writing values stop meeting in one file. The names are
1865
+ // re-exported rather than merely moved, because `SheetGrid.tsx` and `_test/sheetEngine.test.ts`
1866
+ // both import them from THIS module and neither ticket is this one: a moved export would have
1867
+ // changed two import lines, one of which a `verify_grid_ux.py` negative control pins by anchor.
 
1868
  //
1869
+ // ⚠ `pasteCells` STAYED. It writes VALUES and merely carries a style along; a paste is not a
1870
+ // style act, and it belongs beside the other bulk value doors above.
1871
+ // ════════════════════════════════════════════════════════════════════════════════════════
1872
+ export {
1873
+ clearAll, clearFormats, paintPatch, styleCells, styleOf, STYLE_KEYS,
1874
+ } from "./cellStyleOps";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1875
 
1876
  /** One selected rectangle, in the sheet's own zero based coordinates, inclusive of both corners. */
1877
  export interface CellRange {