fsanyoto commited on
Commit
016c754
Β·
verified Β·
1 Parent(s): 56e1f2f

Deploy AIOS web (React glide grid + FastAPI slice)

Browse files
Files changed (39) hide show
  1. api/routes_auth.py +52 -1
  2. api/routes_grid.py +58 -11
  3. royalimports_os/aios_grid.py +94 -1
  4. royalimports_os/core/measure_resolve.py +17 -7
  5. royalimports_os/core/users.py +43 -0
  6. royalimports_os/harness/measure_filter.py +63 -0
  7. web/dist-embed/index.html +0 -0
  8. web/dist-embed/sample_customers.json +479 -466
  9. web/src/customer-grid/ColumnMenu.tsx +225 -257
  10. web/src/customer-grid/CustomerGrid.tsx +245 -27
  11. web/src/customer-grid/FieldSelect.tsx +322 -0
  12. web/src/customer-grid/RecordDetail.css +241 -0
  13. web/src/customer-grid/RecordDetail.tsx +312 -28
  14. web/src/customer-grid/TimeSeriesPanel.tsx +507 -121
  15. web/src/customer-grid/Toolbar.tsx +329 -76
  16. web/src/customer-grid/ViewSidebar.tsx +29 -11
  17. web/src/customer-grid/cells.ts +158 -10
  18. web/src/customer-grid/choiceColors.ts +104 -1
  19. web/src/customer-grid/copyConfig.ts +104 -0
  20. web/src/customer-grid/display.ts +62 -0
  21. web/src/customer-grid/icons.tsx +224 -3
  22. web/src/customer-grid/overlayPlacement.ts +155 -19
  23. web/src/customer-grid/recordFields.ts +235 -0
  24. web/src/customer-grid/theme.ts +103 -52
  25. web/src/customer-grid/timeSeriesData.ts +952 -351
  26. web/src/customer-grid/types.ts +243 -5
  27. web/src/customer-grid/useGetCellContent.ts +59 -9
  28. web/src/customer-grid/useGridColumns.ts +58 -29
  29. web/src/customer-grid/viewModes.tsx +52 -48
  30. web/src/index.css +498 -38
  31. web/src/settings/SettingsModal.tsx +167 -2
  32. web/src/settings/settingsApi.ts +13 -0
  33. web/src/shell/NavExtras.tsx +78 -104
  34. web/src/shell/Shell.tsx +100 -26
  35. web/src/shell/navExtras.css +48 -11
  36. web/src/shell/session.ts +8 -1
  37. web/src/viz/DashboardView.css +38 -0
  38. web/src/viz/DashboardView.tsx +335 -97
  39. web/src/viz/chartData.ts +80 -1
api/routes_auth.py CHANGED
@@ -6,8 +6,10 @@ a branded login page) lands when D-1/D-2 unblock (owner blocker B-4); this is th
6
  replaces, and it is deliberately the same account store so the migration is a swap of the
7
  CREDENTIAL check, not of the user model.
8
  """
 
9
  import hmac
10
  import os
 
11
  import time
12
  from collections import OrderedDict
13
 
@@ -72,7 +74,56 @@ def _public_user(user):
72
  "team_id": perms.scope_team_id(user),
73
  "agent": perms.scope_agent(user),
74
  "modules": sorted(perms.allowed_modules(user) or []) or "all",
75
- "landing": perms.landing_page(user)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
 
78
  @router.post("/login")
 
6
  replaces, and it is deliberately the same account store so the migration is a swap of the
7
  CREDENTIAL check, not of the user model.
8
  """
9
+ import base64 as _b64
10
  import hmac
11
  import os
12
+ import re as _re
13
  import time
14
  from collections import OrderedDict
15
 
 
74
  "team_id": perms.scope_team_id(user),
75
  "agent": perms.scope_agent(user),
76
  "modules": sorted(perms.allowed_modules(user) or []) or "all",
77
+ "landing": perms.landing_page(user),
78
+ # Wave 14 C-AVATAR β€” the user's OWN photo (Settings preview + the shell chip).
79
+ # Everyone else's rides workspace.userAvatars, keyed by display name.
80
+ "avatar": user.get("avatar") or None}
81
+
82
+
83
+ #: Wave 14 C-AVATAR β€” the write-side wall. PNG/JPEG data URLs only; the client downscales to
84
+ #: <=128px before posting, and the server re-validates because a stored data URL is served to
85
+ #: every grid session verbatim.
86
+ _AVATAR_RE = _re.compile(r"^data:image/(png|jpeg);base64,([A-Za-z0-9+/=]+)$")
87
+ _AVATAR_MAX_BYTES = 64 * 1024
88
+
89
+
90
+ @router.post("/me/avatar")
91
+ def set_avatar(body: dict = Body(default=None),
92
+ session: Session = Depends(require_session)):
93
+ import core.store as _store
94
+ raw = str((body or {}).get("dataUrl") or "")
95
+ m = _AVATAR_RE.match(raw)
96
+ if not m:
97
+ raise err(400, "bad_avatar",
98
+ "expected a data:image/png;base64,... or image/jpeg data URL")
99
+ try:
100
+ blob = _b64.b64decode(m.group(2), validate=True)
101
+ except Exception:
102
+ raise err(400, "bad_avatar", "that data URL is not valid base64")
103
+ if len(blob) > _AVATAR_MAX_BYTES:
104
+ raise err(400, "bad_avatar",
105
+ f"avatar too large - {_AVATAR_MAX_BYTES // 1024}KB decoded max "
106
+ f"(downscale to 128px before posting)")
107
+ if not _store.available():
108
+ raise err(503, "store_unavailable", "the tenant store is unavailable")
109
+ # session.uname is the canonical account handle; the session's user RECORD does not
110
+ # carry a "username" key (it is the registry's dict key), so keying the write off the
111
+ # record would silently no-op β€” caught by X7's fresh /me read.
112
+ users.set_avatar(session.uname, raw)
113
+ u2 = dict(session.user)
114
+ u2["avatar"] = raw
115
+ return {"user": _public_user(u2)}
116
+
117
+
118
+ @router.delete("/me/avatar")
119
+ def clear_avatar(session: Session = Depends(require_session)):
120
+ import core.store as _store
121
+ if not _store.available():
122
+ raise err(503, "store_unavailable", "the tenant store is unavailable")
123
+ users.set_avatar(session.uname, None)
124
+ u2 = dict(session.user)
125
+ u2.pop("avatar", None)
126
+ return {"user": _public_user(u2)}
127
 
128
 
129
  @router.post("/login")
api/routes_grid.py CHANGED
@@ -124,8 +124,14 @@ def workspace(scope: str = "customer",
124
  try:
125
  from core import users as _users
126
  workspace["userOptions"] = _users.assignable_people()
 
 
 
 
 
127
  except Exception:
128
  workspace["userOptions"] = []
 
129
 
130
  # THE SURFACE STAMP β€” a MIRROR of the host's own (`_table_grid`'s hide/cohort stamps).
131
  # ⚠ Deliberately NOT `hideViews`: `cohortMode` is what swaps the Views panel for the cohort
@@ -140,10 +146,15 @@ def workspace(scope: str = "customer",
140
 
141
  # ─────────────────────────────────────────────── the TIME-SERIES channel (C-TS, 2026-08-02)
142
  _TS_BUCKETS = ("week", "month", "quarter", "year")
143
- _TS_MAX_BUCKETS = 120 # one grouped query per field makes bucket count nearly free
144
  _TS_MAX_FIELDS = 12
145
  _TS_MAX_PIDS = 5000
146
  _TS_MAX_LAST_N = 120
 
 
 
 
 
147
 
148
 
149
  def _ts_start_of(bucket, d):
@@ -195,14 +206,23 @@ def grid_timeseries(body: dict = Body(default=None),
195
  session: Session = Depends(module_gate(MODULE))):
196
  """Pooled measure values per calendar bucket β€” the time-series view's data channel.
197
 
 
 
 
 
 
 
 
 
198
  The client sends the pids its view currently matches (the filter IS the scope); the server
199
  intersects them with the session's book, so the request can only ever NARROW. Values are
200
- POOLED aggregates computed by the semantic layer's own expression per bucket (the
201
- additivity law: an average is computed at pool grain, never averaged over per-customer
202
- answers). A bucket with no rows is 0 for a sum/count and null for anything else β€” null is
203
- "unanswerable", 0 is a real zero, and the client renders them differently on purpose.
204
  """
205
  from core import measure_resolve
 
206
  from routes_customers import _pool_stamp, _team_agent, allowed_pids
207
 
208
  body = body or {}
@@ -289,13 +309,30 @@ def grid_timeseries(body: dict = Body(default=None),
289
  raise err(400, "bad_timeseries",
290
  "none of the requested fields are measure fields (v1 serves measure-backed "
291
  "fields only)")
292
- mfields = [{"key": k, "measure": dict(fdefs[k]["measure"])} for k in keys]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
 
294
  team_id, agent = _team_agent(session)
295
  stamp = _pool_stamp(rt, team_id, agent)
296
  problems = []
 
297
  answers = measure_resolve.series_values(
298
- mfields, bucket, starts[0].isoformat(), ends[-1].isoformat(),
299
  team_id, frozenset(pool), today, stamp, rt.series_memo,
300
  on_error=lambda tag, e: problems.append(str(e)[:200]))
301
 
@@ -307,7 +344,7 @@ def grid_timeseries(body: dict = Body(default=None),
307
  col["partial"] = True
308
  columns.append(col)
309
  rows = []
310
- for k in keys:
311
  ans = answers.get(k)
312
  if ans is None:
313
  dropped.append({"field": k, "reason": "unresolvable"})
@@ -315,10 +352,20 @@ def grid_timeseries(body: dict = Body(default=None),
315
  vals_by = ans.get("values") or {}
316
  agg_kind = str(ans.get("agg") or "sum")
317
  zero_fill = agg_kind in ("sum", "count")
318
- vals = [vals_by.get(s.isoformat(), 0 if zero_fill else None) for s in starts]
319
- total = round(sum(v for v in vals if v is not None), 2) if zero_fill else None
 
 
 
 
 
 
 
 
320
  rows.append({"field": k, "label": str(fdefs[k].get("label") or k)[:120],
321
- "agg": agg_kind, "values": vals, "total": total})
 
 
322
  meta = {"pool": len(pool), "today": today, "bucket": bucket}
323
  if dropped:
324
  meta["dropped"] = dropped
 
124
  try:
125
  from core import users as _users
126
  workspace["userOptions"] = _users.assignable_people()
127
+ # Wave 14 C-AVATAR β€” the options vocabulary's companion: display name -> data URL.
128
+ # Absent entries fall back to the client's initials disc; a non-data: value is
129
+ # dropped (defence in depth beside the write-side wall in routes_auth).
130
+ workspace["userAvatars"] = {k: v for k, v in _users.avatar_map().items()
131
+ if str(v).startswith("data:image/")}
132
  except Exception:
133
  workspace["userOptions"] = []
134
+ workspace["userAvatars"] = {}
135
 
136
  # THE SURFACE STAMP β€” a MIRROR of the host's own (`_table_grid`'s hide/cohort stamps).
137
  # ⚠ Deliberately NOT `hideViews`: `cohortMode` is what swaps the Views panel for the cohort
 
146
 
147
  # ─────────────────────────────────────────────── the TIME-SERIES channel (C-TS, 2026-08-02)
148
  _TS_BUCKETS = ("week", "month", "quarter", "year")
149
+ _TS_MAX_BUCKETS = 120
150
  _TS_MAX_FIELDS = 12
151
  _TS_MAX_PIDS = 5000
152
  _TS_MAX_LAST_N = 120
153
+ #: C-TSWIN (wave 14): sliding windows cost ONE aggregate query per (metric, bucket) β€” the
154
+ #: price of "bucket N == the grid cell at bucket N's end". The product cap keeps a legal
155
+ #: 120-bucket Γ— 12-metric ask from becoming 1,440 queries in one request; typical panels
156
+ #: (12 Γ— 3) sit two orders of magnitude under it. Dated amendment in the split doc.
157
+ _TS_MAX_CELLS = 720
158
 
159
 
160
  def _ts_start_of(bucket, d):
 
206
  session: Session = Depends(module_gate(MODULE))):
207
  """Pooled measure values per calendar bucket β€” the time-series view's data channel.
208
 
209
+ C-TSWIN (wave 14, ruling R1): AS-OF semantics. Each metric's OWN stored window is
210
+ re-resolved per bucket with `today := min(bucket end, real today)` β€” `ytd` is cumulative
211
+ from Jan 1, `last_90_days` trailing, `all_time` cumulative ever; bucket N equals what the
212
+ grid's measure column would show if today were bucket N's end. Fixed-range (`custom`)
213
+ windows cannot slide and are dropped per field as `window_fixed`. Rows carry
214
+ `window: {kind, label}` so a cumulative row cannot be misread as periodic, and there is
215
+ NO `total` column β€” sliding windows overlap, so a sum of columns would double-count.
216
+
217
  The client sends the pids its view currently matches (the filter IS the scope); the server
218
  intersects them with the session's book, so the request can only ever NARROW. Values are
219
+ POOLED aggregates computed by the semantic layer's own expression (the additivity law: an
220
+ average is computed at pool grain, never averaged over per-customer answers). A bucket
221
+ with no rows is 0 for a sum/count and null for anything else; a bucket that has not
222
+ STARTED yet is null for every kind β€” an unstarted period's YTD is unanswered, not 0.
223
  """
224
  from core import measure_resolve
225
+ from harness import windows as _wn
226
  from routes_customers import _pool_stamp, _team_agent, allowed_pids
227
 
228
  body = body or {}
 
309
  raise err(400, "bad_timeseries",
310
  "none of the requested fields are measure fields (v1 serves measure-backed "
311
  "fields only)")
312
+ mfields, slid_keys = [], []
313
+ for k in keys:
314
+ m = dict(fdefs[k]["measure"])
315
+ if (m.get("window") or {}).get("kind") == "custom":
316
+ # C-TSWIN: a fixed date range cannot slide across buckets β€” named, never silent,
317
+ # the same posture as not_a_measure_field.
318
+ dropped.append({"field": k, "reason": "window_fixed"})
319
+ continue
320
+ mfields.append({"key": k, "measure": m})
321
+ slid_keys.append(k)
322
+ if not mfields:
323
+ raise err(400, "bad_timeseries",
324
+ "every requested metric has a fixed date range - a fixed range cannot "
325
+ "slide across buckets")
326
+ if len(starts) * len(mfields) > _TS_MAX_CELLS:
327
+ raise err(400, "bad_timeseries",
328
+ "that ask is too wide - narrow the span or pick fewer metrics")
329
 
330
  team_id, agent = _team_agent(session)
331
  stamp = _pool_stamp(rt, team_id, agent)
332
  problems = []
333
+ bucket_bounds = [(s.isoformat(), e.isoformat()) for s, e in zip(starts, ends)]
334
  answers = measure_resolve.series_values(
335
+ mfields, bucket, bucket_bounds,
336
  team_id, frozenset(pool), today, stamp, rt.series_memo,
337
  on_error=lambda tag, e: problems.append(str(e)[:200]))
338
 
 
344
  col["partial"] = True
345
  columns.append(col)
346
  rows = []
347
+ for k in slid_keys:
348
  ans = answers.get(k)
349
  if ans is None:
350
  dropped.append({"field": k, "reason": "unresolvable"})
 
352
  vals_by = ans.get("values") or {}
353
  agg_kind = str(ans.get("agg") or "sum")
354
  zero_fill = agg_kind in ("sum", "count")
355
+ vals = []
356
+ for s in starts:
357
+ if s > t:
358
+ # C-TSWIN: an unstarted period is unanswered for EVERY agg kind β€” a future
359
+ # month's YTD zero-filled to 0 would read as "the year reset".
360
+ vals.append(None)
361
+ else:
362
+ vals.append(vals_by.get(s.isoformat(), 0 if zero_fill else None))
363
+ wspec = (fdefs[k].get("measure") or {}).get("window")
364
+ wnorm = _wn.normalize(wspec) or {}
365
  rows.append({"field": k, "label": str(fdefs[k].get("label") or k)[:120],
366
+ "agg": agg_kind, "values": vals,
367
+ "window": {"kind": str(wnorm.get("kind") or ""),
368
+ "label": _wn.label(wspec)}})
369
  meta = {"pool": len(pool), "today": today, "bucket": bucket}
370
  if dropped:
371
  meta["dropped"] = dropped
royalimports_os/aios_grid.py CHANGED
@@ -708,6 +708,16 @@ TS_MAX_FIELDS = 12
708
  MAX_CALENDAR_METRICS = 4
709
  _ISO_DAY = re.compile(r'^\d{4}-\d{2}-\d{2}$')
710
 
 
 
 
 
 
 
 
 
 
 
711
  #: Old wire value -> the value we store today. Applied AFTER the membership test so an unknown
712
  #: mode is still rejected rather than accidentally aliased.
713
  _LEGACY_MODES = {'dashboard': 'chart'}
@@ -811,6 +821,20 @@ def _clean_chart(raw, valid_keys):
811
  pass # a partial size is fine: the client defaults the missing axis
812
  if one:
813
  out['size'] = one
 
 
 
 
 
 
 
 
 
 
 
 
 
 
814
  return out
815
 
816
 
@@ -897,6 +921,68 @@ def _clean_display(raw, valid_keys):
897
  clean_f.append(k)
898
  if clean_f:
899
  out['tsFields'] = clean_f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
900
  charts = raw.get('charts')
901
  if isinstance(charts, list):
902
  clean = [c for c in (_clean_chart(x, valid_keys) for x in charts[:MAX_CHARTS]) if c]
@@ -1364,7 +1450,8 @@ def component_dir():
1364
 
1365
 
1366
  def render(rows, fields, *, workspace=None, height=680, key="aios_grid",
1367
- user_options=None, measures=None, measure_sets=None, today=None, viewer=None):
 
1368
  """Render the Airtable-style grid and return its latest guarded host event.
1369
 
1370
  The preferred custom-component path forwards `key` and supports two-way persistence.
@@ -1393,6 +1480,12 @@ def render(rows, fields, *, workspace=None, height=680, key="aios_grid",
1393
  directory = component_dir()
1394
  payload = {"fields": fields, "rows": rows, "workspace": workspace or {},
1395
  "userOptions": [str(u)[:120] for u in (user_options or [])][:500],
 
 
 
 
 
 
1396
  "measures": list(measures or []),
1397
  "today": str(today) if today else None,
1398
  # Wave-5 item 1: who is looking, host-computed β€” what gates the client's
 
708
  MAX_CALENDAR_METRICS = 4
709
  _ISO_DAY = re.compile(r'^\d{4}-\d{2}-\d{2}$')
710
 
711
+ #: Wave 14 C-ACC ([[loopable-wave14-split]]; rulings R2/R3). Mirrored by types.ts
712
+ #: TS_DELTA_KINDS / TS_MAX_CUSTOM_ROWS / TS_MAX_STYLES β€” the C-DISP byte-identical law.
713
+ TS_DELTA_KINDS = ('abs', 'pct', 'yoy', 'ytd')
714
+ TS_MAX_CUSTOM_ROWS = 12
715
+ TS_MAX_STYLES = 200
716
+ #: R2 β€” a formula row's `expr` is stored VERBATIM and NEVER parsed here (evaluation is client
717
+ #: law; the client refuses unknown refs/cycles/div-zero itself). The charset wall is the whole
718
+ #: server-side contract: row refs `[...]`, arithmetic, numbers β€” no markup, no control chars.
719
+ _TS_EXPR_OK = re.compile(r'^[A-Za-z0-9_ .+\-*/()\[\]]+$')
720
+
721
  #: Old wire value -> the value we store today. Applied AFTER the membership test so an unknown
722
  #: mode is still rejected rather than accidentally aliased.
723
  _LEGACY_MODES = {'dashboard': 'chart'}
 
821
  pass # a partial size is fine: the client defaults the missing axis
822
  if one:
823
  out['size'] = one
824
+
825
+ # ── Wave 14 R3 ([[loopable-wave14-split]]): a METRIC chart may carry a PERIOD β€” the
826
+ # trend-over-buckets encoding. Kept only when the chart's value field is measure-backed:
827
+ # a category column has no time dimension, and a stored period on it would promise a
828
+ # trend the TS channel must refuse. `span` is meaningful only beside `bucket`.
829
+ if isinstance(out.get('y'), str) and out['y'].startswith('measure_'):
830
+ if raw.get('bucket') in TS_BUCKETS:
831
+ out['bucket'] = raw['bucket']
832
+ sp = raw.get('span')
833
+ if isinstance(sp, dict):
834
+ n = sp.get('lastN')
835
+ if (isinstance(n, int) and not isinstance(n, bool)
836
+ and 1 <= n <= TS_MAX_LAST_N):
837
+ out['span'] = {'lastN': n}
838
  return out
839
 
840
 
 
921
  clean_f.append(k)
922
  if clean_f:
923
  out['tsFields'] = clean_f
924
+ # ── Wave 14 C-ACC ([[loopable-wave14-split]] R2; items 17/18) ────────────────────────
925
+ deltas = raw.get('tsDeltas')
926
+ if isinstance(deltas, list):
927
+ clean_d, seen_d = [], set()
928
+ for d in deltas:
929
+ if d in TS_DELTA_KINDS and d not in seen_d:
930
+ seen_d.add(d)
931
+ clean_d.append(d)
932
+ if clean_d:
933
+ out['tsDeltas'] = clean_d
934
+ # Gridlines: stored ONLY as the literal opt-OUT (absent = shown), sparkline ONLY as the
935
+ # literal opt-IN (absent = off) β€” the kanbanClamp asymmetry, one per direction.
936
+ if raw.get('tsGridlines') is False:
937
+ out['tsGridlines'] = False
938
+ if raw.get('tsSparkline') is True:
939
+ out['tsSparkline'] = True
940
+ rows = raw.get('tsRows')
941
+ if isinstance(rows, list):
942
+ clean_r, seen_r = [], set()
943
+ for r in rows[:TS_MAX_CUSTOM_ROWS]:
944
+ if not isinstance(r, dict):
945
+ continue
946
+ rid = str(r.get('id') or '')[:40]
947
+ r_kind = r.get('kind')
948
+ if not rid or rid in seen_r or r_kind not in ('note', 'formula'):
949
+ continue
950
+ label = r.get('label')
951
+ if not isinstance(label, str):
952
+ continue # ABSENT label = malformed; an EMPTY one is a legal spacer row
953
+ # (GRID's dated asymmetry amendments, 2026-08-02)
954
+ one = {'id': rid, 'kind': r_kind, 'label': label.strip()[:120]}
955
+ if r_kind == 'formula':
956
+ expr = r.get('expr')
957
+ if (isinstance(expr, str) and expr.strip()
958
+ and len(expr) <= 200 and _TS_EXPR_OK.match(expr)):
959
+ one['expr'] = expr
960
+ # else: keep the ROW, drop the EXPR β€” it renders "β€”". Vanishing the row
961
+ # would delete the user's label to punish their arithmetic (GRID's dated
962
+ # asymmetry amendment; the calendarMetrics per-entry-drop precedent).
963
+ seen_r.add(rid)
964
+ clean_r.append(one)
965
+ if clean_r:
966
+ out['tsRows'] = clean_r
967
+ styles = raw.get('tsStyles')
968
+ if isinstance(styles, dict):
969
+ clean_s = {}
970
+ for s_key, s_val in styles.items():
971
+ if len(clean_s) >= TS_MAX_STYLES:
972
+ break # capped, not truncated silently: the gate names this
973
+ if not isinstance(s_key, str) or not s_key or len(s_key) > 96:
974
+ continue # key = rowId or "rowId:colKey" β€” the client's grammar
975
+ if not isinstance(s_val, dict):
976
+ continue
977
+ one = {}
978
+ if s_val.get('bold') is True:
979
+ one['bold'] = True
980
+ if s_val.get('line') is True:
981
+ one['line'] = True
982
+ if one:
983
+ clean_s[s_key] = one
984
+ if clean_s:
985
+ out['tsStyles'] = clean_s
986
  charts = raw.get('charts')
987
  if isinstance(charts, list):
988
  clean = [c for c in (_clean_chart(x, valid_keys) for x in charts[:MAX_CHARTS]) if c]
 
1450
 
1451
 
1452
  def render(rows, fields, *, workspace=None, height=680, key="aios_grid",
1453
+ user_options=None, user_avatars=None, measures=None, measure_sets=None,
1454
+ today=None, viewer=None):
1455
  """Render the Airtable-style grid and return its latest guarded host event.
1456
 
1457
  The preferred custom-component path forwards `key` and supports two-way persistence.
 
1480
  directory = component_dir()
1481
  payload = {"fields": fields, "rows": rows, "workspace": workspace or {},
1482
  "userOptions": [str(u)[:120] for u in (user_options or [])][:500],
1483
+ # Wave 14 C-AVATAR β€” display name -> data URL, the userOptions vocabulary's
1484
+ # companion. Same caps; a value that is not a data: URL is dropped here too
1485
+ # (defence in depth beside the API route's write-side wall).
1486
+ "userAvatars": {str(k)[:120]: str(v)
1487
+ for k, v in list((user_avatars or {}).items())[:500]
1488
+ if str(v).startswith("data:image/")},
1489
  "measures": list(measures or []),
1490
  "today": str(today) if today else None,
1491
  # Wave-5 item 1: who is looking, host-computed β€” what gates the client's
royalimports_os/core/measure_resolve.py CHANGED
@@ -83,10 +83,15 @@ def condition_sets(view_configs, pending_cfg, team_id, allowed_pids, today, stam
83
  return out
84
 
85
 
86
- def series_values(fields, bucket, date_from, date_to, team_id, allowed_pids, today, stamp,
87
  memo, on_error=None):
88
  """`{field key: {'values': {bucket_start: v}, 'agg': kind}}` for every measure column
89
- among `fields`, bucketed over [date_from, date_to] β€” the C-TS channel (2026-08-02).
 
 
 
 
 
90
 
91
  Same memo discipline as `column_values`: keys carry (stamp, scope, POOL IDENTITY, the
92
  question); a permanent failure memoises as None (the caller reports that field as
@@ -95,17 +100,22 @@ def series_values(fields, bucket, date_from, date_to, team_id, allowed_pids, tod
95
  """
96
  out = {}
97
  mfields = [f for f in fields or [] if isinstance(f.get('measure'), dict)]
98
- if not mfields:
99
  return out
100
  from harness import measure_filter as _mf
 
101
  pk = _pool_key(allowed_pids)
 
102
  for f in mfields:
103
- mkey = (f.get('measure') or {}).get('key')
104
- key = (stamp, team_id, pk, mkey, bucket, str(date_from), str(date_to))
 
 
 
105
  if key not in memo:
106
  try:
107
- memo[key] = _mf.resolve_series(mkey, bucket, date_from, date_to,
108
- today, team_id, allowed_pids)
109
  except Exception as e:
110
  if on_error:
111
  on_error('measure-series', e)
 
83
  return out
84
 
85
 
86
+ def series_values(fields, bucket, buckets, team_id, allowed_pids, today, stamp,
87
  memo, on_error=None):
88
  """`{field key: {'values': {bucket_start: v}, 'agg': kind}}` for every measure column
89
+ among `fields`, over `buckets` = [(start_iso, end_iso), …] β€” the C-TS channel, C-TSWIN
90
+ semantics since wave 14: each field's OWN window slides across the buckets
91
+ (`today := bucket end`), so two fields on the same measure with different windows are
92
+ DIFFERENT questions β€” the memo key carries the window signature, which the wave-13 key
93
+ (measure-only) silently conflated. `custom` fixed-range windows are the CALLER's to drop
94
+ (`window_fixed`) before calling; one that slips through memoises as a permanent failure.
95
 
96
  Same memo discipline as `column_values`: keys carry (stamp, scope, POOL IDENTITY, the
97
  question); a permanent failure memoises as None (the caller reports that field as
 
100
  """
101
  out = {}
102
  mfields = [f for f in fields or [] if isinstance(f.get('measure'), dict)]
103
+ if not mfields or not buckets:
104
  return out
105
  from harness import measure_filter as _mf
106
+ from harness import windows as _wn
107
  pk = _pool_key(allowed_pids)
108
+ span_from, span_to = str(buckets[0][0]), str(buckets[-1][1])
109
  for f in mfields:
110
+ spec = f.get('measure') or {}
111
+ mkey = spec.get('key')
112
+ w = _wn.normalize(spec.get('window'))
113
+ wsig = None if w is None else tuple(sorted(w.items()))
114
+ key = (stamp, team_id, pk, mkey, bucket, span_from, span_to, wsig)
115
  if key not in memo:
116
  try:
117
+ memo[key] = _mf.resolve_series_slid(mkey, spec.get('window'), buckets,
118
+ today, team_id, allowed_pids)
119
  except Exception as e:
120
  if on_error:
121
  on_error('measure-series', e)
royalimports_os/core/users.py CHANGED
@@ -65,6 +65,10 @@ def _public(username, u):
65
  'role': u.get('role', 'user'), 'bus': u.get('bus', 'all'),
66
  'modules': u.get('modules', 'all'),
67
  'agent': u.get('agent'), 'email': u.get('email'),
 
 
 
 
68
  'epoch': int(u.get('epoch') or 0)}
69
 
70
 
@@ -256,3 +260,42 @@ def assignable_people():
256
  continue
257
  out.append(str(u.get('name') or username))
258
  return sorted(set(out))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  'role': u.get('role', 'user'), 'bus': u.get('bus', 'all'),
66
  'modules': u.get('modules', 'all'),
67
  'agent': u.get('agent'), 'email': u.get('email'),
68
+ # Wave 14 C-AVATAR: the profile photo is public-safe by definition (it is served
69
+ # to every grid session via the workspace map); without it here the API session's
70
+ # user record silently drops it and /me can never show your own photo.
71
+ 'avatar': u.get('avatar') or None,
72
  'epoch': int(u.get('epoch') or 0)}
73
 
74
 
 
260
  continue
261
  out.append(str(u.get('name') or username))
262
  return sorted(set(out))
263
+
264
+
265
+ def set_avatar(username, data_url):
266
+ """Set (or clear, with None/'') the user's profile photo β€” a data URL (wave 14 C-AVATAR,
267
+ [[loopable-wave14-split]] item 11). Stored VERBATIM; the API route owns validation (mime +
268
+ decoded size) because this value is served back to every grid session. Cleared by removing
269
+ the key, so records without a photo keep their pre-wave shape."""
270
+ username = (username or '').strip().lower()
271
+
272
+ def _set(reg):
273
+ u = reg.get(username)
274
+ if u:
275
+ if data_url:
276
+ u['avatar'] = str(data_url)
277
+ else:
278
+ u.pop('avatar', None)
279
+ return reg
280
+ store.update('users', _set)
281
+
282
+
283
+ def avatar_map():
284
+ """{display name -> avatar data URL} for ACTIVE accounts with a photo β€” the companion of
285
+ `assignable_people()`, keyed by the SAME vocabulary: a `user` cell stores the display
286
+ name, so the display name is the only join a renderer has. Two active accounts sharing a
287
+ display name share one option; the first WITH a photo wins the key rather than a coin
288
+ flip deciding whether the option has a face."""
289
+ try:
290
+ reg = registry() or {}
291
+ except Exception:
292
+ return {}
293
+ out = {}
294
+ for username, u in sorted(reg.items()):
295
+ if not isinstance(u, dict) or u.get('active') is False:
296
+ continue
297
+ av = u.get('avatar')
298
+ nm = str(u.get('name') or username)
299
+ if av and nm not in out:
300
+ out[nm] = str(av)
301
+ return out
royalimports_os/harness/measure_filter.py CHANGED
@@ -670,6 +670,69 @@ def resolve_series(key, bucket, date_from, date_to, today, team_id=None, allowed
670
  return {'values': values, 'agg': agg_kind}
671
 
672
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
673
  def resolve_tree(rules, today, team_id=None, allowed_pids=None):
674
  """{rule_id: sorted pids} for every measure condition in a tree.
675
 
 
670
  return {'values': values, 'agg': agg_kind}
671
 
672
 
673
+ def resolve_series_slid(key, window_spec, buckets, today, team_id=None, allowed_pids=None):
674
+ """AS-OF series (C-TSWIN, wave 14 β€” [[loopable-wave14-split]] R1): the measure's OWN
675
+ window re-resolved per bucket with `today := min(bucket end, real today)` β€” so `ytd`
676
+ becomes cumulative from Jan 1, `last_90_days` becomes trailing-90, `all_time` cumulative
677
+ ever. Returns `{'values': {bucket_start_iso: value}, 'agg': kind}`.
678
+
679
+ `buckets` is `[(start_iso, end_iso), …]`. One aggregate query per bucket rather than one
680
+ grouped query β€” deliberately: every part (scope, aggregate expression, BU wall, scale,
681
+ rounding) is `_query_parts`' own, so **bucket N is exactly what the grid's measure column
682
+ would show if the tenant's today were bucket N's end** β€” the two surfaces cannot disagree
683
+ by construction, which is the property the pooled/date_trunc shape could not give a
684
+ sliding window.
685
+
686
+ Absence semantics (the caller's fill law, same as `resolve_series`): a bucket whose
687
+ window holds NO ROWS is ABSENT from the answer (`COALESCE` would have manufactured a 0
688
+ for an empty AVERAGE, so the query carries a COUNT(*) to tell the two apart); a bucket
689
+ whose START is after `today` is absent too β€” an unstarted period's YTD is not 0, it is
690
+ unanswered. `custom` (fixed-range) windows cannot slide and are REFUSED β€” the caller
691
+ drops them as `window_fixed` before ever calling here.
692
+ """
693
+ topic_for(key) # raises for anything not admitted
694
+ if is_composite(key):
695
+ raise _sem.ModelError(
696
+ f"{key!r} is a ratio/derived measure - the series channel computes "
697
+ f"single-aggregate measures only")
698
+ spec = _win.normalize(window_spec)
699
+ if spec is None or spec.get('kind') == 'custom':
700
+ raise _sem.ModelError(
701
+ f"{key!r}: a fixed-range window cannot slide across buckets (window_fixed)")
702
+ meta = _sem.metrics().get(key, {})
703
+ agg_kind = str(meta.get('agg') or 'sum')
704
+ pool = _pool_of(allowed_pids)
705
+ if pool is not None and not pool:
706
+ return {'values': {}, 'agg': agg_kind}
707
+ scale = ADMITTED.get(key, {}).get('input_scale') or 1.0
708
+ mtype = _sem._FORMAT_TYPE.get(meta.get('format'), 'currency')
709
+ nd = 1 if mtype == 'pct' else None
710
+ today_s = str(today)[:10]
711
+ values = {}
712
+ con = _sem._store_con()
713
+ try:
714
+ for start, end in buckets:
715
+ start_s, end_s = str(start)[:10], str(end)[:10]
716
+ if start_s > today_s:
717
+ continue # unstarted period -> unanswered, never 0
718
+ eff = min(end_s, today_s)
719
+ frm, id_col, agg, where, params = _query_parts(key, spec, eff, team_id)
720
+ sql_params = list(params)
721
+ pool_sql = ''
722
+ if pool is not None:
723
+ marks = ','.join('?' for _ in pool)
724
+ pool_sql = f" AND {id_col} IN ({marks})"
725
+ sql_params.extend(int(p) for p in sorted(pool))
726
+ sql = f"SELECT {agg} AS v, COUNT(*) AS n FROM {frm} WHERE {where}{pool_sql}"
727
+ v, nrows = con.execute(sql, sql_params).fetchone()
728
+ if not nrows:
729
+ continue # empty window -> the caller's per-agg fill law
730
+ values[start_s] = round(float(v) * scale, nd)
731
+ finally:
732
+ con.close()
733
+ return {'values': values, 'agg': agg_kind}
734
+
735
+
736
  def resolve_tree(rules, today, team_id=None, allowed_pids=None):
737
  """{rule_id: sorted pids} for every measure condition in a tree.
738
 
web/dist-embed/index.html CHANGED
The diff for this file is too large to render. See raw diff
 
web/dist-embed/sample_customers.json CHANGED
@@ -1,466 +1,479 @@
1
- {
2
- "fields": [
3
- {
4
- "key": "customer",
5
- "label": "Customer",
6
- "type": "text",
7
- "source": "odoo",
8
- "pinned": true,
9
- "default": true,
10
- "description": "The customer's name in Odoo. One row per customer who ordered in the last 24 months."
11
- },
12
- {
13
- "key": "status",
14
- "label": "Status",
15
- "type": "status",
16
- "source": "odoo",
17
- "default": true,
18
- "description": "Where this customer stands versus last year: New, Growing, Declining, Lost or Dormant."
19
- },
20
- {
21
- "key": "odoo_status",
22
- "label": "Odoo record",
23
- "type": "status",
24
- "source": "odoo",
25
- "default": false,
26
- "description": "Whether this customer still exists in Odoo. Archived means deleted there."
27
- },
28
- {
29
- "key": "agent",
30
- "label": "Agent",
31
- "type": "text",
32
- "source": "odoo",
33
- "default": true,
34
- "description": "The sales agent who owns this account."
35
- },
36
- {
37
- "key": "salesperson",
38
- "label": "Salesperson",
39
- "type": "text",
40
- "source": "odoo",
41
- "default": false,
42
- "description": "Who keyed in most of this customer's orders β€” not the Agent, who owns the account."
43
- },
44
- {
45
- "key": "city",
46
- "label": "City",
47
- "type": "text",
48
- "source": "odoo",
49
- "default": true,
50
- "description": "City on the customer's Odoo address."
51
- },
52
- {
53
- "key": "state",
54
- "label": "State",
55
- "type": "text",
56
- "source": "odoo",
57
- "default": true,
58
- "description": "State or province on the customer's Odoo address."
59
- },
60
- {
61
- "key": "country",
62
- "label": "Country",
63
- "type": "text",
64
- "source": "odoo",
65
- "default": false,
66
- "description": "Country on the customer's Odoo address."
67
- },
68
- {
69
- "key": "zip",
70
- "label": "ZIP",
71
- "type": "text",
72
- "source": "odoo",
73
- "default": false,
74
- "description": "Postal code on the customer's Odoo address."
75
- },
76
- {
77
- "key": "customer_since",
78
- "label": "Customer since",
79
- "type": "date",
80
- "source": "odoo",
81
- "default": false,
82
- "description": "When this customer was first set up in Odoo."
83
- },
84
- {
85
- "key": "tags",
86
- "label": "Tags",
87
- "type": "text",
88
- "source": "odoo",
89
- "default": false,
90
- "description": "Odoo labels on this customer, comma-separated."
91
- },
92
- {
93
- "key": "pricelist",
94
- "label": "Price list",
95
- "type": "text",
96
- "source": "odoo",
97
- "default": false,
98
- "description": "The price list this customer buys on."
99
- },
100
- {
101
- "key": "payment_terms",
102
- "label": "Payment terms",
103
- "type": "text",
104
- "source": "odoo",
105
- "default": false,
106
- "description": "Payment terms on this customer's account β€” Net 30, for example."
107
- },
108
- {
109
- "key": "last_order",
110
- "label": "Last order",
111
- "type": "date",
112
- "source": "odoo",
113
- "default": true,
114
- "description": "Date of the most recent confirmed order."
115
- },
116
- {
117
- "key": "overdue_days",
118
- "label": "Overdue days",
119
- "type": "int",
120
- "source": "odoo",
121
- "default": true,
122
- "description": "How many days late this customer is running against their own usual ordering rhythm."
123
- },
124
- {
125
- "_note": "filterable:false β€” DERIVED ANALYTIC: est_missed is min(cycles missed, 3) x AOV, a score we compute rather than an object the business has, so a condition on it would read as a fact about the customer when it is a fact about our arithmetic. It still displays and still sorts. Until wave 6 this flag also covered the frozen-window presets (revenue_ytd / revenue_ly / orders_24m / aov / yoy_pct); those are now DELETED outright under the owner's no-buildable-presets rule β€” see _comment. est_missed itself STAYS: no creatable measure or formula reproduces the cadence model behind it.",
126
- "key": "est_missed",
127
- "label": "Est. missed $",
128
- "type": "currency",
129
- "source": "odoo",
130
- "default": true,
131
- "agg": "sum",
132
- "filterable": false,
133
- "description": "Estimated sales missed while quiet: missed orders (capped at 3) times average order value. An estimate, not money owed."
134
- },
135
- {
136
- "key": "ar_open",
137
- "label": "AR open $",
138
- "type": "currency",
139
- "source": "odoo",
140
- "default": false,
141
- "description": "Invoiced money owed, not yet overdue."
142
- },
143
- {
144
- "key": "ar_overdue",
145
- "label": "AR overdue $",
146
- "type": "currency",
147
- "source": "odoo",
148
- "default": false,
149
- "description": "Invoiced money past due β€” same basis as the Collections page."
150
- },
151
- {
152
- "key": "ar_exposure",
153
- "label": "Credit exposure $",
154
- "type": "currency",
155
- "source": "odoo",
156
- "default": false,
157
- "description": "The most you could be out if they stopped paying today: open, overdue, draft and not-yet-invoiced."
158
- },
159
- {
160
- "key": "days_to_pay",
161
- "label": "Days to pay",
162
- "type": "int",
163
- "source": "odoo",
164
- "default": false,
165
- "description": "Average days to pay an invoice in full. Blank means no fully paid invoice yet."
166
- },
167
- {
168
- "key": "top_category",
169
- "label": "Top category",
170
- "type": "text",
171
- "source": "odoo",
172
- "default": false,
173
- "description": "The category this customer spent the most on in the last 12 months."
174
- },
175
- {
176
- "key": "top_category_pct",
177
- "label": "Top category %",
178
- "type": "pct",
179
- "source": "odoo",
180
- "default": false,
181
- "description": "Share of last-12-months spend that went to the top category."
182
- },
183
- {
184
- "key": "sku_count",
185
- "label": "SKUs bought",
186
- "type": "int",
187
- "source": "odoo",
188
- "default": false,
189
- "description": "Distinct products bought in the last 12 months."
190
- },
191
- {
192
- "key": "top_sku",
193
- "label": "Top SKU",
194
- "type": "text",
195
- "source": "odoo",
196
- "default": false,
197
- "description": "The product this customer spent the most on in the last 12 months."
198
- },
199
- {
200
- "key": "days_since",
201
- "label": "Days since order",
202
- "type": "int",
203
- "source": "odoo",
204
- "default": false,
205
- "description": "Days since the last confirmed order."
206
- },
207
- {
208
- "key": "typical_gap_days",
209
- "label": "Typical gap days",
210
- "type": "int",
211
- "source": "odoo",
212
- "default": false,
213
- "description": "Days this customer usually goes between orders, from their own history."
214
- },
215
- {
216
- "key": "notes",
217
- "label": "Notes",
218
- "type": "text",
219
- "source": "overlay",
220
- "default": false,
221
- "description": "Your notes on this customer. Saved in this app only, visible only to you."
222
- }
223
- ],
224
- "rows": [
225
- {
226
- "pid": 101,
227
- "customer": "Poppy Flowers",
228
- "status": "New",
229
- "agent": "Naomi Linnell Rivera",
230
- "city": "Charlottesville",
231
- "state": "Virginia (US)",
232
- "last_order": "2026-07-21",
233
- "est_missed": 0,
234
- "notes": "",
235
- "country": "United States",
236
- "zip": "02720",
237
- "payment_terms": "30 Days",
238
- "pricelist": "Fisch 1 (USD)",
239
- "tags": "Royal",
240
- "customer_since": "2023-01-10",
241
- "salesperson": "Jessica",
242
- "ar_open": 0,
243
- "ar_overdue": 0,
244
- "ar_exposure": 0,
245
- "top_category": "Styrofoam",
246
- "top_category_pct": 0.47,
247
- "sku_count": 93,
248
- "top_sku": "AQUAFOAM FLORAL FOAM BRICK | 48-Piece per Pack",
249
- "days_to_pay": 34,
250
- "_created": "2023-01-15 09:10:00",
251
- "lat": 25.7617,
252
- "lon": -80.1918,
253
- "odoo_status": "Archived"
254
- },
255
- {
256
- "pid": 102,
257
- "customer": "Meadow & Vine Wholesale",
258
- "status": "Growing",
259
- "agent": "Carla Jimenez",
260
- "city": "Portland",
261
- "state": "Oregon (US)",
262
- "last_order": "2026-07-19",
263
- "est_missed": 0,
264
- "notes": "Expanding to a second storefront.",
265
- "country": "United States",
266
- "zip": "77041",
267
- "payment_terms": "Immediate Payment",
268
- "pricelist": "Royal 1 (USD)",
269
- "tags": "Royal, Key account",
270
- "customer_since": "2024-02-11",
271
- "salesperson": "Naomi",
272
- "ar_open": 1240.5,
273
- "ar_overdue": 0,
274
- "ar_exposure": 1740.5,
275
- "top_category": "Ribbon",
276
- "top_category_pct": 0.95,
277
- "sku_count": 4,
278
- "top_sku": "2\" X 24\" X 36\" GREEN STYROFOAM BOARD",
279
- "days_to_pay": null,
280
- "_created": "2023-02-15 09:11:00",
281
- "lat": 27.9506,
282
- "lon": -82.4572,
283
- "odoo_status": "Active"
284
- },
285
- {
286
- "pid": 103,
287
- "customer": "Bluestem Floral Supply",
288
- "status": "Growing",
289
- "agent": "Naomi Linnell Rivera",
290
- "city": "Kansas City",
291
- "state": "Missouri (US)",
292
- "last_order": "2026-07-17",
293
- "est_missed": 0,
294
- "notes": "",
295
- "country": "United States",
296
- "zip": "11219",
297
- "payment_terms": "60 Days",
298
- "pricelist": "Royal 1 (USD)",
299
- "tags": "Fisch",
300
- "customer_since": "2025-03-12",
301
- "salesperson": "Karen",
302
- "ar_open": 0,
303
- "ar_overdue": 5120.25,
304
- "ar_exposure": 5120.25,
305
- "top_category": "Foams & Finishes",
306
- "top_category_pct": 0.31,
307
- "sku_count": 27,
308
- "top_sku": "SATIN RIBBON 2IN",
309
- "days_to_pay": 61,
310
- "_created": "2023-03-15 09:12:00",
311
- "lat": 28.5384,
312
- "lon": -81.3789,
313
- "odoo_status": "Active"
314
- },
315
- {
316
- "pid": 104,
317
- "customer": "Camellia Row Florist",
318
- "status": "Declining",
319
- "agent": "Devon Marsh",
320
- "city": "Savannah",
321
- "state": "Georgia (US)",
322
- "last_order": "2026-05-30",
323
- "est_missed": 41200,
324
- "notes": "Switched some volume to a local grower.",
325
- "country": "United States",
326
- "zip": "07649",
327
- "payment_terms": "30 Days",
328
- "pricelist": "Fisch 1 (USD)",
329
- "tags": "(none)",
330
- "customer_since": "2026-04-13",
331
- "salesperson": "(none)",
332
- "ar_open": 8300,
333
- "ar_overdue": 940,
334
- "ar_exposure": 11440,
335
- "top_category": "All",
336
- "top_category_pct": 1.0,
337
- "sku_count": 1,
338
- "top_sku": "(none)",
339
- "days_to_pay": 12,
340
- "_created": "2023-04-15 09:13:00",
341
- "lat": 30.3322,
342
- "lon": -81.6557,
343
- "odoo_status": "Active"
344
- },
345
- {
346
- "pid": 105,
347
- "customer": "Harborlight Wholesale Blooms",
348
- "status": "Growing",
349
- "agent": "Carla Jimenez",
350
- "city": "Seattle",
351
- "state": "Washington (US)",
352
- "last_order": "2026-07-22",
353
- "est_missed": 0,
354
- "notes": "Top-10 account.",
355
- "country": "United States",
356
- "zip": "33125",
357
- "payment_terms": "Immediate Payment",
358
- "pricelist": "Royal 1 (USD)",
359
- "tags": "Royal",
360
- "customer_since": "2023-05-14",
361
- "salesperson": "Jessica",
362
- "ar_open": 0,
363
- "ar_overdue": 0,
364
- "ar_exposure": 0,
365
- "top_category": "Styrofoam",
366
- "top_category_pct": 0.47,
367
- "sku_count": 93,
368
- "top_sku": "AQUAFOAM FLORAL FOAM BRICK | 48-Piece per Pack",
369
- "days_to_pay": 34,
370
- "_created": "2023-05-15 09:14:00",
371
- "lat": 26.1224,
372
- "lon": -80.1373,
373
- "odoo_status": "Active"
374
- },
375
- {
376
- "pid": 106,
377
- "customer": "Dogwood & Fern Co.",
378
- "status": "Dormant",
379
- "agent": "Devon Marsh",
380
- "city": "Asheville",
381
- "state": "North Carolina (US)",
382
- "last_order": "2026-02-11",
383
- "est_missed": 52400,
384
- "notes": "No spring order this year.",
385
- "country": "United States",
386
- "zip": "90210",
387
- "payment_terms": "60 Days",
388
- "pricelist": "Royal 1 (USD)",
389
- "tags": "Royal, Key account",
390
- "customer_since": "2024-06-15",
391
- "salesperson": "Naomi",
392
- "ar_open": 1240.5,
393
- "ar_overdue": 0,
394
- "ar_exposure": 1740.5,
395
- "top_category": "Ribbon",
396
- "top_category_pct": 0.95,
397
- "sku_count": 4,
398
- "top_sku": "2\" X 24\" X 36\" GREEN STYROFOAM BOARD",
399
- "days_to_pay": null,
400
- "_created": "2023-06-15 09:15:00",
401
- "lat": 27.3364,
402
- "lon": -82.5307,
403
- "odoo_status": "Active"
404
- },
405
- {
406
- "pid": 107,
407
- "customer": "Verbena Market Florals",
408
- "status": "Lost",
409
- "agent": "Naomi Linnell Rivera",
410
- "city": "Austin",
411
- "state": "Texas (US)",
412
- "last_order": "2025-11-04",
413
- "est_missed": 78300,
414
- "notes": "Went with a competitor on freight terms.",
415
- "country": "United States",
416
- "zip": "08701",
417
- "payment_terms": "30 Days",
418
- "pricelist": "Fisch 1 (USD)",
419
- "tags": "Fisch",
420
- "customer_since": "2025-07-16",
421
- "salesperson": "Karen",
422
- "ar_open": 0,
423
- "ar_overdue": 5120.25,
424
- "ar_exposure": 5120.25,
425
- "top_category": "Foams & Finishes",
426
- "top_category_pct": 0.31,
427
- "sku_count": 27,
428
- "top_sku": "SATIN RIBBON 2IN",
429
- "days_to_pay": 61,
430
- "_created": "2023-07-15 09:16:00",
431
- "lat": null,
432
- "lon": null,
433
- "odoo_status": "Active"
434
- },
435
- {
436
- "pid": 108,
437
- "customer": "Larkspur Lane Supply",
438
- "status": "New",
439
- "agent": "Carla Jimenez",
440
- "city": "Denver",
441
- "state": "Colorado (US)",
442
- "last_order": "2026-07-14",
443
- "est_missed": 0,
444
- "notes": "First order in April.",
445
- "country": "United States",
446
- "zip": "60614",
447
- "payment_terms": "Immediate Payment",
448
- "pricelist": "Royal 1 (USD)",
449
- "tags": "(none)",
450
- "customer_since": "2026-08-17",
451
- "salesperson": "(none)",
452
- "ar_open": 8300,
453
- "ar_overdue": 940,
454
- "ar_exposure": 11440,
455
- "top_category": "All",
456
- "top_category_pct": 1.0,
457
- "sku_count": 1,
458
- "top_sku": "(none)",
459
- "days_to_pay": 12,
460
- "_created": "2023-08-15 09:17:00",
461
- "lat": 33.749,
462
- "lon": -84.388,
463
- "odoo_status": "Active"
464
- }
465
- ]
466
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "fields": [
3
+ {
4
+ "key": "customer",
5
+ "label": "Customer",
6
+ "type": "text",
7
+ "source": "odoo",
8
+ "pinned": true,
9
+ "default": true,
10
+ "description": "The customer's name in Odoo. One row per customer who ordered in the last 24 months."
11
+ },
12
+ {
13
+ "key": "odoo_status",
14
+ "label": "Odoo record",
15
+ "type": "status",
16
+ "source": "odoo",
17
+ "default": false,
18
+ "description": "Whether this customer still exists in Odoo. Archived means deleted there."
19
+ },
20
+ {
21
+ "key": "agent",
22
+ "label": "Agent",
23
+ "type": "text",
24
+ "source": "odoo",
25
+ "default": true,
26
+ "description": "The sales agent who owns this account."
27
+ },
28
+ {
29
+ "key": "dba",
30
+ "label": "DBA",
31
+ "type": "select",
32
+ "source": "odoo",
33
+ "default": false,
34
+ "options": [
35
+ "Fisch",
36
+ "Royal",
37
+ "Both"
38
+ ],
39
+ "description": "The brand this customer buys from - Fisch, Royal, or both. Amazon-channel orders are not a DBA."
40
+ },
41
+ {
42
+ "key": "salesperson",
43
+ "label": "Salesperson",
44
+ "type": "text",
45
+ "source": "odoo",
46
+ "default": false,
47
+ "description": "Who keyed in most of this customer's orders β€” not the Agent, who owns the account."
48
+ },
49
+ {
50
+ "key": "city",
51
+ "label": "City",
52
+ "type": "text",
53
+ "source": "odoo",
54
+ "default": true,
55
+ "description": "City on the customer's Odoo address."
56
+ },
57
+ {
58
+ "key": "state",
59
+ "label": "State",
60
+ "type": "text",
61
+ "source": "odoo",
62
+ "default": true,
63
+ "description": "State or province on the customer's Odoo address."
64
+ },
65
+ {
66
+ "key": "country",
67
+ "label": "Country",
68
+ "type": "text",
69
+ "source": "odoo",
70
+ "default": false,
71
+ "description": "Country on the customer's Odoo address."
72
+ },
73
+ {
74
+ "key": "zip",
75
+ "label": "ZIP",
76
+ "type": "text",
77
+ "source": "odoo",
78
+ "default": false,
79
+ "description": "Postal code on the customer's Odoo address."
80
+ },
81
+ {
82
+ "key": "customer_since",
83
+ "label": "Customer since",
84
+ "type": "date",
85
+ "source": "odoo",
86
+ "default": false,
87
+ "description": "When this customer was first set up in Odoo."
88
+ },
89
+ {
90
+ "key": "tags",
91
+ "label": "Tags",
92
+ "type": "text",
93
+ "source": "odoo",
94
+ "default": false,
95
+ "description": "Odoo labels on this customer, comma-separated."
96
+ },
97
+ {
98
+ "key": "pricelist",
99
+ "label": "Price list",
100
+ "type": "text",
101
+ "source": "odoo",
102
+ "default": false,
103
+ "description": "The price list this customer buys on."
104
+ },
105
+ {
106
+ "key": "payment_terms",
107
+ "label": "Payment terms",
108
+ "type": "text",
109
+ "source": "odoo",
110
+ "default": false,
111
+ "description": "Payment terms on this customer's account β€” Net 30, for example."
112
+ },
113
+ {
114
+ "key": "last_order",
115
+ "label": "Last order",
116
+ "type": "date",
117
+ "source": "odoo",
118
+ "default": true,
119
+ "description": "Date of the most recent confirmed order."
120
+ },
121
+ {
122
+ "key": "overdue_days",
123
+ "label": "Overdue days",
124
+ "type": "int",
125
+ "source": "odoo",
126
+ "default": true,
127
+ "description": "How many days late this customer is running against their own usual ordering rhythm."
128
+ },
129
+ {
130
+ "_note": "filterable:false β€” DERIVED ANALYTIC: est_missed is min(cycles missed, 3) x AOV, a score we compute rather than an object the business has, so a condition on it would read as a fact about the customer when it is a fact about our arithmetic. It still displays and still sorts. Until wave 6 this flag also covered the frozen-window presets (revenue_ytd / revenue_ly / orders_24m / aov / yoy_pct); those are now DELETED outright under the owner's no-buildable-presets rule β€” see _comment. est_missed itself STAYS: no creatable measure or formula reproduces the cadence model behind it.",
131
+ "key": "est_missed",
132
+ "label": "Est. missed $",
133
+ "type": "currency",
134
+ "source": "odoo",
135
+ "default": true,
136
+ "agg": "sum",
137
+ "filterable": false,
138
+ "description": "Estimated sales missed while quiet: missed orders (capped at 3) times average order value. An estimate, not money owed."
139
+ },
140
+ {
141
+ "key": "ar_open",
142
+ "label": "AR open $",
143
+ "type": "currency",
144
+ "source": "odoo",
145
+ "default": false,
146
+ "description": "Invoiced money owed, not yet overdue."
147
+ },
148
+ {
149
+ "key": "ar_overdue",
150
+ "label": "AR overdue $",
151
+ "type": "currency",
152
+ "source": "odoo",
153
+ "default": false,
154
+ "description": "Invoiced money past due β€” same basis as the Collections page."
155
+ },
156
+ {
157
+ "key": "ar_exposure",
158
+ "label": "Credit exposure $",
159
+ "type": "currency",
160
+ "source": "odoo",
161
+ "default": false,
162
+ "description": "The most you could be out if they stopped paying today: open, overdue, draft and not-yet-invoiced."
163
+ },
164
+ {
165
+ "key": "days_to_pay",
166
+ "label": "Days to pay",
167
+ "type": "int",
168
+ "source": "odoo",
169
+ "default": false,
170
+ "description": "Average days to pay an invoice in full. Blank means no fully paid invoice yet."
171
+ },
172
+ {
173
+ "key": "top_category",
174
+ "label": "Top category",
175
+ "type": "text",
176
+ "source": "odoo",
177
+ "default": false,
178
+ "description": "The category this customer spent the most on in the last 12 months."
179
+ },
180
+ {
181
+ "key": "top_category_pct",
182
+ "label": "Top category %",
183
+ "type": "pct",
184
+ "source": "odoo",
185
+ "default": false,
186
+ "description": "Share of last-12-months spend that went to the top category."
187
+ },
188
+ {
189
+ "key": "sku_count",
190
+ "label": "SKUs bought",
191
+ "type": "int",
192
+ "source": "odoo",
193
+ "default": false,
194
+ "description": "Distinct products bought in the last 12 months."
195
+ },
196
+ {
197
+ "key": "top_sku",
198
+ "label": "Top SKU",
199
+ "type": "text",
200
+ "source": "odoo",
201
+ "default": false,
202
+ "description": "The product this customer spent the most on in the last 12 months."
203
+ },
204
+ {
205
+ "key": "days_since",
206
+ "label": "Days since order",
207
+ "type": "int",
208
+ "source": "odoo",
209
+ "default": false,
210
+ "description": "Days since the last confirmed order."
211
+ },
212
+ {
213
+ "key": "typical_gap_days",
214
+ "label": "Typical gap days",
215
+ "type": "int",
216
+ "source": "odoo",
217
+ "default": false,
218
+ "description": "Days this customer usually goes between orders, from their own history."
219
+ },
220
+ {
221
+ "key": "notes",
222
+ "label": "Notes",
223
+ "type": "text",
224
+ "source": "overlay",
225
+ "default": false,
226
+ "description": "Your notes on this customer. Saved in this app only, visible only to you."
227
+ }
228
+ ],
229
+ "rows": [
230
+ {
231
+ "pid": 101,
232
+ "customer": "Poppy Flowers",
233
+ "status": "New",
234
+ "agent": "Naomi Linnell Rivera",
235
+ "city": "Charlottesville",
236
+ "state": "Virginia (US)",
237
+ "last_order": "2026-07-21",
238
+ "est_missed": 0,
239
+ "notes": "",
240
+ "country": "United States",
241
+ "zip": "02720",
242
+ "payment_terms": "30 Days",
243
+ "pricelist": "Fisch 1 (USD)",
244
+ "tags": "Royal",
245
+ "customer_since": "2023-01-10",
246
+ "salesperson": "Jessica",
247
+ "ar_open": 0,
248
+ "ar_overdue": 0,
249
+ "ar_exposure": 0,
250
+ "top_category": "Styrofoam",
251
+ "top_category_pct": 0.47,
252
+ "sku_count": 93,
253
+ "top_sku": "AQUAFOAM FLORAL FOAM BRICK | 48-Piece per Pack",
254
+ "days_to_pay": 34,
255
+ "_created": "2023-01-15 09:10:00",
256
+ "lat": 25.7617,
257
+ "lon": -80.1918,
258
+ "odoo_status": "Archived",
259
+ "dba": "Royal"
260
+ },
261
+ {
262
+ "pid": 102,
263
+ "customer": "Meadow & Vine Wholesale",
264
+ "status": "Growing",
265
+ "agent": "Carla Jimenez",
266
+ "city": "Portland",
267
+ "state": "Oregon (US)",
268
+ "last_order": "2026-07-19",
269
+ "est_missed": 0,
270
+ "notes": "Expanding to a second storefront.",
271
+ "country": "United States",
272
+ "zip": "77041",
273
+ "payment_terms": "Immediate Payment",
274
+ "pricelist": "Royal 1 (USD)",
275
+ "tags": "Royal, Key account",
276
+ "customer_since": "2024-02-11",
277
+ "salesperson": "Naomi",
278
+ "ar_open": 1240.5,
279
+ "ar_overdue": 0,
280
+ "ar_exposure": 1740.5,
281
+ "top_category": "Ribbon",
282
+ "top_category_pct": 0.95,
283
+ "sku_count": 4,
284
+ "top_sku": "2\" X 24\" X 36\" GREEN STYROFOAM BOARD",
285
+ "days_to_pay": null,
286
+ "_created": "2023-02-15 09:11:00",
287
+ "lat": 27.9506,
288
+ "lon": -82.4572,
289
+ "odoo_status": "Active",
290
+ "dba": "Fisch"
291
+ },
292
+ {
293
+ "pid": 103,
294
+ "customer": "Bluestem Floral Supply",
295
+ "status": "Growing",
296
+ "agent": "Naomi Linnell Rivera",
297
+ "city": "Kansas City",
298
+ "state": "Missouri (US)",
299
+ "last_order": "2026-07-17",
300
+ "est_missed": 0,
301
+ "notes": "",
302
+ "country": "United States",
303
+ "zip": "11219",
304
+ "payment_terms": "60 Days",
305
+ "pricelist": "Royal 1 (USD)",
306
+ "tags": "Fisch",
307
+ "customer_since": "2025-03-12",
308
+ "salesperson": "Karen",
309
+ "ar_open": 0,
310
+ "ar_overdue": 5120.25,
311
+ "ar_exposure": 5120.25,
312
+ "top_category": "Foams & Finishes",
313
+ "top_category_pct": 0.31,
314
+ "sku_count": 27,
315
+ "top_sku": "SATIN RIBBON 2IN",
316
+ "days_to_pay": 61,
317
+ "_created": "2023-03-15 09:12:00",
318
+ "lat": 28.5384,
319
+ "lon": -81.3789,
320
+ "odoo_status": "Active",
321
+ "dba": "Both"
322
+ },
323
+ {
324
+ "pid": 104,
325
+ "customer": "Camellia Row Florist",
326
+ "status": "Declining",
327
+ "agent": "Devon Marsh",
328
+ "city": "Savannah",
329
+ "state": "Georgia (US)",
330
+ "last_order": "2026-05-30",
331
+ "est_missed": 41200,
332
+ "notes": "Switched some volume to a local grower.",
333
+ "country": "United States",
334
+ "zip": "07649",
335
+ "payment_terms": "30 Days",
336
+ "pricelist": "Fisch 1 (USD)",
337
+ "tags": "(none)",
338
+ "customer_since": "2026-04-13",
339
+ "salesperson": "(none)",
340
+ "ar_open": 8300,
341
+ "ar_overdue": 940,
342
+ "ar_exposure": 11440,
343
+ "top_category": "All",
344
+ "top_category_pct": 1.0,
345
+ "sku_count": 1,
346
+ "top_sku": "(none)",
347
+ "days_to_pay": 12,
348
+ "_created": "2023-04-15 09:13:00",
349
+ "lat": 30.3322,
350
+ "lon": -81.6557,
351
+ "odoo_status": "Active",
352
+ "dba": "Royal"
353
+ },
354
+ {
355
+ "pid": 105,
356
+ "customer": "Harborlight Wholesale Blooms",
357
+ "status": "Growing",
358
+ "agent": "Carla Jimenez",
359
+ "city": "Seattle",
360
+ "state": "Washington (US)",
361
+ "last_order": "2026-07-22",
362
+ "est_missed": 0,
363
+ "notes": "Top-10 account.",
364
+ "country": "United States",
365
+ "zip": "33125",
366
+ "payment_terms": "Immediate Payment",
367
+ "pricelist": "Royal 1 (USD)",
368
+ "tags": "Royal",
369
+ "customer_since": "2023-05-14",
370
+ "salesperson": "Jessica",
371
+ "ar_open": 0,
372
+ "ar_overdue": 0,
373
+ "ar_exposure": 0,
374
+ "top_category": "Styrofoam",
375
+ "top_category_pct": 0.47,
376
+ "sku_count": 93,
377
+ "top_sku": "AQUAFOAM FLORAL FOAM BRICK | 48-Piece per Pack",
378
+ "days_to_pay": 34,
379
+ "_created": "2023-05-15 09:14:00",
380
+ "lat": 26.1224,
381
+ "lon": -80.1373,
382
+ "odoo_status": "Active",
383
+ "dba": ""
384
+ },
385
+ {
386
+ "pid": 106,
387
+ "customer": "Dogwood & Fern Co.",
388
+ "status": "Dormant",
389
+ "agent": "Devon Marsh",
390
+ "city": "Asheville",
391
+ "state": "North Carolina (US)",
392
+ "last_order": "2026-02-11",
393
+ "est_missed": 52400,
394
+ "notes": "No spring order this year.",
395
+ "country": "United States",
396
+ "zip": "90210",
397
+ "payment_terms": "60 Days",
398
+ "pricelist": "Royal 1 (USD)",
399
+ "tags": "Royal, Key account",
400
+ "customer_since": "2024-06-15",
401
+ "salesperson": "Naomi",
402
+ "ar_open": 1240.5,
403
+ "ar_overdue": 0,
404
+ "ar_exposure": 1740.5,
405
+ "top_category": "Ribbon",
406
+ "top_category_pct": 0.95,
407
+ "sku_count": 4,
408
+ "top_sku": "2\" X 24\" X 36\" GREEN STYROFOAM BOARD",
409
+ "days_to_pay": null,
410
+ "_created": "2023-06-15 09:15:00",
411
+ "lat": 27.3364,
412
+ "lon": -82.5307,
413
+ "odoo_status": "Active",
414
+ "dba": "Fisch"
415
+ },
416
+ {
417
+ "pid": 107,
418
+ "customer": "Verbena Market Florals",
419
+ "status": "Lost",
420
+ "agent": "Naomi Linnell Rivera",
421
+ "city": "Austin",
422
+ "state": "Texas (US)",
423
+ "last_order": "2025-11-04",
424
+ "est_missed": 78300,
425
+ "notes": "Went with a competitor on freight terms.",
426
+ "country": "United States",
427
+ "zip": "08701",
428
+ "payment_terms": "30 Days",
429
+ "pricelist": "Fisch 1 (USD)",
430
+ "tags": "Fisch",
431
+ "customer_since": "2025-07-16",
432
+ "salesperson": "Karen",
433
+ "ar_open": 0,
434
+ "ar_overdue": 5120.25,
435
+ "ar_exposure": 5120.25,
436
+ "top_category": "Foams & Finishes",
437
+ "top_category_pct": 0.31,
438
+ "sku_count": 27,
439
+ "top_sku": "SATIN RIBBON 2IN",
440
+ "days_to_pay": 61,
441
+ "_created": "2023-07-15 09:16:00",
442
+ "lat": null,
443
+ "lon": null,
444
+ "odoo_status": "Active",
445
+ "dba": "Both"
446
+ },
447
+ {
448
+ "pid": 108,
449
+ "customer": "Larkspur Lane Supply",
450
+ "status": "New",
451
+ "agent": "Carla Jimenez",
452
+ "city": "Denver",
453
+ "state": "Colorado (US)",
454
+ "last_order": "2026-07-14",
455
+ "est_missed": 0,
456
+ "notes": "First order in April.",
457
+ "country": "United States",
458
+ "zip": "60614",
459
+ "payment_terms": "Immediate Payment",
460
+ "pricelist": "Royal 1 (USD)",
461
+ "tags": "(none)",
462
+ "customer_since": "2026-08-17",
463
+ "salesperson": "(none)",
464
+ "ar_open": 8300,
465
+ "ar_overdue": 940,
466
+ "ar_exposure": 11440,
467
+ "top_category": "All",
468
+ "top_category_pct": 1.0,
469
+ "sku_count": 1,
470
+ "top_sku": "(none)",
471
+ "days_to_pay": 12,
472
+ "_created": "2023-08-15 09:17:00",
473
+ "lat": 33.749,
474
+ "lon": -84.388,
475
+ "odoo_status": "Active",
476
+ "dba": "Royal"
477
+ }
478
+ ]
479
+ }
web/src/customer-grid/ColumnMenu.tsx CHANGED
@@ -1,8 +1,8 @@
1
- import { useMemo, useState } from "react";
2
- import type { ReactNode } from "react";
3
  import { AnchoredOverlay } from "./OverlaySurface";
4
  import type { AnchorRect } from "./OverlaySurface";
5
- import { FieldTypeIcon } from "./icons";
 
6
  import { CREATABLE_TYPES, choiceOptions, directionLabel, parseOptions, ratingMax }
7
  from "./types";
8
  import type { Field, FieldFormat, FieldScope, FieldType, Measure, Viewer } from "./types";
@@ -11,7 +11,8 @@ import { normalizeWindow, windowLabel } from "./windows";
11
  import { WindowPicker } from "./Toolbar";
12
  import { TYPE_LABELS } from "./iconShapes";
13
  import { validateFormula } from "./formulaEngine";
14
- import { defaultOptionColor, normalizeOptionColor, OPTION_PALETTE } from "./choiceColors";
 
15
 
16
  export interface ColumnMenuState {
17
  fieldKey: string;
@@ -145,136 +146,9 @@ interface ColumnMenuProps {
145
 
146
  type CreatePosition = "left" | "right" | "end";
147
 
148
- // --- wave-7 item W4: menu-action icons (16px, stroke, currentColor β€” never emoji, never an
149
- // icon font; hand-rolled lucide-style paths inline, matching the toolbar's own icon set). ---
150
- const mi = { width: 16, height: 16, viewBox: "0 0 16 16", fill: "none" } as const;
151
- const miStroke = {
152
- stroke: "currentColor",
153
- strokeWidth: 1.3,
154
- strokeLinecap: "round" as const,
155
- strokeLinejoin: "round" as const,
156
- };
157
-
158
- const MenuIcons = {
159
- duplicate: (
160
- <svg {...mi} aria-hidden>
161
- <rect x="5.5" y="5.5" width="8" height="8" rx="1.5" {...miStroke} />
162
- <path d="M10.5 2.5h-7a1 1 0 0 0-1 1v7" {...miStroke} />
163
- </svg>
164
- ),
165
- insertLeft: (
166
- <svg {...mi} aria-hidden>
167
- <line x1="3" y1="2.5" x2="3" y2="13.5" {...miStroke} />
168
- <path d="M13.5 8H6.5M9.2 5.3 6.5 8l2.7 2.7" {...miStroke} />
169
- </svg>
170
- ),
171
- insertRight: (
172
- <svg {...mi} aria-hidden>
173
- <line x1="13" y1="2.5" x2="13" y2="13.5" {...miStroke} />
174
- <path d="M2.5 8h7M6.8 5.3 9.5 8l-2.7 2.7" {...miStroke} />
175
- </svg>
176
- ),
177
- addEnd: (
178
- <svg {...mi} aria-hidden>
179
- <path d="M8 3v10M3 8h10" {...miStroke} />
180
- </svg>
181
- ),
182
- rename: (
183
- <svg {...mi} aria-hidden>
184
- <path d="m9.8 3.2 3 3L6.2 12.8l-3.6.6.6-3.6 6.6-6.6Z" {...miStroke} />
185
- </svg>
186
- ),
187
- description: (
188
- <svg {...mi} aria-hidden>
189
- <path d="M3 4.5h10M3 8h10M3 11.5h6" {...miStroke} />
190
- </svg>
191
- ),
192
- permissions: (
193
- <svg {...mi} aria-hidden>
194
- <rect x="3.5" y="7" width="9" height="6" rx="1" {...miStroke} />
195
- <path d="M5.5 7V5.2a2.5 2.5 0 0 1 5 0V7" {...miStroke} />
196
- </svg>
197
- ),
198
- format: (
199
- <svg {...mi} aria-hidden>
200
- <path d="M3 5h5.5M12.5 5H13M3 11h1M7 11h6" {...miStroke} />
201
- <circle cx="10.5" cy="5" r="1.6" {...miStroke} />
202
- <circle cx="4.9" cy="11" r="1.6" {...miStroke} />
203
- </svg>
204
- ),
205
- swap: (
206
- <svg {...mi} aria-hidden>
207
- <path 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" {...miStroke} />
208
- </svg>
209
- ),
210
- sortAsc: (
211
- <svg {...mi} aria-hidden>
212
- <path d="M4.5 3v10M4.5 13l-2-2M4.5 13l2-2" {...miStroke} />
213
- <path d="M8.5 4.5h2M8.5 8h3.5M8.5 11.5h5" {...miStroke} />
214
- </svg>
215
- ),
216
- sortDesc: (
217
- <svg {...mi} aria-hidden>
218
- <path d="M4.5 3v10M4.5 13l-2-2M4.5 13l2-2" {...miStroke} />
219
- <path d="M8.5 4.5h5M8.5 8h3.5M8.5 11.5h2" {...miStroke} />
220
- </svg>
221
- ),
222
- off: (
223
- <svg {...mi} aria-hidden>
224
- <circle cx="8" cy="8" r="5.5" {...miStroke} />
225
- <line x1="4.4" y1="11.6" x2="11.6" y2="4.4" {...miStroke} />
226
- </svg>
227
- ),
228
- filter: (
229
- <svg {...mi} aria-hidden>
230
- <path d="M2.5 3.5h11L9.5 8.5v3.8L6.5 14V8.5L2.5 3.5Z" {...miStroke} />
231
- </svg>
232
- ),
233
- group: (
234
- <svg {...mi} aria-hidden>
235
- <line x1="2.5" y1="4" x2="13.5" y2="4" {...miStroke} />
236
- <line x1="5.5" y1="8" x2="13.5" y2="8" {...miStroke} />
237
- <line x1="5.5" y1="12" x2="13.5" y2="12" {...miStroke} />
238
- </svg>
239
- ),
240
- pin: (
241
- <svg {...mi} aria-hidden>
242
- <path d="M6 2.5h4l-.5 4L12 9v1H4V9l2.5-2.5L6 2.5Z" {...miStroke} />
243
- <line x1="8" y1="10" x2="8" y2="13.5" {...miStroke} />
244
- </svg>
245
- ),
246
- unpin: (
247
- <svg {...mi} aria-hidden>
248
- <path d="M6 2.5h4l-.5 4L12 9v1H4V9l2.5-2.5L6 2.5Z" {...miStroke} />
249
- <line x1="8" y1="10" x2="8" y2="13.5" {...miStroke} />
250
- <line x1="3" y1="13" x2="13" y2="3" {...miStroke} />
251
- </svg>
252
- ),
253
- hide: (
254
- <svg {...mi} aria-hidden>
255
- <path d="M2.5 8s2-3.5 5.5-3.5S13.5 8 13.5 8s-2 3.5-5.5 3.5S2.5 8 2.5 8Z" {...miStroke} />
256
- <circle cx="8" cy="8" r="1.5" {...miStroke} />
257
- <line x1="3.5" y1="12.5" x2="12.5" y2="3.5" {...miStroke} />
258
- </svg>
259
- ),
260
- trash: (
261
- <svg {...mi} aria-hidden>
262
- <path d="M3.5 4.5h9M6.5 4.5V3h3v1.5M5 4.5l.6 8.5h4.8l.6-8.5" {...miStroke} />
263
- </svg>
264
- ),
265
- } as const;
266
-
267
- /** One action row: icon + label. The icon column is fixed-width so labels align. */
268
- function MenuLabel({ icon, text }: { icon: ReactNode; text: string }) {
269
- return (
270
- <>
271
- <span className="cg-mi-ic" aria-hidden>
272
- {icon}
273
- </span>
274
- <span>{text}</span>
275
- </>
276
- );
277
- }
278
 
279
  /**
280
  * The menu's panes (wave-5 item 2). The NOTE editor and the editors used to render inline in
@@ -379,6 +253,90 @@ function optionAppearanceSignature(
379
  .join("\u0001");
380
  }
381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
382
  function OptionsEditor({
383
  idPrefix,
384
  drafts,
@@ -413,17 +371,14 @@ function OptionsEditor({
413
  <div className="cg-option-list">
414
  {drafts.map((draft, index) => (
415
  <div className="cg-option-row" key={draft.id}>
416
- <input
417
- className="cg-option-color"
418
- type="color"
419
  value={
420
  normalizeOptionColor(draft.color) ??
421
  OPTION_PALETTE[index % OPTION_PALETTE.length].bg
422
  }
423
  disabled={!colorCode}
424
- aria-label={`Color for ${draft.label || `option ${index + 1}`}`}
425
- title="Change option color"
426
- onChange={(event) => update(draft.id, { color: event.target.value })}
427
  />
428
  <input
429
  id={`${idPrefix}-${draft.id}`}
@@ -710,24 +665,21 @@ function ExtraTypeEditor({
710
  />
711
  </label>
712
  <div className="cg-cond-line cg-formula-insert">
713
- <select
714
- className="cg-select"
715
- value=""
716
- aria-label="Insert a field reference"
717
- onChange={(event) => {
718
- if (event.target.value)
719
- onFormulaText(
720
- (formulaText + " {" + event.target.value + "}").trimStart()
721
- );
722
- }}
723
- >
724
- <option value="">Insert a field reference…</option>
725
- {referencable.map((f) => (
726
- <option key={f.key} value={f.key}>
727
- {f.label}
728
- </option>
729
- ))}
730
- </select>
731
  </div>
732
  {formulaText.trim() !== "" && formulaError ? (
733
  <div className="cg-field-hint cg-formula-error">{formulaError}</div>
@@ -1039,8 +991,20 @@ export default function ColumnMenu({
1039
  const editBlocked =
1040
  (editRetypeTouched && !editRetypeValid) ||
1041
  (editFormulaTouched && !editFormulaCheck.ok);
 
 
 
 
 
 
 
 
 
 
1042
  const canSaveEdit =
1043
- !editBlocked && (editNameDirty || editRetypeTouched || editFormulaTouched);
 
 
1044
  const applyEdit = () => {
1045
  if (!canSaveEdit) return;
1046
  if (editRetypeTouched && onRetype) {
@@ -1065,6 +1029,11 @@ export default function ColumnMenu({
1065
  } else if (editNameDirty && onRename) {
1066
  onRename(cleanRename);
1067
  }
 
 
 
 
 
1068
  onClose();
1069
  };
1070
 
@@ -1082,12 +1051,6 @@ export default function ColumnMenu({
1082
  // Item 8c β€” the period draft is valid when it normalizes and differs from what the field
1083
  // already has. Compared through normalizeWindow so `{kind:'ltm'}` and `{kind:'ltm', n:undefined}`
1084
  // read as the same window.
1085
- const currentWindow = field.measure ? normalizeWindow(field.measure.window) : null;
1086
- const draftWindow = periodDraft ? normalizeWindow(periodDraft) : null;
1087
- const periodChanged =
1088
- draftWindow != null &&
1089
- JSON.stringify(draftWindow) !== JSON.stringify(currentWindow);
1090
-
1091
  const typeLineBase = field.measure
1092
  ? "Metric, read-only"
1093
  : field.type === "formula"
@@ -1178,19 +1141,19 @@ export default function ColumnMenu({
1178
  number ("Sales", "Gross margin"), so the label says that. */}
1179
  <label>
1180
  <span>Number</span>
1181
- <select
1182
- className="cg-select"
1183
- value={measureKey}
1184
- aria-label="Number to summarise"
1185
- onChange={(event) => setMeasureKey(event.target.value)}
1186
- >
1187
- {!chosenMeasure && <option value="">Choose a number…</option>}
1188
- {measures.map((m) => (
1189
- <option key={m.key} value={m.key}>
1190
- {m.label}
1191
- </option>
1192
- ))}
1193
- </select>
1194
  </label>
1195
  <label>
1196
  <span>Period</span>
@@ -1353,6 +1316,28 @@ export default function ColumnMenu({
1353
  )}
1354
  </>
1355
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1356
  {!onRetype && field.type === "formula" && onFormula && (
1357
  <ExtraTypeEditor
1358
  kind="formula"
@@ -1387,42 +1372,35 @@ export default function ColumnMenu({
1387
  Show a different field in this column β€” the current one is hidden, not lost.
1388
  </div>
1389
  <div className="cg-column-swap">
1390
- <select
1391
- className="cg-select cg-swap-select"
 
 
 
 
 
 
 
1392
  // Focus falls here when the pane has no editable Name (a read-only source
1393
- // field): the swap select is then the pane's first live control.
1394
- data-overlay-autofocus={onRename ? undefined : true}
1395
- value={swapTo}
1396
- aria-label="Change this column to another field"
1397
- onChange={(event) => setSwapTo(event.target.value)}
1398
- >
1399
- <option value="">Choose a field…</option>
1400
- {presetSwap.length > 0 && (
1401
- <optgroup label="Pre-set fields">
1402
- {presetSwap.map((f) => (
1403
- <option key={f.key} value={f.key}>
1404
- {f.label}
1405
- </option>
1406
- ))}
1407
- </optgroup>
1408
- )}
1409
- {yourSwap.length > 0 && (
1410
- <optgroup label="Your fields">
1411
- {yourSwap.map((f) => (
1412
- <option key={f.key} value={f.key}>
1413
- {f.label}
1414
- </option>
1415
- ))}
1416
- </optgroup>
1417
- )}
1418
- <optgroup label="New field">
1419
- {FIELD_TYPES.map((t) => (
1420
- <option key={t.value} value={NEW_PREFIX + t.value}>
1421
- {t.label}
1422
- </option>
1423
- ))}
1424
- </optgroup>
1425
- </select>
1426
  {!swapToNewType && (
1427
  <button
1428
  type="button"
@@ -1756,32 +1734,22 @@ export default function ColumnMenu({
1756
  <PaneHead title={field.label} sub={typeLine} onClose={onClose} />
1757
 
1758
  {/* Item 8c β€” any measure-carrying column exposes its PERIOD, the property that defines
1759
- it. Pre-set measure fields and user-created measure_ columns ride the same control,
1760
- because they are the same thing: a measure over a window. */}
1761
- {field.measure && onPeriod && (
1762
- <div className="cg-column-period">
 
 
 
 
 
 
 
 
 
1763
  <span className="cg-swap-label">Period</span>
1764
- <span className="cg-measure-window">
1765
- <WindowPicker
1766
- window={periodDraft ?? field.measure.window}
1767
- onWindow={setPeriodDraft}
1768
- />
1769
- </span>
1770
- <div className="cg-form-actions">
1771
- <button
1772
- type="button"
1773
- className="cg-btn cg-btn--primary"
1774
- disabled={!periodChanged}
1775
- onClick={() => {
1776
- if (!draftWindow) return;
1777
- onPeriod(draftWindow);
1778
- onClose();
1779
- }}
1780
- >
1781
- Apply period
1782
- </button>
1783
- </div>
1784
- </div>
1785
  )}
1786
 
1787
  {/* Wave-7 item W4 (contract C6): Airtable's grouping, thin dividers between groups,
@@ -1796,7 +1764,7 @@ export default function ColumnMenu({
1796
  setRenameDraft(field.label);
1797
  setPane("edit");
1798
  }}>
1799
- <MenuLabel icon={MenuIcons.rename} text="Edit field" />
1800
  </button>
1801
 
1802
  <div className="cg-menu-sep" role="separator" aria-hidden />
@@ -1804,17 +1772,17 @@ export default function ColumnMenu({
1804
  {/* Group 1 β€” Duplicate Β· Insert left Β· Insert right (+ Add at end, same family). */}
1805
  {onDuplicate && (
1806
  <button type="button" onClick={() => { onDuplicate(); onClose(); }}>
1807
- <MenuLabel icon={MenuIcons.duplicate} text="Duplicate field" />
1808
  </button>
1809
  )}
1810
  <button type="button" onClick={() => setPosition("left")}>
1811
- <MenuLabel icon={MenuIcons.insertLeft} text="Insert field left" />
1812
  </button>
1813
  <button type="button" onClick={() => setPosition("right")}>
1814
- <MenuLabel icon={MenuIcons.insertRight} text="Insert field right" />
1815
  </button>
1816
  <button type="button" onClick={() => setPosition("end")}>
1817
- <MenuLabel icon={MenuIcons.addEnd} text="Add field at end" />
1818
  </button>
1819
 
1820
  <div className="cg-menu-sep" role="separator" aria-hidden />
@@ -1823,16 +1791,16 @@ export default function ColumnMenu({
1823
  Rename and Change field live INSIDE Edit field now (owner item 8) β€” their old
1824
  rows are gone, not duplicated. */}
1825
  <button type="button" onClick={() => setPane("note")}>
1826
- <MenuLabel icon={MenuIcons.description} text="Edit field description" />
1827
  </button>
1828
  {canPermissions && (
1829
  <button type="button" onClick={() => setPane("permissions")}>
1830
- <MenuLabel icon={MenuIcons.permissions} text="Edit field permissions" />
1831
  </button>
1832
  )}
1833
  {formatKind && (
1834
  <button type="button" onClick={() => setPane("format")}>
1835
- <MenuLabel icon={MenuIcons.format} text="Field format" />
1836
  </button>
1837
  )}
1838
 
@@ -1841,19 +1809,19 @@ export default function ColumnMenu({
1841
  {/* Group 3 β€” sort. Direction wording stays the shipped per-type directionLabel. */}
1842
  <button type="button" onClick={() => { onSort("asc"); onClose(); }}>
1843
  <MenuLabel
1844
- icon={MenuIcons.sortAsc}
1845
  text={`Sort ${directionLabel(field.type, "asc")}`}
1846
  />
1847
  </button>
1848
  <button type="button" onClick={() => { onSort("desc"); onClose(); }}>
1849
  <MenuLabel
1850
- icon={MenuIcons.sortDesc}
1851
  text={`Sort ${directionLabel(field.type, "desc")}`}
1852
  />
1853
  </button>
1854
  {sortedDir != null && (
1855
  <button type="button" onClick={() => { onClearSort(); onClose(); }}>
1856
- <MenuLabel icon={MenuIcons.off} text="Don't sort by this field" />
1857
  </button>
1858
  )}
1859
 
@@ -1868,34 +1836,34 @@ export default function ColumnMenu({
1868
  {(field.filterable !== false ||
1869
  (field.measure != null && measures.length > 0)) && (
1870
  <button type="button" onClick={() => { onFilterBy(); onClose(); }}>
1871
- <MenuLabel icon={MenuIcons.filter} text="Filter by this field" />
1872
  </button>
1873
  )}
1874
  {isFiltered && (
1875
  <button type="button" onClick={() => { onClearFilter(); onClose(); }}>
1876
- <MenuLabel icon={MenuIcons.off} text="Don't filter by this field" />
1877
  </button>
1878
  )}
1879
  {groupable && !isGrouped && (
1880
  <button type="button" onClick={() => { onGroupByField(); onClose(); }}>
1881
- <MenuLabel icon={MenuIcons.group} text="Group by this field" />
1882
  </button>
1883
  )}
1884
  {isGrouped && (
1885
  <button type="button" onClick={() => { onClearGroup(); onClose(); }}>
1886
- <MenuLabel icon={MenuIcons.off} text="Don't group by this field" />
1887
  </button>
1888
  )}
1889
  {/* Item 11c β€” pin: freeze the columns up to this one; Unpin restores the identity
1890
  column alone. */}
1891
  {onPinTo && !pinnedTo && (
1892
  <button type="button" onClick={() => { onPinTo(); onClose(); }}>
1893
- <MenuLabel icon={MenuIcons.pin} text="Pin up to this field" />
1894
  </button>
1895
  )}
1896
  {onUnpin && (
1897
  <button type="button" onClick={() => { onUnpin(); onClose(); }}>
1898
- <MenuLabel icon={MenuIcons.unpin} text="Unpin all fields" />
1899
  </button>
1900
  )}
1901
 
@@ -1908,7 +1876,7 @@ export default function ColumnMenu({
1908
  title={locked ? "The primary field stays visible" : undefined}
1909
  onClick={onHide}
1910
  >
1911
- <MenuLabel icon={MenuIcons.hide} text="Hide field" />
1912
  </button>
1913
  {onDelete && (
1914
  <button
@@ -1922,7 +1890,7 @@ export default function ColumnMenu({
1922
  onClick={() => (confirmDelete ? onDelete() : setConfirmDelete(true))}
1923
  >
1924
  <MenuLabel
1925
- icon={MenuIcons.trash}
1926
  text={confirmDelete ? "Delete permanently?" : "Delete field"}
1927
  />
1928
  </button>
 
1
+ import { useMemo, useRef, useState } from "react";
 
2
  import { AnchoredOverlay } from "./OverlaySurface";
3
  import type { AnchorRect } from "./OverlaySurface";
4
+ import { FieldTypeIcon, MenuLabel } from "./icons";
5
+ import { FieldSelectButton } from "./FieldSelect";
6
  import { CREATABLE_TYPES, choiceOptions, directionLabel, parseOptions, ratingMax }
7
  from "./types";
8
  import type { Field, FieldFormat, FieldScope, FieldType, Measure, Viewer } from "./types";
 
11
  import { WindowPicker } from "./Toolbar";
12
  import { TYPE_LABELS } from "./iconShapes";
13
  import { validateFormula } from "./formulaEngine";
14
+ import { BRAND_SWATCHES, defaultOptionColor, nearestSwatch, normalizeOptionColor,
15
+ OPTION_PALETTE } from "./choiceColors";
16
 
17
  export interface ColumnMenuState {
18
  fieldKey: string;
 
146
 
147
  type CreatePosition = "left" | "right" | "end";
148
 
149
+ // ⚠ wave-7 item W4's menu-action icon set + `MenuLabel` MOVED to `icons.tsx` (wave-14
150
+ // item 19): the view menu needs the same vocabulary, and two hand-drawn padlocks in two
151
+ // files is how one of them ends up a different padlock. `icon=` takes a NAME now.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
 
153
  /**
154
  * The menu's panes (wave-5 item 2). The NOTE editor and the editors used to render inline in
 
253
  .join("\u0001");
254
  }
255
 
256
+ /**
257
+ * Item 22 (R5) β€” the option COLOUR control: ten brand swatches, no free RGB.
258
+ *
259
+ * It was an `<input type="color">`, which offered sixteen million colours in a product whose
260
+ * whole visual argument is five. The trigger keeps the old 24px circle's footprint (it is the
261
+ * same affordance in the same place) and opens a 5Γ—2 grid: each hue's light `-tint` on the top
262
+ * row, its `-pastel` beneath. A stored colour that is not on the palette marks its NEAREST
263
+ * swatch β€” so the picker says what the value reads as β€” and re-picking is what rewrites it.
264
+ */
265
+ function SwatchPicker({
266
+ value,
267
+ disabled,
268
+ label,
269
+ onPick,
270
+ }: {
271
+ value: string | undefined;
272
+ disabled?: boolean;
273
+ /** The option this colours, for the accessible name. */
274
+ label: string;
275
+ onPick: (hex: string) => void;
276
+ }) {
277
+ const [open, setOpen] = useState(false);
278
+ const ref = useRef<HTMLButtonElement>(null);
279
+ const current = nearestSwatch(value);
280
+ return (
281
+ <>
282
+ <button
283
+ ref={ref}
284
+ type="button"
285
+ className="cg-option-color"
286
+ disabled={disabled}
287
+ style={{ background: current?.bg ?? normalizeOptionColor(value) ?? "#FFFFFF" }}
288
+ aria-label={`Colour for ${label}${current ? ` β€” ${current.label}` : ""}`}
289
+ aria-haspopup="dialog"
290
+ aria-expanded={open}
291
+ title="Change option colour"
292
+ onClick={() => setOpen((o) => !o)}
293
+ />
294
+ {open && ref.current && (
295
+ <AnchoredOverlay
296
+ anchor={ref.current}
297
+ className="cg-pop cg-swatch-pop"
298
+ onDismiss={() => setOpen(false)}
299
+ role="dialog"
300
+ ariaLabel={`Colour for ${label}`}
301
+ dataKind="option-colour"
302
+ >
303
+ <div className="cg-swatch-grid">
304
+ {BRAND_SWATCHES.map((swatch) => (
305
+ <button
306
+ key={swatch.id}
307
+ type="button"
308
+ className={"cg-swatch" + (current?.id === swatch.id ? " is-on" : "")}
309
+ style={{ background: swatch.bg, color: swatch.fg }}
310
+ aria-label={swatch.label}
311
+ aria-pressed={current?.id === swatch.id}
312
+ title={swatch.label}
313
+ onClick={() => {
314
+ onPick(swatch.bg);
315
+ setOpen(false);
316
+ }}
317
+ >
318
+ {/* The check is drawn in the swatch's OWN ink, which is also the ink its
319
+ chips will use β€” so the mark doubles as a preview of readability. */}
320
+ {current?.id === swatch.id && (
321
+ <svg width="12" height="12" viewBox="0 0 16 16" fill="none" aria-hidden>
322
+ <path
323
+ d="m3.5 8.5 3 3 6-6.5"
324
+ stroke="currentColor"
325
+ strokeWidth="2"
326
+ strokeLinecap="round"
327
+ strokeLinejoin="round"
328
+ />
329
+ </svg>
330
+ )}
331
+ </button>
332
+ ))}
333
+ </div>
334
+ </AnchoredOverlay>
335
+ )}
336
+ </>
337
+ );
338
+ }
339
+
340
  function OptionsEditor({
341
  idPrefix,
342
  drafts,
 
371
  <div className="cg-option-list">
372
  {drafts.map((draft, index) => (
373
  <div className="cg-option-row" key={draft.id}>
374
+ <SwatchPicker
 
 
375
  value={
376
  normalizeOptionColor(draft.color) ??
377
  OPTION_PALETTE[index % OPTION_PALETTE.length].bg
378
  }
379
  disabled={!colorCode}
380
+ label={draft.label || `option ${index + 1}`}
381
+ onPick={(hex) => update(draft.id, { color: hex })}
 
382
  />
383
  <input
384
  id={`${idPrefix}-${draft.id}`}
 
665
  />
666
  </label>
667
  <div className="cg-cond-line cg-formula-insert">
668
+ <FieldSelectButton
669
+ ariaLabel="Insert a field reference"
670
+ placeholder="Insert a field reference…"
671
+ // An ACTION picker, not a value one: it never holds a selection, so it stays in
672
+ // the placeholder state and `keepOpen` lets a formula take three references
673
+ // without three trips through the button.
674
+ value={undefined}
675
+ keepOpen
676
+ onChange={(key) =>
677
+ onFormulaText((formulaText + " {" + key + "}").trimStart())
678
+ }
679
+ fields={referencable.map((f) => ({
680
+ key: f.key, label: f.label, type: f.type,
681
+ }))}
682
+ />
 
 
 
683
  </div>
684
  {formulaText.trim() !== "" && formulaError ? (
685
  <div className="cg-field-hint cg-formula-error">{formulaError}</div>
 
991
  const editBlocked =
992
  (editRetypeTouched && !editRetypeValid) ||
993
  (editFormulaTouched && !editFormulaCheck.ok);
994
+ // Item 21 (2026-08-02) β€” the PERIOD moved into this pane, so its dirty-check has to be
995
+ // computed before the pane's save gate rather than beside the menu's own button. Same three
996
+ // lines, hoisted: `canSaveEdit` reads `periodChanged`, and a `const` read before its
997
+ // initialiser is a TDZ crash at render, not a compile error.
998
+ const currentWindow = field.measure ? normalizeWindow(field.measure.window) : null;
999
+ const draftWindow = periodDraft ? normalizeWindow(periodDraft) : null;
1000
+ const periodChanged =
1001
+ draftWindow != null &&
1002
+ JSON.stringify(draftWindow) !== JSON.stringify(currentWindow);
1003
+ const canPeriod = !!field.measure && !!onPeriod;
1004
  const canSaveEdit =
1005
+ !editBlocked &&
1006
+ (editNameDirty || editRetypeTouched || editFormulaTouched ||
1007
+ (canPeriod && periodChanged));
1008
  const applyEdit = () => {
1009
  if (!canSaveEdit) return;
1010
  if (editRetypeTouched && onRetype) {
 
1029
  } else if (editNameDirty && onRename) {
1030
  onRename(cleanRename);
1031
  }
1032
+ // Item 21 β€” the period is an INDEPENDENT property of a measure column, not a branch of
1033
+ // the identity edit, so it applies ALONGSIDE whatever the chain above did rather than
1034
+ // instead of it: renaming "Sales YTD" to "Sales" and re-pointing it at the last 90 days
1035
+ // is one edit to the user and must not silently drop half of itself.
1036
+ if (canPeriod && periodChanged && draftWindow) onPeriod!(draftWindow);
1037
  onClose();
1038
  };
1039
 
 
1051
  // Item 8c β€” the period draft is valid when it normalizes and differs from what the field
1052
  // already has. Compared through normalizeWindow so `{kind:'ltm'}` and `{kind:'ltm', n:undefined}`
1053
  // read as the same window.
 
 
 
 
 
 
1054
  const typeLineBase = field.measure
1055
  ? "Metric, read-only"
1056
  : field.type === "formula"
 
1141
  number ("Sales", "Gross margin"), so the label says that. */}
1142
  <label>
1143
  <span>Number</span>
1144
+ {/* Item 20 (C-FLDSEL) β€” "Choose a number…" was an `<option value="">` that
1145
+ only rendered while nothing was chosen; it is the picker's PLACEHOLDER
1146
+ now, so the prompt is a state of the control rather than a row of the
1147
+ vocabulary that could be picked. */}
1148
+ <FieldSelectButton
1149
+ ariaLabel="Number to summarise"
1150
+ placeholder="Choose a number…"
1151
+ value={chosenMeasure ? measureKey : undefined}
1152
+ onChange={setMeasureKey}
1153
+ fields={measures.map((m) => ({
1154
+ key: m.key, label: m.label, type: "measure" as const,
1155
+ }))}
1156
+ />
1157
  </label>
1158
  <label>
1159
  <span>Period</span>
 
1316
  )}
1317
  </>
1318
  )}
1319
+ {/* Item 21 (owner, 2026-08-02) β€” the PERIOD lives here, with the field's other
1320
+ properties, instead of floating above the action list on the menu pane. A metric
1321
+ column IS "a number over a period": the window is as much a part of its
1322
+ definition as its name is, and it was the one property you edited from a
1323
+ different window than every other one.
1324
+ It shares this pane's ONE Save (`applyEdit` applies it alongside a rename) β€”
1325
+ the old "Apply period" button became a second primary action in a pane that
1326
+ already had one, which is the ambiguity the move was supposed to remove. */}
1327
+ {canPeriod && (
1328
+ <label className="cg-edit-period">
1329
+ <span>Period</span>
1330
+ <span className="cg-measure-window">
1331
+ <WindowPicker
1332
+ window={periodDraft ?? field.measure!.window}
1333
+ onWindow={setPeriodDraft}
1334
+ />
1335
+ </span>
1336
+ <span className="cg-field-hint">
1337
+ The window this number is computed over, for every customer.
1338
+ </span>
1339
+ </label>
1340
+ )}
1341
  {!onRetype && field.type === "formula" && onFormula && (
1342
  <ExtraTypeEditor
1343
  kind="formula"
 
1372
  Show a different field in this column β€” the current one is hidden, not lost.
1373
  </div>
1374
  <div className="cg-column-swap">
1375
+ {/* Item 20 β€” the ONE picker on this surface that keeps its groups, and it is
1376
+ not a contradiction of the filter list's flatness: those three headings
1377
+ separate DIFFERENT KINDS OF ACT (show a pre-set column Β· show one of yours Β·
1378
+ make a new one), not three flavours of the same noun. The type mark does
1379
+ the work the "New field" labels were doing on their own. */}
1380
+ <FieldSelectButton
1381
+ className="cg-swap-select"
1382
+ ariaLabel="Change this column to another field"
1383
+ placeholder="Choose a field…"
1384
  // Focus falls here when the pane has no editable Name (a read-only source
1385
+ // field): the swap picker is then the pane's first live control.
1386
+ overlayAutofocus={!onRename}
1387
+ value={swapTo || undefined}
1388
+ onChange={setSwapTo}
1389
+ fields={[
1390
+ ...presetSwap.map((f) => ({
1391
+ key: f.key, label: f.label, type: f.type, group: "Pre-set fields",
1392
+ })),
1393
+ ...yourSwap.map((f) => ({
1394
+ key: f.key, label: f.label, type: f.type, group: "Your fields",
1395
+ })),
1396
+ ...FIELD_TYPES.map((t) => ({
1397
+ key: NEW_PREFIX + t.value,
1398
+ label: t.label,
1399
+ type: t.value,
1400
+ group: "New field",
1401
+ })),
1402
+ ]}
1403
+ />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1404
  {!swapToNewType && (
1405
  <button
1406
  type="button"
 
1734
  <PaneHead title={field.label} sub={typeLine} onClose={onClose} />
1735
 
1736
  {/* Item 8c β€” any measure-carrying column exposes its PERIOD, the property that defines
1737
+ it. Item 21 (2026-08-02) moved the EDITOR into the Edit-field pane; what stays here
1738
+ is one line that STATES the period and opens that pane, because the window is the
1739
+ first thing you want to know about a metric column and the menu had become the only
1740
+ place it was written down. A row, not a control: the menu pane edits nothing inline. */}
1741
+ {canPeriod && (
1742
+ <button
1743
+ type="button"
1744
+ className="cg-column-periodline"
1745
+ onClick={() => {
1746
+ setRenameDraft(field.label);
1747
+ setPane("edit");
1748
+ }}
1749
+ >
1750
  <span className="cg-swap-label">Period</span>
1751
+ <span className="cg-column-periodval">{windowLabel(field.measure!.window)}</span>
1752
+ </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1753
  )}
1754
 
1755
  {/* Wave-7 item W4 (contract C6): Airtable's grouping, thin dividers between groups,
 
1764
  setRenameDraft(field.label);
1765
  setPane("edit");
1766
  }}>
1767
+ <MenuLabel icon="rename" text="Edit field" />
1768
  </button>
1769
 
1770
  <div className="cg-menu-sep" role="separator" aria-hidden />
 
1772
  {/* Group 1 β€” Duplicate Β· Insert left Β· Insert right (+ Add at end, same family). */}
1773
  {onDuplicate && (
1774
  <button type="button" onClick={() => { onDuplicate(); onClose(); }}>
1775
+ <MenuLabel icon="duplicate" text="Duplicate field" />
1776
  </button>
1777
  )}
1778
  <button type="button" onClick={() => setPosition("left")}>
1779
+ <MenuLabel icon="insertLeft" text="Insert field left" />
1780
  </button>
1781
  <button type="button" onClick={() => setPosition("right")}>
1782
+ <MenuLabel icon="insertRight" text="Insert field right" />
1783
  </button>
1784
  <button type="button" onClick={() => setPosition("end")}>
1785
+ <MenuLabel icon="addEnd" text="Add field at end" />
1786
  </button>
1787
 
1788
  <div className="cg-menu-sep" role="separator" aria-hidden />
 
1791
  Rename and Change field live INSIDE Edit field now (owner item 8) β€” their old
1792
  rows are gone, not duplicated. */}
1793
  <button type="button" onClick={() => setPane("note")}>
1794
+ <MenuLabel icon="description" text="Edit field description" />
1795
  </button>
1796
  {canPermissions && (
1797
  <button type="button" onClick={() => setPane("permissions")}>
1798
+ <MenuLabel icon="permissions" text="Edit field permissions" />
1799
  </button>
1800
  )}
1801
  {formatKind && (
1802
  <button type="button" onClick={() => setPane("format")}>
1803
+ <MenuLabel icon="format" text="Field format" />
1804
  </button>
1805
  )}
1806
 
 
1809
  {/* Group 3 β€” sort. Direction wording stays the shipped per-type directionLabel. */}
1810
  <button type="button" onClick={() => { onSort("asc"); onClose(); }}>
1811
  <MenuLabel
1812
+ icon="sortAsc"
1813
  text={`Sort ${directionLabel(field.type, "asc")}`}
1814
  />
1815
  </button>
1816
  <button type="button" onClick={() => { onSort("desc"); onClose(); }}>
1817
  <MenuLabel
1818
+ icon="sortDesc"
1819
  text={`Sort ${directionLabel(field.type, "desc")}`}
1820
  />
1821
  </button>
1822
  {sortedDir != null && (
1823
  <button type="button" onClick={() => { onClearSort(); onClose(); }}>
1824
+ <MenuLabel icon="off" text="Don't sort by this field" />
1825
  </button>
1826
  )}
1827
 
 
1836
  {(field.filterable !== false ||
1837
  (field.measure != null && measures.length > 0)) && (
1838
  <button type="button" onClick={() => { onFilterBy(); onClose(); }}>
1839
+ <MenuLabel icon="filter" text="Filter by this field" />
1840
  </button>
1841
  )}
1842
  {isFiltered && (
1843
  <button type="button" onClick={() => { onClearFilter(); onClose(); }}>
1844
+ <MenuLabel icon="off" text="Don't filter by this field" />
1845
  </button>
1846
  )}
1847
  {groupable && !isGrouped && (
1848
  <button type="button" onClick={() => { onGroupByField(); onClose(); }}>
1849
+ <MenuLabel icon="group" text="Group by this field" />
1850
  </button>
1851
  )}
1852
  {isGrouped && (
1853
  <button type="button" onClick={() => { onClearGroup(); onClose(); }}>
1854
+ <MenuLabel icon="off" text="Don't group by this field" />
1855
  </button>
1856
  )}
1857
  {/* Item 11c β€” pin: freeze the columns up to this one; Unpin restores the identity
1858
  column alone. */}
1859
  {onPinTo && !pinnedTo && (
1860
  <button type="button" onClick={() => { onPinTo(); onClose(); }}>
1861
+ <MenuLabel icon="pin" text="Pin up to this field" />
1862
  </button>
1863
  )}
1864
  {onUnpin && (
1865
  <button type="button" onClick={() => { onUnpin(); onClose(); }}>
1866
+ <MenuLabel icon="unpin" text="Unpin all fields" />
1867
  </button>
1868
  )}
1869
 
 
1876
  title={locked ? "The primary field stays visible" : undefined}
1877
  onClick={onHide}
1878
  >
1879
+ <MenuLabel icon="hide" text="Hide field" />
1880
  </button>
1881
  {onDelete && (
1882
  <button
 
1890
  onClick={() => (confirmDelete ? onDelete() : setConfirmDelete(true))}
1891
  >
1892
  <MenuLabel
1893
+ icon="trash"
1894
  text={confirmDelete ? "Delete permanently?" : "Delete field"}
1895
  />
1896
  </button>
web/src/customer-grid/CustomerGrid.tsx CHANGED
@@ -58,16 +58,18 @@ import { cleanCharts } from "../viz/chartData";
58
  import type { ChartSpec } from "../viz/chartData";
59
  import { MapView } from "./MapView";
60
  import { lightTheme, STATUS_ROW_THEME, HOVER_ROW_THEME, HOVER_NEUTRAL,
61
- ACTIVE_ROW_NEUTRAL } from "./theme";
62
- import { formatDisplay, ratingCellRenderer } from "./cells";
63
- import { optionTint } from "./choiceColors";
 
64
  import {
65
  EMPTY_GRID_COPY_PROVENANCE,
66
  markGridCopy,
67
  observeCopyEvent,
68
  planFieldPaste,
69
  } from "./clipboard";
70
- import { cellTipText, expandButtonRect, infoMarkRect, tipLeft } from "./overlayPlacement";
 
71
  import { AnchoredOverlay } from "./OverlaySurface";
72
  import type { AnchorRect } from "./OverlaySurface";
73
  import { StarIcon } from "./Stars";
@@ -97,6 +99,28 @@ import type { WindowSpec } from "./windows";
97
  import { windowLabel } from "./windows";
98
 
99
  const ROW_PX: Record<RowHeightMode, number> = { short: 28, medium: 34, tall: 48 };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
  const ALL_VIEW_ID = "all-customers";
101
 
102
  /**
@@ -115,6 +139,25 @@ function measureCellText(text: string): number {
115
  }
116
  return _tipCtx ? _tipCtx.measureText(text).width : 0;
117
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
118
  /**
119
  * Owner item 8 (2026-07-27): the first render shows this many rows; "See more" reveals the rest.
120
  * A DISPLAY cap only β€” the pipeline still runs over the whole book, the toolbar count is still
@@ -829,12 +872,41 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
829
  return m;
830
  }, [capped, displayRows, pidToIndex]);
831
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
832
  const getCellContent = useGetCellContent(
833
  displayRows,
834
  visibleCols,
835
  fieldByKey,
836
  overlayEdits,
837
- canEditField
 
 
 
 
838
  );
839
  const { gridSelection, selectedPids, onGridSelectionChange, selectPids, togglePid,
840
  setActiveCell, clearSelection } =
@@ -937,9 +1009,14 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
937
  if (args.kind === "cell" && vrow?.kind === "data" && row !== undefined) {
938
  const pid = vrow.record.pid;
939
  const b = gridRef.current?.getBounds(0, row);
940
- // Clamped to the grid's own box: with a grouping active `freezeColumns` is 0, so the
941
- // primary column scrolls away and glide's bounds go with it β€” and a `position: fixed`
942
- // button would follow it straight over the views rail.
 
 
 
 
 
943
  const at = b
944
  ? expandButtonRect(b, gridBoxRef.current?.getBoundingClientRect())
945
  : null;
@@ -1095,21 +1172,73 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
1095
  */
1096
  const drawGridHeader = useCallback<DrawHeaderCallback>(
1097
  (args, drawContent) => {
1098
- drawContent();
1099
  const field = args.column.id ? fieldByKey.get(args.column.id) : undefined;
1100
- if (!field || !(field.note || field.description)) return;
1101
- const at = infoMarkRect(args.rect, args.menuBounds.width);
1102
- // null = the column is too narrow to carry the mark without covering its own label.
1103
- if (!at) return;
1104
- args.spriteManager.drawSprite(
1105
- "aiosInfo",
1106
- "normal",
1107
- args.ctx,
1108
- at.x,
1109
- at.y,
1110
- at.size,
1111
- args.theme
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1112
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1113
  },
1114
  [fieldByKey]
1115
  );
@@ -2332,14 +2461,20 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2332
  * Wave-6 item 11c β€” PIN. "Pin up to this field" freezes every visible column through the
2333
  * clicked one; when the field sits past the clamp (8), it is REORDERED into the frozen
2334
  * prefix first (the contract's wording). Pinning the identity column reads as "just the
2335
- * identity" = the legacy 1, stored as ABSENT. Grouped mode paints frozenCount 0 (spans
2336
- * break under freezing) but the setting persists for when grouping is cleared.
 
 
 
 
 
 
2337
  */
2338
  const visibleKeys = useMemo(
2339
  () => order.filter((key) => visible.has(key)),
2340
  [order, visible]
2341
  );
2342
- const frozenN = Math.min(MAX_FROZEN, Math.max(1, config.frozenCount ?? 1));
2343
  const pinFieldTo = useCallback(
2344
  (key: string) => {
2345
  const index = visibleKeys.indexOf(key);
@@ -2909,6 +3044,12 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2909
  // Inventing a name or a count for a set we were given no membership for would be
2910
  // disclosing the very thing the permission gate withheld.
2911
  cohortLock={cohortLockChip}
 
 
 
 
 
 
2912
  fields={fields}
2913
  visible={visible}
2914
  lockedKey={lockedKey}
@@ -2983,7 +3124,19 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
2983
  getCellContent={getCellContent}
2984
  rows={displayRows.length}
2985
  theme={lightTheme}
2986
- freezeColumns={config.groupBy ? 0 : frozenN}
 
 
 
 
 
 
 
 
 
 
 
 
2987
  rowHeight={rowHeight}
2988
  headerHeight={36}
2989
  rowMarkers="both"
@@ -3011,7 +3164,7 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
3011
  smoothScrollY
3012
  width={gridSize.width}
3013
  height={gridSize.height}
3014
- customRenderers={[ratingCellRenderer]}
3015
  headerIcons={HEADER_ICONS}
3016
  rightElement={
3017
  // Wave-6 item 4 β€” the far-right "+" of the header row: the create-field
@@ -3215,6 +3368,7 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
3215
  <button
3216
  type="button"
3217
  className="cg-btn cg-btn--danger cg-selbar-remove"
 
3218
  onClick={removeSelectionFromCohort}
3219
  >
3220
  Remove from cohort
@@ -3223,6 +3377,7 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
3223
  <button
3224
  type="button"
3225
  className="cg-btn cg-btn--primary cg-selbar-add"
 
3226
  ref={selAddRef}
3227
  onClick={() => {
3228
  // Item 4: seed the new-cohort name as `<view name> Β· <today>` β€” today from
@@ -3239,7 +3394,8 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
3239
  Add to cohort
3240
  </button>
3241
  )}
3242
- <button type="button" className="cg-btn" onClick={clearSelection}>
 
3243
  Clear
3244
  </button>
3245
  </div>
@@ -3469,6 +3625,7 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
3469
  <button
3470
  type="button"
3471
  className="cg-btn cg-btn--primary"
 
3472
  disabled={!selListName.trim()}
3473
  onClick={() => addSelectionToList("", selListName.trim())}
3474
  >
@@ -3543,6 +3700,7 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
3543
  <button
3544
  type="button"
3545
  className="cg-btn cg-btn--primary"
 
3546
  disabled={addCustPicked.size === 0}
3547
  onClick={addCustomersToCohort}
3548
  >
@@ -3555,6 +3713,7 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
3555
  <button
3556
  type="button"
3557
  className="cg-btn"
 
3558
  onClick={() => setAddCustOpen(false)}
3559
  >
3560
  Cancel
@@ -3664,6 +3823,59 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
3664
  closePicker();
3665
  }}
3666
  >
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3667
  <span
3668
  className="cg-pick-pill"
3669
  style={tint ? { background: tint.bg, color: tint.fg } : undefined}
@@ -3679,6 +3891,7 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
3679
  <button
3680
  type="button"
3681
  className="cg-btn"
 
3682
  onClick={closePicker}
3683
  >
3684
  Done
@@ -3772,6 +3985,11 @@ function CustomerGrid({ scope = "customer" }: { scope?: SurfaceScope } = {}) {
3772
  }
3773
  onNotesCommit={(key, value) => patchOverlay(detailPid, { [key]: value })}
3774
  viewer={viewer}
 
 
 
 
 
3775
  />
3776
  )}
3777
  </div>
 
58
  import type { ChartSpec } from "../viz/chartData";
59
  import { MapView } from "./MapView";
60
  import { lightTheme, STATUS_ROW_THEME, HOVER_ROW_THEME, HOVER_NEUTRAL,
61
+ ACTIVE_ROW_NEUTRAL, CUSTOM_FIELD_MARK } from "./theme";
62
+ import { avatarInitials, formatDisplay, ratingCellRenderer, setAvatarRepaint, userCellRenderer }
63
+ from "./cells";
64
+ import { optionTint, pickTint } from "./choiceColors";
65
  import {
66
  EMPTY_GRID_COPY_PROVENANCE,
67
  markGridCopy,
68
  observeCopyEvent,
69
  planFieldPaste,
70
  } from "./clipboard";
71
+ import { cellTipText, expandButtonRect, GROUP_HEADER_FONT, GROUP_LABEL_PAD, headerMarkLayout,
72
+ headerMarkSizes, tipLeft } from "./overlayPlacement";
73
  import { AnchoredOverlay } from "./OverlaySurface";
74
  import type { AnchorRect } from "./OverlaySurface";
75
  import { StarIcon } from "./Stars";
 
99
  import { windowLabel } from "./windows";
100
 
101
  const ROW_PX: Record<RowHeightMode, number> = { short: 28, medium: 34, tall: 48 };
102
+
103
+ /**
104
+ * Wave-14 R7 β€” **a button label is ONE LINE.** Every button row in this file is a flex row with
105
+ * no width reservation, so on a narrow grid box the items shrink and their labels wrap:
106
+ * "Remove from cohort" becomes two lines, the row grows, and the bar stops being a bar. It only
107
+ * happens below a width no fixed-size screenshot is taken at, which is why it survived.
108
+ *
109
+ * ⚠ Applied INLINE rather than on `.cg-btn`, where it belongs: `index.css` is PANEL's fence this
110
+ * wave. A mailbox line asks them to hoist it onto `.cg-btn` globally β€” after which this is
111
+ * redundant, and harmless, because it says exactly the same thing.
112
+ */
113
+ const ONE_LINE = { whiteSpace: "nowrap" } as const;
114
+
115
+ /**
116
+ * How many VISIBLE columns glide freezes. Module-level and used twice on purpose (item 15): the
117
+ * `freezeColumns` prop and the group bar's label fit must read ONE answer, because the label is
118
+ * clipped to exactly this strip and a second copy of the clamp would let the two disagree by a
119
+ * column β€” which shows up as a label cut early for no visible reason.
120
+ */
121
+ function frozenCountOf(config: ViewConfig): number {
122
+ return Math.min(MAX_FROZEN, Math.max(1, config.frozenCount ?? 1));
123
+ }
124
  const ALL_VIEW_ID = "all-customers";
125
 
126
  /**
 
139
  }
140
  return _tipCtx ? _tipCtx.measureText(text).width : 0;
141
  }
142
+ /**
143
+ * Item 15 β€” the GROUP BAR's measurer, and it is a SECOND context on purpose.
144
+ *
145
+ * `measureCellText` above is set to plain "13px", which is right for ordinary cells and WRONG for
146
+ * a group bar: that row carries `baseFontStyle: GROUP_HEADER_FONT` (semibold), and glide paints a
147
+ * cell with the merged theme's font. Measuring the fit with the lighter weight under-truncates
148
+ * and the label overflows into the frozen strip's hard clip β€” the exact failure `fitGroupLabel`
149
+ * exists to prevent. Font string built from the SAME constant the cell's themeOverride uses, so
150
+ * the two cannot drift.
151
+ */
152
+ let _groupCtx: CanvasRenderingContext2D | null | undefined;
153
+ function measureGroupText(text: string): number {
154
+ if (_groupCtx === undefined) {
155
+ _groupCtx = document.createElement("canvas").getContext("2d");
156
+ if (_groupCtx)
157
+ _groupCtx.font = `${GROUP_HEADER_FONT} ${lightTheme.fontFamily ?? "Inter, sans-serif"}`;
158
+ }
159
+ return _groupCtx ? _groupCtx.measureText(text).width : 0;
160
+ }
161
  /**
162
  * Owner item 8 (2026-07-27): the first render shows this many rows; "See more" reveals the rest.
163
  * A DISPLAY cap only β€” the pipeline still runs over the whole book, the toolbar count is still
 
872
  return m;
873
  }, [capped, displayRows, pidToIndex]);
874
 
875
+ // C-AVATAR (wave-14 item 11) β€” profile photos, absent until HOST serves them. The tick is the
876
+ // async half: `cells.setAvatarRepaint` fires it when an Image finishes decoding, and it is a
877
+ // dep of `getCellContent`, which is the only thing glide watches. See useGetCellContent.
878
+ const [avatarTick, setAvatarTick] = useState(0);
879
+ useEffect(() => {
880
+ setAvatarRepaint(() => setAvatarTick((t) => t + 1));
881
+ return () => setAvatarRepaint(undefined);
882
+ }, []);
883
+ const userAvatars = payload?.workspace?.userAvatars;
884
+ /**
885
+ * Item 15 β€” the frozen strip's usable width, which is what a GROUP BAR's label is clipped to
886
+ * now that the first column is pinned in every mode. `null` when nothing is grouped (no bar to
887
+ * clip) β€” see `fitGroupLabel` for why the clip exists and why the count outranks the name.
888
+ */
889
+ const groupLabelSpace = useMemo(() => {
890
+ if (!config.groupBy) return null;
891
+ const n = Math.min(frozenCountOf(config), visibleCols.length);
892
+ let px = 0;
893
+ // `GridColumn` is a union β€” only its SIZED member declares `width`, and `useGridColumns`
894
+ // always builds that one. Narrowed rather than asserted so an auto-sized column (which we
895
+ // do not create) would read 0 and simply not be counted, instead of throwing in a memo.
896
+ for (let i = 0; i < n; i += 1)
897
+ px += (visibleCols[i] as { width?: number } | undefined)?.width ?? 0;
898
+ return Math.max(0, px - GROUP_LABEL_PAD);
899
+ }, [config, visibleCols]);
900
  const getCellContent = useGetCellContent(
901
  displayRows,
902
  visibleCols,
903
  fieldByKey,
904
  overlayEdits,
905
+ canEditField,
906
+ userAvatars,
907
+ avatarTick,
908
+ groupLabelSpace,
909
+ measureGroupText
910
  );
911
  const { gridSelection, selectedPids, onGridSelectionChange, selectPids, togglePid,
912
  setActiveCell, clearSelection } =
 
1009
  if (args.kind === "cell" && vrow?.kind === "data" && row !== undefined) {
1010
  const pid = vrow.record.pid;
1011
  const b = gridRef.current?.getBounds(0, row);
1012
+ // Clamped to the grid's own box. ⚠ RETARGETED wave-14 item 15: this used to say "with a
1013
+ // grouping active `freezeColumns` is 0, so the primary column scrolls away". It no
1014
+ // longer does β€” the first column is now frozen in EVERY mode. The clamp stays because
1015
+ // its other half is still live: glide's bounds are VIEWPORT coordinates, so a row
1016
+ // scrolled under the header or past the bottom still reports a rect outside the grid,
1017
+ // and a `position: fixed` button with no clamp would paint over the chrome on a row
1018
+ // nobody can see. The horizontal legs are now defence in depth (a column drag, a box
1019
+ // narrower than the frozen strip) rather than the everyday case.
1020
  const at = b
1021
  ? expandButtonRect(b, gridBoxRef.current?.getBoundingClientRect())
1022
  : null;
 
1172
  */
1173
  const drawGridHeader = useCallback<DrawHeaderCallback>(
1174
  (args, drawContent) => {
 
1175
  const field = args.column.id ? fieldByKey.get(args.column.id) : undefined;
1176
+ // ⚠⚠ WAVE-14 ITEM 2 β€” THE ONE LINE THAT MAKES AN INVOLVED HEADER BOLD, and it is not a
1177
+ // font setting anywhere near where you would look for one.
1178
+ //
1179
+ // glide's `drawGridHeaders` does, verbatim:
1180
+ // if (theme !== outerTheme) ctx.font = theme.baseFontFull; // :38-40
1181
+ // i.e. the moment a column carries ANY `themeOverride` its header title is painted in the
1182
+ // CELL font ("13px") instead of the header font ("600 13px"). That is why the owner's
1183
+ // filtered/sorted/grouped headers had already lost their weight β€” nothing in our code
1184
+ // asked for it, and setting `headerFontStyle` on the involved theme alone would have
1185
+ // changed precisely nothing, because glide never reads it on that path. Re-asserting the
1186
+ // MERGED theme's header font on the ctx here is what puts it back, for every column,
1187
+ // uniformly: on a column with no override this is a no-op (glide set the same value at
1188
+ // :21), and glide's own save/restore around each column stops it leaking to the next.
1189
+ //
1190
+ // Built from `headerFontStyle` + `fontFamily` rather than reading `headerFontFull`,
1191
+ // which is real at runtime but is declared on `FullTheme`, not the public `Theme` the
1192
+ // callback is typed with β€” same string, no cast, and it is exactly how
1193
+ // `mergeAndRealizeTheme` composes it.
1194
+ //
1195
+ // Bonus fix, worth knowing: `drawHeaderInner` passes `theme.headerFontFull` to
1196
+ // `getMiddleCenterBias`, which measures with the CURRENT ctx font but CACHES under the
1197
+ // string it was handed. Before this line, an overridden column measured its baseline bias
1198
+ // in the 13px font and filed it under the "600 13px" key, so whichever column drew first
1199
+ // decided the vertical centring for all of them.
1200
+ args.ctx.font = `${args.theme.headerFontStyle} ${args.theme.fontFamily}`;
1201
+ drawContent();
1202
+ if (!field) return;
1203
+ const hasInfo = !!(field.note || field.description);
1204
+ const isCustom = field.source === "overlay";
1205
+ // ONE layout for both marks, from the same `headerMarkSizes` order `useGridColumns` used
1206
+ // to reserve the label's room β€” so the number of marks drawn and the number reserved for
1207
+ // cannot disagree. null = the column is too narrow to carry them without covering its own
1208
+ // label, and then NOTHING is drawn (all-or-nothing; see headerMarkLayout).
1209
+ const marks = headerMarkLayout(
1210
+ args.rect,
1211
+ args.menuBounds.width,
1212
+ headerMarkSizes(hasInfo, isCustom)
1213
  );
1214
+ if (!marks) return;
1215
+ let slot = 0;
1216
+ if (hasInfo) {
1217
+ const at = marks[slot++];
1218
+ args.spriteManager.drawSprite(
1219
+ "aiosInfo",
1220
+ "normal",
1221
+ args.ctx,
1222
+ at.x,
1223
+ at.y,
1224
+ at.size,
1225
+ args.theme
1226
+ );
1227
+ }
1228
+ if (isCustom) {
1229
+ // Wave-14 item 1 / R11 β€” the user-created-field marker that REPLACES the yellow header
1230
+ // wash. A muted dot: quiet enough to ignore while reading, present enough to answer
1231
+ // "which of these columns are mine?" at a glance. Never a background β€” the owner killed
1232
+ // the wash, and a paler wash would have been the same answer in a lower voice.
1233
+ const at = marks[slot++];
1234
+ const ctx = args.ctx;
1235
+ ctx.save();
1236
+ ctx.beginPath();
1237
+ ctx.arc(at.x + at.size / 2, at.y + at.size / 2, at.size / 2, 0, Math.PI * 2);
1238
+ ctx.fillStyle = CUSTOM_FIELD_MARK;
1239
+ ctx.fill();
1240
+ ctx.restore();
1241
+ }
1242
  },
1243
  [fieldByKey]
1244
  );
 
2461
  * Wave-6 item 11c β€” PIN. "Pin up to this field" freezes every visible column through the
2462
  * clicked one; when the field sits past the clamp (8), it is REORDERED into the frozen
2463
  * prefix first (the contract's wording). Pinning the identity column reads as "just the
2464
+ * identity" = the legacy 1, stored as ABSENT.
2465
+ *
2466
+ * ⚠ CORRECTED wave-14 item 15. This used to read "Grouped mode paints frozenCount 0 (spans
2467
+ * break under freezing)". **Spans do not break under freezing** β€” glide splits them
2468
+ * (`getSpanBounds` β†’ `[frozenRect, contentRect]`) and draws the row's contents from the frozen
2469
+ * half. What IS true, and is the real cost of the pin, is that those contents are then clipped
2470
+ * to the frozen strip's width; `fitGroupLabel` is what makes that clip honest. The clamp is
2471
+ * gone: `freezeColumns` is `frozenN` in every mode.
2472
  */
2473
  const visibleKeys = useMemo(
2474
  () => order.filter((key) => visible.has(key)),
2475
  [order, visible]
2476
  );
2477
+ const frozenN = frozenCountOf(config);
2478
  const pinFieldTo = useCallback(
2479
  (key: string) => {
2480
  const index = visibleKeys.indexOf(key);
 
3044
  // Inventing a name or a count for a set we were given no membership for would be
3045
  // disclosing the very thing the permission gate withheld.
3046
  cohortLock={cohortLockChip}
3047
+ // Wave-14 close-out stitch (HOST): PANEL's item-13 door β€” absent, the
3048
+ // copy-configuration modal renders nowhere (absent beats present-and-inert).
3049
+ // `updateConfig` takes a FULL config, so the partial patch spreads over the
3050
+ // live one; `copyConfig.ts` computed it against this same view's config.
3051
+ copyViews={views.filter((v) => v.id !== activeViewId)}
3052
+ onCopyConfig={(patch) => updateConfig({ ...config, ...patch })}
3053
  fields={fields}
3054
  visible={visible}
3055
  lockedKey={lockedKey}
 
3124
  getCellContent={getCellContent}
3125
  rows={displayRows.length}
3126
  theme={lightTheme}
3127
+ // ⭐ Wave-14 item 15 (R8) β€” was `config.groupBy ? 0 : frozenN`: a grouping UNPINNED
3128
+ // EVERY column, which is the "the first field does not stay pinned" the owner
3129
+ // reported. The clamp existed on the assumption that glide cannot draw a group
3130
+ // bar's `span` across the freeze boundary. **It can, and it is built for it.**
3131
+ // `getSpanBounds` (`data-grid-render.walk.js`) returns `[frozenRect, contentRect]`
3132
+ // β€” it SPLITS a straddling span in two β€” and the cell renderer keys its
3133
+ // already-drawn set on `${row},${startCol},${endCol},${c.sticky}` so the same span
3134
+ // is drawn once per pass, taking `areas[0]` when sticky and `areas[1]` when not.
3135
+ // The scrollable half then sets `skipContents = true`, so the bar's TEXT is painted
3136
+ // by the frozen half and its background continues across the scroll region.
3137
+ // Net effect, which is exactly what was wanted: with a grouping active the group
3138
+ // label rides the pinned first column and stays readable while you scroll right.
3139
+ freezeColumns={frozenN}
3140
  rowHeight={rowHeight}
3141
  headerHeight={36}
3142
  rowMarkers="both"
 
3164
  smoothScrollY
3165
  width={gridSize.width}
3166
  height={gridSize.height}
3167
+ customRenderers={[ratingCellRenderer, userCellRenderer]}
3168
  headerIcons={HEADER_ICONS}
3169
  rightElement={
3170
  // Wave-6 item 4 β€” the far-right "+" of the header row: the create-field
 
3368
  <button
3369
  type="button"
3370
  className="cg-btn cg-btn--danger cg-selbar-remove"
3371
+ style={ONE_LINE}
3372
  onClick={removeSelectionFromCohort}
3373
  >
3374
  Remove from cohort
 
3377
  <button
3378
  type="button"
3379
  className="cg-btn cg-btn--primary cg-selbar-add"
3380
+ style={ONE_LINE}
3381
  ref={selAddRef}
3382
  onClick={() => {
3383
  // Item 4: seed the new-cohort name as `<view name> Β· <today>` β€” today from
 
3394
  Add to cohort
3395
  </button>
3396
  )}
3397
+ <button type="button" className="cg-btn" style={ONE_LINE}
3398
+ onClick={clearSelection}>
3399
  Clear
3400
  </button>
3401
  </div>
 
3625
  <button
3626
  type="button"
3627
  className="cg-btn cg-btn--primary"
3628
+ style={ONE_LINE}
3629
  disabled={!selListName.trim()}
3630
  onClick={() => addSelectionToList("", selListName.trim())}
3631
  >
 
3700
  <button
3701
  type="button"
3702
  className="cg-btn cg-btn--primary"
3703
+ style={ONE_LINE}
3704
  disabled={addCustPicked.size === 0}
3705
  onClick={addCustomersToCohort}
3706
  >
 
3713
  <button
3714
  type="button"
3715
  className="cg-btn"
3716
+ style={ONE_LINE}
3717
  onClick={() => setAddCustOpen(false)}
3718
  >
3719
  Cancel
 
3823
  closePicker();
3824
  }}
3825
  >
3826
+ {/* Wave-14 item 11 / R6 β€” a PICKER shows the avatar AND the name. The grid
3827
+ cell shows the face alone (you already know who your people are); this is
3828
+ where you find out which face is whose, so dropping the name here would
3829
+ make the feature unusable the first time two colleagues share initials.
3830
+ ⚠ Inline styles, no new class rules: `index.css` is PANEL's fence this
3831
+ wave. The class name is a QA hook only and styles nothing. */}
3832
+ {pickerField.type === "user" && (
3833
+ <span
3834
+ className="cg-pick-avatar"
3835
+ aria-hidden="true"
3836
+ style={{
3837
+ display: "inline-flex",
3838
+ alignItems: "center",
3839
+ justifyContent: "center",
3840
+ flex: "0 0 auto",
3841
+ width: 20,
3842
+ height: 20,
3843
+ borderRadius: "50%",
3844
+ overflow: "hidden",
3845
+ marginRight: 8,
3846
+ fontSize: 9,
3847
+ fontWeight: 600,
3848
+ lineHeight: 1,
3849
+ position: "relative",
3850
+ background: pickTint(choice).bg,
3851
+ color: pickTint(choice).fg,
3852
+ }}
3853
+ >
3854
+ {/* ⚠ The initials are ALWAYS rendered and the photo is laid OVER them, so
3855
+ a corrupt data URL hides itself and the fallback is already underneath.
3856
+ C-AVATAR's rule is "never a broken-image glyph, anywhere" β€” the canvas
3857
+ path honours it via `img.onerror`, and this is the DOM path's version
3858
+ of the same promise. It cannot fire until HOST serves a photo, which is
3859
+ exactly why it is easy to ship without. */}
3860
+ {avatarInitials(choice)}
3861
+ {userAvatars?.[choice] && (
3862
+ <img
3863
+ src={userAvatars[choice]}
3864
+ alt=""
3865
+ onError={(e) => {
3866
+ e.currentTarget.style.visibility = "hidden";
3867
+ }}
3868
+ style={{
3869
+ position: "absolute",
3870
+ inset: 0,
3871
+ width: "100%",
3872
+ height: "100%",
3873
+ objectFit: "cover",
3874
+ }}
3875
+ />
3876
+ )}
3877
+ </span>
3878
+ )}
3879
  <span
3880
  className="cg-pick-pill"
3881
  style={tint ? { background: tint.bg, color: tint.fg } : undefined}
 
3891
  <button
3892
  type="button"
3893
  className="cg-btn"
3894
+ style={ONE_LINE}
3895
  onClick={closePicker}
3896
  >
3897
  Done
 
3985
  }
3986
  onNotesCommit={(key, value) => patchOverlay(detailPid, { [key]: value })}
3987
  viewer={viewer}
3988
+ // Wave-14 close-out stitch (HOST): TSREC's two light-switch props, unwired when
3989
+ // the GRID session ended β€” item 9's picker vocabulary + item 11's photos. Same
3990
+ // values the grid's own surfaces already read (the wave-13 sixth-prop precedent).
3991
+ userOptions={payload?.userOptions ?? []}
3992
+ userAvatars={userAvatars}
3993
  />
3994
  )}
3995
  </div>
web/src/customer-grid/FieldSelect.tsx ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / FieldSelect.tsx
3
+ // Wave-14 item 20 (contract C-FLDSEL) β€” the field picker that can show an icon.
4
+ //
5
+ // A native <select> cannot render a mark beside an option, so every surface that
6
+ // asks "which field?" was a bare list of labels while the column header, the
7
+ // Hide-fields panel and the create picker all wore the type vocabulary. This is
8
+ // that vocabulary's fourth painter: a button in the `.cg-select` footprint that
9
+ // opens a listbox of icon + label rows.
10
+ //
11
+ // THREE STATES, not two β€” the whole reason this replaces a <select>:
12
+ // unset -> the PLACEHOLDER, never the first field
13
+ // set and offered -> that field's mark + label
14
+ // set but NOT offered -> the field's own label if the caller still passes it
15
+ // (Toolbar's `withCurrentField` does), else the raw key
16
+ // in a muted "missing" slot
17
+ // The third is why `<select>` was dangerous here: a `value` matching no <option>
18
+ // renders the FIRST one, so a saved view holding a dropped column displayed a
19
+ // different field than it held and the first edit wrote that displayed one back
20
+ // ([[cg-condition-builder-items]]).
21
+ //
22
+ // The rows are real <button>s under role="listbox"/role="option", exactly as
23
+ // ColumnMenu's TypePicker ships them: Enter/Space activate natively, Tab moves,
24
+ // and the arrow keys are the only thing this file has to add.
25
+ // ---------------------------------------------------------------------------
26
+
27
+ import { Fragment, useMemo, useRef, useState } from "react";
28
+ import type { KeyboardEvent as ReactKeyboardEvent, ReactNode } from "react";
29
+ import { AnchoredOverlay } from "./OverlaySurface";
30
+ import { FieldTypeIcon } from "./icons";
31
+ import { TYPE_LABELS } from "./iconShapes";
32
+ import type { FieldType } from "./types";
33
+
34
+ /** The pseudo-kind rides along: a metric is picked from these lists like a column is. */
35
+ export type FieldSelectType = FieldType | "measure";
36
+
37
+ export interface FieldSelectItem {
38
+ key: string;
39
+ label: string;
40
+ /** The type mark. Omit only when `icon` supplies a mark from another vocabulary. */
41
+ type?: FieldSelectType;
42
+ /** Overrides the type mark β€” the copy-configuration modal picks VIEWS, which wear their
43
+ * display-mode mark rather than a field type. */
44
+ icon?: ReactNode;
45
+ /** A quiet heading above this row. Rows are rendered in the order given; a heading is
46
+ * emitted whenever the group CHANGES, so the caller owns the grouping by ordering its
47
+ * own list. ⚠ Do not group the filter builder's field list β€” owner item 1 of the previous
48
+ * wave made that ONE FLAT LIST on purpose. */
49
+ group?: string;
50
+ /** A second line under the label (a metric's period, a view's mode). */
51
+ hint?: string;
52
+ disabled?: boolean;
53
+ }
54
+
55
+ /** Re-exported so a consumer needs one import for the pair (C-FLDSEL names both). */
56
+ export { FieldTypeIcon };
57
+
58
+ function ItemMark({ item }: { item: FieldSelectItem }) {
59
+ if (item.icon) return <>{item.icon}</>;
60
+ if (!item.type) return <span className="cg-fsel-nomark" aria-hidden />;
61
+ return (
62
+ <FieldTypeIcon
63
+ type={item.type}
64
+ title={item.type === "measure" ? "Metric" : TYPE_LABELS[item.type]}
65
+ />
66
+ );
67
+ }
68
+
69
+ function CaretDown() {
70
+ return (
71
+ <svg
72
+ className="cg-fsel-caret"
73
+ width="10"
74
+ height="10"
75
+ viewBox="0 0 16 16"
76
+ fill="none"
77
+ aria-hidden
78
+ >
79
+ <path
80
+ d="M4 6l4 4 4-4"
81
+ stroke="currentColor"
82
+ strokeWidth={1.5}
83
+ strokeLinecap="round"
84
+ strokeLinejoin="round"
85
+ />
86
+ </svg>
87
+ );
88
+ }
89
+
90
+ function CheckMark() {
91
+ return (
92
+ <svg
93
+ className="cg-type-check"
94
+ width="14"
95
+ height="14"
96
+ viewBox="0 0 16 16"
97
+ fill="none"
98
+ aria-hidden
99
+ >
100
+ <path
101
+ d="m3.5 8.5 3 3 6-6.5"
102
+ stroke="currentColor"
103
+ strokeWidth={1.6}
104
+ strokeLinecap="round"
105
+ strokeLinejoin="round"
106
+ />
107
+ </svg>
108
+ );
109
+ }
110
+
111
+ /** Above this many rows the find box earns its place; below it, it is one more thing to
112
+ * look past on a list you can already see all of. */
113
+ const SEARCH_FROM = 8;
114
+
115
+ export function FieldSelectButton({
116
+ fields,
117
+ value,
118
+ onChange,
119
+ placeholder = "Choose a field…",
120
+ allow,
121
+ ariaLabel,
122
+ className,
123
+ disabled,
124
+ /** Rendered above the list β€” the surface's own sentence ("Group by", "Copy from"). */
125
+ title,
126
+ /** Keeps the picker open after a choice (the reference-inserter picks repeatedly). */
127
+ keepOpen,
128
+ /** Marks this control as its pane's initial focus target β€” the attribute `AnchoredOverlay`'s
129
+ * `initialFocus` selector looks for. A replaced `<select>` that carried it must keep it,
130
+ * or the pane opens with focus nowhere. */
131
+ overlayAutofocus,
132
+ }: {
133
+ fields: readonly FieldSelectItem[];
134
+ value?: string;
135
+ onChange: (key: string) => void;
136
+ placeholder?: string;
137
+ /** Restrict the OFFER by type. The current value is still resolved against the full list,
138
+ * so narrowing the offer never hides what the rule actually holds. */
139
+ allow?: readonly FieldSelectType[];
140
+ ariaLabel?: string;
141
+ className?: string;
142
+ disabled?: boolean;
143
+ title?: string;
144
+ keepOpen?: boolean;
145
+ overlayAutofocus?: boolean;
146
+ }) {
147
+ const [open, setOpen] = useState(false);
148
+ const [q, setQ] = useState("");
149
+ const triggerRef = useRef<HTMLButtonElement>(null);
150
+ const listRef = useRef<HTMLDivElement>(null);
151
+
152
+ const offered = useMemo(
153
+ () =>
154
+ allow
155
+ ? fields.filter((f) => f.type != null && allow.includes(f.type))
156
+ : fields,
157
+ [fields, allow]
158
+ );
159
+ /**
160
+ * ⚠ `""` is a VALUE here, not the absence of one β€” the map's encodings offer an explicit
161
+ * "No colour" row whose key is the empty string, so the list can MARK the none state
162
+ * instead of leaving every row unmarked. Which means "is anything set" cannot be `!!value`,
163
+ * and (the bug this replaced) the label cannot be `current?.label ?? value ?? placeholder`:
164
+ * `??` falls through on null/undefined only, so an empty-string value rendered an EMPTY
165
+ * BUTTON where the placeholder belonged.
166
+ */
167
+ const isSet = value != null;
168
+ // Resolved over the FULL list, never the offer β€” see the three states above.
169
+ const current = isSet ? fields.find((f) => f.key === value) : undefined;
170
+ const needle = q.trim().toLowerCase();
171
+ const shown = needle
172
+ ? offered.filter((f) => f.label.toLowerCase().includes(needle))
173
+ : offered;
174
+
175
+ // No explicit re-focus of the trigger: `AnchoredOverlay`'s `restoreFocus` (default) already
176
+ // returns focus to whatever was focused when it mounted, which is this button. Doing it here
177
+ // too would be a second answer to the same question, and the two would disagree the day the
178
+ // overlay's rule changes.
179
+ const close = () => {
180
+ setOpen(false);
181
+ setQ("");
182
+ };
183
+
184
+ /** Arrow keys move between the option buttons; the find box is part of the loop, so
185
+ * ArrowDown out of it lands on the first row rather than on nothing. */
186
+ const onListKeyDown = (event: ReactKeyboardEvent) => {
187
+ if (event.key !== "ArrowDown" && event.key !== "ArrowUp"
188
+ && event.key !== "Home" && event.key !== "End") return;
189
+ const rows = Array.from(
190
+ listRef.current?.querySelectorAll<HTMLButtonElement>("button.cg-type-row") ?? []
191
+ ).filter((el) => !el.disabled);
192
+ if (!rows.length) return;
193
+ event.preventDefault();
194
+ const at = rows.indexOf(document.activeElement as HTMLButtonElement);
195
+ if (event.key === "Home") return rows[0].focus();
196
+ if (event.key === "End") return rows[rows.length - 1].focus();
197
+ const step = event.key === "ArrowDown" ? 1 : -1;
198
+ // From outside the rows (the find box), Down enters at the top and Up at the bottom.
199
+ const next = at < 0 ? (step === 1 ? 0 : rows.length - 1)
200
+ : (at + step + rows.length) % rows.length;
201
+ rows[next].focus();
202
+ };
203
+
204
+ let lastGroup: string | undefined;
205
+
206
+ return (
207
+ <>
208
+ <button
209
+ ref={triggerRef}
210
+ type="button"
211
+ disabled={disabled}
212
+ className={
213
+ "cg-select cg-fsel" +
214
+ (current ? "" : isSet && value !== "" ? " is-missing" : " is-empty") +
215
+ (className ? ` ${className}` : "")
216
+ }
217
+ aria-label={ariaLabel}
218
+ aria-haspopup="listbox"
219
+ aria-expanded={open}
220
+ data-overlay-autofocus={overlayAutofocus ? true : undefined}
221
+ onClick={() => setOpen((o) => !o)}
222
+ >
223
+ {current ? (
224
+ <ItemMark item={current} />
225
+ ) : (
226
+ // No mark, but the SLOT stays: an unresolvable value and the placeholder both keep
227
+ // the label in the same column as every resolved row above and below them.
228
+ <span className="cg-fsel-nomark" aria-hidden />
229
+ )}
230
+ <span className="cg-fsel-label">
231
+ {/* Set to something this table no longer offers AND the caller did not pass a row
232
+ for it: the key is shown VERBATIM in the amber `is-missing` slot. Unreadable is
233
+ the honest rendering of a broken reference, and it is the one thing a <select>
234
+ could never do β€” it would show its first option instead. */}
235
+ {current?.label ?? (isSet && value !== "" ? value : placeholder)}
236
+ </span>
237
+ <CaretDown />
238
+ </button>
239
+ {open && triggerRef.current && (
240
+ <AnchoredOverlay
241
+ anchor={triggerRef.current}
242
+ className="cg-pop cg-fsel-pop"
243
+ onDismiss={close}
244
+ role="dialog"
245
+ ariaLabel={ariaLabel ?? title ?? "Choose a field"}
246
+ initialFocus={
247
+ offered.length >= SEARCH_FROM ? ".cg-fsel-search input" : "button.cg-type-row"
248
+ }
249
+ dataKind="field-select"
250
+ >
251
+ <div className="cg-fsel-body" onKeyDown={onListKeyDown}>
252
+ {title && <div className="cg-pop-title">{title}</div>}
253
+ {offered.length >= SEARCH_FROM && (
254
+ <div className="cg-type-search cg-fsel-search">
255
+ <svg width="13" height="13" viewBox="0 0 16 16" fill="none" aria-hidden>
256
+ <circle cx="7" cy="7" r="4.4" stroke="currentColor" strokeWidth="1.35" />
257
+ <path
258
+ d="m10.4 10.4 3.1 3.1"
259
+ stroke="currentColor"
260
+ strokeWidth="1.35"
261
+ strokeLinecap="round"
262
+ />
263
+ </svg>
264
+ <input
265
+ type="text"
266
+ value={q}
267
+ placeholder="Find a field…"
268
+ aria-label="Find a field"
269
+ onChange={(event) => setQ(event.target.value)}
270
+ />
271
+ </div>
272
+ )}
273
+ <div className="cg-type-list" role="listbox" ref={listRef}
274
+ aria-label={ariaLabel ?? title ?? "Fields"}>
275
+ {shown.map((item) => {
276
+ const heading = item.group && item.group !== lastGroup ? item.group : null;
277
+ lastGroup = item.group;
278
+ return (
279
+ // A Fragment, not a wrapper: `.cg-type-list` is the flex column that lays
280
+ // the rows out, and a wrapper would need `display: contents` to stay out of
281
+ // the way β€” which drops the element from the accessibility tree in exactly
282
+ // the container that is claiming to be a listbox.
283
+ <Fragment key={item.key}>
284
+ {heading && (
285
+ <div className="cg-fsel-group" role="presentation">
286
+ {heading}
287
+ </div>
288
+ )}
289
+ <button
290
+ type="button"
291
+ role="option"
292
+ disabled={item.disabled}
293
+ aria-selected={item.key === value}
294
+ className={"cg-type-row" + (item.key === value ? " is-on" : "")}
295
+ onClick={() => {
296
+ onChange(item.key);
297
+ if (keepOpen) setQ("");
298
+ else close();
299
+ }}
300
+ >
301
+ <ItemMark item={item} />
302
+ <span className="cg-type-label">
303
+ {item.label}
304
+ {item.hint && <span className="cg-fsel-hint">{item.hint}</span>}
305
+ </span>
306
+ {item.key === value && <CheckMark />}
307
+ </button>
308
+ </Fragment>
309
+ );
310
+ })}
311
+ {shown.length === 0 && (
312
+ <div className="cg-pop-note">
313
+ {offered.length === 0 ? "No field to choose here." : "No field matches."}
314
+ </div>
315
+ )}
316
+ </div>
317
+ </div>
318
+ </AnchoredOverlay>
319
+ )}
320
+ </>
321
+ );
322
+ }
web/src/customer-grid/RecordDetail.css CHANGED
@@ -217,6 +217,206 @@
217
  margin-top: 7px;
218
  }
219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  /* ==========================================================================
221
  Wave 2026-08-02 item 5 (C-LAYOUT) β€” the six-dot reorder handle.
222
  ==========================================================================
@@ -580,6 +780,47 @@
580
  }
581
  }
582
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
583
  @media (prefers-reduced-motion: reduce) {
584
  .cg-record-modal {
585
  animation: none;
 
217
  margin-top: 7px;
218
  }
219
 
220
+ /* ==========================================================================
221
+ Wave 14 item 9 β€” an editor for EVERY user-created field type.
222
+ ==========================================================================
223
+ Until now one type was editable here (notes) and the other eight read. The
224
+ affordance law item 2 established is what makes this scale without a legend:
225
+
226
+ --lp-surface-2 (warm grey) read-only
227
+ --lp-surface (white) yours to change
228
+
229
+ so `--live` is the ONLY thing that says "this responds", across nine row
230
+ shapes. It is deliberately the same white the textarea already used, not a
231
+ new colour: adding a third fill would turn a two-state signal into a puzzle.
232
+
233
+ ONE BOX PER ROW. The controls are borderless and transparent INSIDE the
234
+ slot rather than bordered themselves β€” a bordered input inside a bordered
235
+ slot draws two rectangles 1px apart, which reads as a rendering fault, and
236
+ it would also break the single label-left/value-right grid every other row
237
+ sits on. The focus ring therefore lands on the SLOT (`:focus-within`) and
238
+ the control's own outline is suppressed; the ring is the same 2px inset
239
+ blue as the textarea and the comment composer, because it is the same
240
+ gesture in the same modal.
241
+
242
+ ⚠ `font: inherit` is NOT used on these controls. The `font` shorthand
243
+ RESETS `font-variant-numeric`, which `.cg-detail-value` sets to tabular-nums
244
+ (index.css:2013) β€” so the shorthand would silently un-align every number in
245
+ the panel. The longhands are spelled out instead. */
246
+ .cg-record-main .cg-detail-value--live {
247
+ background: var(--lp-surface);
248
+ }
249
+
250
+ .cg-record-main .cg-detail-value--live:hover:not(:focus-within) {
251
+ border-color: color-mix(in srgb, var(--lp-line) 45%, var(--lp-muted));
252
+ }
253
+
254
+ .cg-record-main .cg-detail-value--live:focus-within {
255
+ outline: 2px solid var(--lp-blue-deep);
256
+ outline-offset: -1px;
257
+ border-color: transparent;
258
+ }
259
+
260
+ /* The slot as a ROW: an avatar, a currency mark or a hint sits beside its
261
+ control instead of above it. */
262
+ .cg-record-main .cg-detail-pickslot {
263
+ display: flex;
264
+ align-items: center;
265
+ gap: 7px;
266
+ }
267
+
268
+ .cg-record-main .cg-detail-select,
269
+ .cg-record-main .cg-detail-input {
270
+ flex: 1 1 auto;
271
+ min-width: 0;
272
+ width: 100%;
273
+ padding: 0;
274
+ border: 0;
275
+ background: transparent;
276
+ color: var(--lp-ink);
277
+ font-family: inherit;
278
+ font-size: inherit;
279
+ font-weight: inherit;
280
+ line-height: 1.45;
281
+ }
282
+
283
+ /* The ring is on the slot; a second one inside it would draw a rectangle
284
+ around a rectangle. */
285
+ .cg-record-main .cg-detail-select:focus,
286
+ .cg-record-main .cg-detail-input:focus {
287
+ outline: none;
288
+ }
289
+
290
+ .cg-record-main .cg-detail-select {
291
+ /* The native arrow is kept β€” it is the only thing that says "pick" once the
292
+ border has been handed to the slot. */
293
+ cursor: pointer;
294
+ margin-left: -2px;
295
+ }
296
+
297
+ .cg-record-main .cg-detail-input--num {
298
+ text-align: right;
299
+ }
300
+
301
+ /* Spinners removed, and not for looks: this panel SCROLLS, and a wheel event
302
+ over a focused number input changes the value in Chrome. A currency figure
303
+ silently edited by scrolling past it is data loss with no gesture behind it.
304
+ The right-aligned tabular figure and the unit mark carry the type. */
305
+ .cg-record-main .cg-detail-input--num::-webkit-outer-spin-button,
306
+ .cg-record-main .cg-detail-input--num::-webkit-inner-spin-button {
307
+ appearance: none;
308
+ margin: 0;
309
+ }
310
+
311
+ .cg-record-main .cg-detail-input--num {
312
+ -moz-appearance: textfield;
313
+ appearance: textfield;
314
+ }
315
+
316
+ .cg-record-main .cg-detail-unit,
317
+ .cg-record-main .cg-detail-hint {
318
+ flex: 0 0 auto;
319
+ color: var(--lp-muted);
320
+ font-size: var(--lp-fs-2xs);
321
+ }
322
+
323
+ .cg-record-main .cg-detail-hint {
324
+ font-style: italic;
325
+ }
326
+
327
+ .cg-record-main .cg-detail-nochoice {
328
+ color: var(--lp-muted);
329
+ font-size: var(--lp-fs-2xs);
330
+ }
331
+
332
+ /* Multiselect: a chip row, not a `<select multiple>`. The native control needs
333
+ ctrl-click for a second value and paints a four-row scrollbox for a
334
+ three-choice field; a chip says its own state and takes one click. */
335
+ .cg-record-main .cg-detail-chips {
336
+ display: flex;
337
+ flex-wrap: wrap;
338
+ gap: 5px;
339
+ }
340
+
341
+ .cg-record-main .cg-detail-chip {
342
+ height: 22px;
343
+ padding: 0 9px;
344
+ border: 1px solid var(--lp-line);
345
+ border-radius: var(--lp-r-pill);
346
+ background: var(--lp-surface-2);
347
+ color: var(--lp-muted);
348
+ font-family: inherit;
349
+ font-size: var(--lp-fs-2xs);
350
+ line-height: 1;
351
+ white-space: nowrap;
352
+ cursor: pointer;
353
+ }
354
+
355
+ .cg-record-main .cg-detail-chip:hover {
356
+ border-color: var(--lp-blue-deep);
357
+ }
358
+
359
+ /* Tint fills, `-deep` on the text β€” the brand rule. The base pastel is not a
360
+ readable ink at 12px. */
361
+ .cg-record-main .cg-detail-chip.is-on {
362
+ border-color: var(--lp-blue-deep);
363
+ background: var(--lp-blue-tint);
364
+ color: var(--lp-blue-deep);
365
+ font-weight: 600;
366
+ }
367
+
368
+ .cg-record-main .cg-detail-chip:focus-visible {
369
+ outline: 2px solid var(--lp-blue-deep);
370
+ outline-offset: 1px;
371
+ }
372
+
373
+ /* Rating: the stars ARE the picker. Clicking the lit star clears the value β€”
374
+ without it a rating could be changed here but never removed. */
375
+ .cg-record-main .cg-detail-stars {
376
+ display: inline-flex;
377
+ align-items: center;
378
+ gap: 1px;
379
+ }
380
+
381
+ .cg-record-main .cg-detail-star {
382
+ display: grid;
383
+ place-items: center;
384
+ padding: 0 1px;
385
+ border: 0;
386
+ background: transparent;
387
+ color: inherit;
388
+ cursor: pointer;
389
+ line-height: 0;
390
+ }
391
+
392
+ .cg-record-main .cg-detail-star:focus-visible {
393
+ outline: 2px solid var(--lp-blue-deep);
394
+ outline-offset: 1px;
395
+ border-radius: var(--lp-r-sm);
396
+ }
397
+
398
+ /* ==========================================================================
399
+ Wave 14 item 11 (C-AVATAR) β€” the person, as a face.
400
+ ==========================================================================
401
+ R6: cells show the disc alone; here it sits BESIDE the name, because two
402
+ initials at 20px identify nobody by themselves. The initials pastel is
403
+ `pickTint`'s hash β€” the same one the option pills use β€” so one person is one
404
+ colour on every surface, and it is the DESIGNED state rather than the error
405
+ state: every deployment renders it until a photo is uploaded. */
406
+ .cg-record-main .cg-detail-avatar {
407
+ flex: 0 0 auto;
408
+ width: 20px;
409
+ height: 20px;
410
+ display: inline-grid;
411
+ place-items: center;
412
+ border-radius: 50%;
413
+ object-fit: cover;
414
+ font-size: 9px;
415
+ font-weight: 700;
416
+ letter-spacing: 0.01em;
417
+ line-height: 1;
418
+ }
419
+
420
  /* ==========================================================================
421
  Wave 2026-08-02 item 5 (C-LAYOUT) β€” the six-dot reorder handle.
422
  ==========================================================================
 
780
  }
781
  }
782
 
783
+ /* ==========================================================================
784
+ Wave 14 R7 β€” one line, no wraps: the record modal's button rows.
785
+ ==========================================================================
786
+ Audited every row of controls this session renders. Two were real risks and
787
+ the rest were already sound, which is worth recording so the next sweep does
788
+ not re-derive it:
789
+
790
+ Β· the header (β€Ή β€Ί Β· "Record 3 of 1,234" Β· Γ—) β€” the buttons are fixed
791
+ 28px squares, but the POSITION is variable text in a 44/46px fixed-height
792
+ row. At a narrow width it wrapped to two lines and pushed itself out of
793
+ the header it lives in.
794
+ Β· the comment composer's foot β€” a character counter opposite a Post
795
+ button under `space-between`; the counter wrapped before the button
796
+ shrank, which moved the button off its baseline.
797
+ Β· Documents rows were ALREADY correct (index.css: name ellipsises,
798
+ meta and delete are `flex: 0 0 auto`) β€” left alone.
799
+ Β· the tab row, the chip rows and the star row are new this wave and were
800
+ built nowrap; the declarations below are what make that a rule rather
801
+ than a coincidence of the current labels.
802
+
803
+ `nowrap` is the assertion. A label that outgrows its space now overflows
804
+ VISIBLY instead of quietly reflowing β€” the failure you can see beats the one
805
+ you cannot. */
806
+ .cg-record-modal .cg-detail-pos,
807
+ .cg-record-tab,
808
+ .cg-record-main .cg-detail-chip,
809
+ .cg-record-comment-compose-foot button {
810
+ white-space: nowrap;
811
+ }
812
+
813
+ .cg-record-comment-compose-foot span {
814
+ min-width: 0;
815
+ overflow: hidden;
816
+ text-overflow: ellipsis;
817
+ white-space: nowrap;
818
+ }
819
+
820
+ .cg-record-comment-compose-foot button {
821
+ flex: 0 0 auto;
822
+ }
823
+
824
  @media (prefers-reduced-motion: reduce) {
825
  .cg-record-modal {
826
  animation: none;
web/src/customer-grid/RecordDetail.tsx CHANGED
@@ -2,9 +2,26 @@ import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "re
2
  import type { ReactNode, TextareaHTMLAttributes } from "react";
3
  import { BodyPortal, useOverlayLayer } from "./OverlaySurface";
4
  import { checkboxOn, formatDisplay } from "./cells";
5
- import { StarRow } from "./Stars";
6
  import { isPickType, mayEditField, ratingMax } from "./types";
7
  import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  // C-EMBED β€” the ONLY thing item 13 takes from the grid's side of the house. Not a hook, not a
9
  // context, not a slice of CustomerGrid's state: the panel was written to receive every input
10
  // as a prop precisely so it could be mounted twice, and importing anything else from over
@@ -67,6 +84,24 @@ export interface RecordDetailProps {
67
  * question nobody asked. The tab appears the moment the host says which surface this is.
68
  */
69
  scope?: SurfaceScope;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  }
71
 
72
  /**
@@ -134,6 +169,45 @@ function AutoTextarea({
134
  return <textarea ref={ref} value={value} {...rest} />;
135
  }
136
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
  /** The six dots. An inline SVG, never a glyph β€” the owner constant, and `β Ώ` renders as a
138
  * different width in every fallback font the grid has been seen in. */
139
  function SixDots() {
@@ -169,6 +243,8 @@ export default function RecordDetail({
169
  recordLayout,
170
  onRecordLayout,
171
  scope,
 
 
172
  }: RecordDetailProps) {
173
  const panelRef = useRef<HTMLDivElement>(null);
174
  const titleId = useId();
@@ -176,12 +252,17 @@ export default function RecordDetail({
176
  const title = String(record[titleKey] ?? "Untitled");
177
  const showComments = !isStreamlitComponent();
178
  const overlayFields = fields.filter((field) => field.source === "overlay");
179
- // Picked fields (select / assignee / multiselect) are PICKED, NEVER TYPED β€” a textarea here
180
- // would let "Done", "done" and "DONE" into a constrained column through the side door. They
181
- // render read-only in the drawer; editing them stays with the grid's anchored picker.
182
- // Wave-5: rating joins the read-only set for the same reason (its picker is the door), a
183
- // checkbox gets a real checkbox, and a field the VIEWER may not edit renders read-only β€”
184
- // the drawer must not be the side door around field permissions either.
 
 
 
 
 
185
  const typedOverlay = overlayFields.filter(
186
  (field) =>
187
  !isPickType(field.type) &&
@@ -350,16 +431,31 @@ export default function RecordDetail({
350
 
351
  /** One row of the interleaved list: the handle, the label, and the type's own value slot. */
352
  const renderRow = (field: Field, index: number) => {
353
- const editable = field.source === "overlay" && mayEditField(field, viewer);
354
- const isTyped =
355
- field.source === "overlay" &&
 
 
 
 
 
 
 
 
 
 
356
  !isPickType(field.type) &&
357
  field.type !== "checkbox" &&
358
- field.type !== "rating";
359
- const isEdit = editable && isTyped;
 
 
 
 
360
  const cls =
361
  "cg-detail-field" +
362
  (isEdit ? " cg-detail-field--edit" : "") +
 
363
  (dropKey === field.key ? " is-dropzone" : "") +
364
  (dragKey === field.key ? " is-dragging" : "");
365
 
@@ -374,7 +470,7 @@ export default function RecordDetail({
374
  // width, which the mobile breakpoint changes.
375
  <div className="cg-detail-editwrap">
376
  <AutoTextarea
377
- id={`cg-ov-${field.key}`}
378
  className="cg-detail-textarea"
379
  value={raw}
380
  placeholder={`Add ${field.label.toLowerCase()}…`}
@@ -402,7 +498,7 @@ export default function RecordDetail({
402
  } else if (field.source === "overlay" && field.type === "checkbox") {
403
  slot = (
404
  <input
405
- id={`cg-ov-${field.key}`}
406
  type="checkbox"
407
  className="cg-detail-checkbox"
408
  checked={checkboxOn(record[field.key] as string | number | null)}
@@ -412,36 +508,222 @@ export default function RecordDetail({
412
  }
413
  />
414
  );
415
- } else if (field.source === "overlay" && field.type === "rating") {
416
- const n = Math.max(
417
- 0,
418
- Math.min(ratingMax(field), Math.round(Number(record[field.key]) || 0))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
419
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
  slot = (
421
  <span
422
  className="cg-detail-value"
423
- title="Set from the column's star picker on the table"
 
 
424
  >
425
- <StarRow value={n} max={ratingMax(field)} />
426
  </span>
427
  );
428
  } else {
429
- // Everything read-only, with the reason it is read-only where there is one: a picked
430
- // field has its own door, and a permission-restricted one is not the drawer's to open.
 
431
  const reason =
432
  field.source !== "overlay"
433
  ? undefined
434
- : isPickType(field.type)
435
- ? "Picked from the column's choices on the table"
436
  : "You do not have permission to edit this field";
 
437
  slot = (
438
- <span className="cg-detail-value" title={reason}>
 
439
  {formatDisplay(field, record[field.key]) || "β€”"}
440
  </span>
441
  );
442
  }
443
 
444
- const labelIsFor = isEdit || (field.source === "overlay" && field.type === "checkbox");
 
 
 
 
445
  return (
446
  <div
447
  className={cls}
@@ -471,11 +753,13 @@ export default function RecordDetail({
471
  >
472
  {grip(field, index)}
473
  {labelIsFor ? (
474
- <label className="cg-detail-label" htmlFor={`cg-ov-${field.key}`}>
475
  {field.label}
476
  </label>
477
  ) : (
478
- <span className="cg-detail-label">{field.label}</span>
 
 
479
  )}
480
  {slot}
481
  </div>
 
2
  import type { ReactNode, TextareaHTMLAttributes } from "react";
3
  import { BodyPortal, useOverlayLayer } from "./OverlaySurface";
4
  import { checkboxOn, formatDisplay } from "./cells";
5
+ import { StarRow, StarIcon } from "./Stars";
6
  import { isPickType, mayEditField, ratingMax } from "./types";
7
  import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
8
+ // Item 9 (wave 14) β€” the pure value round-trip. Everything that could silently
9
+ // LOSE a stored value moving it into an editor and back lives there, gated by
10
+ // `web/verify_record_fields.py`; this file is dispatch and markup.
11
+ import {
12
+ choiceEntries,
13
+ composeDateValue,
14
+ composeNumberValue,
15
+ composeRatingValue,
16
+ dateInputValue,
17
+ multiParts,
18
+ numberInputValue,
19
+ ratingValue,
20
+ rawText,
21
+ toggleMulti,
22
+ userInitials,
23
+ } from "./recordFields";
24
+ import { pickTint } from "./choiceColors";
25
  // C-EMBED β€” the ONLY thing item 13 takes from the grid's side of the house. Not a hook, not a
26
  // context, not a slice of CustomerGrid's state: the panel was written to receive every input
27
  // as a prop precisely so it could be mounted twice, and importing anything else from over
 
84
  * question nobody asked. The tab appears the moment the host says which surface this is.
85
  */
86
  scope?: SurfaceScope;
87
+ /**
88
+ * Wave 14 item 9 β€” the assignable people for `user`-type fields, from
89
+ * `CustomersPayload.userOptions`. A `user` field takes its vocabulary from the HOST, not
90
+ * from the field definition, so this is the one thing item 9 cannot build for itself.
91
+ *
92
+ * ⚠ ABSENT (or empty) RENDERS THE FIELD READ-ONLY, never an empty picker: a picker with no
93
+ * choices is a writer whose only reachable value is `""`, so opening it could clear an
94
+ * assignment and could never set one. The grid says the same thing in words when it hits
95
+ * this state (`CustomerGrid.tsx:3632`).
96
+ */
97
+ userOptions?: string[];
98
+ /**
99
+ * Wave 14 item 11 (C-AVATAR) β€” `username β†’ data URL`, from `GridWorkspace.userAvatars`.
100
+ * Absent, or missing this user, renders the initials fallback: a deterministic pastel disc,
101
+ * never a broken-image glyph. The photo is an upgrade to a complete surface, not a
102
+ * dependency of one.
103
+ */
104
+ userAvatars?: Record<string, string>;
105
  }
106
 
107
  /**
 
169
  return <textarea ref={ref} value={value} {...rest} />;
170
  }
171
 
172
+ /**
173
+ * Wave 14 item 11 (C-AVATAR) β€” one person, as a face.
174
+ *
175
+ * R6: the grid's CELLS show the photo/icon ONLY; the record modal and its pickers show the
176
+ * avatar **and the name**. So this renders the disc alone and its callers put the name beside
177
+ * it β€” the disc is 20px here, and two initials at that size identify nobody on their own.
178
+ *
179
+ * **Fallback FIRST, on purpose.** The photo is `userAvatars[name]` when the host has one, and
180
+ * the initials disc when it does not β€” which is every deployment until C-AVATAR lands, plus
181
+ * every user who never uploaded one, plus every render before the workspace read returns.
182
+ * That is the majority state, not the error state, so it is the one that is designed: a
183
+ * deterministic pastel from `pickTint` (the same hash the option pills use, so the same person
184
+ * is the same colour everywhere) and never a broken-image glyph.
185
+ *
186
+ * ⚠ Data URLs only. C-AVATAR is explicit that these are never fetched from an external host β€”
187
+ * same-origin-safe, CSP-safe, and no third party learns who is looking at which record.
188
+ */
189
+ function UserAvatar({
190
+ name,
191
+ avatars,
192
+ }: {
193
+ name: string;
194
+ avatars?: Record<string, string>;
195
+ }) {
196
+ const photo = avatars?.[name];
197
+ if (photo && photo.startsWith("data:image/"))
198
+ return <img className="cg-detail-avatar" src={photo} alt="" aria-hidden />;
199
+ const tint = pickTint(name);
200
+ return (
201
+ <span
202
+ className="cg-detail-avatar cg-detail-avatar--initials"
203
+ style={{ background: tint.bg, color: tint.fg }}
204
+ aria-hidden
205
+ >
206
+ {userInitials(name)}
207
+ </span>
208
+ );
209
+ }
210
+
211
  /** The six dots. An inline SVG, never a glyph β€” the owner constant, and `β Ώ` renders as a
212
  * different width in every fallback font the grid has been seen in. */
213
  function SixDots() {
 
243
  recordLayout,
244
  onRecordLayout,
245
  scope,
246
+ userOptions,
247
+ userAvatars,
248
  }: RecordDetailProps) {
249
  const panelRef = useRef<HTMLDivElement>(null);
250
  const titleId = useId();
 
252
  const title = String(record[titleKey] ?? "Untitled");
253
  const showComments = !isStreamlitComponent();
254
  const overlayFields = fields.filter((field) => field.source === "overlay");
255
+ // ⚠ These five buckets are the DEFAULT ORDER of the interleaved list (C-LAYOUT) and NOTHING
256
+ // ELSE. They used to double as the editability split β€” picked/rating fields rendered
257
+ // read-only here because "their picker is the door" β€” and **wave-14 item 9 removes that
258
+ // split entirely**: every user-created type now has its own editor in this panel, and the
259
+ // constrained types get a CONSTRAINED control (a select, a chip row, a star row), never a
260
+ // textarea. The concern the old comment protected was letting "Done", "done" and "DONE" into
261
+ // a closed vocabulary through a free-text side door; a picker cannot do that.
262
+ //
263
+ // The one gate that survives is `mayEditField` β€” stratum, read-only-by-nature
264
+ // (formula/created_time) and the viewer's permissions, in one verdict. The drawer must not
265
+ // be the side door around field permissions either.
266
  const typedOverlay = overlayFields.filter(
267
  (field) =>
268
  !isPickType(field.type) &&
 
431
 
432
  /** One row of the interleaved list: the handle, the label, and the type's own value slot. */
433
  const renderRow = (field: Field, index: number) => {
434
+ const inputId = `cg-ov-${field.key}`;
435
+ // ONE verdict, `types.mayEditField` β€” stratum + read-only-by-nature + permissions.
436
+ // No second permission test anywhere below: a `formula` or `created_time` field must stay
437
+ // read-only after item 9, and that is this function's answer, not a type check of mine.
438
+ const mayEdit = mayEditField(field, viewer);
439
+ // The ONE exception, and it is a vocabulary problem rather than a permission one: a `user`
440
+ // field with no supplied people has nothing to offer, so it reads rather than pretends.
441
+ const noVocabulary = field.type === "user" && !userOptions?.length;
442
+ const editable = mayEdit && !noVocabulary;
443
+ // The free-TEXT family keeps the AutoTextarea (and the `--edit` class its CSS chain hangs
444
+ // off). Every other editable type gets a constrained control below.
445
+ const isEdit =
446
+ editable &&
447
  !isPickType(field.type) &&
448
  field.type !== "checkbox" &&
449
+ field.type !== "rating" &&
450
+ field.type !== "date" &&
451
+ field.type !== "int" &&
452
+ field.type !== "currency" &&
453
+ field.type !== "pct";
454
+ const isControl = editable && !isEdit;
455
  const cls =
456
  "cg-detail-field" +
457
  (isEdit ? " cg-detail-field--edit" : "") +
458
+ (isControl ? " cg-detail-field--control" : "") +
459
  (dropKey === field.key ? " is-dropzone" : "") +
460
  (dragKey === field.key ? " is-dragging" : "");
461
 
 
470
  // width, which the mobile breakpoint changes.
471
  <div className="cg-detail-editwrap">
472
  <AutoTextarea
473
+ id={inputId}
474
  className="cg-detail-textarea"
475
  value={raw}
476
  placeholder={`Add ${field.label.toLowerCase()}…`}
 
498
  } else if (field.source === "overlay" && field.type === "checkbox") {
499
  slot = (
500
  <input
501
+ id={inputId}
502
  type="checkbox"
503
  className="cg-detail-checkbox"
504
  checked={checkboxOn(record[field.key] as string | number | null)}
 
508
  }
509
  />
510
  );
511
+ } else if (isControl && field.type === "rating") {
512
+ // Item 9 β€” the stars ARE the picker now. Clicking the lit star clears the field
513
+ // (`composeRatingValue`): without it a rating could be changed here but never removed,
514
+ // and the grid's separate Clear row has no counterpart in a one-row slot.
515
+ const max = ratingMax(field);
516
+ const n = ratingValue(field, record[field.key]);
517
+ slot = (
518
+ <span
519
+ className="cg-detail-value cg-detail-value--live"
520
+ role="group"
521
+ aria-labelledby={`${inputId}-lbl`}
522
+ >
523
+ <span className="cg-detail-stars">
524
+ {Array.from({ length: max }, (_, i) => i + 1).map((star) => (
525
+ <button
526
+ key={star}
527
+ type="button"
528
+ className="cg-detail-star"
529
+ aria-pressed={star <= n}
530
+ aria-label={
531
+ star === n
532
+ ? `Clear ${field.label}`
533
+ : `${star} star${star === 1 ? "" : "s"}`
534
+ }
535
+ title={star === n ? "Click again to clear" : undefined}
536
+ onClick={() =>
537
+ onNotesCommit(
538
+ field.key,
539
+ composeRatingValue(field, record[field.key], star)
540
+ )
541
+ }
542
+ >
543
+ <StarIcon on={star <= n} />
544
+ </button>
545
+ ))}
546
+ </span>
547
+ </span>
548
  );
549
+ } else if (isControl && (field.type === "select" || field.type === "user")) {
550
+ // A NATIVE select, deliberately (C-FLDSEL swaps the field-CHOOSING surfaces, not the
551
+ // value pickers). The stale entry is what stops the browser's "no matching option β†’
552
+ // paint the FIRST one" behaviour from showing a different choice than the cell holds.
553
+ //
554
+ // ⚠ R6 asks for avatar + NAME in the record modal, and that is what this renders β€” the
555
+ // disc beside the picker, which carries the SELECTED person. The option LIST has no
556
+ // avatars because an `<option>` cannot contain an image; that is the same platform
557
+ // limit this wave already ruled on for field-type icons (item 20's whole reason for
558
+ // existing), and the answer there was a custom listbox. Building a second one for user
559
+ // values would trade the native keyboard and a11y behaviour C-FLDSEL explicitly says
560
+ // not to lose, for a picture in a list you are already reading by name.
561
+ const current = rawText(record[field.key]);
562
+ const entries = choiceEntries(field, userOptions, current);
563
+ slot = (
564
+ <span className="cg-detail-value cg-detail-value--live cg-detail-pickslot">
565
+ {field.type === "user" && current !== "" && (
566
+ <UserAvatar name={current} avatars={userAvatars} />
567
+ )}
568
+ <select
569
+ id={inputId}
570
+ className="cg-detail-select"
571
+ value={current}
572
+ onChange={(event) => onNotesCommit(field.key, event.target.value)}
573
+ >
574
+ <option value="">
575
+ {field.type === "user" ? "Unassigned" : "None"}
576
+ </option>
577
+ {entries.map((entry) => (
578
+ <option key={entry.value} value={entry.value}>
579
+ {entry.label}
580
+ </option>
581
+ ))}
582
+ </select>
583
+ </span>
584
+ );
585
+ } else if (isControl && field.type === "multiselect") {
586
+ // A chip row rather than a `<select multiple>`: the native control needs ctrl-click to
587
+ // add a second value and shows a scrollbox of four rows for a three-choice field. Each
588
+ // toggle commits on its own β€” the event log absorbs the burst, exactly as the grid's
589
+ // picker does.
590
+ const current = record[field.key];
591
+ const held = multiParts(current);
592
+ const entries = choiceEntries(field, userOptions, current);
593
+ slot = (
594
+ <span
595
+ className="cg-detail-value cg-detail-value--live"
596
+ role="group"
597
+ aria-labelledby={`${inputId}-lbl`}
598
+ >
599
+ {entries.length === 0 ? (
600
+ <span className="cg-detail-nochoice">
601
+ No choices yet. Add them from the column menu.
602
+ </span>
603
+ ) : (
604
+ <span className="cg-detail-chips">
605
+ {entries.map((entry) => {
606
+ const on = held.includes(entry.value);
607
+ return (
608
+ <button
609
+ key={entry.value}
610
+ type="button"
611
+ className={"cg-detail-chip" + (on ? " is-on" : "")}
612
+ aria-pressed={on}
613
+ title={entry.stale ? "No longer a choice on this field" : undefined}
614
+ onClick={() =>
615
+ onNotesCommit(field.key, toggleMulti(current, entry.value))
616
+ }
617
+ >
618
+ {entry.label}
619
+ </button>
620
+ );
621
+ })}
622
+ </span>
623
+ )}
624
+ </span>
625
+ );
626
+ } else if (isControl && field.type === "date") {
627
+ // `dateInputValue` returns null for text a date input cannot represent. Falling back to
628
+ // a TEXT box there is the whole point: a date picker fed "02/08/2026" paints BLANK, so a
629
+ // record that has a date would look like one that has none β€” and the next save would
630
+ // make that true. See recordFields.ts note (1).
631
+ const current = record[field.key];
632
+ const iso = dateInputValue(current);
633
+ slot =
634
+ iso === null ? (
635
+ <span className="cg-detail-value cg-detail-value--live cg-detail-pickslot">
636
+ <input
637
+ id={inputId}
638
+ type="text"
639
+ className="cg-detail-input"
640
+ value={rawText(current)}
641
+ title="This value is not a date the picker can read β€” it is shown as stored."
642
+ onChange={(event) => onNotesChange(field.key, event.target.value)}
643
+ onBlur={(event) => onNotesCommit(field.key, event.target.value)}
644
+ />
645
+ <span className="cg-detail-hint">not a recognised date</span>
646
+ </span>
647
+ ) : (
648
+ <span className="cg-detail-value cg-detail-value--live">
649
+ <input
650
+ id={inputId}
651
+ type="date"
652
+ className="cg-detail-input"
653
+ value={iso}
654
+ onChange={(event) =>
655
+ onNotesCommit(field.key, composeDateValue(current, event.target.value))
656
+ }
657
+ />
658
+ </span>
659
+ );
660
+ } else if (
661
+ isControl &&
662
+ (field.type === "int" || field.type === "currency" || field.type === "pct")
663
+ ) {
664
+ // The plain number, never the display string: `display.ts` renders "$1,234.50" and a
665
+ // number input rejects the mark and the separator, so a formatted value would render as
666
+ // an EMPTY box over a populated cell. The unit lives beside the box instead.
667
+ const unit = field.type === "currency" ? "$" : field.type === "pct" ? "%" : "";
668
+ slot = (
669
+ <span className="cg-detail-value cg-detail-value--live cg-detail-pickslot">
670
+ {field.type === "currency" && <span className="cg-detail-unit">{unit}</span>}
671
+ <input
672
+ id={inputId}
673
+ type="number"
674
+ className="cg-detail-input cg-detail-input--num"
675
+ value={numberInputValue(record[field.key])}
676
+ step={field.type === "int" ? 1 : "any"}
677
+ placeholder="β€”"
678
+ onChange={(event) => onNotesChange(field.key, event.target.value)}
679
+ onBlur={(event) => {
680
+ // Junk the browser let through is REFUSED, not coerced: `num()` downstream turns
681
+ // it into a real 0, and a fabricated zero on a currency row is a wrong number
682
+ // that reconciles against nothing.
683
+ const next = composeNumberValue(event.target.value);
684
+ if (next === null) onNotesChange(field.key, numberInputValue(record[field.key]));
685
+ else onNotesCommit(field.key, next);
686
+ }}
687
+ />
688
+ {field.type === "pct" && <span className="cg-detail-unit">{unit}</span>}
689
+ </span>
690
+ );
691
+ } else if (field.source === "overlay" && field.type === "rating") {
692
+ // Read-only rating (no permission, or an Odoo-sourced star column).
693
  slot = (
694
  <span
695
  className="cg-detail-value"
696
+ title={
697
+ noVocabulary ? undefined : "You do not have permission to edit this field"
698
+ }
699
  >
700
+ <StarRow value={ratingValue(field, record[field.key])} max={ratingMax(field)} />
701
  </span>
702
  );
703
  } else {
704
+ // Everything read-only, with the reason where there is one. After item 9 a picked field
705
+ // is no longer read-only BY DESIGN, so the only reasons left are real ones: no
706
+ // permission, no vocabulary to pick from, or a value the ERP owns.
707
  const reason =
708
  field.source !== "overlay"
709
  ? undefined
710
+ : noVocabulary
711
+ ? "No assignable people were supplied for this workspace"
712
  : "You do not have permission to edit this field";
713
+ const isUser = field.type === "user" && rawText(record[field.key]) !== "";
714
  slot = (
715
+ <span className={"cg-detail-value" + (isUser ? " cg-detail-pickslot" : "")} title={reason}>
716
+ {isUser && <UserAvatar name={rawText(record[field.key])} avatars={userAvatars} />}
717
  {formatDisplay(field, record[field.key]) || "β€”"}
718
  </span>
719
  );
720
  }
721
 
722
+ // Every native control gets its label back. Without this the label stops being clickable
723
+ // for most of the panel the moment item 9 lands β€” the grouped controls (stars, chips) take
724
+ // `aria-labelledby` instead, because a `<label for>` can only point at ONE element.
725
+ const groupLabel = isControl && (field.type === "rating" || field.type === "multiselect");
726
+ const labelIsFor = !groupLabel && (isEdit || isControl || (field.source === "overlay" && field.type === "checkbox"));
727
  return (
728
  <div
729
  className={cls}
 
753
  >
754
  {grip(field, index)}
755
  {labelIsFor ? (
756
+ <label className="cg-detail-label" htmlFor={inputId}>
757
  {field.label}
758
  </label>
759
  ) : (
760
+ <span className="cg-detail-label" id={groupLabel ? `${inputId}-lbl` : undefined}>
761
+ {field.label}
762
+ </span>
763
  )}
764
  {slot}
765
  </div>
web/src/customer-grid/TimeSeriesPanel.tsx CHANGED
@@ -1,5 +1,5 @@
1
  /**
2
- * TimeSeriesPanel.tsx β€” owner item 7 (contract C-TS): metric ROWS x time-bucket COLUMNS.
3
  *
4
  * ⚠ **HOST-AGNOSTIC ON PURPOSE β€” it reads no CustomerGrid state, ever.** RECORD re-mounts this
5
  * exact component inside the record modal for item 13 (contract C-EMBED) with `pids=[pid]` and
@@ -10,10 +10,22 @@
10
  * `web/verify_timeseries.py` gates under node. This file is layout, fetch orchestration and
11
  * one chart adapter β€” deliberately nothing a wrong number could hide in.
12
  *
13
- * `locked` is the item-13 posture: the pid set is FIXED by the caller (one record) and the
14
- * panel says so rather than pretending the reader chose it. Bucket/span/field controls stay
15
- * live either way β€” the owner's words were that the filter surface is the lock, not the
16
- * controls.
 
 
 
 
 
 
 
 
 
 
 
 
17
  */
18
 
19
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -24,16 +36,42 @@ import { isStreamlitComponent } from "./hostBridge";
24
  import {
25
  DEFAULT_TS_BUCKET,
26
  DEFAULT_TS_LAST_N,
 
27
  buildTsCsv,
28
  buildTsRequest,
 
29
  buildTsTable,
30
  formatTsDelta,
31
  formatTsValue,
 
 
 
32
  tsRowToChartModel,
33
  } from "./timeSeriesData";
34
- import type { TsPayload, TsTable, TsTableRow } from "./timeSeriesData";
35
- import { TS_BUCKETS, TS_MAX_FIELDS } from "./types";
36
- import type { DisplaySpec, Field, TsBucket } from "./types";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  import { toVegaLiteSpec } from "../viz/vega/toVegaLiteSpec";
38
  import VegaLiteChart from "../viz/vega/VegaLiteChart";
39
 
@@ -47,6 +85,10 @@ const BUCKET_LABELS: Record<TsBucket, string> = {
47
  /** The rolling spans offered, per bucket. Capped well inside `TS_MAX_LAST_N`. */
48
  const LAST_N_CHOICES = [6, 12, 24, 36];
49
 
 
 
 
 
50
  export interface TimeSeriesPanelProps {
51
  scope: SurfaceScope;
52
  /** The rows in scope. The server intersects with the caller's book regardless. */
@@ -62,14 +104,22 @@ export interface TimeSeriesPanelProps {
62
  }
63
 
64
  /**
65
- * v1 eligibility, per C-TS: measure-backed fields only. A formula field has no time dimension
66
- * of its own, so it is not offered β€” and the panel says that plainly instead of showing an
67
- * empty picker that looks broken.
68
  */
69
  function measureFields(fields: Field[]): Field[] {
70
  return fields.filter((f) => f.key.startsWith("measure_"));
71
  }
72
 
 
 
 
 
 
 
 
 
73
  export default function TimeSeriesPanel({
74
  scope,
75
  pids,
@@ -94,11 +144,18 @@ export default function TimeSeriesPanel({
94
  return live.length ? live : eligible.slice(0, 1).map((f) => f.key);
95
  }, [display?.tsFields, eligible]);
96
 
 
 
 
 
 
 
 
 
97
  const [payload, setPayload] = useState<TsPayload | null>(null);
98
  const [state, setState] = useState<"idle" | "loading" | "error">("idle");
99
  const [errStatus, setErrStatus] = useState(0);
100
  const [charted, setCharted] = useState<Set<string>>(new Set());
101
- const [showDelta, setShowDelta] = useState(false);
102
  // Guards a slow response from overwriting a newer one β€” the request the user is waiting on
103
  // is the LAST one they asked for, not the last one to arrive.
104
  const reqRef = useRef(0);
@@ -128,15 +185,19 @@ export default function TimeSeriesPanel({
128
  });
129
  }, [embedded, scope, pids, bucket, lastN, selected]);
130
 
131
- const table: TsTable = useMemo(() => buildTsTable(payload), [payload]);
 
 
 
 
132
 
133
  const onCsv = useCallback(() => {
134
- const csv = buildTsCsv(table);
135
  triggerDownload(
136
  "Time series.csv",
137
  new Blob(["ο»Ώ" + csv], { type: "text/csv;charset=utf-8" })
138
  );
139
- }, [table]);
140
 
141
  const toggleChart = useCallback((key: string) => {
142
  setCharted((prev) => {
@@ -147,6 +208,36 @@ export default function TimeSeriesPanel({
147
  });
148
  }, []);
149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  // ── the Streamlit embed. C-TS: an honest placeholder, and above all it must not crash the
151
  // component β€” the grid still runs inside app.py and a throw here would take the page.
152
  if (embedded) {
@@ -160,13 +251,15 @@ export default function TimeSeriesPanel({
160
  if (!eligible.length) {
161
  return (
162
  <div className="cg-mode-empty">
163
- This table has no measure fields yet. A time series needs a metric with a time
164
- dimension β€” add one from a column menu, then pick it here. Formula fields cannot be
165
- charted over time.
166
  </div>
167
  );
168
  }
169
 
 
 
 
170
  return (
171
  <div className="cg-ts">
172
  <div className="cg-ts-bar">
@@ -200,49 +293,57 @@ export default function TimeSeriesPanel({
200
  ))}
201
  </select>
202
  </label>
203
- <button
204
- type="button"
205
- className={"cg-tb-btn" + (showDelta ? " is-on" : "")}
206
- onClick={() => setShowDelta((v) => !v)}
207
- aria-pressed={showDelta}
208
- >
209
- Change vs prior
210
- </button>
211
- <button type="button" className="cg-tb-btn" onClick={onCsv} disabled={table.empty}>
212
- Export CSV
213
- </button>
214
- <span className="cg-ts-pool">
215
- {locked
216
- ? "This record"
217
- : `${table.pool.toLocaleString()} ${table.pool === 1 ? "customer" : "customers"}`}
218
- </span>
219
- </div>
220
 
221
- <div className="cg-ts-fields">
222
- <span className="cg-ts-ctl-k">Metrics</span>
223
- {eligible.map((f) => {
224
- const on = selected.includes(f.key);
225
- return (
226
  <button
227
- key={f.key}
228
  type="button"
229
- className={"cg-ts-chip" + (on ? " is-on" : "")}
230
- aria-pressed={on}
231
  disabled={!onDisplay}
232
- onClick={() => {
233
- const next = on
234
- ? selected.filter((k) => k !== f.key)
235
- : [...selected, f.key].slice(0, TS_MAX_FIELDS);
236
- // Never persist an EMPTY metric list: it would read back as "no data" on the
237
- // next open. Un-picking the last one is a no-op, the same way the grid
238
- // refuses to hide its last column.
239
- if (next.length) onDisplay?.({ tsFields: next });
240
- }}
241
  >
242
- {f.label}
243
  </button>
244
- );
245
- })}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
  </div>
247
 
248
  {state === "error" && (
@@ -257,44 +358,115 @@ export default function TimeSeriesPanel({
257
 
258
  {state === "loading" && !payload && <div className="cg-ts-note">Loading…</div>}
259
 
260
- {payload && table.empty && (
261
- <div className="cg-ts-note">No metrics returned a series for this span.</div>
262
- )}
263
-
264
- {payload && !table.empty && (
265
  <div className="cg-ts-scroll">
266
- <table className="cg-ts-table">
267
  <thead>
268
  <tr>
269
  <th className="cg-ts-stick">Metric</th>
270
- {table.columns.map((c) => (
271
  <th key={c.key} className={c.partial ? "is-partial" : undefined}>
272
  {c.label}
273
  {c.partial && <span className="cg-ts-partial"> Β· partial</span>}
274
  </th>
275
  ))}
276
  <th className="cg-ts-total">Total</th>
 
277
  </tr>
278
  </thead>
279
  <tbody>
280
- {table.rows.map((r) => (
281
  <TsRowBlock
282
- key={r.field}
283
- row={r}
284
- table={table}
285
- showDelta={showDelta}
286
- charted={charted.has(r.field)}
287
- onToggleChart={() => toggleChart(r.field)}
 
 
 
 
 
 
 
 
 
 
 
 
 
288
  />
289
  ))}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
  </tbody>
291
  </table>
292
  </div>
293
  )}
294
 
295
- {table.notes.length > 0 && (
 
 
 
 
296
  <ul className="cg-ts-notes">
297
- {table.notes.map((n) => (
298
  <li key={n}>{n}</li>
299
  ))}
300
  </ul>
@@ -303,8 +475,58 @@ export default function TimeSeriesPanel({
303
  );
304
  }
305
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306
  /**
307
- * One metric: its value row, an optional delta sub-row, and an optional line chart.
308
  *
309
  * The chart is built from `tsRowToChartModel`, NOT from `viz/chartData.buildChartData` β€” see
310
  * that function's note. `buildChartData` caps at 12 buckets, which for a time series means
@@ -312,81 +534,171 @@ export default function TimeSeriesPanel({
312
  */
313
  function TsRowBlock({
314
  row,
315
- table,
316
- showDelta,
 
 
317
  charted,
 
 
318
  onToggleChart,
 
 
 
319
  }: {
320
- row: TsTableRow;
321
- table: TsTable;
322
- showDelta: boolean;
 
 
323
  charted: boolean;
 
 
324
  onToggleChart: () => void;
 
 
 
325
  }) {
326
  const spec = useMemo(() => {
327
- if (!charted) return null;
328
- const model = tsRowToChartModel(row, table.columns);
329
  if (!model.points.length) return null;
330
  return toVegaLiteSpec({
331
- spec: { id: row.field, kind: "line", agg: row.agg as never },
332
  model,
333
  yTitle: row.label,
334
  formatValue: (n) => n.toLocaleString(undefined, { maximumFractionDigits: 2 }),
335
  });
336
- }, [charted, row, table.columns]);
337
 
338
- const colCount = table.columns.length + 2;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
 
340
  return (
341
  <>
342
- <tr>
343
  <th scope="row" className="cg-ts-stick">
344
- <button
345
- type="button"
346
- className="cg-ts-rowbtn"
347
- onClick={onToggleChart}
348
- aria-pressed={charted}
349
- title={charted ? "Show as a row of numbers" : "Show as a line"}
350
- >
351
- {row.label}
352
- </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
353
  </th>
354
- {row.cells.map((c, i) => (
355
- <td
356
- key={table.columns[i]?.key ?? i}
357
- className={c.partial ? "is-partial" : undefined}
358
- >
359
- {formatTsValue(c.value, (n) =>
360
- n.toLocaleString(undefined, { maximumFractionDigits: 2 })
361
- )}
362
- </td>
363
- ))}
 
 
 
 
 
 
364
  <td className="cg-ts-total">
365
  {/* An avg/min/max row has NO total β€” the cell stays empty rather than carrying an
366
- average of averages. See timeSeriesData's header note (2). */}
 
367
  {row.total == null
368
  ? ""
369
  : row.total.toLocaleString(undefined, { maximumFractionDigits: 2 })}
370
  </td>
 
 
 
 
 
371
  </tr>
372
- {showDelta && (
373
- <tr className="cg-ts-delta">
374
- <th scope="row" className="cg-ts-stick">
375
- vs prior
376
- </th>
377
- {row.cells.map((c, i) => (
378
- <td
379
- key={table.columns[i]?.key ?? i}
380
- className={
381
- c.delta == null ? undefined : c.delta >= 0 ? "is-up" : "is-down"
382
- }
383
- >
384
- {formatTsDelta(c.delta)}
385
- </td>
386
- ))}
387
- <td className="cg-ts-total" />
388
- </tr>
389
- )}
390
  {charted && (
391
  <tr className="cg-ts-chartrow">
392
  <td colSpan={colCount}>
@@ -403,3 +715,77 @@ function TsRowBlock({
403
  </>
404
  );
405
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  /**
2
+ * TimeSeriesPanel.tsx β€” owner item 7 (contract C-TS), rebuilt for wave-14 items 16c Β· 17 Β· 18.
3
  *
4
  * ⚠ **HOST-AGNOSTIC ON PURPOSE β€” it reads no CustomerGrid state, ever.** RECORD re-mounts this
5
  * exact component inside the record modal for item 13 (contract C-EMBED) with `pids=[pid]` and
 
10
  * `web/verify_timeseries.py` gates under node. This file is layout, fetch orchestration and
11
  * one chart adapter β€” deliberately nothing a wrong number could hide in.
12
  *
13
+ * ── What wave 14 changed, and why ──────────────────────────────────────────────────────────
14
+ *
15
+ * The panel WAS a chip bar over a fixed table: you toggled metrics on and off above the data,
16
+ * and the table was a read-only report of whatever survived. The owner asked for a SHEET β€”
17
+ * something you build rather than something you filter. So:
18
+ *
19
+ * Β· the metric chips are GONE. A metric is a ROW, added from a "+ Add metric" row at the
20
+ * bottom the way a spreadsheet grows, and removed from the row itself. The list of what is
21
+ * on screen and the list of what could be are the same list, in the same place.
22
+ * Β· rows carry the server's WINDOW LABEL as a sublabel (R1/C-TSWIN). Under identical month
23
+ * headings, a year-to-date row and a trailing-90 row are different claims, and nothing on
24
+ * screen used to say which one you were reading.
25
+ * Β· custom NOTE and FORMULA rows (R2) β€” the reader's own arithmetic, evaluated per column
26
+ * against the resolved buckets, refusing rather than inventing on every failure.
27
+ * Β· "Change vs prior" was ONE toggle producing ONE sub-row. It is now four named comparisons
28
+ * (item 18), each of which can refuse for its own stated reason.
29
  */
30
 
31
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
 
36
  import {
37
  DEFAULT_TS_BUCKET,
38
  DEFAULT_TS_LAST_N,
39
+ TS_DELTA_LABELS,
40
  buildTsCsv,
41
  buildTsRequest,
42
+ buildTsSheet,
43
  buildTsTable,
44
  formatTsDelta,
45
  formatTsValue,
46
+ resolveTsStyle,
47
+ sparklinePoints,
48
+ sparklineSegments,
49
  tsRowToChartModel,
50
  } from "./timeSeriesData";
51
+ import type {
52
+ TsDeltaSubRow,
53
+ TsPayload,
54
+ TsSheet,
55
+ TsSheetRow,
56
+ TsTableRow,
57
+ } from "./timeSeriesData";
58
+ import {
59
+ TS_BUCKETS,
60
+ TS_DELTA_KINDS,
61
+ TS_MAX_CUSTOM_ROWS,
62
+ TS_MAX_FIELDS,
63
+ TS_ROW_LABEL_MAX,
64
+ TS_MAX_EXPR,
65
+ } from "./types";
66
+ import type {
67
+ DisplaySpec,
68
+ Field,
69
+ TsBucket,
70
+ TsCellStyle,
71
+ TsCustomRow,
72
+ TsDeltaKind,
73
+ } from "./types";
74
+ import { FieldSelectButton } from "./FieldSelect";
75
  import { toVegaLiteSpec } from "../viz/vega/toVegaLiteSpec";
76
  import VegaLiteChart from "../viz/vega/VegaLiteChart";
77
 
 
85
  /** The rolling spans offered, per bucket. Capped well inside `TS_MAX_LAST_N`. */
86
  const LAST_N_CHOICES = [6, 12, 24, 36];
87
 
88
+ /** The sparkline's box. Small enough to sit in a table cell, wide enough to have a shape. */
89
+ const SPARK_W = 72;
90
+ const SPARK_H = 18;
91
+
92
  export interface TimeSeriesPanelProps {
93
  scope: SurfaceScope;
94
  /** The rows in scope. The server intersects with the caller's book regardless. */
 
104
  }
105
 
106
  /**
107
+ * v1 eligibility, per C-TS: measure-backed fields only. A formula FIELD has no time dimension
108
+ * of its own, so it is not offered β€” a formula ROW on this sheet is a different thing entirely
109
+ * (R2: arithmetic over the buckets that are already here) and it is offered.
110
  */
111
  function measureFields(fields: Field[]): Field[] {
112
  return fields.filter((f) => f.key.startsWith("measure_"));
113
  }
114
 
115
+ /** A stable-enough id for a new custom row. `TS_ROW_ID_MAX` is 40; this is 12. */
116
+ function newRowId(existing: readonly TsCustomRow[]): string {
117
+ let n = existing.length + 1;
118
+ const taken = new Set(existing.map((r) => r.id));
119
+ while (taken.has(`tsr_${n}`)) n += 1;
120
+ return `tsr_${n}`;
121
+ }
122
+
123
  export default function TimeSeriesPanel({
124
  scope,
125
  pids,
 
144
  return live.length ? live : eligible.slice(0, 1).map((f) => f.key);
145
  }, [display?.tsFields, eligible]);
146
 
147
+ const customRows = useMemo(() => display?.tsRows ?? [], [display?.tsRows]);
148
+ const deltaKinds = useMemo(() => display?.tsDeltas ?? [], [display?.tsDeltas]);
149
+ const styles = display?.tsStyles;
150
+ // ⚠ PRESENCE, not truthiness β€” `tsGridlines` is `false | undefined` and absent means SHOWN.
151
+ // `!display?.tsGridlines` would hide the gridlines on every view that never chose.
152
+ const gridlines = display?.tsGridlines !== false;
153
+ const sparkline = display?.tsSparkline === true;
154
+
155
  const [payload, setPayload] = useState<TsPayload | null>(null);
156
  const [state, setState] = useState<"idle" | "loading" | "error">("idle");
157
  const [errStatus, setErrStatus] = useState(0);
158
  const [charted, setCharted] = useState<Set<string>>(new Set());
 
159
  // Guards a slow response from overwriting a newer one β€” the request the user is waiting on
160
  // is the LAST one they asked for, not the last one to arrive.
161
  const reqRef = useRef(0);
 
185
  });
186
  }, [embedded, scope, pids, bucket, lastN, selected]);
187
 
188
+ const table = useMemo(() => buildTsTable(payload), [payload]);
189
+ const sheet: TsSheet = useMemo(
190
+ () => buildTsSheet(table, { customRows, deltas: deltaKinds, bucket }),
191
+ [table, customRows, deltaKinds, bucket]
192
+ );
193
 
194
  const onCsv = useCallback(() => {
195
+ const csv = buildTsCsv(sheet);
196
  triggerDownload(
197
  "Time series.csv",
198
  new Blob(["ο»Ώ" + csv], { type: "text/csv;charset=utf-8" })
199
  );
200
+ }, [sheet]);
201
 
202
  const toggleChart = useCallback((key: string) => {
203
  setCharted((prev) => {
 
208
  });
209
  }, []);
210
 
211
+ // ── display writers. Each one DELETES its key for the default rather than storing a second
212
+ // spelling of it β€” the `kanbanClamp` law, which `tsGridlines` and `tsSparkline` inherit
213
+ // exactly (the host accepts only the literal `false` / literal `true`).
214
+ const setMetrics = (keys: string[]) => {
215
+ // Never persist an EMPTY metric list: it would read back as "no data" on the next open.
216
+ if (!keys.length) return;
217
+ onDisplay?.({ tsFields: keys.slice(0, TS_MAX_FIELDS) });
218
+ };
219
+ const setRows = (rows: TsCustomRow[]) =>
220
+ onDisplay?.({ tsRows: rows.length ? rows.slice(0, TS_MAX_CUSTOM_ROWS) : undefined });
221
+ const toggleDelta = (kind: TsDeltaKind) => {
222
+ const next = deltaKinds.includes(kind)
223
+ ? deltaKinds.filter((k) => k !== kind)
224
+ : [...deltaKinds, kind];
225
+ onDisplay?.({ tsDeltas: next.length ? next : undefined });
226
+ };
227
+ const setStyle = (rowId: string, patch: TsCellStyle) => {
228
+ const next: Record<string, TsCellStyle> = { ...(styles ?? {}) };
229
+ const merged = { ...resolveTsStyle(styles, rowId), ...patch };
230
+ // A style that reduces to nothing is DELETED, never stored as `{}`: an empty object is the
231
+ // absent state's second spelling, and 200 of them would evict real emphasis under the cap
232
+ // (GRID's C-TYPES2 asymmetry #1, mirrored here so a save round-trips unchanged).
233
+ const kept: TsCellStyle = {};
234
+ if (merged.bold) kept.bold = true;
235
+ if (merged.line) kept.line = true;
236
+ if (kept.bold || kept.line) next[rowId] = kept;
237
+ else delete next[rowId];
238
+ onDisplay?.({ tsStyles: Object.keys(next).length ? next : undefined });
239
+ };
240
+
241
  // ── the Streamlit embed. C-TS: an honest placeholder, and above all it must not crash the
242
  // component β€” the grid still runs inside app.py and a throw here would take the page.
243
  if (embedded) {
 
251
  if (!eligible.length) {
252
  return (
253
  <div className="cg-mode-empty">
254
+ This table has no metric fields yet. A time series needs a metric with a time
255
+ dimension β€” add one from a column menu, then pick it here.
 
256
  </div>
257
  );
258
  }
259
 
260
+ const unused = eligible.filter((f) => !selected.includes(f.key));
261
+ const colCount = sheet.columns.length + 2 + (sparkline ? 1 : 0);
262
+
263
  return (
264
  <div className="cg-ts">
265
  <div className="cg-ts-bar">
 
293
  ))}
294
  </select>
295
  </label>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
296
 
297
+ {/* Item 18 β€” four named comparisons where there used to be one unnamed toggle.
298
+ "Change vs prior" could not say WHICH prior, and there are four honest answers. */}
299
+ <span className="cg-ts-group">
300
+ <span className="cg-ts-ctl-k">Compare</span>
301
+ {TS_DELTA_KINDS.map((kind) => (
302
  <button
303
+ key={kind}
304
  type="button"
305
+ className={"cg-ts-tog" + (deltaKinds.includes(kind) ? " is-on" : "")}
306
+ aria-pressed={deltaKinds.includes(kind)}
307
  disabled={!onDisplay}
308
+ onClick={() => toggleDelta(kind)}
 
 
 
 
 
 
 
 
309
  >
310
+ {TS_DELTA_LABELS[kind]}
311
  </button>
312
+ ))}
313
+ </span>
314
+
315
+ <span className="cg-ts-group">
316
+ <button
317
+ type="button"
318
+ className={"cg-ts-tog" + (gridlines ? " is-on" : "")}
319
+ aria-pressed={gridlines}
320
+ disabled={!onDisplay}
321
+ // The literal `false` is the ONLY storable opt-out; the default is stored by
322
+ // DELETING the key. Writing `true` would be a second spelling the host drops,
323
+ // and the toggle would look broken.
324
+ onClick={() => onDisplay?.({ tsGridlines: gridlines ? false : undefined })}
325
+ >
326
+ Gridlines
327
+ </button>
328
+ <button
329
+ type="button"
330
+ className={"cg-ts-tog" + (sparkline ? " is-on" : "")}
331
+ aria-pressed={sparkline}
332
+ disabled={!onDisplay}
333
+ onClick={() => onDisplay?.({ tsSparkline: sparkline ? undefined : true })}
334
+ >
335
+ Trend
336
+ </button>
337
+ </span>
338
+
339
+ <button type="button" className="cg-tb-btn" onClick={onCsv} disabled={sheet.empty}>
340
+ Export CSV
341
+ </button>
342
+ <span className="cg-ts-pool">
343
+ {locked
344
+ ? "This record"
345
+ : `${sheet.pool.toLocaleString()} ${sheet.pool === 1 ? "customer" : "customers"}`}
346
+ </span>
347
  </div>
348
 
349
  {state === "error" && (
 
358
 
359
  {state === "loading" && !payload && <div className="cg-ts-note">Loading…</div>}
360
 
361
+ {payload && (
 
 
 
 
362
  <div className="cg-ts-scroll">
363
+ <table className={"cg-ts-table" + (gridlines ? "" : " is-nogrid")}>
364
  <thead>
365
  <tr>
366
  <th className="cg-ts-stick">Metric</th>
367
+ {sheet.columns.map((c) => (
368
  <th key={c.key} className={c.partial ? "is-partial" : undefined}>
369
  {c.label}
370
  {c.partial && <span className="cg-ts-partial"> Β· partial</span>}
371
  </th>
372
  ))}
373
  <th className="cg-ts-total">Total</th>
374
+ {sparkline && <th className="cg-ts-sparkhead">Trend</th>}
375
  </tr>
376
  </thead>
377
  <tbody>
378
+ {sheet.rows.map((row) => (
379
  <TsRowBlock
380
+ key={row.id}
381
+ row={row}
382
+ sheet={sheet}
383
+ style={resolveTsStyle(styles, row.id)}
384
+ styles={styles}
385
+ sparkline={sparkline}
386
+ charted={charted.has(row.id)}
387
+ editable={!!onDisplay}
388
+ metricRow={table.rows.find((r) => r.field === row.id)}
389
+ onToggleChart={() => toggleChart(row.id)}
390
+ onStyle={(patch) => setStyle(row.id, patch)}
391
+ onRemove={() => {
392
+ if (row.kind === "metric")
393
+ setMetrics(selected.filter((k) => k !== row.id));
394
+ else setRows(customRows.filter((r) => r.id !== row.id));
395
+ }}
396
+ onEditRow={(patch) =>
397
+ setRows(customRows.map((r) => (r.id === row.id ? { ...r, ...patch } : r)))
398
+ }
399
  />
400
  ))}
401
+ {/* Item 17 β€” the sheet GROWS from its bottom edge, the way a spreadsheet does.
402
+ This row is both the list of what could be added and the control that adds
403
+ it; a picker somewhere else would be a second inventory to keep in sync. */}
404
+ {onDisplay && (
405
+ <tr className="cg-ts-addrow">
406
+ <th className="cg-ts-stick" colSpan={colCount}>
407
+ <span className="cg-ts-addbar">
408
+ {/* C-FLDSEL (item 20) β€” the type mark travels with the name. `value` is
409
+ deliberately left UNSET: this control never displays a choice, it
410
+ only makes one, so the placeholder IS its resting state (which is
411
+ also the scar the contract names β€” a native <select> with no value
412
+ paints its first option and claims a choice nobody made). */}
413
+ <FieldSelectButton
414
+ fields={unused}
415
+ value={undefined}
416
+ onChange={(key) => setMetrics([...selected, key])}
417
+ className="cg-select cg-ts-addsel"
418
+ ariaLabel="Add a metric row"
419
+ disabled={!unused.length || selected.length >= TS_MAX_FIELDS}
420
+ placeholder={
421
+ !unused.length
422
+ ? "Every metric is on the sheet"
423
+ : selected.length >= TS_MAX_FIELDS
424
+ ? `At the ${TS_MAX_FIELDS}-metric limit`
425
+ : "+ Add metric"
426
+ }
427
+ />
428
+ <button
429
+ type="button"
430
+ className="cg-ts-tog"
431
+ disabled={customRows.length >= TS_MAX_CUSTOM_ROWS}
432
+ onClick={() =>
433
+ setRows([
434
+ ...customRows,
435
+ { id: newRowId(customRows), kind: "note", label: "" },
436
+ ])
437
+ }
438
+ >
439
+ + Note
440
+ </button>
441
+ <button
442
+ type="button"
443
+ className="cg-ts-tog"
444
+ disabled={customRows.length >= TS_MAX_CUSTOM_ROWS}
445
+ onClick={() =>
446
+ setRows([
447
+ ...customRows,
448
+ { id: newRowId(customRows), kind: "formula", label: "", expr: "" },
449
+ ])
450
+ }
451
+ >
452
+ + Formula
453
+ </button>
454
+ </span>
455
+ </th>
456
+ </tr>
457
+ )}
458
  </tbody>
459
  </table>
460
  </div>
461
  )}
462
 
463
+ {payload && sheet.empty && (
464
+ <div className="cg-ts-note">No metrics returned a series for this span.</div>
465
+ )}
466
+
467
+ {sheet.notes.length > 0 && (
468
  <ul className="cg-ts-notes">
469
+ {sheet.notes.map((n) => (
470
  <li key={n}>{n}</li>
471
  ))}
472
  </ul>
 
475
  );
476
  }
477
 
478
+ /** A row's own controls: emphasis, then removal. Hover-revealed, always in the tab order. */
479
+ function RowTools({
480
+ style,
481
+ editable,
482
+ onStyle,
483
+ onRemove,
484
+ label,
485
+ }: {
486
+ style: TsCellStyle;
487
+ editable: boolean;
488
+ onStyle: (patch: TsCellStyle) => void;
489
+ onRemove: () => void;
490
+ label: string;
491
+ }) {
492
+ if (!editable) return null;
493
+ return (
494
+ <span className="cg-ts-rowtools">
495
+ <button
496
+ type="button"
497
+ className={"cg-ts-rowtool" + (style.bold ? " is-on" : "")}
498
+ aria-pressed={!!style.bold}
499
+ aria-label={`Bold ${label}`}
500
+ title="Bold"
501
+ onClick={() => onStyle({ bold: style.bold ? undefined : true })}
502
+ >
503
+ B
504
+ </button>
505
+ <button
506
+ type="button"
507
+ className={"cg-ts-rowtool" + (style.line ? " is-on" : "")}
508
+ aria-pressed={!!style.line}
509
+ aria-label={`Rule above ${label}`}
510
+ title="Rule above"
511
+ onClick={() => onStyle({ line: style.line ? undefined : true })}
512
+ >
513
+ ―
514
+ </button>
515
+ <button
516
+ type="button"
517
+ className="cg-ts-rowtool"
518
+ aria-label={`Remove ${label}`}
519
+ title="Remove row"
520
+ onClick={onRemove}
521
+ >
522
+ Γ—
523
+ </button>
524
+ </span>
525
+ );
526
+ }
527
+
528
  /**
529
+ * One sheet row: its values, its delta sub-rows, and an optional line chart.
530
  *
531
  * The chart is built from `tsRowToChartModel`, NOT from `viz/chartData.buildChartData` β€” see
532
  * that function's note. `buildChartData` caps at 12 buckets, which for a time series means
 
534
  */
535
  function TsRowBlock({
536
  row,
537
+ sheet,
538
+ style,
539
+ styles,
540
+ sparkline,
541
  charted,
542
+ editable,
543
+ metricRow,
544
  onToggleChart,
545
+ onStyle,
546
+ onRemove,
547
+ onEditRow,
548
  }: {
549
+ row: TsSheetRow;
550
+ sheet: TsSheet;
551
+ style: TsCellStyle;
552
+ styles: Record<string, TsCellStyle> | undefined;
553
+ sparkline: boolean;
554
  charted: boolean;
555
+ editable: boolean;
556
+ metricRow: TsTableRow | undefined;
557
  onToggleChart: () => void;
558
+ onStyle: (patch: TsCellStyle) => void;
559
+ onRemove: () => void;
560
+ onEditRow: (patch: Partial<TsCustomRow>) => void;
561
  }) {
562
  const spec = useMemo(() => {
563
+ if (!charted || !metricRow) return null;
564
+ const model = tsRowToChartModel(metricRow, sheet.columns);
565
  if (!model.points.length) return null;
566
  return toVegaLiteSpec({
567
+ spec: { id: row.id, kind: "line", agg: (row.agg ?? "sum") as never },
568
  model,
569
  yTitle: row.label,
570
  formatValue: (n) => n.toLocaleString(undefined, { maximumFractionDigits: 2 }),
571
  });
572
+ }, [charted, metricRow, sheet.columns, row.id, row.agg, row.label]);
573
 
574
+ const colCount = sheet.columns.length + 2 + (sparkline ? 1 : 0);
575
+ const rowCls =
576
+ (style.line ? "is-ruled" : "") + (style.bold ? " is-bold" : "") || undefined;
577
+
578
+ // A NOTE row is a label across the sheet β€” a section heading in a financial model, not a
579
+ // series with empty cells. Spanning it is what stops twelve blank cells from reading as
580
+ // twelve unanswerable ones ("β€”" already means something else here).
581
+ if (row.kind === "note") {
582
+ return (
583
+ <tr className={"cg-ts-noterow " + (rowCls ?? "")}>
584
+ <th className="cg-ts-stick" colSpan={colCount}>
585
+ <span className="cg-ts-rowhead">
586
+ {editable ? (
587
+ <input
588
+ className="cg-ts-rowinput"
589
+ value={row.label}
590
+ maxLength={TS_ROW_LABEL_MAX}
591
+ placeholder="Note β€” type a heading for this section"
592
+ aria-label="Note row label"
593
+ onChange={(e) => onEditRow({ label: e.target.value })}
594
+ />
595
+ ) : (
596
+ <span className="cg-ts-rowlabel">{row.label}</span>
597
+ )}
598
+ <RowTools
599
+ style={style}
600
+ editable={editable}
601
+ onStyle={onStyle}
602
+ onRemove={onRemove}
603
+ label={row.label || "note row"}
604
+ />
605
+ </span>
606
+ </th>
607
+ </tr>
608
+ );
609
+ }
610
 
611
  return (
612
  <>
613
+ <tr className={rowCls}>
614
  <th scope="row" className="cg-ts-stick">
615
+ <span className="cg-ts-rowhead">
616
+ <span className="cg-ts-rowmain">
617
+ {row.kind === "formula" ? (
618
+ editable ? (
619
+ <input
620
+ className="cg-ts-rowinput"
621
+ value={row.label}
622
+ maxLength={TS_ROW_LABEL_MAX}
623
+ placeholder="Formula row name"
624
+ aria-label="Formula row label"
625
+ onChange={(e) => onEditRow({ label: e.target.value })}
626
+ />
627
+ ) : (
628
+ <span className="cg-ts-rowlabel">{row.label}</span>
629
+ )
630
+ ) : (
631
+ <button
632
+ type="button"
633
+ className="cg-ts-rowbtn"
634
+ onClick={onToggleChart}
635
+ aria-pressed={charted}
636
+ title={charted ? "Show as a row of numbers" : "Show as a line"}
637
+ >
638
+ {row.label}
639
+ </button>
640
+ )}
641
+ {/* R1 β€” the metric's OWN window. Two rows under the same month headings can be
642
+ a cumulative year-to-date and a trailing 90 days; without this line they
643
+ look like the same kind of number. */}
644
+ {row.sublabel && <span className="cg-ts-rowsub">{row.sublabel}</span>}
645
+ {row.kind === "formula" &&
646
+ (editable ? (
647
+ <input
648
+ className="cg-ts-rowinput cg-ts-rowexpr"
649
+ value={row.expr ?? ""}
650
+ maxLength={TS_MAX_EXPR}
651
+ spellCheck={false}
652
+ placeholder="= [Sales] - [Returns]"
653
+ aria-label="Formula"
654
+ onChange={(e) => onEditRow({ expr: e.target.value })}
655
+ />
656
+ ) : (
657
+ <span className="cg-ts-rowsub">{row.expr}</span>
658
+ ))}
659
+ </span>
660
+ <RowTools
661
+ style={style}
662
+ editable={editable}
663
+ onStyle={onStyle}
664
+ onRemove={onRemove}
665
+ label={row.label || "row"}
666
+ />
667
+ </span>
668
  </th>
669
+ {row.cells.map((c, i) => {
670
+ const col = sheet.columns[i];
671
+ const cellStyle = resolveTsStyle(styles, row.id, col?.key);
672
+ return (
673
+ <td
674
+ key={col?.key ?? i}
675
+ className={
676
+ (c.partial ? "is-partial" : "") + (cellStyle.bold ? " is-bold" : "") || undefined
677
+ }
678
+ >
679
+ {formatTsValue(c.value, (n) =>
680
+ n.toLocaleString(undefined, { maximumFractionDigits: 2 })
681
+ )}
682
+ </td>
683
+ );
684
+ })}
685
  <td className="cg-ts-total">
686
  {/* An avg/min/max row has NO total β€” the cell stays empty rather than carrying an
687
+ average of averages. See timeSeriesData's header note (2). Formula and note rows
688
+ carry none either: an arbitrary expression is not additive across periods. */}
689
  {row.total == null
690
  ? ""
691
  : row.total.toLocaleString(undefined, { maximumFractionDigits: 2 })}
692
  </td>
693
+ {sparkline && (
694
+ <td className="cg-ts-spark">
695
+ <Sparkline values={row.cells.map((c) => c.value)} label={row.label} />
696
+ </td>
697
+ )}
698
  </tr>
699
+ {row.deltas.map((d) => (
700
+ <TsDeltaRow key={d.kind} delta={d} sparkline={sparkline} />
701
+ ))}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
702
  {charted && (
703
  <tr className="cg-ts-chartrow">
704
  <td colSpan={colCount}>
 
715
  </>
716
  );
717
  }
718
+
719
+ /**
720
+ * One comparison sub-row.
721
+ *
722
+ * ONE typography for all four (item 18's "standardized type"): the same 2xs size, the sign
723
+ * carried by a `-deep` tint, refusals as "β€”". A comparison that cannot be answered AT ALL
724
+ * (no year in the span; year-to-date growth asked of a trailing-90 row) renders its dashes and
725
+ * the sheet's footnotes say why once β€” the alternative is a column of dashes indistinguishable
726
+ * from missing data.
727
+ */
728
+ function TsDeltaRow({
729
+ delta,
730
+ sparkline,
731
+ }: {
732
+ delta: TsDeltaSubRow;
733
+ sparkline: boolean;
734
+ }) {
735
+ return (
736
+ <tr className="cg-ts-delta">
737
+ <th scope="row" className="cg-ts-stick">
738
+ {delta.label}
739
+ </th>
740
+ {delta.values.map((v, i) => (
741
+ <td key={i} className={v == null ? undefined : v >= 0 ? "is-up" : "is-down"}>
742
+ {delta.percent
743
+ ? formatTsDelta(v)
744
+ : v == null
745
+ ? "β€”"
746
+ : `${v > 0 ? "+" : ""}${v.toLocaleString(undefined, { maximumFractionDigits: 2 })}`}
747
+ </td>
748
+ ))}
749
+ <td className="cg-ts-total" />
750
+ {sparkline && <td className="cg-ts-spark" />}
751
+ </tr>
752
+ );
753
+ }
754
+
755
+ /**
756
+ * The trend column: a hand-rolled polyline, no library.
757
+ *
758
+ * ⚠ Gaps BREAK the line rather than being bridged. A stroke drawn straight across an
759
+ * unanswerable period asserts a value for it β€” the same lie the table refuses one cell to the
760
+ * left, at 72 pixels wide.
761
+ */
762
+ function Sparkline({ values, label }: { values: (number | null)[]; label: string }) {
763
+ const segments = useMemo(
764
+ () => sparklineSegments(values, SPARK_W, SPARK_H),
765
+ [values]
766
+ );
767
+ if (!segments.length) return <span className="cg-ts-sparkempty">β€”</span>;
768
+ const answered = values.filter((v) => v != null).length;
769
+ return (
770
+ <svg
771
+ className="cg-ts-sparksvg"
772
+ width={SPARK_W}
773
+ height={SPARK_H}
774
+ viewBox={`0 0 ${SPARK_W} ${SPARK_H}`}
775
+ role="img"
776
+ aria-label={`${label}: trend over ${answered} of ${values.length} periods`}
777
+ >
778
+ {segments.map((s, i) => (
779
+ <polyline
780
+ key={i}
781
+ points={sparklinePoints(s)}
782
+ fill="none"
783
+ stroke="currentColor"
784
+ strokeWidth="1.25"
785
+ strokeLinejoin="round"
786
+ strokeLinecap="round"
787
+ />
788
+ ))}
789
+ </svg>
790
+ );
791
+ }
web/src/customer-grid/Toolbar.tsx CHANGED
@@ -28,7 +28,11 @@ import type {
28
  ScopeCounts,
29
  SortRule,
30
  SortSpec,
 
31
  } from "./types";
 
 
 
32
  import { COHORT_FIELD, COHORT_OPS, MAX_COHORT_IDS, MAX_FILTER_DEPTH, MEASURE_OPS,
33
  MEASURE_PAIR_OPS, RANK_OPS, STAT_KINDS, STAT_LABELS, VALUE_FREE_OPS, cohortIds,
34
  directionLabel, filterableFields, isDateFamilyType, isFilterGroup, isGroupableField,
@@ -38,7 +42,9 @@ import type { AnchorMode, WindowKind, WindowSpec } from "./windows";
38
  import { ANCHOR_LABELS, ANCHOR_MODES, MAX_N, N_KINDS, WINDOW_KINDS, WINDOW_LABELS }
39
  from "./windows";
40
  import { AnchoredOverlay } from "./OverlaySurface";
41
- import { FieldTypeIcon } from "./icons";
 
 
42
  import { TYPE_LABELS } from "./iconShapes";
43
  import { countLabel, countLabelCompact, poolProgressLabel } from "./counts";
44
  import type { PoolProgress } from "./counts";
@@ -322,6 +328,10 @@ function cohortOpLabel(op: FilterOp | CohortOp): string {
322
  }
323
  }
324
 
 
 
 
 
325
  /** A measure condition is identified by its window, so a new one needs a default window. */
326
  const DEFAULT_WINDOW: WindowSpec = { kind: "ltm" };
327
 
@@ -357,8 +367,12 @@ function withCurrentField(
357
  fieldByKey: Map<string, Field>,
358
  measureByKey: Map<string, Measure>,
359
  hasCohorts: boolean
360
- ): { key: string; label: string }[] {
361
- const out = fields.map((f) => ({ key: f.key, label: f.label }));
 
 
 
 
362
  const known = new Set(out.map((o) => o.key));
363
  if (!current || known.has(current) || measureByKey.has(current)) return out;
364
  if (current === COHORT_FIELD && hasCohorts) return out;
@@ -367,7 +381,7 @@ function withCurrentField(
367
  // bug, and the property that matters is that the condition says what it says. Found by
368
  // reading the screenshot; every assertion in the run was green.
369
  const f = fieldByKey.get(current);
370
- out.push({ key: current, label: f ? f.label : current });
371
  return out;
372
  }
373
 
@@ -466,6 +480,19 @@ export interface ToolbarProps {
466
  * cohort-leaf law), so the banner has to say which kind of nothing this is.
467
  */
468
  cohortLock?: { name?: string; count?: number };
 
 
 
 
 
 
 
 
 
 
 
 
 
469
 
470
  recordCount: number;
471
  /** Server-windowed tables only. When present the count is rendered from the SCOPE, never
@@ -512,7 +539,11 @@ const stroke = {
512
  strokeLinejoin: "round" as const,
513
  };
514
 
515
- function IconFields() {
 
 
 
 
516
  return (
517
  <svg {...ic} aria-hidden>
518
  <rect x="2" y="3" width="12" height="10" rx="1.5" {...stroke} />
@@ -569,6 +600,21 @@ function IconSearch() {
569
  </svg>
570
  );
571
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
572
  function Chevron() {
573
  return (
574
  <svg width="10" height="10" viewBox="0 0 16 16" fill="none" aria-hidden>
@@ -741,7 +787,7 @@ function RhsPicker({
741
  onPatch,
742
  }: {
743
  rule: FilterRule;
744
- options: { key: string; label: string }[];
745
  isMeasure: boolean;
746
  onPatch: (p: Partial<FilterRule>) => void;
747
  }) {
@@ -749,16 +795,16 @@ function RhsPicker({
749
  const colId = rhsColId(rhs) ?? "";
750
  return (
751
  <span className="cg-cond-rhs">
752
- <select
753
- className="cg-select cg-cond-field"
754
- value={colId}
755
- aria-label="Compare with field"
756
- onChange={(e) => {
757
- const key = e.target.value;
758
- if (!key) {
759
- onPatch({ rhs: { kind: isMeasure ? "measure" : "field", colId: "" } as FilterRhs });
760
- return;
761
- }
762
  onPatch({
763
  rhs: isMeasure
764
  ? { kind: "measure", colId: key,
@@ -766,14 +812,7 @@ function RhsPicker({
766
  : { kind: "field", colId: key },
767
  });
768
  }}
769
- >
770
- <option value="">Select a field…</option>
771
- {options.map((o) => (
772
- <option key={o.key} value={o.key}>
773
- {o.label}
774
- </option>
775
- ))}
776
- </select>
777
  {isMeasure && colId !== "" && (
778
  <WindowPicker
779
  window={(rhs?.kind === "measure" && rhs.window) || DEFAULT_WINDOW}
@@ -1132,6 +1171,9 @@ function ConditionLevel({
1132
  onNodes: (nodes: FilterNode[]) => void;
1133
  onConj: (c: Conjunction) => void;
1134
  }) {
 
 
 
1135
  const setNode = (i: number, next: FilterNode) =>
1136
  onNodes(nodes.map((n, j) => (j === i ? next : n)));
1137
  const removeNode = (i: number) => onNodes(nodes.filter((_, j) => j !== i));
@@ -1181,14 +1223,33 @@ function ConditionLevel({
1181
  )}
1182
  </div>
1183
  ))}
 
 
 
 
 
 
 
 
 
1184
  <div className="cg-builder-add">
1185
- <button type="button" className="cg-link-btn" onClick={addCondition}>
 
 
 
 
 
 
 
1186
  + Add condition
1187
  </button>
1188
  <button
1189
  type="button"
1190
- className="cg-link-btn"
1191
- onClick={addGroup}
 
 
 
1192
  disabled={!canNest}
1193
  title={
1194
  canNest
@@ -1287,12 +1348,12 @@ function LeafRow({
1287
  // Owner item 4: the value box is REPLACEABLE by another attribute. Offered where a
1288
  // comparison between two of the same kind of thing means something β€” numbers against
1289
  // numbers, dates against dates, a measure against a measure over its own period.
1290
- const rhsOptions = isMeasure
1291
- ? measures.map((m) => ({ key: m.key, label: m.label }))
1292
  : fields
1293
  .filter((f) => f.key !== rule.colId
1294
  && (isNumericType(t) ? isNumericType(f.type) : f.type === t))
1295
- .map((f) => ({ key: f.key, label: f.label }));
1296
  const canCompareField = !isCohort && rule.op !== "within"
1297
  && !VALUE_FREE_OPS.has(rule.op as FilterOp) && !isRankOp(rule.op)
1298
  && rhsOptions.length > 0 && (isMeasure || isNumericType(t) || isDateFamily(t));
@@ -1326,27 +1387,26 @@ function LeafRow({
1326
  <span className={"cg-cond-row" + (isMeasure ? " is-measure" : "")
1327
  + (isCohort ? " is-cohort" : "")
1328
  + (rule.rhs != null ? " has-rhs" : "")}>
1329
- <select
1330
- className="cg-select cg-cond-field"
 
 
 
 
 
 
1331
  value={rule.colId}
1332
- aria-label="Field"
1333
- onChange={(e) => onField(e.target.value)}
1334
- >
1335
- {/* ONE flat list (owner item 1). A measure used to sit under a "Measures (pick a
1336
- period)" optgroup; the owner's instruction was that it is all the same list β€”
1337
- you pick a thing to filter on, and a measure simply also asks for a period. */}
1338
- {withCurrentField(fields, rule.colId, fieldByKey, measureByKey, hasCohorts).map((o) => (
1339
- <option key={o.key} value={o.key}>
1340
- {o.label}
1341
- </option>
1342
- ))}
1343
- {measures.map((m) => (
1344
- <option key={m.key} value={m.key}>
1345
- {m.label}
1346
- </option>
1347
- ))}
1348
- {hasCohorts && <option value={COHORT_FIELD}>Cohort</option>}
1349
- </select>
1350
  {isMeasure && (
1351
  <WindowPicker
1352
  window={rule.window ?? DEFAULT_WINDOW}
@@ -1531,6 +1591,127 @@ function GroupNode({
1531
  );
1532
  }
1533
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1534
  function FilterBuilder({
1535
  fields,
1536
  fieldByKey,
@@ -1543,6 +1724,9 @@ function FilterBuilder({
1543
  onFilterConj,
1544
  statusValues,
1545
  cohortLock,
 
 
 
1546
  }: {
1547
  fields: Field[];
1548
  fieldByKey: Map<string, Field>;
@@ -1555,7 +1739,13 @@ function FilterBuilder({
1555
  onFilterConj: (c: Conjunction) => void;
1556
  statusValues: Record<string, string[]>;
1557
  cohortLock?: { name?: string; count?: number };
 
 
 
1558
  }) {
 
 
 
1559
  return (
1560
  <div className="cg-pop-body cg-builder">
1561
  <div className="cg-pop-title">Filter</div>
@@ -1609,17 +1799,57 @@ function FilterBuilder({
1609
  Quartiles and deciles are equal-size slices BY RANK, not by value.
1610
  </div>
1611
  )}
1612
- {filters.length > 0 && (
 
 
 
 
 
 
 
 
 
1613
  <div className="cg-pop-footer cg-builder-footer">
1614
- <button
1615
- type="button"
1616
- className="cg-link-btn"
1617
- onClick={() => onFilters([])}
1618
- >
1619
- Clear all
1620
- </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
1621
  </div>
1622
  )}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1623
  </div>
1624
  );
1625
  }
@@ -1660,18 +1890,19 @@ function SortBuilder({
1660
  <div className="cg-cond-line" key={i}>
1661
  <span className="cg-cond-prefix">{i === 0 ? "Sort by" : "then by"}</span>
1662
  <span className="cg-cond-row">
1663
- <select
1664
- className="cg-select cg-cond-field"
 
 
 
 
 
1665
  value={rule.colId}
1666
- aria-label="Sort field"
1667
- onChange={(e) => update(i, { colId: e.target.value })}
1668
- >
1669
- {fields.map((fl) => (
1670
- <option key={fl.key} value={fl.key}>
1671
- {fl.label}
1672
- </option>
1673
- ))}
1674
- </select>
1675
  <select
1676
  className="cg-select cg-cond-op"
1677
  value={rule.dir}
@@ -1826,6 +2057,14 @@ function FieldsPanel({
1826
  key={f.key}
1827
  className={
1828
  "cg-check-row" +
 
 
 
 
 
 
 
 
1829
  (locked ? " is-locked" : "") +
1830
  (dragKey === f.key ? " is-dragging" : "") +
1831
  (overKey === f.key && dragKey !== null && dragKey !== f.key
@@ -1978,7 +2217,11 @@ function FieldsPanel({
1978
  <div className="cg-builder-empty">No field matches your search.</div>
1979
  )}
1980
  </div>
1981
- <div className="cg-pop-footer">
 
 
 
 
1982
  <button
1983
  type="button"
1984
  className="cg-link-btn"
@@ -2026,6 +2269,8 @@ export default function Toolbar({
2026
  unresolvedCount = 0,
2027
  lists = [],
2028
  cohortLock,
 
 
2029
  search,
2030
  onSearch,
2031
  recordCount,
@@ -2120,7 +2365,7 @@ export default function Toolbar({
2120
 
2121
  {/* Fields β€” show / hide columns, searchable, Pre-set chips (item 7 remainder) */}
2122
  {/* Owner item 23 β€” "Hide fields", the panel's actual job and Airtable's wording. */}
2123
- <Popover label="Hide fields" icon={<IconFields />} active={shownCount < fields.length}>
2124
  {() => (
2125
  <FieldsPanel
2126
  fields={orderedFields ?? fields}
@@ -2160,6 +2405,9 @@ export default function Toolbar({
2160
  onFilterConj={onFilterConj}
2161
  statusValues={statusValues}
2162
  cohortLock={cohortLock}
 
 
 
2163
  />
2164
  )}
2165
  </Popover>
@@ -2271,11 +2519,12 @@ export default function Toolbar({
2271
  )}
2272
  </Popover>
2273
 
2274
- {cohortAction}
2275
-
2276
- <span className="cg-tb-spacer" />
2277
-
2278
- {/* Search */}
 
2279
  <div className="cg-search">
2280
  <span className="cg-search-icon" aria-hidden>
2281
  <IconSearch />
@@ -2299,6 +2548,10 @@ export default function Toolbar({
2299
  )}
2300
  </div>
2301
 
 
 
 
 
2302
  {pendingMeasureCount > 0 && (
2303
  // A measure condition is answered by the server. Between the keystroke and the answer
2304
  // the condition matches NOTHING β€” never everything, which would show every row under a
 
28
  ScopeCounts,
29
  SortRule,
30
  SortSpec,
31
+ ViewConfig,
32
  } from "./types";
33
+ import { viewDisplayMode } from "./types";
34
+ import { COPY_PARTS, COPY_PART_KEYS, copyViewConfig } from "./copyConfig";
35
+ import type { CopyPart } from "./copyConfig";
36
  import { COHORT_FIELD, COHORT_OPS, MAX_COHORT_IDS, MAX_FILTER_DEPTH, MEASURE_OPS,
37
  MEASURE_PAIR_OPS, RANK_OPS, STAT_KINDS, STAT_LABELS, VALUE_FREE_OPS, cohortIds,
38
  directionLabel, filterableFields, isDateFamilyType, isFilterGroup, isGroupableField,
 
42
  import { ANCHOR_LABELS, ANCHOR_MODES, MAX_N, N_KINDS, WINDOW_KINDS, WINDOW_LABELS }
43
  from "./windows";
44
  import { AnchoredOverlay } from "./OverlaySurface";
45
+ import { EyeOffIcon, FieldTypeIcon, ModeIcon } from "./icons";
46
+ import { FieldSelectButton } from "./FieldSelect";
47
+ import type { FieldSelectItem, FieldSelectType } from "./FieldSelect";
48
  import { TYPE_LABELS } from "./iconShapes";
49
  import { countLabel, countLabelCompact, poolProgressLabel } from "./counts";
50
  import type { PoolProgress } from "./counts";
 
328
  }
329
  }
330
 
331
+ /** Item 20 β€” the mark a MEASURE row wears in every picker on this surface. Named once so the
332
+ * three lists that offer measures cannot drift into two different glyphs for one concept. */
333
+ const MEASURE_MARK: FieldSelectType = "measure";
334
+
335
  /** A measure condition is identified by its window, so a new one needs a default window. */
336
  const DEFAULT_WINDOW: WindowSpec = { kind: "ltm" };
337
 
 
367
  fieldByKey: Map<string, Field>,
368
  measureByKey: Map<string, Measure>,
369
  hasCohorts: boolean
370
+ ): FieldSelectItem[] {
371
+ // Item 20: the rows carry their TYPE now, because the picker paints the type mark. Same
372
+ // list, same order, same `withCurrent` rule β€” only the shape of a row grew a field.
373
+ const out: FieldSelectItem[] = fields.map((f) => ({
374
+ key: f.key, label: f.label, type: f.type,
375
+ }));
376
  const known = new Set(out.map((o) => o.key));
377
  if (!current || known.has(current) || measureByKey.has(current)) return out;
378
  if (current === COHORT_FIELD && hasCohorts) return out;
 
381
  // bug, and the property that matters is that the condition says what it says. Found by
382
  // reading the screenshot; every assertion in the run was green.
383
  const f = fieldByKey.get(current);
384
+ out.push({ key: current, label: f ? f.label : current, type: f?.type });
385
  return out;
386
  }
387
 
 
480
  * cohort-leaf law), so the banner has to say which kind of nothing this is.
481
  */
482
  cohortLock?: { name?: string; count?: number };
483
+ /**
484
+ * Item 13 (C-COPYVIEW) β€” the OTHER views of this table the reader can see, so the filter
485
+ * builder can offer "Copy from another view". Pass `views.filter(v => v.id !== activeViewId)`.
486
+ *
487
+ * BOTH of these are optional and the door renders only when both are present. That is the
488
+ * house posture for a control whose host half may not be wired yet (`onCohortLock` on the
489
+ * view rail, `onFieldOrder` on the Fields panel): a missing prop makes the action ABSENT,
490
+ * never present-and-silently-inert.
491
+ */
492
+ copyViews?: { id: string; name: string; config: ViewConfig }[];
493
+ /** Apply the chosen slices to the ACTIVE view, as ONE update. The patch is already computed
494
+ * (`copyConfig.ts`, gated by `verify_copy_config.py`) β€” the caller only persists it. */
495
+ onCopyConfig?: (patch: Partial<ViewConfig>) => void;
496
 
497
  recordCount: number;
498
  /** Server-windowed tables only. When present the count is rendered from the SCOPE, never
 
539
  strokeLinejoin: "round" as const,
540
  };
541
 
542
+ // ⚠ Item 12: this three-column-rules mark used to open the Hide-fields panel as `IconFields`,
543
+ // where it named the NOUN and left the verb to be guessed. The button wears the struck-through
544
+ // eye now (`icons.tsx`). The glyph itself was right for something else, so it is RENAMED
545
+ // rather than deleted-and-reinvented: it is the copy-configuration modal's "Field order".
546
+ function IconColumns() {
547
  return (
548
  <svg {...ic} aria-hidden>
549
  <rect x="2" y="3" width="12" height="10" rx="1.5" {...stroke} />
 
600
  </svg>
601
  );
602
  }
603
+ /**
604
+ * Item 13 β€” the mark on each copy-configuration row. Every one is a glyph this toolbar
605
+ * ALREADY paints for the same concept (the Filter / Sort / Group / Rows buttons, and the eye
606
+ * the Hide-fields button now wears), so the modal teaches nothing new: you recognise the row
607
+ * by the control it will overwrite.
608
+ */
609
+ const COPY_PART_ICONS: Record<CopyPart, ReactNode> = {
610
+ filters: <IconFilter />,
611
+ sorts: <IconSort />,
612
+ groupBy: <IconGroup />,
613
+ visible: <EyeOffIcon />,
614
+ order: <IconColumns />,
615
+ rowHeightMode: <IconRows />,
616
+ };
617
+
618
  function Chevron() {
619
  return (
620
  <svg width="10" height="10" viewBox="0 0 16 16" fill="none" aria-hidden>
 
787
  onPatch,
788
  }: {
789
  rule: FilterRule;
790
+ options: FieldSelectItem[];
791
  isMeasure: boolean;
792
  onPatch: (p: Partial<FilterRule>) => void;
793
  }) {
 
795
  const colId = rhsColId(rhs) ?? "";
796
  return (
797
  <span className="cg-cond-rhs">
798
+ {/* Item 20 β€” the empty comparand was an `<option value="">` that a select renders as
799
+ its first row; here it is the picker's PLACEHOLDER state, so "not chosen yet" is a
800
+ state of the control rather than an entry in the vocabulary. */}
801
+ <FieldSelectButton
802
+ className="cg-cond-field"
803
+ ariaLabel="Compare with field"
804
+ placeholder="Select a field…"
805
+ value={colId || undefined}
806
+ fields={options}
807
+ onChange={(key) => {
808
  onPatch({
809
  rhs: isMeasure
810
  ? { kind: "measure", colId: key,
 
812
  : { kind: "field", colId: key },
813
  });
814
  }}
815
+ />
 
 
 
 
 
 
 
816
  {isMeasure && colId !== "" && (
817
  <WindowPicker
818
  window={(rhs?.kind === "measure" && rhs.window) || DEFAULT_WINDOW}
 
1171
  onNodes: (nodes: FilterNode[]) => void;
1172
  onConj: (c: Conjunction) => void;
1173
  }) {
1174
+ /** Item 13 / R9 β€” which add-link was last used at THIS level. Per level, because the state
1175
+ * belongs to the row of buttons the user clicked, not to the builder as a whole. */
1176
+ const [lastAdd, setLastAdd] = useState<"condition" | "group" | null>(null);
1177
  const setNode = (i: number, next: FilterNode) =>
1178
  onNodes(nodes.map((n, j) => (j === i ? next : n)));
1179
  const removeNode = (i: number) => onNodes(nodes.filter((_, j) => j !== i));
 
1223
  )}
1224
  </div>
1225
  ))}
1226
+ {/* Item 13 (owner, 2026-08-02) β€” the two add-links are BOLD, and the one you just used
1227
+ holds a dark-blue state.
1228
+ ⚠ R9 says that state lasts while the popover is open and a fresh open starts
1229
+ neutral β€” which is exactly what a `useState` HERE gives for free, because `Popover`
1230
+ renders its children only while open (`{open && <AnchoredOverlay…>}`) and unmounts
1231
+ them on close. Nothing persists it, nothing has to clear it, and there is no way for
1232
+ it to survive a reopen. A `:active` pseudo-class would have been the wrong tool
1233
+ twice over: it lasts for the duration of the mouse-down, and it says "you are
1234
+ pressing this" rather than "this is the one you have been using". */}
1235
  <div className="cg-builder-add">
1236
+ <button
1237
+ type="button"
1238
+ className={"cg-link-btn" + (lastAdd === "condition" ? " is-on" : "")}
1239
+ onClick={() => {
1240
+ setLastAdd("condition");
1241
+ addCondition();
1242
+ }}
1243
+ >
1244
  + Add condition
1245
  </button>
1246
  <button
1247
  type="button"
1248
+ className={"cg-link-btn" + (lastAdd === "group" ? " is-on" : "")}
1249
+ onClick={() => {
1250
+ setLastAdd("group");
1251
+ addGroup();
1252
+ }}
1253
  disabled={!canNest}
1254
  title={
1255
  canNest
 
1348
  // Owner item 4: the value box is REPLACEABLE by another attribute. Offered where a
1349
  // comparison between two of the same kind of thing means something β€” numbers against
1350
  // numbers, dates against dates, a measure against a measure over its own period.
1351
+ const rhsOptions: FieldSelectItem[] = isMeasure
1352
+ ? measures.map((m) => ({ key: m.key, label: m.label, type: MEASURE_MARK }))
1353
  : fields
1354
  .filter((f) => f.key !== rule.colId
1355
  && (isNumericType(t) ? isNumericType(f.type) : f.type === t))
1356
+ .map((f) => ({ key: f.key, label: f.label, type: f.type }));
1357
  const canCompareField = !isCohort && rule.op !== "within"
1358
  && !VALUE_FREE_OPS.has(rule.op as FilterOp) && !isRankOp(rule.op)
1359
  && rhsOptions.length > 0 && (isMeasure || isNumericType(t) || isDateFamily(t));
 
1387
  <span className={"cg-cond-row" + (isMeasure ? " is-measure" : "")
1388
  + (isCohort ? " is-cohort" : "")
1389
  + (rule.rhs != null ? " has-rhs" : "")}>
1390
+ {/* ONE flat list (owner item 1). A measure used to sit under a "Measures (pick a
1391
+ period)" optgroup; the owner's instruction was that it is all the same list β€”
1392
+ you pick a thing to filter on, and a measure simply also asks for a period. Item 20
1393
+ adds the type MARK to each row and takes NO grouping with it: the marks are what the
1394
+ optgroup was reaching for, and they say it per row instead of splitting the list. */}
1395
+ <FieldSelectButton
1396
+ className="cg-cond-field"
1397
+ ariaLabel="Field"
1398
  value={rule.colId}
1399
+ onChange={onField}
1400
+ fields={[
1401
+ ...withCurrentField(fields, rule.colId, fieldByKey, measureByKey, hasCohorts),
1402
+ ...measures.map((m) => ({ key: m.key, label: m.label, type: MEASURE_MARK })),
1403
+ // A cohort leaf asks about membership of a SET, which is the multiselect mark's
1404
+ // own meaning β€” the vocabulary already had the right glyph for it.
1405
+ ...(hasCohorts
1406
+ ? [{ key: COHORT_FIELD, label: "Cohort", type: "multiselect" as const }]
1407
+ : []),
1408
+ ]}
1409
+ />
 
 
 
 
 
 
 
1410
  {isMeasure && (
1411
  <WindowPicker
1412
  window={rule.window ?? DEFAULT_WINDOW}
 
1591
  );
1592
  }
1593
 
1594
+ /**
1595
+ * Item 13 (contract C-COPYVIEW) β€” "Copy configuration from <view> to this view".
1596
+ *
1597
+ * Shape per `reference/Airtable 13.png`: a source picker in the title sentence, one row per
1598
+ * copyable slice, Select all / Clear all, Cancel / Copy.
1599
+ *
1600
+ * TWO deliberate departures from the screenshot, both booked rather than improvised:
1601
+ * - Airtable's rows are PILL TOGGLES; these are the app's own `.cg-check-row` checkboxes.
1602
+ * A toggle would be a new control vocabulary (and a new a11y surface) for a list that is
1603
+ * exactly what a checkbox list is for β€” several independent yes/no choices applied by one
1604
+ * button, not seven settings that take effect as you flip them.
1605
+ * - "Column widths and row height" is not offered: `widths` records how wide THIS reader
1606
+ * dragged THIS view's columns, and importing that re-lays-out a table nobody complained
1607
+ * about. Row height is offered on its own, which is the half of that row people mean.
1608
+ *
1609
+ * The merge itself lives in `copyConfig.ts` and is gated (`verify_copy_config.py`): this panel
1610
+ * only collects the choice. That split is on purpose β€” the panel is invisible to every node
1611
+ * gate in the repo, and the arithmetic is the part that writes durable state.
1612
+ */
1613
+ function CopyConfigPanel({
1614
+ views,
1615
+ lockedKey,
1616
+ onApply,
1617
+ onClose,
1618
+ }: {
1619
+ views: { id: string; name: string; config: ViewConfig }[];
1620
+ lockedKey: string;
1621
+ onApply: (patch: Partial<ViewConfig>) => void;
1622
+ onClose: () => void;
1623
+ }) {
1624
+ const [sourceId, setSourceId] = useState<string>("");
1625
+ // "Filter conditions" starts on: this modal opens from the Filter popover, so it is the
1626
+ // slice the person was already looking at. Everything else starts off β€” a copy that
1627
+ // silently replaced a view's column order would be the surprise this whole panel exists
1628
+ // to avoid.
1629
+ const [parts, setParts] = useState<Set<CopyPart>>(() => new Set<CopyPart>(["filters"]));
1630
+ const source = views.find((v) => v.id === sourceId);
1631
+ const toggle = (key: CopyPart) =>
1632
+ setParts((prev) => {
1633
+ const next = new Set(prev);
1634
+ if (next.has(key)) next.delete(key);
1635
+ else next.add(key);
1636
+ return next;
1637
+ });
1638
+ return (
1639
+ <div className="cg-pop-body cg-copycfg">
1640
+ <div className="cg-copycfg-head">
1641
+ <span>Copy configuration from</span>
1642
+ <FieldSelectButton
1643
+ className="cg-copycfg-source"
1644
+ ariaLabel="View to copy from"
1645
+ placeholder="Choose a view…"
1646
+ value={sourceId || undefined}
1647
+ onChange={setSourceId}
1648
+ fields={views.map((v) => ({
1649
+ key: v.id,
1650
+ label: v.name,
1651
+ // Views wear their DISPLAY MODE mark, not a field type β€” the picker takes an
1652
+ // `icon` for exactly this. `viewDisplayMode` asks only for `Pick<SavedView,
1653
+ // "config">`, which is what the caller already has to pass here.
1654
+ icon: <ModeIcon mode={viewDisplayMode(v)} />,
1655
+ }))}
1656
+ />
1657
+ <span>to this view</span>
1658
+ </div>
1659
+ <div className="cg-pop-note">Select what to copy. This view keeps everything else.</div>
1660
+ <div className="cg-pop-list">
1661
+ {COPY_PARTS.map((part) => (
1662
+ <label key={part.key} className="cg-check-row" title={part.blurb}>
1663
+ <input
1664
+ type="checkbox"
1665
+ checked={parts.has(part.key)}
1666
+ onChange={() => toggle(part.key)}
1667
+ />
1668
+ <span className="cg-mi-ic" aria-hidden>
1669
+ {COPY_PART_ICONS[part.key]}
1670
+ </span>
1671
+ <span className="cg-check-label">{part.label}</span>
1672
+ </label>
1673
+ ))}
1674
+ </div>
1675
+ <div className="cg-pop-footer cg-copycfg-bulk">
1676
+ <button
1677
+ type="button"
1678
+ className="cg-link-btn"
1679
+ onClick={() => setParts(new Set(COPY_PART_KEYS))}
1680
+ >
1681
+ Select all
1682
+ </button>
1683
+ <button type="button" className="cg-link-btn" onClick={() => setParts(new Set())}>
1684
+ Clear all
1685
+ </button>
1686
+ </div>
1687
+ <div className="cg-form-actions cg-copycfg-actions">
1688
+ <button
1689
+ type="button"
1690
+ className="cg-btn cg-btn--primary"
1691
+ disabled={!source || parts.size === 0}
1692
+ title={
1693
+ !source
1694
+ ? "Choose the view to copy from"
1695
+ : parts.size === 0
1696
+ ? "Choose at least one thing to copy"
1697
+ : undefined
1698
+ }
1699
+ onClick={() => {
1700
+ if (!source) return;
1701
+ onApply(copyViewConfig(source.config, parts, lockedKey));
1702
+ onClose();
1703
+ }}
1704
+ >
1705
+ Copy configuration
1706
+ </button>
1707
+ <button type="button" className="cg-btn" onClick={onClose}>
1708
+ Cancel
1709
+ </button>
1710
+ </div>
1711
+ </div>
1712
+ );
1713
+ }
1714
+
1715
  function FilterBuilder({
1716
  fields,
1717
  fieldByKey,
 
1724
  onFilterConj,
1725
  statusValues,
1726
  cohortLock,
1727
+ lockedKey,
1728
+ copyViews,
1729
+ onCopyConfig,
1730
  }: {
1731
  fields: Field[];
1732
  fieldByKey: Map<string, Field>;
 
1739
  onFilterConj: (c: Conjunction) => void;
1740
  statusValues: Record<string, string[]>;
1741
  cohortLock?: { name?: string; count?: number };
1742
+ lockedKey: string;
1743
+ copyViews?: { id: string; name: string; config: ViewConfig }[];
1744
+ onCopyConfig?: (patch: Partial<ViewConfig>) => void;
1745
  }) {
1746
+ const [copying, setCopying] = useState(false);
1747
+ const copyRef = useRef<HTMLButtonElement>(null);
1748
+ const canCopy = !!onCopyConfig && (copyViews?.length ?? 0) > 0;
1749
  return (
1750
  <div className="cg-pop-body cg-builder">
1751
  <div className="cg-pop-title">Filter</div>
 
1799
  Quartiles and deciles are equal-size slices BY RANK, not by value.
1800
  </div>
1801
  )}
1802
+ {/* The footer carries "Clear all" (only when there is something to clear) and the
1803
+ copy-configuration door.
1804
+ ⚠ The door is in the FOOTER rather than beside the add-links, where the reference
1805
+ screenshot has it, for one structural reason: `.cg-builder-add` is emitted once per
1806
+ NESTING LEVEL, so a link there would repeat inside every condition group and offer
1807
+ to overwrite the whole view from inside one of its brackets. The footer is the one
1808
+ place in this popover that means "the view", which is what the copy acts on. It is
1809
+ also offered when there are NO conditions yet, which is when somebody most wants to
1810
+ start from another view. */}
1811
+ {(filters.length > 0 || canCopy) && (
1812
  <div className="cg-pop-footer cg-builder-footer">
1813
+ {filters.length > 0 && (
1814
+ <button
1815
+ type="button"
1816
+ className="cg-link-btn"
1817
+ onClick={() => onFilters([])}
1818
+ >
1819
+ Clear all
1820
+ </button>
1821
+ )}
1822
+ {canCopy && (
1823
+ <button
1824
+ ref={copyRef}
1825
+ type="button"
1826
+ className={"cg-link-btn cg-copy-link" + (copying ? " is-on" : "")}
1827
+ aria-expanded={copying}
1828
+ onClick={() => setCopying((v) => !v)}
1829
+ >
1830
+ Copy from another view
1831
+ </button>
1832
+ )}
1833
  </div>
1834
  )}
1835
+ {copying && copyRef.current && (
1836
+ <AnchoredOverlay
1837
+ anchor={copyRef.current}
1838
+ className="cg-pop cg-copycfg-pop"
1839
+ placement="bottom-end"
1840
+ onDismiss={() => setCopying(false)}
1841
+ role="dialog"
1842
+ ariaLabel="Copy configuration from another view"
1843
+ dataKind="copy-config"
1844
+ >
1845
+ <CopyConfigPanel
1846
+ views={copyViews ?? []}
1847
+ lockedKey={lockedKey}
1848
+ onApply={(patch) => onCopyConfig?.(patch)}
1849
+ onClose={() => setCopying(false)}
1850
+ />
1851
+ </AnchoredOverlay>
1852
+ )}
1853
  </div>
1854
  );
1855
  }
 
1890
  <div className="cg-cond-line" key={i}>
1891
  <span className="cg-cond-prefix">{i === 0 ? "Sort by" : "then by"}</span>
1892
  <span className="cg-cond-row">
1893
+ {/* Item 20 β€” and it closes a latent `withCurrent` hole on the way: a sort on a
1894
+ field the table no longer has used to render as this list's FIRST option,
1895
+ so the rule said one thing and the row showed another. The picker renders
1896
+ the unresolvable key in its `is-missing` slot instead. */}
1897
+ <FieldSelectButton
1898
+ className="cg-cond-field"
1899
+ ariaLabel="Sort field"
1900
  value={rule.colId}
1901
+ onChange={(key) => update(i, { colId: key })}
1902
+ fields={fields.map((fl) => ({
1903
+ key: fl.key, label: fl.label, type: fl.type,
1904
+ }))}
1905
+ />
 
 
 
 
1906
  <select
1907
  className="cg-select cg-cond-op"
1908
  value={rule.dir}
 
2057
  key={f.key}
2058
  className={
2059
  "cg-check-row" +
2060
+ // Item 12 β€” the ROW is the control (clicking anywhere on it toggles the
2061
+ // checkbox, which the <label> wrapper has always done: measured, not assumed
2062
+ // β€” `useOverlayLayer`'s pointerdown listener returns early inside its own
2063
+ // panel, so nothing cancels label activation). What the row could NOT do was
2064
+ // SAY which state it was in without reading a 15px checkbox, so a hidden
2065
+ // field's row now reads as hidden. The checkbox stays: it is the a11y control
2066
+ // and the keyboard one.
2067
+ (on ? "" : " is-off") +
2068
  (locked ? " is-locked" : "") +
2069
  (dragKey === f.key ? " is-dragging" : "") +
2070
  (overKey === f.key && dragKey !== null && dragKey !== f.key
 
2217
  <div className="cg-builder-empty">No field matches your search.</div>
2218
  )}
2219
  </div>
2220
+ {/* Item 12 (owner, 2026-08-02) β€” the two bulk actions sit in a quiet grey box rather
2221
+ than floating under a hairline. They act on ALL fields at once, which is a different
2222
+ kind of act from the per-row checkboxes above them; the box says so without a second
2223
+ heading, and it is what Airtable does with the same pair. */}
2224
+ <div className="cg-pop-footer cg-fields-footer">
2225
  <button
2226
  type="button"
2227
  className="cg-link-btn"
 
2269
  unresolvedCount = 0,
2270
  lists = [],
2271
  cohortLock,
2272
+ copyViews,
2273
+ onCopyConfig,
2274
  search,
2275
  onSearch,
2276
  recordCount,
 
2365
 
2366
  {/* Fields β€” show / hide columns, searchable, Pre-set chips (item 7 remainder) */}
2367
  {/* Owner item 23 β€” "Hide fields", the panel's actual job and Airtable's wording. */}
2368
+ <Popover label="Hide fields" icon={<EyeOffIcon />} active={shownCount < fields.length}>
2369
  {() => (
2370
  <FieldsPanel
2371
  fields={orderedFields ?? fields}
 
2405
  onFilterConj={onFilterConj}
2406
  statusValues={statusValues}
2407
  cohortLock={cohortLock}
2408
+ lockedKey={lockedKey}
2409
+ copyViews={copyViews}
2410
+ onCopyConfig={onCopyConfig}
2411
  />
2412
  )}
2413
  </Popover>
 
2519
  )}
2520
  </Popover>
2521
 
2522
+ {/* Item 14 (owner, 2026-08-02) β€” SEARCH sits immediately right of "Rows", inside the
2523
+ control cluster, not marooned across the spacer. Deliberately BEFORE `cohortAction`:
2524
+ that slot is empty on the customer surface and holds "+ Add customers" on the cohort
2525
+ one, so putting search after it would make "immediately right of Rows" true on one
2526
+ page and false on the other. The spacer below now pushes only the COUNT to the far
2527
+ edge, which is the one thing in this strip that belongs there. */}
2528
  <div className="cg-search">
2529
  <span className="cg-search-icon" aria-hidden>
2530
  <IconSearch />
 
2548
  )}
2549
  </div>
2550
 
2551
+ {cohortAction}
2552
+
2553
+ <span className="cg-tb-spacer" />
2554
+
2555
  {pendingMeasureCount > 0 && (
2556
  // A measure condition is answered by the server. Between the keystroke and the answer
2557
  // the condition matches NOTHING β€” never everything, which would show every row under a
web/src/customer-grid/ViewSidebar.tsx CHANGED
@@ -36,7 +36,7 @@ import {
36
  MODE_LABELS,
37
  MODE_TONE,
38
  } from "./iconShapes";
39
- import { FolderMark, LockMark, ToneModeIcon } from "./icons";
40
  import { groupByFolder } from "./folders";
41
 
42
  interface ViewSidebarProps {
@@ -1062,7 +1062,7 @@ export default function ViewSidebar({
1062
  setMenu(null);
1063
  }}
1064
  >
1065
- Export
1066
  </button>
1067
  <div className="cg-menu-sep" role="separator" aria-hidden />
1068
  </>
@@ -1080,7 +1080,7 @@ export default function ViewSidebar({
1080
  setMenu(null);
1081
  }}
1082
  >
1083
- Rename
1084
  </button>
1085
  )}
1086
  {canEditMenuView && (
@@ -1093,7 +1093,10 @@ export default function ViewSidebar({
1093
  setMenu(null);
1094
  }}
1095
  >
1096
- {menuView.note ? "Edit description" : "Add description"}
 
 
 
1097
  </button>
1098
  )}
1099
  <button
@@ -1104,7 +1107,7 @@ export default function ViewSidebar({
1104
  setMenu(null);
1105
  }}
1106
  >
1107
- Duplicate
1108
  </button>
1109
  {onAddToList && (
1110
  <button
@@ -1118,7 +1121,7 @@ export default function ViewSidebar({
1118
  setMenu(null);
1119
  }}
1120
  >
1121
- Add to cohort
1122
  </button>
1123
  )}
1124
  {/* Item 12 (C-LOCK) β€” LOCK the view to a cohort. This menu is the ONLY emitter of
@@ -1139,7 +1142,10 @@ export default function ViewSidebar({
1139
  setMenu(null);
1140
  }}
1141
  >
1142
- {menuView.config?.cohortLock ? "Change cohort lock…" : "Lock to cohort…"}
 
 
 
1143
  </button>
1144
  )}
1145
  {/* I12 (C3) β€” freeze the DISPLAY MODE. Offered only to the creator or an admin,
@@ -1155,9 +1161,21 @@ export default function ViewSidebar({
1155
  setMenu(null);
1156
  }}
1157
  >
1158
- {isModeFrozen(menuView)
1159
- ? "Unlock view"
1160
- : `Lock as ${MODE_LABELS[viewDisplayMode(menuView)]}`}
 
 
 
 
 
 
 
 
 
 
 
 
1161
  </button>
1162
  )}
1163
  {/* ⚠ Delete is gated on the HOST's actual rule, NOT on `locked`. C3 widens `locked`
@@ -1173,7 +1191,7 @@ export default function ViewSidebar({
1173
  setMenu(null);
1174
  }}
1175
  >
1176
- Delete
1177
  </button>
1178
  )}
1179
  </AnchoredOverlay>
 
36
  MODE_LABELS,
37
  MODE_TONE,
38
  } from "./iconShapes";
39
+ import { FolderMark, LockMark, MenuLabel, ModeIcon, ToneModeIcon } from "./icons";
40
  import { groupByFolder } from "./folders";
41
 
42
  interface ViewSidebarProps {
 
1062
  setMenu(null);
1063
  }}
1064
  >
1065
+ <MenuLabel icon="download" text="Export" />
1066
  </button>
1067
  <div className="cg-menu-sep" role="separator" aria-hidden />
1068
  </>
 
1080
  setMenu(null);
1081
  }}
1082
  >
1083
+ <MenuLabel icon="rename" text="Rename" />
1084
  </button>
1085
  )}
1086
  {canEditMenuView && (
 
1093
  setMenu(null);
1094
  }}
1095
  >
1096
+ <MenuLabel
1097
+ icon="description"
1098
+ text={menuView.note ? "Edit description" : "Add description"}
1099
+ />
1100
  </button>
1101
  )}
1102
  <button
 
1107
  setMenu(null);
1108
  }}
1109
  >
1110
+ <MenuLabel icon="duplicate" text="Duplicate" />
1111
  </button>
1112
  {onAddToList && (
1113
  <button
 
1121
  setMenu(null);
1122
  }}
1123
  >
1124
+ <MenuLabel icon="cohortAdd" text="Add to cohort" />
1125
  </button>
1126
  )}
1127
  {/* Item 12 (C-LOCK) β€” LOCK the view to a cohort. This menu is the ONLY emitter of
 
1142
  setMenu(null);
1143
  }}
1144
  >
1145
+ <MenuLabel
1146
+ icon="permissions"
1147
+ text={menuView.config?.cohortLock ? "Change cohort lock…" : "Lock to cohort…"}
1148
+ />
1149
  </button>
1150
  )}
1151
  {/* I12 (C3) β€” freeze the DISPLAY MODE. Offered only to the creator or an admin,
 
1161
  setMenu(null);
1162
  }}
1163
  >
1164
+ {/* The FROZEN action wears the mode's own mark rather than a second padlock:
1165
+ "Lock as Kanban" beside the kanban glyph says what gets frozen, which a
1166
+ padlock cannot. Unlocking is the undo, so it takes the open shackle. */}
1167
+ <MenuLabel
1168
+ icon={
1169
+ isModeFrozen(menuView)
1170
+ ? "unlock"
1171
+ : <ModeIcon mode={viewDisplayMode(menuView)} size={16} />
1172
+ }
1173
+ text={
1174
+ isModeFrozen(menuView)
1175
+ ? "Unlock view"
1176
+ : `Lock as ${MODE_LABELS[viewDisplayMode(menuView)]}`
1177
+ }
1178
+ />
1179
  </button>
1180
  )}
1181
  {/* ⚠ Delete is gated on the HOST's actual rule, NOT on `locked`. C3 widens `locked`
 
1191
  setMenu(null);
1192
  }}
1193
  >
1194
+ <MenuLabel icon="trash" text="Delete" />
1195
  </button>
1196
  )}
1197
  </AnchoredOverlay>
web/src/customer-grid/cells.ts CHANGED
@@ -32,16 +32,24 @@ import type {
32
  GridCell,
33
  } from "@glideapps/glide-data-grid";
34
  import type { Field } from "./types";
35
- import { ratingMax } from "./types";
36
- import { STATUS_BUBBLE } from "./theme";
37
- import { optionTint } from "./choiceColors";
38
- import { checkboxOn, dateTimeText, num, numberText } from "./display";
39
- import type { CellValue } from "./display";
 
 
 
 
40
 
41
  // Wave-7 (item W2): the pure display-string half moved to display.ts so the
42
  // export builders can run under node without dragging glide along. Re-exported
43
  // here so every existing import keeps working unchanged.
44
  export { checkboxOn, dateTimeText, formatDisplay } from "./display";
 
 
 
 
45
 
46
  /** Stable pill tint for a user-defined choice. Hashed from the VALUE, so the same choice keeps
47
  * its colour across rows, sessions and users without anyone picking one β€” and a renamed option
@@ -106,6 +114,122 @@ function drawStar(
106
  }
107
  }
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  /** Registered once on the DataEditor (customRenderers). Pure canvas paths. */
110
  export const ratingCellRenderer: CustomRenderer<RatingCell> = {
111
  kind: GridCellKind.Custom,
@@ -136,7 +260,14 @@ export const ratingCellRenderer: CustomRenderer<RatingCell> = {
136
  * computed. A real 0 arrives as the NUMBER 0 (the pool and the zero-group both emit it) and
137
  * still renders "$0". Mirrors the blank-vs-zero rule the engine already has (`isBlank`: 0 is
138
  * NOT blank). */
139
- export function makeCell(field: Field, v: CellValue, editable: boolean): GridCell {
 
 
 
 
 
 
 
140
  const ro = { allowOverlay: editable, readonly: !editable };
141
  const blank = v == null || v === "";
142
 
@@ -239,20 +370,37 @@ export function makeCell(field: Field, v: CellValue, editable: boolean): GridCel
239
  allowOverlay: false,
240
  themeOverride: STATUS_BUBBLE[String(v ?? "").toLowerCase()],
241
  };
242
- case "select":
243
  case "user": {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  // Picked, never typed. `allowOverlay:false` keeps glide's text editor OUT of the way β€”
245
  // a free-text editor on a constrained field is how a column ends up holding "Done",
246
  // "done" and "DONE" as three different values. CustomerGrid opens an anchored picker on
247
  // click instead (onCellClicked), which is also why this stays dependency-free: glide's
248
  // dropdown cell lives in a separate package we deliberately have not added.
249
  const s = String(v ?? "");
250
- const tint = optionTint(field, s);
251
  return {
252
  kind: GridCellKind.Bubble,
253
  data: s ? [s] : [],
254
  allowOverlay: false,
255
- themeOverride: tint ? { bgBubble: tint.bg, textBubble: tint.fg } : undefined,
256
  };
257
  }
258
  case "multiselect": {
@@ -263,7 +411,7 @@ export function makeCell(field: Field, v: CellValue, editable: boolean): GridCel
263
  .split(",")
264
  .map((s) => s.trim())
265
  .filter((s) => s !== "");
266
- const tint = parts.length ? optionTint(field, parts[0]) : undefined;
267
  return {
268
  kind: GridCellKind.Bubble,
269
  data: parts,
 
32
  GridCell,
33
  } from "@glideapps/glide-data-grid";
34
  import type { Field } from "./types";
35
+ import { ratingMax } from "./types";
36
+ import { STATUS_BUBBLE } from "./theme";
37
+ // ⚠ ALIASED: this module has its own `pickTint` (the bubble table above) and choiceColors has
38
+ // another. C-AVATAR names choiceColors' as the avatar fallback's source, so the two stay
39
+ // distinguishable at the call site rather than one silently shadowing the other.
40
+ import { optionTint, pickTint as choicePickTint } from "./choiceColors";
41
+ import { avatarInitials, avatarSize, checkboxOn, dateTimeText, num, numberText, userCellPayload }
42
+ from "./display";
43
+ import type { CellValue, UserCellData } from "./display";
44
 
45
  // Wave-7 (item W2): the pure display-string half moved to display.ts so the
46
  // export builders can run under node without dragging glide along. Re-exported
47
  // here so every existing import keeps working unchanged.
48
  export { checkboxOn, dateTimeText, formatDisplay } from "./display";
49
+ // C-AVATAR β€” the pure halves live in display.ts (node-reachable, so a gate can hold them);
50
+ // re-exported here so callers keep importing "the cell module" for everything avatar-shaped.
51
+ export { avatarInitials, avatarSize, userCellPayload } from "./display";
52
+ export type { UserCellData } from "./display";
53
 
54
  /** Stable pill tint for a user-defined choice. Hashed from the VALUE, so the same choice keeps
55
  * its colour across rows, sessions and users without anyone picking one β€” and a renamed option
 
114
  }
115
  }
116
 
117
+ // --- user: the assignee AVATAR (wave-14 item 11 / R6 / contract C-AVATAR) -----
118
+ //
119
+ // R6: a grid cell shows the PHOTO OR ICON ONLY β€” no name text. (Pickers and the record modal
120
+ // are where a name belongs; the column is a glanceable "who owns this", and thirty repetitions
121
+ // of "Farhan Sanyoto" down a column is the thing the owner asked to stop reading.)
122
+ //
123
+ // The name is still the cell's COPY value. An avatar-only cell with no `copyData` makes an
124
+ // assignee column copy as nothing β€” a real regression that no screenshot shows.
125
+
126
+ export type UserCell = CustomCell<UserCellData>;
127
+
128
+ /**
129
+ * Decoded avatar images, keyed by their data URL. `null` = this URL failed to decode, so we
130
+ * stop retrying it and paint the fallback forever (a corrupt stored photo must not spin).
131
+ *
132
+ * ⚠ Module scope, like the tint tables above: an Image per cell per frame would re-decode a
133
+ * base64 payload on every scroll tick.
134
+ */
135
+ const _avatarImgs = new Map<string, HTMLImageElement | null>();
136
+ let _avatarRepaint: (() => void) | undefined;
137
+
138
+ /**
139
+ * ⚠ THE HALF THAT IS EASY TO FORGET. glide repaints when `getCellContent`'s identity changes β€”
140
+ * it knows nothing about an `Image.onload` that fires three frames later. Without this hook the
141
+ * fallback initials paint once and STAY, and because the fallback is a deliberate, correct-looking
142
+ * design, nothing on screen says the photo never arrived. (Same shape as wave-13's "honest empty
143
+ * state that made the failure look deliberate".)
144
+ *
145
+ * CustomerGrid calls this once and bumps a counter that is in `useGetCellContent`'s deps.
146
+ */
147
+ export function setAvatarRepaint(fn: (() => void) | undefined): void {
148
+ _avatarRepaint = fn;
149
+ }
150
+
151
+ function avatarImage(dataUrl: string): HTMLImageElement | null {
152
+ const hit = _avatarImgs.get(dataUrl);
153
+ if (hit !== undefined) return hit;
154
+ // A DOM-less environment (a node gate, a locked-down embed) has no Image constructor. Cache
155
+ // the refusal so the fallback is what paints, rather than throwing inside a draw call.
156
+ if (typeof Image === "undefined") {
157
+ _avatarImgs.set(dataUrl, null);
158
+ return null;
159
+ }
160
+ const img = new Image();
161
+ _avatarImgs.set(dataUrl, img);
162
+ img.onload = () => _avatarRepaint?.();
163
+ img.onerror = () => {
164
+ _avatarImgs.set(dataUrl, null);
165
+ _avatarRepaint?.();
166
+ };
167
+ img.src = dataUrl;
168
+ return img;
169
+ }
170
+
171
+ /** C-AVATAR β€” the circle, photo or not. Exported so any other canvas surface paints the same
172
+ * avatar rather than growing a second almost-matching one. */
173
+ export function drawAvatar(
174
+ ctx: CanvasRenderingContext2D,
175
+ cx: number,
176
+ cy: number,
177
+ r: number,
178
+ name: string,
179
+ photo: string | undefined,
180
+ fontFamily: string
181
+ ): void {
182
+ const img = photo ? avatarImage(photo) : null;
183
+ // `complete` alone is not enough: a FAILED decode is also "complete", with a zero natural size.
184
+ if (img && img.complete && img.naturalWidth > 0) {
185
+ ctx.save();
186
+ ctx.beginPath();
187
+ ctx.arc(cx, cy, r, 0, Math.PI * 2);
188
+ ctx.clip();
189
+ // COVER, not contain: a portrait must fill the circle, not sit letterboxed inside it.
190
+ const scale = Math.max((r * 2) / img.naturalWidth, (r * 2) / img.naturalHeight);
191
+ const w = img.naturalWidth * scale;
192
+ const h = img.naturalHeight * scale;
193
+ ctx.drawImage(img, cx - w / 2, cy - h / 2, w, h);
194
+ ctx.restore();
195
+ return;
196
+ }
197
+ // The fallback, and it is the DEFAULT state until HOST's C-AVATAR lands β€” never a broken-image
198
+ // glyph. Hashed from the full name so one person keeps one colour across rows and sessions.
199
+ const tint = choicePickTint(name);
200
+ ctx.save();
201
+ ctx.beginPath();
202
+ ctx.arc(cx, cy, r, 0, Math.PI * 2);
203
+ ctx.fillStyle = tint.bg;
204
+ ctx.fill();
205
+ ctx.fillStyle = tint.fg;
206
+ ctx.font = `600 ${Math.round(r * 0.9)}px ${fontFamily}`;
207
+ ctx.textAlign = "center";
208
+ ctx.textBaseline = "middle";
209
+ ctx.fillText(avatarInitials(name), cx, cy + 0.5);
210
+ ctx.restore();
211
+ }
212
+
213
+ /** Registered once on the DataEditor (customRenderers), beside the rating renderer. */
214
+ export const userCellRenderer: CustomRenderer<UserCell> = {
215
+ kind: GridCellKind.Custom,
216
+ isMatch: (cell): cell is UserCell =>
217
+ (cell.data as UserCellData | undefined)?.kind === "aios-user",
218
+ draw: (args, cell) => {
219
+ const { ctx, rect, theme } = args;
220
+ const { name, photo } = cell.data;
221
+ if (!name) return true; // unassigned paints nothing β€” an empty circle would look assigned
222
+ const d = avatarSize(rect.height);
223
+ const cx = rect.x + theme.cellHorizontalPadding + d / 2;
224
+ const cy = rect.y + rect.height / 2;
225
+ // Never paint outside the cell: a column dragged narrow drops the avatar rather than
226
+ // bleeding it over its neighbour.
227
+ if (cx + d / 2 > rect.x + rect.width - theme.cellHorizontalPadding) return true;
228
+ drawAvatar(ctx, cx, cy, d / 2, name, photo, theme.fontFamily);
229
+ return true;
230
+ },
231
+ };
232
+
233
  /** Registered once on the DataEditor (customRenderers). Pure canvas paths. */
234
  export const ratingCellRenderer: CustomRenderer<RatingCell> = {
235
  kind: GridCellKind.Custom,
 
260
  * computed. A real 0 arrives as the NUMBER 0 (the pool and the zero-group both emit it) and
261
  * still renders "$0". Mirrors the blank-vs-zero rule the engine already has (`isBlank`: 0 is
262
  * NOT blank). */
263
+ export function makeCell(
264
+ field: Field,
265
+ v: CellValue,
266
+ editable: boolean,
267
+ /** C-AVATAR β€” username β†’ data URL, straight off `GridWorkspace.userAvatars`. Absent, or a
268
+ * username absent from it, paints the initials fallback. */
269
+ userAvatars?: Record<string, string>
270
+ ): GridCell {
271
  const ro = { allowOverlay: editable, readonly: !editable };
272
  const blank = v == null || v === "";
273
 
 
370
  allowOverlay: false,
371
  themeOverride: STATUS_BUBBLE[String(v ?? "").toLowerCase()],
372
  };
 
373
  case "user": {
374
+ // Wave-14 item 11 / R6 β€” the AVATAR ONLY, no name text. Split out of the `select` branch
375
+ // below (it was a name pill until this wave) because "who owns this" is a face, not a
376
+ // sentence, once a column has thirty rows of it.
377
+ //
378
+ // Still `allowOverlay:false`, for the same reason `select` is: the value is PICKED, never
379
+ // typed, and CustomerGrid opens its anchored picker on click (onCellClicked β†’ isPickType,
380
+ // which already includes `user`, so the click path needs no change).
381
+ //
382
+ // ⚠ `copyData` carries the NAME. The cell shows no text, so without this the column would
383
+ // copy and export as empty β€” invisible in every screenshot. Built by `userCellPayload` in
384
+ // display.ts so a node gate can actually assert that (this module imports glide).
385
+ return {
386
+ kind: GridCellKind.Custom,
387
+ ...userCellPayload(String(v ?? ""), userAvatars),
388
+ allowOverlay: false,
389
+ };
390
+ }
391
+ case "select": {
392
  // Picked, never typed. `allowOverlay:false` keeps glide's text editor OUT of the way β€”
393
  // a free-text editor on a constrained field is how a column ends up holding "Done",
394
  // "done" and "DONE" as three different values. CustomerGrid opens an anchored picker on
395
  // click instead (onCellClicked), which is also why this stays dependency-free: glide's
396
  // dropdown cell lives in a separate package we deliberately have not added.
397
  const s = String(v ?? "");
398
+ const tint = optionTint(field, s);
399
  return {
400
  kind: GridCellKind.Bubble,
401
  data: s ? [s] : [],
402
  allowOverlay: false,
403
+ themeOverride: tint ? { bgBubble: tint.bg, textBubble: tint.fg } : undefined,
404
  };
405
  }
406
  case "multiselect": {
 
411
  .split(",")
412
  .map((s) => s.trim())
413
  .filter((s) => s !== "");
414
+ const tint = parts.length ? optionTint(field, parts[0]) : undefined;
415
  return {
416
  kind: GridCellKind.Bubble,
417
  data: parts,
web/src/customer-grid/choiceColors.ts CHANGED
@@ -24,6 +24,94 @@ export function normalizeOptionColor(value: unknown): string | undefined {
24
  return value.trim().toUpperCase();
25
  }
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  export function pickTint(value: string): ChoiceTint {
28
  let hash = 0;
29
  for (let i = 0; i < value.length; i += 1)
@@ -72,10 +160,25 @@ export function optionTextColor(background: string): string {
72
  : "#FFFFFF";
73
  }
74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  export function optionTint(field: Field, value: string): ChoiceTint | undefined {
76
  if (!value || field.colorCodeOptions === false) return undefined;
77
  const custom = assignedOptionColor(field, value);
78
- return custom ? { bg: custom, fg: optionTextColor(custom) } : pickTint(value);
79
  }
80
 
81
  /** Default shown by the field editor before a user chooses a custom colour. */
 
24
  return value.trim().toUpperCase();
25
  }
26
 
27
+ // ---------------------------------------------------------------------------
28
+ // Wave-14 item 22 (R5) β€” THE BRAND SWATCHES: the 5 palette hues Γ— 2 strengths.
29
+ //
30
+ // The option colour used to be an `<input type="color">`, i.e. sixteen million choices in a
31
+ // product whose entire visual argument is five. R5 fixes the offer at ten: each hue's `-tint`
32
+ // (the wash the app already uses for chips and involved columns) and its `-pastel` β€” the
33
+ // `--lp-<hue>` FILL weight.
34
+ //
35
+ // ⚠ THE INK IS MEASURED, NOT ASSUMED, and the two strengths do not take the same one.
36
+ // The palette law puts text on the `-deep` weight, and on a TINT that measures 4.98–5.35:1
37
+ // (AA for normal text). On a PASTEL the same inks measure 3.10–4.06:1 β€” every one of them
38
+ // fails. So a pastel swatch takes the standard dark ink, which measures 8.25–11.58:1 there.
39
+ // The law is about which weight carries text on the tint wash; a stronger fill needs a
40
+ // stronger ink, and the alternative was ten swatches of which five were unreadable.
41
+ // blue's tint ink is #4F6079, NOT `--lp-blue-deep` (#768FB6): that token's own comment in
42
+ // index.css reserves it for "focus rings, control borders" and it measures 2.96:1 here.
43
+ // The shipped OPTION_PALETTE already made this call; this keeps it.
44
+ // ---------------------------------------------------------------------------
45
+
46
+ /** The standard dark ink, from `optionTextColor`'s own pair. */
47
+ const INK_DARK = "#182230";
48
+
49
+ export type SwatchStrength = "tint" | "pastel";
50
+
51
+ export interface BrandSwatch extends ChoiceTint {
52
+ /** Stable id for keys/tests; `<hue>-<strength>`. */
53
+ id: string;
54
+ hue: "blue" | "green" | "yellow" | "red" | "purple";
55
+ strength: SwatchStrength;
56
+ /** Plain words, for the swatch's title and accessible name. */
57
+ label: string;
58
+ }
59
+
60
+ export const BRAND_SWATCHES: readonly BrandSwatch[] = [
61
+ { id: "blue-tint", hue: "blue", strength: "tint", bg: "#EDF3FD", fg: "#4F6079", label: "Light blue" },
62
+ { id: "green-tint", hue: "green", strength: "tint", bg: "#EBF6EF", fg: "#35754E", label: "Light green" },
63
+ { id: "yellow-tint", hue: "yellow", strength: "tint", bg: "#FBF4E0", fg: "#7E6428", label: "Light yellow" },
64
+ { id: "red-tint", hue: "red", strength: "tint", bg: "#FCEEEC", fg: "#A3453C", label: "Light red" },
65
+ { id: "purple-tint", hue: "purple", strength: "tint", bg: "#F1EEFB", fg: "#6B57A8", label: "Light purple" },
66
+ { id: "blue-pastel", hue: "blue", strength: "pastel", bg: "#9DBFF2", fg: INK_DARK, label: "Blue" },
67
+ { id: "green-pastel", hue: "green", strength: "pastel", bg: "#A5D8B4", fg: INK_DARK, label: "Green" },
68
+ { id: "yellow-pastel", hue: "yellow", strength: "pastel", bg: "#F5D989", fg: INK_DARK, label: "Yellow" },
69
+ { id: "red-pastel", hue: "red", strength: "pastel", bg: "#F0A8A0", fg: INK_DARK, label: "Red" },
70
+ { id: "purple-pastel", hue: "purple", strength: "pastel", bg: "#C3B3EE", fg: INK_DARK, label: "Purple" },
71
+ ];
72
+
73
+ /**
74
+ * The swatch a stored colour reads as.
75
+ *
76
+ * Distance is the "redmean" weighted Euclidean approximation rather than raw RGB: plain RGB
77
+ * distance calls #EDF3FD closer to #FBF4E0 than to #9DBFF2, which would map a pale blue onto
78
+ * the yellow family. Exact palette members land on themselves (distance 0), so a colour
79
+ * already on the palette is not "nearest" to anything else.
80
+ *
81
+ * ⚠ DISPLAY ONLY. Nothing here rewrites what is stored β€” `normalizeOptionColor`,
82
+ * `optionSettings` and `optionAppearanceSignature` are the PERSIST path and are untouched, so
83
+ * an untouched legacy field stays byte-stable and a stored colour changes only when somebody
84
+ * re-picks one.
85
+ */
86
+ export function nearestSwatch(value: unknown): BrandSwatch | undefined {
87
+ const hex = normalizeOptionColor(value);
88
+ if (!hex) return undefined;
89
+ const r = channel(hex, 1);
90
+ const g = channel(hex, 3);
91
+ const b = channel(hex, 5);
92
+ let best = BRAND_SWATCHES[0];
93
+ let bestD = Number.POSITIVE_INFINITY;
94
+ for (const swatch of BRAND_SWATCHES) {
95
+ const dr = r - channel(swatch.bg, 1);
96
+ const dg = g - channel(swatch.bg, 3);
97
+ const db = b - channel(swatch.bg, 5);
98
+ const rmean = (r + channel(swatch.bg, 1)) / 2;
99
+ const d = (2 + rmean / 256) * dr * dr + 4 * dg * dg + (2 + (255 - rmean) / 256) * db * db;
100
+ if (d < bestD) {
101
+ bestD = d;
102
+ best = swatch;
103
+ }
104
+ }
105
+ return best;
106
+ }
107
+
108
+ /** A stored colour, rendered on-brand: its nearest swatch, or (for an unparseable value) the
109
+ * legacy behaviour of the colour itself under whichever standard ink reads on it. */
110
+ export function brandedTint(color: string): ChoiceTint {
111
+ const swatch = nearestSwatch(color);
112
+ return swatch ? { bg: swatch.bg, fg: swatch.fg } : { bg: color, fg: optionTextColor(color) };
113
+ }
114
+
115
  export function pickTint(value: string): ChoiceTint {
116
  let hash = 0;
117
  for (let i = 0; i < value.length; i += 1)
 
160
  : "#FFFFFF";
161
  }
162
 
163
+ /**
164
+ * The tint a value is PAINTED in β€” grid cells, kanban cards, the cell picker, every surface.
165
+ *
166
+ * Item 22: a user-assigned colour now renders as its nearest BRAND SWATCH. That is the
167
+ * "everywhere" half of the owner's item β€” a magenta chosen through the old free-RGB input
168
+ * would otherwise keep painting magenta on every screen for as long as nobody re-picked it,
169
+ * and the point of removing the input was that the product stops showing colours that are not
170
+ * its own. The stored value is untouched (see `nearestSwatch`), so nothing is lost and the
171
+ * next re-pick is what makes it permanent.
172
+ *
173
+ * The DEFAULT branch is deliberately NOT snapped: `pickTint` already returns members of
174
+ * `OPTION_PALETTE`, five of which ARE the tint swatches, and re-hashing labels onto the wider
175
+ * list would repaint every uncoloured option in every tenant AND break `optionSettings`'
176
+ * byte-stability rule, which compares against `defaultOptionColor` to decide what to persist.
177
+ */
178
  export function optionTint(field: Field, value: string): ChoiceTint | undefined {
179
  if (!value || field.colorCodeOptions === false) return undefined;
180
  const custom = assignedOptionColor(field, value);
181
+ return custom ? brandedTint(custom) : pickTint(value);
182
  }
183
 
184
  /** Default shown by the field editor before a user chooses a custom colour. */
web/src/customer-grid/copyConfig.ts ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // customer-grid / copyConfig.ts
3
+ // Wave-14 item 13 (contract C-COPYVIEW) β€” "Copy configuration from <view> to this view".
4
+ //
5
+ // PURE. The modal collects a source view and a set of parts; this turns that into the ONE
6
+ // `Partial<ViewConfig>` the caller passes to `updateConfig`. It is a separate module with its
7
+ // own gate for one reason: it is the only thing in PANEL's fence this wave that writes
8
+ // DURABLE state, and the wrong answer here is silent β€” a patch that names one key too many
9
+ // overwrites a property of the target view that the user never asked about and cannot see was
10
+ // touched until they next open the thing it broke.
11
+ //
12
+ // THE RULES, in the order they matter:
13
+ //
14
+ // 1. **An ALLOW-LIST, never a spread.** The patch can only ever contain the six keys below.
15
+ // `ViewConfig` also carries `display`, `widths`, `memberPids`, `frozenCount` and
16
+ // `cohortLock`; a `{...source}` with a few `delete`s would silently start copying the
17
+ // seventh key the day somebody adds one.
18
+ // 2. **`cohortLock` is never copied, even when "Filter conditions" is chosen.** A lock is not
19
+ // a condition β€” the engine intersects it FIRST, it cannot be expressed or removed as a
20
+ // row, and the host validates it against the sets the SESSION can see
21
+ // ([[cg-cohort-set-conditions]]). Copying it would hand one view's permission boundary to
22
+ // another view by way of a checkbox labelled "Filter conditions".
23
+ // 3. **`filters` drags `filterConj` with it.** They are one answer to one question. Copy the
24
+ // tree without the root conjunction and a source view meaning "any of these three" lands
25
+ // as "all of these three" β€” same rows on screen, different set, nothing to see.
26
+ // 4. **Deep copy.** A patch holding the SOURCE's own arrays would alias two views onto one
27
+ // filter tree: editing a condition in the target would edit it in the source too, until
28
+ // something forced a reload. JSON round-trip, which every slice here survives (they are
29
+ // the wire shapes).
30
+ // 5. **Nothing chosen = `{}`.** The caller must treat an empty patch as a no-op rather than
31
+ // as "write nothing over everything".
32
+ // ---------------------------------------------------------------------------
33
+
34
+ import type { ViewConfig } from "./types";
35
+
36
+ /** The slices offered, in the modal's own order. */
37
+ export type CopyPart =
38
+ | "filters" | "sorts" | "groupBy" | "visible" | "order" | "rowHeightMode";
39
+
40
+ /**
41
+ * The offer, v1 (C-COPYVIEW). `reference/Airtable 13.png` also lists "Column widths and row
42
+ * height"; `widths` is deliberately NOT here β€” column widths are a property of how wide THIS
43
+ * reader dragged THIS view's columns, and importing them silently re-lays-out a table the
44
+ * user was not complaining about. It is one line to add if the owner asks for it.
45
+ */
46
+ export const COPY_PARTS: readonly { key: CopyPart; label: string; blurb: string }[] = [
47
+ { key: "filters", label: "Filter conditions",
48
+ blurb: "Which records the view shows, and how the conditions combine." },
49
+ { key: "sorts", label: "Sorts", blurb: "The order records are listed in." },
50
+ { key: "groupBy", label: "Groups", blurb: "The field records are bucketed by." },
51
+ { key: "visible", label: "Hidden fields", blurb: "Which columns are shown." },
52
+ { key: "order", label: "Field order", blurb: "Left-to-right column order." },
53
+ { key: "rowHeightMode", label: "Row height", blurb: "Short, medium or tall rows." },
54
+ ];
55
+
56
+ export const COPY_PART_KEYS: readonly CopyPart[] = COPY_PARTS.map((p) => p.key);
57
+
58
+ export function isCopyPart(value: unknown): value is CopyPart {
59
+ return typeof value === "string" && (COPY_PART_KEYS as readonly string[]).includes(value);
60
+ }
61
+
62
+ /** JSON round-trip: every slice here is a wire shape, so this is a faithful deep copy AND it
63
+ * drops any `undefined` member, which is exactly how absent is spelled on the wire. */
64
+ function clone<T>(value: T): T {
65
+ return JSON.parse(JSON.stringify(value)) as T;
66
+ }
67
+
68
+ /**
69
+ * The patch. `lockedKey` β€” when given β€” is force-kept in a copied `visible` list: the identity
70
+ * column cannot be hidden, and a source view that somehow lacks it would otherwise hand the
71
+ * target a list the grid has to silently correct.
72
+ */
73
+ export function copyViewConfig(
74
+ source: ViewConfig | undefined | null,
75
+ parts: Iterable<CopyPart | string>,
76
+ lockedKey?: string
77
+ ): Partial<ViewConfig> {
78
+ const out: Partial<ViewConfig> = {};
79
+ if (!source) return out;
80
+ const chosen = new Set<CopyPart>();
81
+ for (const part of parts) if (isCopyPart(part)) chosen.add(part);
82
+ if (chosen.size === 0) return out;
83
+
84
+ if (chosen.has("filters")) {
85
+ out.filters = clone(Array.isArray(source.filters) ? source.filters : []);
86
+ // Rule 3 β€” the root conjunction rides with the tree. `undefined` is a legal value here
87
+ // (legacy views mean "and"), and writing it explicitly is how the target stops meaning
88
+ // whatever IT used to mean.
89
+ out.filterConj = source.filterConj;
90
+ }
91
+ if (chosen.has("sorts")) out.sorts = clone(Array.isArray(source.sorts) ? source.sorts : []);
92
+ if (chosen.has("groupBy")) out.groupBy = source.groupBy ?? null;
93
+ if (chosen.has("visible")) {
94
+ const visible = clone(Array.isArray(source.visible) ? source.visible : []);
95
+ // One statement, deliberately: the gate mutates a compiled LINE, and a wrapped ternary
96
+ // carries tsc's current indentation into the needle (wave-13 RECORD learning).
97
+ const keepLocked = !!lockedKey && !visible.includes(lockedKey);
98
+ out.visible = keepLocked ? [lockedKey!, ...visible] : visible;
99
+ }
100
+ if (chosen.has("order")) out.order = clone(Array.isArray(source.order) ? source.order : []);
101
+ if (chosen.has("rowHeightMode") && source.rowHeightMode)
102
+ out.rowHeightMode = source.rowHeightMode;
103
+ return out;
104
+ }
web/src/customer-grid/display.ts CHANGED
@@ -13,6 +13,68 @@ import { ratingMax } from "./types";
13
 
14
  export type CellValue = string | number | null | undefined;
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  export function num(v: CellValue): number {
17
  const n = typeof v === "number" ? v : Number(v);
18
  return Number.isFinite(n) ? n : 0;
 
13
 
14
  export type CellValue = string | number | null | undefined;
15
 
16
+ // --- C-AVATAR (wave-14 item 11): the two PURE halves of the assignee avatar ---
17
+ // They live here rather than in cells.ts for this module's founding reason: cells.ts imports
18
+ // glide, so nothing in it can be reached by a node gate. The canvas drawing stays there; the
19
+ // arithmetic and the string handling β€” the parts that can be wrong in ways a screenshot of one
20
+ // avatar will not show β€” are here, and `cells.ts` re-exports both.
21
+
22
+ /**
23
+ * Up to two letters for the fallback circle.
24
+ *
25
+ * ⚠ The LOCAL PART only. Usernames in this tenant are email-shaped, and splitting
26
+ * "fsanyoto@gmail.com" on its separators gives ["fsanyoto@gmail", "com"] β†’ "FC" β€” a person's
27
+ * avatar reading as their mail provider. Cutting at "@" first gives "FS".
28
+ *
29
+ * ⚠ A HYPHEN IS NOT A SEPARATOR. Space, dot and underscore divide a given name from a family
30
+ * name in a username; a hyphen almost always JOINS a compound one β€” Jo-Anne, Marie-Claire,
31
+ * Al-Rashid. Treating it as a separator turns "jo-anne_smith" into "JA", which is not that
32
+ * person's initials and is wrong in the one way nobody can spot: it looks like initials.
33
+ */
34
+ export function avatarInitials(name: string): string {
35
+ const local = name.split("@")[0];
36
+ const parts = local.trim().split(/[\s._]+/).filter(Boolean);
37
+ if (parts.length === 0) return "?";
38
+ if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
39
+ return (parts[0][0] + parts[1][0]).toUpperCase();
40
+ }
41
+
42
+ /**
43
+ * The avatar's diameter for a row of `height` px: 22 on a comfortable row, never larger, and
44
+ * never so small it stops being a face. Bounded on BOTH sides on purpose β€” a `tall` row (48px)
45
+ * must not grow a 42px portrait, and a `short` one (28px) must not shrink to a dot.
46
+ */
47
+ export function avatarSize(height: number): number {
48
+ return Math.max(14, Math.min(22, height - 6));
49
+ }
50
+
51
+ export interface UserCellData {
52
+ kind: "aios-user";
53
+ /** The assignee's username. "" = unassigned; the cell then paints nothing at all. */
54
+ name: string;
55
+ /** C-AVATAR data URL, when the workspace served one for this user. */
56
+ photo?: string;
57
+ }
58
+
59
+ /**
60
+ * The `user` cell's payload β€” HERE rather than inline in `cells.ts` for one reason: `copyData`.
61
+ *
62
+ * ⚠ R6 removed the NAME from the cell, so the cell renders no text at all. glide's copy and
63
+ * export take `copyData`, which means an assignee column silently copies and exports as EMPTY
64
+ * unless it is set β€” a real regression that appears in no screenshot, because the screenshot
65
+ * shows the avatar working perfectly. `cells.ts` imports glide and is therefore unreachable from
66
+ * a node gate; this is, so the claim can actually be asserted.
67
+ */
68
+ export function userCellPayload(
69
+ name: string,
70
+ userAvatars?: Record<string, string>
71
+ ): { data: UserCellData; copyData: string } {
72
+ return {
73
+ data: { kind: "aios-user", name, photo: userAvatars?.[name] },
74
+ copyData: name,
75
+ };
76
+ }
77
+
78
  export function num(v: CellValue): number {
79
  const n = typeof v === "number" ? v : Number(v);
80
  return Number.isFinite(n) ? n : 0;
web/src/customer-grid/icons.tsx CHANGED
@@ -13,6 +13,7 @@
13
  // fast refresh keeps working (oxlint react/only-export-components).
14
  // ---------------------------------------------------------------------------
15
 
 
16
  import type { DisplayMode, FieldType, FolderIcon, FolderTone } from "./types";
17
  import { DEFAULT_FOLDER_SHAPE, DEFAULT_FOLDER_TONE } from "./types";
18
  import type { IconShape } from "./iconShapes";
@@ -51,13 +52,20 @@ function Shapes({ shapes }: { shapes: IconShape[] }) {
51
  /** The field-type mark for panels/menus (I20). Decorative by default β€” the row
52
  * it sits in already names the field; a screen reader reading "currency icon"
53
  * before every label is noise. Pass `title` where the icon teaches the
54
- * vocabulary (the Fields panel) so hovering it names the type. */
 
 
 
 
 
 
 
55
  export function FieldTypeIcon({
56
  type,
57
  size = 14,
58
  title,
59
  }: {
60
- type: FieldType;
61
  size?: number;
62
  title?: string;
63
  }) {
@@ -72,7 +80,7 @@ export function FieldTypeIcon({
72
  aria-label={title}
73
  >
74
  {title && <title>{title}</title>}
75
- <Shapes shapes={TYPE_SHAPES[type]} />
76
  </svg>
77
  );
78
  }
@@ -177,6 +185,219 @@ export function ChartKindIcon({
177
  );
178
  }
179
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
  /**
181
  * Wave-9 contract C3 (I12) β€” the "this view's mode is frozen" mark. Drawn from the same
182
  * stroke vocabulary as everything else here; deliberately small and muted, because it
 
13
  // fast refresh keeps working (oxlint react/only-export-components).
14
  // ---------------------------------------------------------------------------
15
 
16
+ import type { ReactNode } from "react";
17
  import type { DisplayMode, FieldType, FolderIcon, FolderTone } from "./types";
18
  import { DEFAULT_FOLDER_SHAPE, DEFAULT_FOLDER_TONE } from "./types";
19
  import type { IconShape } from "./iconShapes";
 
52
  /** The field-type mark for panels/menus (I20). Decorative by default β€” the row
53
  * it sits in already names the field; a screen reader reading "currency icon"
54
  * before every label is noise. Pass `title` where the icon teaches the
55
+ * vocabulary (the Fields panel) so hovering it names the type.
56
+ *
57
+ * Wave-14 C-FLDSEL: `type` widened to carry the "measure" PSEUDO-KIND, which is not a
58
+ * `FieldType` (a measure column's real type is currency/int/pct β€” widening the union would
59
+ * let it leak into every switch that renders cells). It paints the CURRENCY mark, which is
60
+ * the decision the create-picker already shipped and its reason still holds: inventing a
61
+ * 17th glyph for a pseudo-kind would put a mark on screen that no column header ever wears.
62
+ * Every caller that used to spell that mapping out at the call site now stops. */
63
  export function FieldTypeIcon({
64
  type,
65
  size = 14,
66
  title,
67
  }: {
68
+ type: FieldType | "measure";
69
  size?: number;
70
  title?: string;
71
  }) {
 
80
  aria-label={title}
81
  >
82
  {title && <title>{title}</title>}
83
+ <Shapes shapes={TYPE_SHAPES[type === "measure" ? "currency" : type]} />
84
  </svg>
85
  );
86
  }
 
185
  );
186
  }
187
 
188
+ // ---------------------------------------------------------------------------
189
+ // MENU ACTION ICONS (wave-7 item W4, moved here by wave-14 item 19).
190
+ //
191
+ // These lived privately in ColumnMenu.tsx, which was fine while the column menu was the only
192
+ // menu with icons. Item 19 puts icons on the VIEW menu too, and the alternative to one home
193
+ // was a second hand-drawn padlock that would drift from the first β€” the same argument
194
+ // iconShapes.ts records for the canvas/React split, one layer up.
195
+ //
196
+ // Exported as a COMPONENT taking a name, not as a record of nodes: a record would be a
197
+ // non-component export from a components file, which is the `only-export-components` warning
198
+ // the whole icons.tsx/iconShapes.ts split exists to avoid.
199
+ // ---------------------------------------------------------------------------
200
+
201
+ const mi = { width: 16, height: 16, viewBox: "0 0 16 16", fill: "none" } as const;
202
+ const miStroke = {
203
+ stroke: "currentColor",
204
+ strokeWidth: 1.3,
205
+ strokeLinecap: "round" as const,
206
+ strokeLinejoin: "round" as const,
207
+ };
208
+
209
+ const MENU_ICONS = {
210
+ duplicate: (
211
+ <>
212
+ <rect x="5.5" y="5.5" width="8" height="8" rx="1.5" {...miStroke} />
213
+ <path d="M10.5 2.5h-7a1 1 0 0 0-1 1v7" {...miStroke} />
214
+ </>
215
+ ),
216
+ insertLeft: (
217
+ <>
218
+ <line x1="3" y1="2.5" x2="3" y2="13.5" {...miStroke} />
219
+ <path d="M13.5 8H6.5M9.2 5.3 6.5 8l2.7 2.7" {...miStroke} />
220
+ </>
221
+ ),
222
+ insertRight: (
223
+ <>
224
+ <line x1="13" y1="2.5" x2="13" y2="13.5" {...miStroke} />
225
+ <path d="M2.5 8h7M6.8 5.3 9.5 8l-2.7 2.7" {...miStroke} />
226
+ </>
227
+ ),
228
+ addEnd: <path d="M8 3v10M3 8h10" {...miStroke} />,
229
+ rename: <path d="m9.8 3.2 3 3L6.2 12.8l-3.6.6.6-3.6 6.6-6.6Z" {...miStroke} />,
230
+ description: <path d="M3 4.5h10M3 8h10M3 11.5h6" {...miStroke} />,
231
+ permissions: (
232
+ <>
233
+ <rect x="3.5" y="7" width="9" height="6" rx="1" {...miStroke} />
234
+ <path d="M5.5 7V5.2a2.5 2.5 0 0 1 5 0V7" {...miStroke} />
235
+ </>
236
+ ),
237
+ /** The same padlock with an OPEN shackle β€” "unlock" as the picture of undoing the one above,
238
+ * rather than as a padlock with a slash, which every other `off` row already uses. */
239
+ unlock: (
240
+ <>
241
+ <rect x="3.5" y="7" width="9" height="6" rx="1" {...miStroke} />
242
+ <path d="M5.5 7V5.2a2.5 2.5 0 0 1 5 0" {...miStroke} />
243
+ </>
244
+ ),
245
+ format: (
246
+ <>
247
+ <path d="M3 5h5.5M12.5 5H13M3 11h1M7 11h6" {...miStroke} />
248
+ <circle cx="10.5" cy="5" r="1.6" {...miStroke} />
249
+ <circle cx="4.9" cy="11" r="1.6" {...miStroke} />
250
+ </>
251
+ ),
252
+ swap: (
253
+ <path
254
+ 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"
255
+ {...miStroke}
256
+ />
257
+ ),
258
+ sortAsc: (
259
+ <>
260
+ <path d="M4.5 3v10M4.5 13l-2-2M4.5 13l2-2" {...miStroke} />
261
+ <path d="M8.5 4.5h2M8.5 8h3.5M8.5 11.5h5" {...miStroke} />
262
+ </>
263
+ ),
264
+ sortDesc: (
265
+ <>
266
+ <path d="M4.5 3v10M4.5 13l-2-2M4.5 13l2-2" {...miStroke} />
267
+ <path d="M8.5 4.5h5M8.5 8h3.5M8.5 11.5h2" {...miStroke} />
268
+ </>
269
+ ),
270
+ off: (
271
+ <>
272
+ <circle cx="8" cy="8" r="5.5" {...miStroke} />
273
+ <line x1="4.4" y1="11.6" x2="11.6" y2="4.4" {...miStroke} />
274
+ </>
275
+ ),
276
+ filter: <path d="M2.5 3.5h11L9.5 8.5v3.8L6.5 14V8.5L2.5 3.5Z" {...miStroke} />,
277
+ group: (
278
+ <>
279
+ <line x1="2.5" y1="4" x2="13.5" y2="4" {...miStroke} />
280
+ <line x1="5.5" y1="8" x2="13.5" y2="8" {...miStroke} />
281
+ <line x1="5.5" y1="12" x2="13.5" y2="12" {...miStroke} />
282
+ </>
283
+ ),
284
+ pin: (
285
+ <>
286
+ <path d="M6 2.5h4l-.5 4L12 9v1H4V9l2.5-2.5L6 2.5Z" {...miStroke} />
287
+ <line x1="8" y1="10" x2="8" y2="13.5" {...miStroke} />
288
+ </>
289
+ ),
290
+ unpin: (
291
+ <>
292
+ <path d="M6 2.5h4l-.5 4L12 9v1H4V9l2.5-2.5L6 2.5Z" {...miStroke} />
293
+ <line x1="8" y1="10" x2="8" y2="13.5" {...miStroke} />
294
+ <line x1="3" y1="13" x2="13" y2="3" {...miStroke} />
295
+ </>
296
+ ),
297
+ hide: (
298
+ <>
299
+ <path d="M2.5 8s2-3.5 5.5-3.5S13.5 8 13.5 8s-2 3.5-5.5 3.5S2.5 8 2.5 8Z" {...miStroke} />
300
+ <circle cx="8" cy="8" r="1.5" {...miStroke} />
301
+ <line x1="3.5" y1="12.5" x2="12.5" y2="3.5" {...miStroke} />
302
+ </>
303
+ ),
304
+ trash: <path d="M3.5 4.5h9M6.5 4.5V3h3v1.5M5 4.5l.6 8.5h4.8l.6-8.5" {...miStroke} />,
305
+ /** Item 19 β€” the view menu's own three. */
306
+ download: (
307
+ <>
308
+ <path d="M8 2.5v7M5.3 6.8 8 9.5l2.7-2.7" {...miStroke} />
309
+ <path d="M3 11v1.5a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1V11" {...miStroke} />
310
+ </>
311
+ ),
312
+ cohortAdd: (
313
+ <>
314
+ <path d="M2.5 4h7M2.5 7.5h5M2.5 11h4" {...miStroke} />
315
+ <path d="M11.5 8.5v5M9 11h5" {...miStroke} />
316
+ </>
317
+ ),
318
+ } as const;
319
+
320
+ export type MenuIconName = keyof typeof MENU_ICONS;
321
+
322
+ /** One 16px menu glyph, by name. */
323
+ export function MenuIcon({ name }: { name: MenuIconName }) {
324
+ return (
325
+ <svg {...mi} aria-hidden>
326
+ {MENU_ICONS[name]}
327
+ </svg>
328
+ );
329
+ }
330
+
331
+ /**
332
+ * One menu action row: icon + label. The icon column is fixed-width so labels align.
333
+ *
334
+ * `icon` is a NAME by default; a node is accepted for the rows whose mark is not part of this
335
+ * vocabulary (the view menu's "Lock as Kanban" wears the KANBAN mark, because the picture of
336
+ * what gets frozen says more than a second padlock).
337
+ */
338
+ export function MenuLabel({
339
+ icon,
340
+ text,
341
+ }: {
342
+ icon: MenuIconName | ReactNode;
343
+ text: string;
344
+ }) {
345
+ return (
346
+ <>
347
+ <span className="cg-mi-ic" aria-hidden>
348
+ {typeof icon === "string" ? <MenuIcon name={icon as MenuIconName} /> : icon}
349
+ </span>
350
+ <span className="cg-mi-text">{text}</span>
351
+ </>
352
+ );
353
+ }
354
+
355
+ /**
356
+ * Wave-14 item 12 β€” the HIDE-FIELDS mark: an eye with a slash through it.
357
+ *
358
+ * The toolbar button that opens the panel wore `IconFields` (three vertical column rules),
359
+ * which named the NOUN and left the verb to be guessed β€” the same complaint that renamed the
360
+ * panel "Hide fields" in the first place. A struck-through eye says what the control does.
361
+ *
362
+ * It lives here rather than beside the toolbar's private `Icon*` set because it has two
363
+ * consumers: the toolbar button, and the copy-configuration modal's "Hidden fields" row
364
+ * (item 13), which must wear the SAME mark for the same concept. Paths are inline for the
365
+ * same reason `LockMark`'s are: `iconShapes.ts` holds the geometry the glide CANVAS also
366
+ * paints, and no header ever draws this one.
367
+ */
368
+ export function EyeOffIcon({ size = 14 }: { size?: number }) {
369
+ return (
370
+ <svg
371
+ className="cg-eyeoff-icon"
372
+ width={size}
373
+ height={size}
374
+ viewBox="0 0 16 16"
375
+ fill="none"
376
+ aria-hidden
377
+ >
378
+ <path
379
+ d="M2.5 8s2-3.5 5.5-3.5S13.5 8 13.5 8s-2 3.5-5.5 3.5S2.5 8 2.5 8Z"
380
+ stroke="currentColor"
381
+ strokeWidth={1.4}
382
+ strokeLinecap="round"
383
+ strokeLinejoin="round"
384
+ />
385
+ <path
386
+ d="M9.6 8a1.6 1.6 0 1 1-3.2 0 1.6 1.6 0 0 1 3.2 0Z"
387
+ stroke="currentColor"
388
+ strokeWidth={1.4}
389
+ strokeLinejoin="round"
390
+ />
391
+ <path
392
+ d="M3.3 12.7 12.7 3.3"
393
+ stroke="currentColor"
394
+ strokeWidth={1.4}
395
+ strokeLinecap="round"
396
+ />
397
+ </svg>
398
+ );
399
+ }
400
+
401
  /**
402
  * Wave-9 contract C3 (I12) β€” the "this view's mode is frozen" mark. Drawn from the same
403
  * stroke vocabulary as everything else here; deliberately small and muted, because it
web/src/customer-grid/overlayPlacement.ts CHANGED
@@ -135,15 +135,136 @@ export function infoMarkRect(
135
  size = INFO_MARK_SIZE,
136
  gap = INFO_MARK_GAP
137
  ): { x: number; y: number; size: number } | null {
138
- const x = header.x + header.width - menuSlotWidth - gap - size;
139
- if (x - header.x < INFO_MARK_MIN_LABEL) return null;
140
- return {
141
- x: Math.round(x),
142
- // Vertically centred in the header band β€” the same band the label's baseline is centred
143
- // in, which is what "centred with the field name" means on a canvas.
144
- y: Math.round(header.y + (header.height - size) / 2),
145
- size,
146
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  }
148
 
149
  // ------------------------------------------------- owner item 16: the header title vs the (i)
@@ -182,13 +303,21 @@ export const HEADER_MENU_SLOT = 30;
182
  */
183
  export function headerLabelSpace(
184
  width: number,
185
- hasInfoMark: boolean,
 
 
 
 
 
 
186
  menuSlotWidth = HEADER_MENU_SLOT
187
  ): number | null {
188
- if (!hasInfoMark) return null;
189
- const mark = infoMarkRect({ x: 0, y: 0, width, height: 32 }, menuSlotWidth);
190
- if (!mark) return null;
191
- return Math.max(0, mark.x - HEADER_LABEL_X - HEADER_LABEL_GAP);
 
 
192
  }
193
 
194
  /** The ellipsis glyph, as ONE character β€” "..." is three and measures wider. */
@@ -263,11 +392,18 @@ export function expandButtonRect(
263
  primary: { x: number; y: number; width: number; height: number },
264
  /**
265
  * The grid's own box, in the same viewport space. ⚠ NOT optional in practice: the button is
266
- * `position: fixed`, and glide's bounds follow the primary column WHEREVER it goes β€”
267
- * including off-screen, because `freezeColumns` is 0 while a grouping is active
268
- * (`CustomerGrid`'s DataEditor prop), so the primary column scrolls away like any other. An
269
- * unclamped fixed button then paints at a negative x, over the views rail, on a row nobody
270
- * can see. Painted, plausible and in the wrong place ([[ui-invisible-to-assertions]]).
 
 
 
 
 
 
 
271
  */
272
  box?: { x: number; y: number; width: number; height: number },
273
  size = EXPAND_BTN_SIZE,
 
135
  size = INFO_MARK_SIZE,
136
  gap = INFO_MARK_GAP
137
  ): { x: number; y: number; size: number } | null {
138
+ return headerMarkLayout(header, menuSlotWidth, [size], gap)?.[0] ?? null;
139
+ }
140
+
141
+ // -------------------------------------- wave-14 item 15: the GROUP BAR's label vs the freeze
142
+
143
+ /**
144
+ * THE GROUP BAR'S FONT β€” the ONE copy, read by the cell that paints it
145
+ * (`useGetCellContent.groupHeaderCell`'s `themeOverride.baseFontStyle`) AND by the canvas context
146
+ * that measures it (`CustomerGrid.measureGroupText`).
147
+ *
148
+ * ⚠ It is SEMIBOLD, and that is the whole reason this constant exists rather than two literals.
149
+ * Glide paints a cell with the MERGED theme's `baseFontFull` (`data-grid-render.cells.js:269`),
150
+ * so a group bar paints at 600 while the grid's ordinary cell measurer
151
+ * (`measureCellText`) is set to plain "13px". Measuring the fit at the lighter weight
152
+ * UNDER-truncates β€” semibold Inter is ~4-6% wider β€” and the label then overflows into exactly
153
+ * the hard mid-glyph `ctx.clip()` that `fitGroupLabel` exists to prevent. Worse as the frozen
154
+ * strip gets WIDER, which is the opposite of intuition.
155
+ *
156
+ * This is the third instance of one bug: a measurement pinned to a weight the renderer no longer
157
+ * uses (`measureHeaderText`'s 600 vs the involved header's 700 was the second). Hence one
158
+ * constant, no literals, and a gate leg asserting it is not the base cell font.
159
+ */
160
+ export const GROUP_HEADER_FONT = "600 13px";
161
+
162
+ /**
163
+ * Glide's own cell padding β€” the group bar's text does not get the full strip.
164
+ *
165
+ * Glide insets text by `cellHorizontalPadding` (8) on the LEFT and clips at the rect's right
166
+ * edge, so the strictly-usable width is `width - 8`. Reserving 16 (both sides) is DELIBERATELY
167
+ * conservative: it makes the label a few pixels shorter than it strictly must be, which is the
168
+ * safe direction to be wrong. ⚠ Do not let this slack be the thing that hides a font-weight
169
+ * mismatch β€” see `GROUP_HEADER_FONT`.
170
+ */
171
+ export const GROUP_LABEL_PAD = 16;
172
+
173
+ /**
174
+ * Item 15 β€” the collapsible group bar's label, fitted to the FROZEN STRIP.
175
+ *
176
+ * ⚠ Why this has to exist, because it is the non-obvious half of pinning the first column.
177
+ * Freezing does NOT make a group bar's `span` vanish: glide SPLITS it, `getSpanBounds` returning
178
+ * `[frozenRect, contentRect]`, and paints the row's CONTENTS from the frozen half only (the
179
+ * scrollable half sets `skipContents`). But `frozenRect` is exactly the frozen columns' own
180
+ * width β€” substitute `sourceIndex = 0`, `startCol = 0`, `firstNonSticky = 1` and both of its
181
+ * loops run zero times β€” and glide clips to it with `ctx.rect(…); ctx.clip()` while `fillText`
182
+ * carries no `maxWidth`. So the label is cut MID-GLYPH, with no ellipsis, at the freeze line.
183
+ * Before the pin the bar drew across the whole row and this could not happen; the pin is what
184
+ * the owner asked for (R8), so the truncation has to become honest rather than the pin reverted.
185
+ *
186
+ * The COUNT survives and the LABEL is what gives way. The count is the number the reader came
187
+ * for and cannot be reconstructed from a prefix; a name usually can. So the label ellipsises and
188
+ * `(count)` is always re-appended.
189
+ */
190
+ export function fitGroupLabel(
191
+ marker: string,
192
+ label: string,
193
+ count: string,
194
+ space: number | null,
195
+ measure: (text: string) => number
196
+ ): string {
197
+ const compose = (text: string) => `${marker} ${text} (${count})`;
198
+ const full = compose(label);
199
+ if (space == null || space <= 0) return full;
200
+ if (measure(full) <= space) return full;
201
+ // What the label may occupy = the space minus everything in the line that is NOT the label.
202
+ const room = space - measure(compose(""));
203
+ // No room for a name at all: say the whole thing and let glide clip it. A bar reading
204
+ // "β–Ό (1,247)" names no group, which is worse than one whose name is cut short.
205
+ if (room <= 0) return full;
206
+ return compose(fitHeaderTitle(label, room, measure));
207
+ }
208
+
209
+ // ------------------------------------------ wave-14 R11: the header's right-hand MARK STRIP
210
+
211
+ /** The user-created-field dot (item 1 / R11). Small on purpose: it is an affordance saying
212
+ * "this column is yours, not Odoo's", not a category badge. */
213
+ export const CUSTOM_MARK_SIZE = 6;
214
+ /** Clearance BETWEEN two marks in the strip. */
215
+ export const HEADER_MARK_GAP = 6;
216
+
217
+ /**
218
+ * R11 β€” where the header's right-hand marks go, laid out from the OUTSIDE IN.
219
+ *
220
+ * There are two of them now: the description "(i)" (wave-9 I3) and the user-created-field dot
221
+ * (wave-14 item 1, replacing the yellow header wash the owner killed). They share one strip so
222
+ * they can never be drawn on the same pixels, and so the title's truncation reserve accounts for
223
+ * however many are actually present.
224
+ *
225
+ * `sizes` is the slot widths from the right edge inwards β€” build it with `headerMarkSizes()` so
226
+ * the ORDER lives in exactly one place. Slot 0 is adjacent to the menu strip; the (i) keeps it,
227
+ * because it is the one a pointer goes looking for and a hover target that moves between columns
228
+ * is worse than a passive dot that does.
229
+ *
230
+ * **All-or-nothing**: if the innermost slot would eat the label, this returns `null` and NOTHING
231
+ * is drawn. That is what lets `headerLabelSpace` and `CustomerGrid.drawGridHeader` read the same
232
+ * answer from one function β€” a per-mark decision would let the reserve say "no truncation" while
233
+ * the drawer still painted a mark over the name, which is the exact failure the wave-9 comment
234
+ * above warns about ([[ui-invisible-to-assertions]]).
235
+ */
236
+ export function headerMarkLayout(
237
+ header: { x: number; y: number; width: number; height: number },
238
+ menuSlotWidth: number,
239
+ sizes: readonly number[],
240
+ gap = INFO_MARK_GAP
241
+ ): { x: number; y: number; size: number }[] | null {
242
+ if (sizes.length === 0) return null;
243
+ const out: { x: number; y: number; size: number }[] = [];
244
+ let right = header.x + header.width - menuSlotWidth - gap;
245
+ for (const size of sizes) {
246
+ const x = right - size;
247
+ if (x - header.x < INFO_MARK_MIN_LABEL) return null;
248
+ out.push({
249
+ x: Math.round(x),
250
+ // Vertically centred in the header band β€” the same band the label's baseline is centred
251
+ // in, which is what "centred with the field name" means on a canvas.
252
+ y: Math.round(header.y + (header.height - size) / 2),
253
+ size,
254
+ });
255
+ right = x - HEADER_MARK_GAP;
256
+ }
257
+ return out;
258
+ }
259
+
260
+ /** The strip's ORDER, in one place: (i) outermost, the user-created dot inboard of it. Both the
261
+ * truncation reserve and the drawing path read this, so they cannot disagree about how many
262
+ * marks a column carries or which is which. */
263
+ export function headerMarkSizes(hasInfoMark: boolean, isCustomField: boolean): number[] {
264
+ const out: number[] = [];
265
+ if (hasInfoMark) out.push(INFO_MARK_SIZE);
266
+ if (isCustomField) out.push(CUSTOM_MARK_SIZE);
267
+ return out;
268
  }
269
 
270
  // ------------------------------------------------- owner item 16: the header title vs the (i)
 
303
  */
304
  export function headerLabelSpace(
305
  width: number,
306
+ /**
307
+ * Wave-14 R11 β€” the marks this header carries. `true`/`false` is the pre-R11 shape (the (i)
308
+ * alone) and still means exactly what it meant; a `number[]` from `headerMarkSizes()` is the
309
+ * general form, and it is what a column with BOTH an (i) and a user-created dot must pass or
310
+ * the label gets reserved room for only one of them.
311
+ */
312
+ marks: boolean | readonly number[],
313
  menuSlotWidth = HEADER_MENU_SLOT
314
  ): number | null {
315
+ const sizes = marks === true ? [INFO_MARK_SIZE] : marks === false ? [] : marks;
316
+ // The INNERMOST mark is the one the label must clear, and `headerMarkLayout` is all-or-nothing,
317
+ // so this is still ONE geometry source queried twice rather than two copies of the arithmetic.
318
+ const layout = headerMarkLayout({ x: 0, y: 0, width, height: 32 }, menuSlotWidth, sizes);
319
+ if (!layout) return null;
320
+ return Math.max(0, layout[layout.length - 1].x - HEADER_LABEL_X - HEADER_LABEL_GAP);
321
  }
322
 
323
  /** The ellipsis glyph, as ONE character β€” "..." is three and measures wider. */
 
392
  primary: { x: number; y: number; width: number; height: number },
393
  /**
394
  * The grid's own box, in the same viewport space. ⚠ NOT optional in practice: the button is
395
+ * `position: fixed`, and glide's bounds are VIEWPORT coordinates that follow the primary cell
396
+ * WHEREVER it goes β€” including outside the grid. An unclamped fixed button then paints over
397
+ * the chrome, on a row nobody can see: painted, plausible and in the wrong place
398
+ * ([[ui-invisible-to-assertions]]).
399
+ *
400
+ * ⚠ RETARGETED wave-14 item 15 (R8). This used to justify itself with "`freezeColumns` is 0
401
+ * while a grouping is active, so the primary column scrolls away like any other" β€” TRUE then,
402
+ * FALSE now: the first column is frozen in every mode, because glide splits a group bar's
403
+ * span across the freeze boundary rather than losing it (`getSpanBounds`). The VERTICAL case
404
+ * is what keeps this parameter load-bearing β€” a row scrolled under the header or past the
405
+ * bottom still reports a rect outside the box. The horizontal legs remain as defence in depth
406
+ * (a column drag, a box narrower than the frozen strip), and they are still asserted.
407
  */
408
  box?: { x: number; y: number; width: number; height: number },
409
  size = EXPAND_BTN_SIZE,
web/src/customer-grid/recordFields.ts ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------------------
2
+ // recordFields.ts β€” owner item 9 (wave 14): the PURE half of "edit every
3
+ // user-created field type in the record modal".
4
+ //
5
+ // Item 9 turns the record panel from a viewer with one editable type (notes)
6
+ // into a writer for nine of them. Everything a wrong implementation could
7
+ // SILENTLY destroy lives here, so `web/verify_record_fields.py` can gate it
8
+ // under node β€” the component itself is then dispatch and markup.
9
+ //
10
+ // The four ways this could quietly lose a user's data, each of which is a leg
11
+ // in the gate:
12
+ //
13
+ // 1. A STORED VALUE THE EDITOR CANNOT SHOW. `<input type="date">` accepts
14
+ // `YYYY-MM-DD` and NOTHING else: hand it "02/08/2026" and it renders
15
+ // BLANK, so a record that has a date looks like a record that has none β€”
16
+ // and the next save writes that emptiness through. The grid stores a date
17
+ // cell as the raw string the user typed (`cells.ts:192`), so unparseable
18
+ // text is a real state, not a hypothetical. It falls back to a text box
19
+ // holding the truth rather than to an empty picker.
20
+ // 2. A TIME DESTROYED BY A DATE PICKER. A value carrying `14:30:00` cannot be
21
+ // represented in a date input at all. Picking a new day must not silently
22
+ // drop the clock half of a value the user never touched.
23
+ // 3. A `<select>` WHOSE VALUE IS NOT IN ITS OPTIONS. The browser then renders
24
+ // the FIRST option, so a field holding a since-deleted choice would DISPLAY
25
+ // as some other choice β€” and a blur would save that lie
26
+ // ([[cg-condition-builder-items]], the same scar one surface over).
27
+ // 4. A MULTISELECT ROUND TRIP THAT IS NOT IDEMPOTENT. The wire is one
28
+ // comma-joined string; split/join must survive spaces, empties and repeats
29
+ // or toggling a chip twice would rewrite the cell.
30
+ //
31
+ // Nothing here formats for READING β€” that is `display.ts`'s job and it stays
32
+ // the one renderer. These functions exist only to move a value INTO an editor
33
+ // and back out again unharmed.
34
+ // ---------------------------------------------------------------------------
35
+
36
+ import type { Field } from "./types";
37
+ import { choiceOptions, ratingMax } from "./types";
38
+
39
+ /** The cell value as the overlay stores it: always text on the way out. */
40
+ export function rawText(v: unknown): string {
41
+ return v == null ? "" : String(v);
42
+ }
43
+
44
+ // ------------------------------------------------------------------- dates
45
+
46
+ /** An ISO date prefix, validated as a real calendar day (2026-13-45 is not). */
47
+ function isoDatePrefix(raw: string): string | null {
48
+ const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(raw);
49
+ if (!m) return null;
50
+ const [, y, mo, d] = m;
51
+ // Round-trip through UTC so the check cannot be moved by the reader's zone:
52
+ // `new Date("2026-02-30T00:00:00Z")` rolls to March 2, and the mismatch is
53
+ // what catches it.
54
+ const probe = new Date(`${y}-${mo}-${d}T00:00:00Z`);
55
+ if (Number.isNaN(probe.getTime())) return null;
56
+ const back = probe.toISOString().slice(0, 10);
57
+ return back === `${y}-${mo}-${d}` ? back : null;
58
+ }
59
+
60
+ /**
61
+ * The `value` for an `<input type="date">`, or **null when this stored text is
62
+ * not a date the picker can represent** β€” the caller must then fall back to a
63
+ * text input carrying the raw string. (1) in the header note.
64
+ *
65
+ * Deliberately NOT `Date.parse`: "08/02/2026" is the 8th of February in half
66
+ * the world and the 2nd of August in the other half, and a picker that guesses
67
+ * would rewrite the value to its guess on the first save. Refusing to
68
+ * interpret it keeps the ambiguity visible and editable.
69
+ */
70
+ export function dateInputValue(v: unknown): string | null {
71
+ const raw = rawText(v).trim();
72
+ if (raw === "") return "";
73
+ return isoDatePrefix(raw);
74
+ }
75
+
76
+ /**
77
+ * The clock half of a stored date, verbatim and including its separator
78
+ * (" 14:30:00", "T14:30:00Z"), or "" when there is none. (2) in the header.
79
+ */
80
+ export function dateTimeSuffix(v: unknown): string {
81
+ const raw = rawText(v);
82
+ return isoDatePrefix(raw) ? raw.slice(10) : "";
83
+ }
84
+
85
+ /**
86
+ * What to STORE when the picker reports `picked` over a cell holding `prev`.
87
+ *
88
+ * Clearing the date clears the whole value: a time of day with no day is not a
89
+ * value, it is a fragment that would render as unparseable text forever after.
90
+ * Otherwise any time component the user never saw is carried through unchanged.
91
+ */
92
+ export function composeDateValue(prev: unknown, picked: string): string {
93
+ const day = picked.trim();
94
+ if (day === "") return "";
95
+ return day + dateTimeSuffix(prev);
96
+ }
97
+
98
+ // ------------------------------------------------------------- multiselect
99
+
100
+ /**
101
+ * The comma-joined wire β†’ the member list. Trimmed, empties dropped,
102
+ * duplicates collapsed (first spelling wins, exactly like `parseOptions`), so
103
+ * a hand-typed "A, ,A" is one member and toggling is idempotent. (4).
104
+ */
105
+ export function multiParts(v: unknown): string[] {
106
+ const seen = new Set<string>();
107
+ const out: string[] = [];
108
+ for (const piece of rawText(v).split(",")) {
109
+ const s = piece.trim();
110
+ if (!s || seen.has(s)) continue;
111
+ seen.add(s);
112
+ out.push(s);
113
+ }
114
+ return out;
115
+ }
116
+
117
+ /** The member list β†’ the wire. Matches the grid picker's `next.join(",")`. */
118
+ export function joinMulti(parts: string[]): string {
119
+ return parts.join(",");
120
+ }
121
+
122
+ /** Add or remove one choice, order-preserving (new members append). */
123
+ export function toggleMulti(v: unknown, choice: string): string {
124
+ const parts = multiParts(v);
125
+ const at = parts.indexOf(choice);
126
+ if (at >= 0) parts.splice(at, 1);
127
+ else parts.push(choice);
128
+ return joinMulti(parts);
129
+ }
130
+
131
+ // ------------------------------------------------------------------ choices
132
+
133
+ export interface ChoiceEntry {
134
+ value: string;
135
+ label: string;
136
+ /** The cell holds this, but the field no longer offers it. */
137
+ stale?: true;
138
+ }
139
+
140
+ /**
141
+ * The option list a `select`/`user`/`multiselect` editor must render β€” the
142
+ * declared choices, **plus the current value when the field no longer offers
143
+ * it**. (3) in the header note.
144
+ *
145
+ * Without the stale entry a `<select value="Naomi">` whose options lost "Naomi"
146
+ * falls back to painting its FIRST option, so the panel would show a different
147
+ * person than the cell holds and a blur would make that true. The stale row
148
+ * says what the cell says and labels why it is odd.
149
+ *
150
+ * `user` fields take their vocabulary from the host (`payload.userOptions`),
151
+ * not from the field β€” so an absent list is "nobody was supplied", which the
152
+ * caller renders read-only rather than as a picker that can only save "".
153
+ */
154
+ export function choiceEntries(
155
+ field: Field,
156
+ userOptions: string[] | undefined,
157
+ current: unknown
158
+ ): ChoiceEntry[] {
159
+ const declared =
160
+ field.type === "user" ? (userOptions ?? []) : choiceOptions(field);
161
+ const entries: ChoiceEntry[] = declared.map((value) => ({ value, label: value }));
162
+ const held =
163
+ field.type === "multiselect" ? multiParts(current) : [rawText(current).trim()];
164
+ for (const value of held) {
165
+ if (value === "" || declared.includes(value)) continue;
166
+ entries.push({ value, label: `${value} (no longer a choice)`, stale: true });
167
+ }
168
+ return entries;
169
+ }
170
+
171
+ // ------------------------------------------------------------------ numbers
172
+
173
+ /**
174
+ * The `value` for a numeric `<input type="number">`.
175
+ *
176
+ * Formatting is deliberately absent: `display.ts` renders "$1,234.50" for
177
+ * reading, and a number input rejects a value with a currency mark or a
178
+ * thousands separator β€” it would render EMPTY over a populated cell, which is
179
+ * failure (1) again in a different type. The editor shows the plain number.
180
+ */
181
+ export function numberInputValue(v: unknown): string {
182
+ const raw = rawText(v).trim();
183
+ if (raw === "") return "";
184
+ const n = Number(raw);
185
+ return Number.isFinite(n) ? String(n) : "";
186
+ }
187
+
188
+ /**
189
+ * What to STORE from a numeric input. An empty box CLEARS the cell (""), never
190
+ * writes 0 β€” "no figure" and "the figure is zero" are different claims and the
191
+ * overlay can hold both. Junk that the browser let through is refused rather
192
+ * than coerced, because `num()` downstream turns junk into a real 0.
193
+ */
194
+ export function composeNumberValue(typed: string): string | null {
195
+ const s = typed.trim();
196
+ if (s === "") return "";
197
+ const n = Number(s);
198
+ return Number.isFinite(n) ? s : null;
199
+ }
200
+
201
+ // ------------------------------------------------------------------ rating
202
+
203
+ /** The stars actually lit: clamped into 0..max, never a fractional star. */
204
+ export function ratingValue(field: Field, v: unknown): number {
205
+ const n = Math.round(Number(rawText(v)));
206
+ if (!Number.isFinite(n)) return 0;
207
+ return Math.max(0, Math.min(ratingMax(field), n));
208
+ }
209
+
210
+ /**
211
+ * Clicking star `n`. Clicking the star that is ALREADY the value clears the
212
+ * field β€” the same gesture radio groups everywhere use to undo themselves, and
213
+ * without it a rating could be changed but never removed from this panel (the
214
+ * grid's picker has an explicit Clear row; this panel has the star).
215
+ */
216
+ export function composeRatingValue(field: Field, v: unknown, star: number): string {
217
+ const now = ratingValue(field, v);
218
+ const next = Math.max(1, Math.min(ratingMax(field), Math.round(star)));
219
+ return next === now ? "" : String(next);
220
+ }
221
+
222
+ // ---------------------------------------------------------------- avatars
223
+
224
+ /**
225
+ * Item 11 / C-AVATAR β€” the initials fallback, shared by every surface this
226
+ * session owns. Two letters from two words, else the first two of one; empty
227
+ * input yields "?" rather than an empty circle, because a blank disc reads as a
228
+ * rendering fault rather than as "unassigned".
229
+ */
230
+ export function userInitials(name: string): string {
231
+ const parts = name.trim().split(/\s+/).filter(Boolean);
232
+ if (!parts.length) return "?";
233
+ if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
234
+ return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
235
+ }
web/src/customer-grid/theme.ts CHANGED
@@ -93,12 +93,12 @@ export const lightTheme: Partial<Theme> = {
93
  // a pale hex of ours, an unset theme key. Muted ink reads on #f6f7f9 and
94
  // stays quiet next to the header label.
95
  fgIconHeader: LP_MUTED,
96
- bgIconHeader: LP_LINE,
97
- fontFamily:
98
- "Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
99
- baseFontStyle: "13px",
100
- headerFontStyle: "600 13px",
101
- };
102
 
103
  /**
104
  * Status β†’ bubble tint. Keys are LOWERCASED status values so a cell can look
@@ -159,62 +159,113 @@ export const HOVER_ROW_THEME: Record<string, Partial<Theme>> = {
159
  };
160
 
161
  /**
162
- * Neutral hover wash for rows with no status tint (or when color-by is off) β€”
163
- * a faint navy, matching the AIOS accent. Stable module reference.
164
- */
165
- export const HOVER_NEUTRAL: Partial<Theme> = { bgCell: "rgba(157, 191, 242, 0.22)" };
166
-
167
- /**
168
- * Owner item 17 β€” the row holding the ACTIVE cell, i.e. the one the user just clicked.
 
169
  *
170
- * Item 17 replaces "a click opens the record" with "a click highlights". Glide's own accent
171
- * ring marks the CELL, but a 1px ring on one cell of a 12-column row is not what a person means
172
- * by highlighted, and it is invisible from two feet away β€” the click would read as having done
173
- * nothing at all, which is a worse answer than the panel it replaced.
174
  *
175
- * Deliberately DEEPER than `HOVER_NEUTRAL` (0.22) and shallower than a status wash: hover is
176
- * transient and follows the pointer, this persists after the pointer leaves. Same hue so the
177
- * two read as one family rather than as two unrelated states, and the same stable module
178
- * reference for the same reason as the tables above.
 
 
179
  */
180
- export const ACTIVE_ROW_NEUTRAL: Partial<Theme> = { bgCell: "rgba(157, 191, 242, 0.34)" };
 
 
 
181
 
182
  /**
183
- * Owner item 22 β€” which control a column is INVOLVED IN, and the header tint that says so.
184
  *
185
  * The chip in the toolbar says a filter exists; this says WHICH FIELD it is about. Without the
186
  * pair, "Filter Β· 2" on a 20-column table still leaves the user hunting for the two columns it
187
  * means.
188
  *
189
- * The header identifies the field with the full pastel; a lighter family tint carries that
190
- * same signal through its records. The hierarchy stays visible without turning every value
191
- * into a saturated block.
192
- *
193
- * ⚠ Literal hex, mirroring `--lp-*-tint`: glide's theme is a canvas theme and cannot read a CSS
194
- * variable. That duplication is deliberate and is what `verify_icons`' I7c parity check exists
195
- * to police β€” do not "fix" it by reaching for `getComputedStyle`.
196
  */
197
  export type ControlTone = "filter" | "sort" | "group";
198
 
199
- export const COLUMN_TONE_THEME: Record<ControlTone, Partial<Theme>> = {
200
- filter: {
201
- bgHeader: LP_GREEN,
202
- bgHeaderHovered: LP_GREEN,
203
- bgCell: LP_GREEN_TINT,
204
- },
205
- sort: {
206
- bgHeader: LP_YELLOW,
207
- bgHeaderHovered: LP_YELLOW,
208
- bgCell: LP_YELLOW_TINT,
209
- },
210
- group: {
211
- bgHeader: LP_PURPLE,
212
- bgHeaderHovered: LP_PURPLE,
213
- bgCell: LP_PURPLE_TINT,
214
- },
215
- };
216
-
217
- /** Editable/custom fields are identified at the header only, never by a whole yellow column. */
218
- export const CUSTOM_FIELD_HEADER: Partial<Theme> = {
219
- bgHeader: "rgba(245, 217, 137, 0.34)",
220
- };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
  // a pale hex of ours, an unset theme key. Muted ink reads on #f6f7f9 and
94
  // stays quiet next to the header label.
95
  fgIconHeader: LP_MUTED,
96
+ bgIconHeader: LP_LINE,
97
+ fontFamily:
98
+ "Inter, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif",
99
+ baseFontStyle: "13px",
100
+ headerFontStyle: "600 13px",
101
+ };
102
 
103
  /**
104
  * Status β†’ bubble tint. Keys are LOWERCASED status values so a cell can look
 
159
  };
160
 
161
  /**
162
+ * Owner item 8 (wave 14) β€” **ONE** neutral row wash, for BOTH the hovered row and the row
163
+ * holding the active cell. Rows with no status tint, or with color-by off.
164
+ *
165
+ * The owner's complaint was that these were two different colours (a faint navy at 0.22 for
166
+ * hover, a deeper one at 0.34 for active), so a row that was both changed appearance for no
167
+ * reason a reader could name. They are now the SAME REFERENCE, not two equal literals: "hover
168
+ * and active are the same colour" is then a property of the module rather than a convention two
169
+ * constants have to keep agreeing on, and "overlap changes nothing" cannot regress.
170
  *
171
+ * Neutral ink rather than the accent hue (item 8 says grey), and low-alpha rgba rather than a
172
+ * hex, because `bgCell` is the ONE theme key glide alpha-BLENDS instead of replacing
173
+ * (`common/styles.js mergeAndRealizeTheme`) β€” a hex here would erase whatever it lands on.
 
174
  *
175
+ * ⚠ WEIGHT, and the single knob if it reads wrong: 0.06 of LP_INK over white β‰ˆ #F2F2F3, which
176
+ * measures a hair LIGHTER than the outgoing hover wash (perceptual L 241.9 vs 240.1) and much
177
+ * lighter than the outgoing active one (232.0). That is the ask β€” "subtle" β€” but item 17's
178
+ * doc note still holds: this wash is the only from-two-feet-away evidence that a click landed,
179
+ * because glide's accent ring marks one cell of a twelve-column row. If it reads as nothing on
180
+ * screen, raise THIS number; do not re-split the two states.
181
  */
182
+ export const ROW_HIGHLIGHT_NEUTRAL: Partial<Theme> = { bgCell: "rgba(32, 36, 51, 0.06)" };
183
+ /** Item 8 β€” the hovered row and the active row are the same wash, by identity. */
184
+ export const HOVER_NEUTRAL = ROW_HIGHLIGHT_NEUTRAL;
185
+ export const ACTIVE_ROW_NEUTRAL = ROW_HIGHLIGHT_NEUTRAL;
186
 
187
  /**
188
+ * Owner item 22 β€” which control a column is INVOLVED IN.
189
  *
190
  * The chip in the toolbar says a filter exists; this says WHICH FIELD it is about. Without the
191
  * pair, "Filter Β· 2" on a 20-column table still leaves the user hunting for the two columns it
192
  * means.
193
  *
194
+ * The tone is still resolved per control (`useGridColumns.columnTones`, filter > group > sort)
195
+ * because PANEL's toolbar chips still hue-code β€” but as of wave-14 R4 it no longer changes what
196
+ * this table paints. See `COLUMN_TONE_THEME`.
 
 
 
 
197
  */
198
  export type ControlTone = "filter" | "sort" | "group";
199
 
200
+ /**
201
+ * ⭐ Wave-14 items 1 + 2 + 10 (owner rulings R4 + R11) β€” **ONE uniform, faint, warm-grey wash for
202
+ * any involved column, whichever control involves it.** Hue coding now lives ONLY in the toolbar
203
+ * chips.
204
+ *
205
+ * What was wrong, all three at once, and why one object fixes all of them:
206
+ *
207
+ * 1. **The tint vanished on click (item 1).** The old table set `bgHeader` + `bgHeaderHovered`
208
+ * and NOT `bgHeaderHasFocus`, so the moment a cell in that column was selected glide painted
209
+ * the base `bgHeaderHasFocus: LP_BLUE_TINT` straight over the tone
210
+ * (`data-grid-render.header.js:48,59`). All three keys are set here, to the same colour, so
211
+ * there is no state in which the header changes identity.
212
+ * 2. **The bold was already gone (item 2), and NOT because of a font setting.** glide's
213
+ * `drawGridHeaders` does `if (theme !== outerTheme) ctx.font = theme.baseFontFull` before
214
+ * drawing a header β€” the CELL font β€” so ANY column carrying a `themeOverride` painted its
215
+ * title at "13px" regular instead of "600 13px". Setting `headerFontStyle` alone would have
216
+ * changed nothing; `CustomerGrid.drawGridHeader` re-asserts the header font on the ctx, and
217
+ * that is what makes the 700 below actually reach the screen. The two must ship together.
218
+ * 3. **The saturated pastels were the "too loud" complaint (item 10).** `Airtable 11.png` shows
219
+ * involved columns carrying a barely-there wash and headers that read as ordinary headers;
220
+ * #F1F0ED is one warm step off the base `LP_WASH` header β€” visible when you compare two
221
+ * columns, invisible as noise.
222
+ *
223
+ * ⚠ `bgCell` is rgba, NOT a hex, and that is load-bearing: `mergeAndRealizeTheme` alpha-BLENDS
224
+ * `bgCell` and hard-replaces every other key (glide `common/styles.js`). An opaque tint here
225
+ * would ERASE a colour-by row's status wash wherever the two met β€” which is what the outgoing
226
+ * `LP_*_TINT` values did. Same warm family as the header, at a third of its strength.
227
+ *
228
+ * ⚠ Literal hex/rgba, mirroring the CSS tokens: glide's theme is a canvas theme and cannot read
229
+ * a CSS variable. That duplication is deliberate and is what `verify_icons`' I7c parity check
230
+ * exists to police β€” do not "fix" it by reaching for `getComputedStyle`.
231
+ */
232
+ export const INVOLVED_COLUMN_THEME: Partial<Theme> = {
233
+ // The same value in all three header states β€” see reason 1 above.
234
+ bgHeader: "#F1F0ED",
235
+ bgHeaderHovered: "#F1F0ED",
236
+ bgHeaderHasFocus: "#F1F0ED",
237
+ // #F1F0ED is rgb(115,105,75) at 10% over white; this is the same ink at 5%, i.e. β‰ˆ #F8F8F6.
238
+ bgCell: "rgba(115, 105, 75, 0.05)",
239
+ // Item 2 β€” bold. Only reaches the canvas because drawGridHeader re-asserts the header font.
240
+ headerFontStyle: "700 13px",
241
+ };
242
+
243
+ /**
244
+ * R4 β€” all three controls, ONE theme, by identity rather than by three equal literals: "the tint
245
+ * does not depend on which control" is then a property of this module and cannot drift.
246
+ *
247
+ * The `Record<ControlTone, …>` shape is kept deliberately. `columnTones` still resolves exactly
248
+ * one tone per column with the documented filter > group > sort precedence β€” that precedence is
249
+ * now INERT for paint, but it is still what PANEL's chips and any future per-control affordance
250
+ * read, and collapsing the type here would ripple into both for no gain.
251
+ */
252
+ export const COLUMN_TONE_THEME: Record<ControlTone, Partial<Theme>> = {
253
+ filter: INVOLVED_COLUMN_THEME,
254
+ sort: INVOLVED_COLUMN_THEME,
255
+ group: INVOLVED_COLUMN_THEME,
256
+ };
257
+
258
+ /**
259
+ * Wave-14 item 1 / R11 β€” **the yellow is dead.** `CUSTOM_FIELD_HEADER`'s
260
+ * `rgba(245, 217, 137, 0.34)` header wash is GONE and is not replaced by another wash: R11 says
261
+ * the marker must be a quiet neutral affordance, never a background.
262
+ *
263
+ * A user-created field is now marked by a small muted DOT in the header's right-hand mark strip,
264
+ * painted by `CustomerGrid.drawGridHeader` on the geometry in `overlayPlacement.headerMarkRect`
265
+ * β€” the same strip the description "(i)" uses, so the two can never land on each other and the
266
+ * title's truncation reserve accounts for both.
267
+ *
268
+ * Kept as a named constant because the dot needs an ink and this is where the grid's canvas
269
+ * colours live. Muted rather than a pastel: it is an affordance, not a category.
270
+ */
271
+ export const CUSTOM_FIELD_MARK = LP_MUTED;
web/src/customer-grid/timeSeriesData.ts CHANGED
@@ -1,351 +1,952 @@
1
- /**
2
- * timeSeriesData.ts β€” owner item 7 (contract C-TS), the PURE half of the time-series view.
3
- *
4
- * Rows are metric fields, columns are time buckets. Everything that decides what a cell SAYS
5
- * lives here so `web/verify_timeseries.py` can gate it under node with no DOM: the panel is
6
- * then only layout, and none of the arithmetic hides inside a component.
7
- *
8
- * The wire shape is HOST's, shipped and gated by `verify_api.py` E1d. Four of its properties
9
- * are load-bearing and every one of them is a way this table could lie:
10
- *
11
- * 1. **Zero-fill is asymmetric.** An empty bucket is `0` for a sum/count measure and `null`
12
- * for everything else. `null` means UNANSWERABLE (the store was cold for that window), and
13
- * an unanswerable bucket drawn as 0 is a fabricated data point β€” the flat stretch on a
14
- * chart that never happened. `null` renders "β€”", never 0.
15
- * 2. **`total` is present only for sum/count rows.** An average is not additive across
16
- * buckets, so there is no total to show and we do not invent one: avg/min/max rows get an
17
- * EMPTY totals cell. Computing `mean(values)` there would be an average of averages β€”
18
- * exactly the additivity law C-TS names, and wrong by a different amount every time.
19
- * 3. **A `partial` column is a bucket whose calendar end is past today.** Drawn unmarked
20
- * beside complete buckets, a half-month reads as a collapse. It is marked.
21
- * 4. **`meta.dropped` / `meta.problems` are answers, not noise.** A field the server could
22
- * not series (not a measure; a composite ratio with no single aggregate expression) must
23
- * be SAID. Silently rendering the rows that worked is the [[no-unverifiable-aggregates]]
24
- * failure wearing a smaller hat.
25
- *
26
- * And one consequence of (1) that only shows up in the delta row: because sum/count buckets
27
- * zero-fill to 0, "percent change vs the prior bucket" has a GUARANTEED division-by-zero path.
28
- * See `deltaPct`.
29
- */
30
-
31
- import type { ChartAgg, ChartModel } from "../viz/chartData";
32
- import { TS_MAX_BUCKETS, TS_MAX_FIELDS, TS_MAX_LAST_N, TS_BUCKETS } from "./types";
33
- import type { TsBucket } from "./types";
34
-
35
- // ---------------------------------------------------------------- the wire
36
-
37
- /** One time bucket = one column. `key` is the bucket's START as an ISO date. */
38
- export interface TsColumn {
39
- key: string;
40
- label: string;
41
- from: string;
42
- to: string;
43
- /** The bucket's calendar end is past today β€” it is still filling. */
44
- partial?: boolean;
45
- }
46
-
47
- /** One metric field = one row. `values` is positional against `columns`. */
48
- export interface TsRow {
49
- field: string;
50
- label: string;
51
- agg: string;
52
- values: (number | null)[];
53
- /** Present ONLY for sum/count. See the header note (2). */
54
- total?: number | null;
55
- }
56
-
57
- export interface TsMeta {
58
- pool: number;
59
- today?: string;
60
- bucket?: string;
61
- /** Fields the server refused, with why. Rendered, never swallowed. */
62
- dropped?: { field: string; reason: string }[];
63
- problems?: string[];
64
- }
65
-
66
- export interface TsPayload {
67
- columns: TsColumn[];
68
- rows: TsRow[];
69
- meta: TsMeta;
70
- }
71
-
72
- export interface TsRequest {
73
- pids: number[];
74
- bucket: TsBucket;
75
- span: { lastN: number } | { from?: string; to?: string };
76
- fields: string[];
77
- }
78
-
79
- /** The aggregates that ADD UP across buckets, and so may carry a total. */
80
- const ADDITIVE_AGGS: ReadonlySet<string> = new Set(["sum", "count"]);
81
-
82
- export function isAdditiveAgg(agg: string): boolean {
83
- return ADDITIVE_AGGS.has(agg);
84
- }
85
-
86
- // ------------------------------------------------------------- the request
87
-
88
- export const DEFAULT_TS_BUCKET: TsBucket = "month";
89
- export const DEFAULT_TS_LAST_N = 12;
90
-
91
- /**
92
- * Build the POST body, clamped to the SAME caps the server enforces.
93
- *
94
- * Clamping here is not belt-and-braces: an over-cap request is a 400, and a 400 renders as
95
- * "the panel is broken" rather than as the honest "narrow the span". We ask a question the
96
- * server can answer, and the picker never offers past the cap in the first place.
97
- *
98
- * ⚠ `lastN` WINS over `from`/`to` when both are somehow present β€” the host's documented
99
- * precedence. Mirroring it means a saved view carrying both resolves to the same window at
100
- * both ends instead of two different tables that each look right.
101
- */
102
- export function buildTsRequest(opts: {
103
- pids: number[];
104
- bucket?: TsBucket;
105
- span?: { from?: string; to?: string; lastN?: number };
106
- fields: string[];
107
- }): TsRequest {
108
- const bucket = (TS_BUCKETS as readonly string[]).includes(opts.bucket ?? "")
109
- ? (opts.bucket as TsBucket)
110
- : DEFAULT_TS_BUCKET;
111
- const s = opts.span ?? {};
112
- let span: TsRequest["span"];
113
- if (typeof s.lastN === "number" && Number.isFinite(s.lastN)) {
114
- span = { lastN: Math.max(1, Math.min(TS_MAX_LAST_N, Math.round(s.lastN))) };
115
- } else if (s.from || s.to) {
116
- span = { from: s.from, to: s.to };
117
- } else {
118
- span = { lastN: DEFAULT_TS_LAST_N };
119
- }
120
- return {
121
- pids: opts.pids,
122
- bucket,
123
- span,
124
- fields: opts.fields.slice(0, TS_MAX_FIELDS),
125
- };
126
- }
127
-
128
- // ------------------------------------------------------------ the view model
129
-
130
- export interface TsCell {
131
- /** Raw value, or null = unanswerable. */
132
- value: number | null;
133
- /** Percent change vs the PRIOR bucket, or null when the question has no answer. */
134
- delta: number | null;
135
- partial: boolean;
136
- }
137
-
138
- export interface TsTableRow {
139
- field: string;
140
- label: string;
141
- agg: string;
142
- cells: TsCell[];
143
- /** Only additive rows carry one. `undefined` = render an EMPTY cell, never a computed one. */
144
- total?: number;
145
- /** True when every value in the row is null β€” the row is present but unanswered. */
146
- allUnanswered: boolean;
147
- }
148
-
149
- export interface TsTable {
150
- columns: TsColumn[];
151
- rows: TsTableRow[];
152
- /** Every honest disclosure the payload owes the reader, ready to render. */
153
- notes: string[];
154
- pool: number;
155
- /** No rows at all (before or after drops). */
156
- empty: boolean;
157
- }
158
-
159
- /**
160
- * Percent change vs the prior bucket.
161
- *
162
- * Three refusals, and each one is a number this function will NOT invent:
163
- * - no prior bucket (the first column) -> null
164
- * - the prior bucket is unanswerable (null) -> null (not "up from nothing")
165
- * - the prior bucket is exactly 0 -> null (the change is undefined, not +∞,
166
- * and NOT 0% β€” and zero-fill makes
167
- * this the common case, not the edge)
168
- * A null current value is also null: "β€”" cannot have grown.
169
- *
170
- * The denominator is `Math.abs(prior)`, so a move from -100 to -50 reads as +50%, not -50%.
171
- * With a signed denominator the arithmetic is right and the SIGN is backwards, which is the
172
- * worst kind of wrong on a margin row.
173
- */
174
- export function deltaPct(current: number | null, prior: number | null): number | null {
175
- if (current == null || prior == null) return null;
176
- if (prior === 0) return null;
177
- if (!Number.isFinite(current) || !Number.isFinite(prior)) return null;
178
- return ((current - prior) / Math.abs(prior)) * 100;
179
- }
180
-
181
- /** Human text for a cell. `null` is "β€”" β€” the number-shaped hole, never a zero. */
182
- export function formatTsValue(
183
- value: number | null,
184
- format?: (n: number) => string
185
- ): string {
186
- if (value == null) return "β€”";
187
- return format ? format(value) : String(value);
188
- }
189
-
190
- /** Human text for a delta. Refusals render as "β€”", and a real 0 renders as "0.0%". */
191
- export function formatTsDelta(delta: number | null): string {
192
- if (delta == null) return "β€”";
193
- const sign = delta > 0 ? "+" : "";
194
- return `${sign}${delta.toFixed(1)}%`;
195
- }
196
-
197
- function dropReasonText(reason: string): string {
198
- switch (reason) {
199
- case "not_a_measure_field":
200
- return "not a measure β€” only measure fields have a time dimension";
201
- case "unresolvable":
202
- return "a composite measure has no single aggregate to bucket";
203
- default:
204
- return reason;
205
- }
206
- }
207
-
208
- /**
209
- * Turn the wire payload into the table the panel renders.
210
- *
211
- * Nothing here is recovered or filled in. A row the server did not send is not a row; a value
212
- * it sent as null stays null; a total it withheld stays withheld.
213
- */
214
- export function buildTsTable(payload: TsPayload | null): TsTable {
215
- if (!payload) {
216
- return { columns: [], rows: [], notes: [], pool: 0, empty: true };
217
- }
218
- const columns = payload.columns ?? [];
219
- const rows: TsTableRow[] = (payload.rows ?? []).map((r) => {
220
- const values = r.values ?? [];
221
- const cells: TsCell[] = columns.map((c, i) => ({
222
- value: values[i] ?? null,
223
- delta: deltaPct(values[i] ?? null, i > 0 ? (values[i - 1] ?? null) : null),
224
- partial: c.partial === true,
225
- }));
226
- // (2) in the header note. An avg/min/max row gets NO total β€” not a computed one, not 0.
227
- const total =
228
- isAdditiveAgg(r.agg) && typeof r.total === "number" && Number.isFinite(r.total)
229
- ? r.total
230
- : undefined;
231
- return {
232
- field: r.field,
233
- label: r.label,
234
- agg: r.agg,
235
- cells,
236
- total,
237
- allUnanswered: cells.length > 0 && cells.every((c) => c.value == null),
238
- };
239
- });
240
-
241
- const notes: string[] = [];
242
- const meta = payload.meta ?? { pool: 0 };
243
- for (const d of meta.dropped ?? [])
244
- notes.push(`${d.field} is not shown β€” ${dropReasonText(d.reason)}.`);
245
- for (const p of meta.problems ?? []) notes.push(p);
246
- const partials = columns.filter((c) => c.partial).length;
247
- if (partials > 0)
248
- notes.push(
249
- partials === 1
250
- ? "The last column is a partial period β€” it is still filling."
251
- : `${partials} columns are partial periods β€” they are still filling.`
252
- );
253
- const unanswered = rows.filter((r) => r.allUnanswered).length;
254
- if (unanswered > 0)
255
- notes.push(
256
- `${unanswered} of ${rows.length} metrics returned no values for this span (shown as "β€”").`
257
- );
258
-
259
- return {
260
- columns,
261
- rows,
262
- notes,
263
- pool: meta.pool ?? 0,
264
- empty: rows.length === 0,
265
- };
266
- }
267
-
268
- // ------------------------------------------------------------------- chart
269
-
270
- /**
271
- * One metric row β†’ a `ChartModel` the `viz/vega` adapter can draw.
272
- *
273
- * ⚠ Built HERE rather than through `viz/chartData.buildChartData`, and that is the whole
274
- * point of the function. `buildChartData` applies `MAX_BUCKETS = 12` β€” a cap that is right for
275
- * a categorical bar chart of the top groups and CATASTROPHIC for a time series, where dropping
276
- * buckets means dropping PERIODS. HOST's amendment makes 120 buckets legal, so routing 120
277
- * months through the 12-cap would silently amputate a decade and still print a total that
278
- * covered it.
279
- *
280
- * The server already decided the column set and refuses past `TS_MAX_BUCKETS`, so there is
281
- * nothing left to cap: every column the panel holds is drawn. The disclosure fields on
282
- * `ChartModel` are therefore all zero, honestly β€” nothing was omitted.
283
- *
284
- * Unanswerable buckets are SKIPPED, not zeroed: a line must break where the data does.
285
- */
286
- export function tsRowToChartModel(row: TsTableRow, columns: TsColumn[]): ChartModel {
287
- const points = row.cells
288
- .map((cell, i) => ({ cell, col: columns[i] }))
289
- .filter((p) => p.col && p.cell.value != null)
290
- .map((p) => ({
291
- key: p.col.key,
292
- label: p.col.label,
293
- value: p.cell.value as number,
294
- n: 1,
295
- seriesKey: row.field,
296
- seriesLabel: row.label,
297
- }));
298
- return {
299
- points,
300
- xOrder: columns.map((c) => c.key),
301
- seriesOrder: [row.field],
302
- // Nothing was capped, so nothing is omitted. Reporting a non-zero here would make the
303
- // card claim a truncation that did not happen.
304
- omitted: 0,
305
- omittedValue: 0,
306
- omittedSeries: 0,
307
- omittedSeriesValue: 0,
308
- blanks: row.cells.filter((c) => c.value == null).length,
309
- missingY: 0,
310
- rows: points.length,
311
- nonPositive: 0,
312
- nonPositiveValue: 0,
313
- };
314
- }
315
-
316
- // --------------------------------------------------------------------- CSV
317
-
318
- function csvCell(v: string): string {
319
- return /[",\r\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
320
- }
321
-
322
- /**
323
- * RFC-4180 CSV of the table AS SHOWN, matching `export.ts`'s shape (CRLF rows, quoted only
324
- * where needed) so a time-series export opens like every other export this app makes.
325
- *
326
- * An unanswerable cell exports as an EMPTY field, not as "β€”" and not as 0: the reader is a
327
- * spreadsheet, and there `β€”` is text that poisons a column while `0` is a lie that sums.
328
- * A withheld total exports empty for the same reason.
329
- */
330
- export function buildTsCsv(table: TsTable): string {
331
- const head = ["Metric", ...table.columns.map((c) => c.label), "Total"];
332
- const lines = [head.map(csvCell).join(",")];
333
- for (const r of table.rows) {
334
- const cells = [
335
- csvCell(r.label),
336
- ...r.cells.map((c) => (c.value == null ? "" : String(c.value))),
337
- r.total == null ? "" : String(r.total),
338
- ];
339
- lines.push(cells.join(","));
340
- }
341
- return lines.join("\r\n") + "\r\n";
342
- }
343
-
344
- /** The caps, re-exported so the panel and the gate read ONE source. */
345
- export const TS_LIMITS = {
346
- maxBuckets: TS_MAX_BUCKETS,
347
- maxFields: TS_MAX_FIELDS,
348
- maxLastN: TS_MAX_LAST_N,
349
- } as const;
350
-
351
- export type { ChartAgg };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * timeSeriesData.ts β€” owner item 7 (contract C-TS), the PURE half of the time-series view.
3
+ *
4
+ * Rows are metric fields, columns are time buckets. Everything that decides what a cell SAYS
5
+ * lives here so `web/verify_timeseries.py` can gate it under node with no DOM: the panel is
6
+ * then only layout, and none of the arithmetic hides inside a component.
7
+ *
8
+ * The wire shape is HOST's, shipped and gated by `verify_api.py` E1d. Four of its properties
9
+ * are load-bearing and every one of them is a way this table could lie:
10
+ *
11
+ * 1. **Zero-fill is asymmetric.** An empty bucket is `0` for a sum/count measure and `null`
12
+ * for everything else. `null` means UNANSWERABLE (the store was cold for that window), and
13
+ * an unanswerable bucket drawn as 0 is a fabricated data point β€” the flat stretch on a
14
+ * chart that never happened. `null` renders "β€”", never 0.
15
+ * 2. **`total` is present only for sum/count rows.** An average is not additive across
16
+ * buckets, so there is no total to show and we do not invent one: avg/min/max rows get an
17
+ * EMPTY totals cell. Computing `mean(values)` there would be an average of averages β€”
18
+ * exactly the additivity law C-TS names, and wrong by a different amount every time.
19
+ * 3. **A `partial` column is a bucket whose calendar end is past today.** Drawn unmarked
20
+ * beside complete buckets, a half-month reads as a collapse. It is marked.
21
+ * 4. **`meta.dropped` / `meta.problems` are answers, not noise.** A field the server could
22
+ * not series (not a measure; a composite ratio with no single aggregate expression) must
23
+ * be SAID. Silently rendering the rows that worked is the [[no-unverifiable-aggregates]]
24
+ * failure wearing a smaller hat.
25
+ *
26
+ * And one consequence of (1) that only shows up in the delta row: because sum/count buckets
27
+ * zero-fill to 0, "percent change vs the prior bucket" has a GUARANTEED division-by-zero path.
28
+ * See `deltaPct`.
29
+ */
30
+
31
+ import type { ChartAgg, ChartModel } from "../viz/chartData";
32
+ import { TS_MAX_BUCKETS, TS_MAX_FIELDS, TS_MAX_LAST_N, TS_BUCKETS } from "./types";
33
+ import type { TsBucket, TsCellStyle, TsCustomRow, TsDeltaKind } from "./types";
34
+
35
+ // ---------------------------------------------------------------- the wire
36
+
37
+ /** One time bucket = one column. `key` is the bucket's START as an ISO date. */
38
+ export interface TsColumn {
39
+ key: string;
40
+ label: string;
41
+ from: string;
42
+ to: string;
43
+ /** The bucket's calendar end is past today β€” it is still filling. */
44
+ partial?: boolean;
45
+ }
46
+
47
+ /**
48
+ * C-TSWIN (item 16) β€” the metric's OWN stored window, as the server resolved it.
49
+ *
50
+ * The wave-14 law: a bucket's value is the metric's window evaluated with
51
+ * `today := min(bucket end, real today)`. So a `ytd` row is CUMULATIVE from January 1 of the
52
+ * bucket's year and a `last_90_days` row is a trailing 90 days ending at each bucket β€” two
53
+ * rows under identical month headings that mean completely different things. `label` is the
54
+ * same string the column menu's period picker shows, and the panel renders it as the row's
55
+ * SUBLABEL: without it a cumulative row is indistinguishable from a periodic one, which is
56
+ * exactly the misreading item 16 exists to end.
57
+ */
58
+ export interface TsWindow {
59
+ kind: string;
60
+ label: string;
61
+ }
62
+
63
+ /** One metric field = one row. `values` is positional against `columns`. */
64
+ export interface TsRow {
65
+ field: string;
66
+ label: string;
67
+ agg: string;
68
+ values: (number | null)[];
69
+ /** Present ONLY for sum/count. See the header note (2). */
70
+ total?: number | null;
71
+ /** C-TSWIN β€” the window these buckets were resolved under. Absent = the server has not
72
+ * said, and a row that cannot state its window cannot answer "YTD growth". */
73
+ window?: TsWindow;
74
+ }
75
+
76
+ export interface TsMeta {
77
+ pool: number;
78
+ today?: string;
79
+ bucket?: string;
80
+ /** Fields the server refused, with why. Rendered, never swallowed. */
81
+ dropped?: { field: string; reason: string }[];
82
+ problems?: string[];
83
+ }
84
+
85
+ export interface TsPayload {
86
+ columns: TsColumn[];
87
+ rows: TsRow[];
88
+ meta: TsMeta;
89
+ }
90
+
91
+ export interface TsRequest {
92
+ pids: number[];
93
+ bucket: TsBucket;
94
+ span: { lastN: number } | { from?: string; to?: string };
95
+ fields: string[];
96
+ }
97
+
98
+ /** The aggregates that ADD UP across buckets, and so may carry a total. */
99
+ const ADDITIVE_AGGS: ReadonlySet<string> = new Set(["sum", "count"]);
100
+
101
+ export function isAdditiveAgg(agg: string): boolean {
102
+ return ADDITIVE_AGGS.has(agg);
103
+ }
104
+
105
+ // ------------------------------------------------------------- the request
106
+
107
+ export const DEFAULT_TS_BUCKET: TsBucket = "month";
108
+ export const DEFAULT_TS_LAST_N = 12;
109
+
110
+ /**
111
+ * Build the POST body, clamped to the SAME caps the server enforces.
112
+ *
113
+ * Clamping here is not belt-and-braces: an over-cap request is a 400, and a 400 renders as
114
+ * "the panel is broken" rather than as the honest "narrow the span". We ask a question the
115
+ * server can answer, and the picker never offers past the cap in the first place.
116
+ *
117
+ * ⚠ `lastN` WINS over `from`/`to` when both are somehow present β€” the host's documented
118
+ * precedence. Mirroring it means a saved view carrying both resolves to the same window at
119
+ * both ends instead of two different tables that each look right.
120
+ */
121
+ export function buildTsRequest(opts: {
122
+ pids: number[];
123
+ bucket?: TsBucket;
124
+ span?: { from?: string; to?: string; lastN?: number };
125
+ fields: string[];
126
+ }): TsRequest {
127
+ const bucket = (TS_BUCKETS as readonly string[]).includes(opts.bucket ?? "")
128
+ ? (opts.bucket as TsBucket)
129
+ : DEFAULT_TS_BUCKET;
130
+ const s = opts.span ?? {};
131
+ let span: TsRequest["span"];
132
+ if (typeof s.lastN === "number" && Number.isFinite(s.lastN)) {
133
+ span = { lastN: Math.max(1, Math.min(TS_MAX_LAST_N, Math.round(s.lastN))) };
134
+ } else if (s.from || s.to) {
135
+ span = { from: s.from, to: s.to };
136
+ } else {
137
+ span = { lastN: DEFAULT_TS_LAST_N };
138
+ }
139
+ return {
140
+ pids: opts.pids,
141
+ bucket,
142
+ span,
143
+ fields: opts.fields.slice(0, TS_MAX_FIELDS),
144
+ };
145
+ }
146
+
147
+ // ------------------------------------------------------------ the view model
148
+
149
+ export interface TsCell {
150
+ /** Raw value, or null = unanswerable. */
151
+ value: number | null;
152
+ /** Percent change vs the PRIOR bucket, or null when the question has no answer. */
153
+ delta: number | null;
154
+ partial: boolean;
155
+ }
156
+
157
+ export interface TsTableRow {
158
+ field: string;
159
+ label: string;
160
+ agg: string;
161
+ cells: TsCell[];
162
+ /** Only additive rows carry one. `undefined` = render an EMPTY cell, never a computed one. */
163
+ total?: number;
164
+ /** True when every value in the row is null β€” the row is present but unanswered. */
165
+ allUnanswered: boolean;
166
+ /** C-TSWIN β€” the window this row's buckets were resolved under, when the server said. */
167
+ window?: TsWindow;
168
+ }
169
+
170
+ export interface TsTable {
171
+ columns: TsColumn[];
172
+ rows: TsTableRow[];
173
+ /** Every honest disclosure the payload owes the reader, ready to render. */
174
+ notes: string[];
175
+ pool: number;
176
+ /** No rows at all (before or after drops). */
177
+ empty: boolean;
178
+ }
179
+
180
+ /**
181
+ * Percent change vs the prior bucket.
182
+ *
183
+ * Three refusals, and each one is a number this function will NOT invent:
184
+ * - no prior bucket (the first column) -> null
185
+ * - the prior bucket is unanswerable (null) -> null (not "up from nothing")
186
+ * - the prior bucket is exactly 0 -> null (the change is undefined, not +∞,
187
+ * and NOT 0% β€” and zero-fill makes
188
+ * this the common case, not the edge)
189
+ * A null current value is also null: "β€”" cannot have grown.
190
+ *
191
+ * The denominator is `Math.abs(prior)`, so a move from -100 to -50 reads as +50%, not -50%.
192
+ * With a signed denominator the arithmetic is right and the SIGN is backwards, which is the
193
+ * worst kind of wrong on a margin row.
194
+ */
195
+ export function deltaPct(current: number | null, prior: number | null): number | null {
196
+ if (current == null || prior == null) return null;
197
+ if (prior === 0) return null;
198
+ if (!Number.isFinite(current) || !Number.isFinite(prior)) return null;
199
+ return ((current - prior) / Math.abs(prior)) * 100;
200
+ }
201
+
202
+ /** Human text for a cell. `null` is "β€”" β€” the number-shaped hole, never a zero. */
203
+ export function formatTsValue(
204
+ value: number | null,
205
+ format?: (n: number) => string
206
+ ): string {
207
+ if (value == null) return "β€”";
208
+ return format ? format(value) : String(value);
209
+ }
210
+
211
+ /** Human text for a delta. Refusals render as "β€”", and a real 0 renders as "0.0%". */
212
+ export function formatTsDelta(delta: number | null): string {
213
+ if (delta == null) return "β€”";
214
+ const sign = delta > 0 ? "+" : "";
215
+ return `${sign}${delta.toFixed(1)}%`;
216
+ }
217
+
218
+ function dropReasonText(reason: string): string {
219
+ switch (reason) {
220
+ case "not_a_measure_field":
221
+ return "not a measure β€” only measure fields have a time dimension";
222
+ case "unresolvable":
223
+ return "a composite measure has no single aggregate to bucket";
224
+ // C-TSWIN β€” a metric pinned to a FIXED date range has nothing to slide: every bucket would
225
+ // report the same figure, which is a flat line that means "we asked the wrong question",
226
+ // not "nothing changed". The server drops it and this says why in words.
227
+ case "window_fixed":
228
+ return "its period is a fixed date range, so it cannot slide across buckets";
229
+ default:
230
+ return reason;
231
+ }
232
+ }
233
+
234
+ /**
235
+ * Turn the wire payload into the table the panel renders.
236
+ *
237
+ * Nothing here is recovered or filled in. A row the server did not send is not a row; a value
238
+ * it sent as null stays null; a total it withheld stays withheld.
239
+ */
240
+ export function buildTsTable(payload: TsPayload | null): TsTable {
241
+ if (!payload) {
242
+ return { columns: [], rows: [], notes: [], pool: 0, empty: true };
243
+ }
244
+ const columns = payload.columns ?? [];
245
+ const rows: TsTableRow[] = (payload.rows ?? []).map((r) => {
246
+ const values = r.values ?? [];
247
+ const cells: TsCell[] = columns.map((c, i) => ({
248
+ value: values[i] ?? null,
249
+ delta: deltaPct(values[i] ?? null, i > 0 ? (values[i - 1] ?? null) : null),
250
+ partial: c.partial === true,
251
+ }));
252
+ // (2) in the header note. An avg/min/max row gets NO total β€” not a computed one, not 0.
253
+ const total =
254
+ isAdditiveAgg(r.agg) && typeof r.total === "number" && Number.isFinite(r.total)
255
+ ? r.total
256
+ : undefined;
257
+ return {
258
+ field: r.field,
259
+ label: r.label,
260
+ agg: r.agg,
261
+ cells,
262
+ total,
263
+ allUnanswered: cells.length > 0 && cells.every((c) => c.value == null),
264
+ window: r.window,
265
+ };
266
+ });
267
+
268
+ const notes: string[] = [];
269
+ const meta = payload.meta ?? { pool: 0 };
270
+ for (const d of meta.dropped ?? [])
271
+ notes.push(`${d.field} is not shown β€” ${dropReasonText(d.reason)}.`);
272
+ for (const p of meta.problems ?? []) notes.push(p);
273
+ const partials = columns.filter((c) => c.partial).length;
274
+ if (partials > 0)
275
+ notes.push(
276
+ partials === 1
277
+ ? "The last column is a partial period β€” it is still filling."
278
+ : `${partials} columns are partial periods β€” they are still filling.`
279
+ );
280
+ const unanswered = rows.filter((r) => r.allUnanswered).length;
281
+ if (unanswered > 0)
282
+ notes.push(
283
+ `${unanswered} of ${rows.length} metrics returned no values for this span (shown as "β€”").`
284
+ );
285
+
286
+ return {
287
+ columns,
288
+ rows,
289
+ notes,
290
+ pool: meta.pool ?? 0,
291
+ empty: rows.length === 0,
292
+ };
293
+ }
294
+
295
+ // ════════════════════════════════════════════════════════════════���══════════════════════════
296
+ // WAVE 14 β€” the SHEET: custom rows (R2), delta sub-rows (item 18), sparklines, styles.
297
+ // ═══════════════════════════════════════════════════════════════════════════════════════════
298
+ //
299
+ // `buildTsTable` above stays exactly what it was β€” the server's metric rows, and every refusal
300
+ // it already makes. Everything below COMPOSES on top of it rather than replacing it, so the
301
+ // five negative controls guarding those refusals still bite on the path the panel actually
302
+ // renders. A sheet is: the metric rows, then the user's own rows, with delta sub-rows under
303
+ // the ones that carry a series.
304
+
305
+ // ------------------------------------------------------------ the formula language (R2)
306
+
307
+ /**
308
+ * The parsed form of a `kind:"formula"` row's `expr`.
309
+ *
310
+ * Parsed ONCE per row and evaluated per COLUMN, which is not just cheaper: a syntax error is a
311
+ * property of the expression, so it must be reported once for the row rather than as twelve
312
+ * identical footnotes under twelve identical em dashes.
313
+ */
314
+ export type TsNode =
315
+ | { t: "num"; v: number }
316
+ | { t: "ref"; name: string }
317
+ | { t: "neg"; a: TsNode }
318
+ | { t: "bin"; op: "+" | "-" | "*" | "/"; a: TsNode; b: TsNode };
319
+
320
+ export type TsFormulaError = "syntax" | "unknown_ref" | "cycle" | "div_zero";
321
+
322
+ type Token =
323
+ | { k: "num"; v: number }
324
+ | { k: "ref"; name: string }
325
+ | { k: "op"; v: string };
326
+
327
+ /**
328
+ * `+ - * / ( )`, numeric literals, and `[reference]` β€” the whole language, per R2.
329
+ *
330
+ * ⚠ There is no `eval`, no `Function`, and no operator this list does not name. The host stores
331
+ * `expr` VERBATIM behind a charset wall and never parses it (C-ACC), which makes this the ONLY
332
+ * interpreter β€” a permissive one here would be the whole security story, not a convenience.
333
+ */
334
+ function tokenize(expr: string): Token[] | null {
335
+ const out: Token[] = [];
336
+ let i = 0;
337
+ while (i < expr.length) {
338
+ const ch = expr[i];
339
+ if (ch === " " || ch === "\t") {
340
+ i += 1;
341
+ continue;
342
+ }
343
+ if (ch === "[") {
344
+ const end = expr.indexOf("]", i + 1);
345
+ if (end < 0) return null;
346
+ out.push({ k: "ref", name: expr.slice(i + 1, end).trim() });
347
+ i = end + 1;
348
+ continue;
349
+ }
350
+ if ("+-*/()".includes(ch)) {
351
+ out.push({ k: "op", v: ch });
352
+ i += 1;
353
+ continue;
354
+ }
355
+ const m = /^\d+(\.\d+)?|^\.\d+/.exec(expr.slice(i));
356
+ if (!m) return null;
357
+ out.push({ k: "num", v: Number(m[0]) });
358
+ i += m[0].length;
359
+ }
360
+ return out;
361
+ }
362
+
363
+ /**
364
+ * Recursive descent, standard precedence. Returns null on ANY malformation β€” an expression
365
+ * that half-parses is the one failure mode worth refusing outright, because "2 +" evaluating
366
+ * to 2 would print a number the user never asked for and could not distinguish from one they
367
+ * did.
368
+ */
369
+ export function parseTsFormula(expr: string): TsNode | null {
370
+ const tokens = tokenize(expr ?? "");
371
+ if (!tokens || !tokens.length) return null;
372
+ let at = 0;
373
+ const peek = () => tokens[at];
374
+ const eat = (v: string) => {
375
+ const t = peek();
376
+ if (t && t.k === "op" && t.v === v) {
377
+ at += 1;
378
+ return true;
379
+ }
380
+ return false;
381
+ };
382
+
383
+ function primary(): TsNode | null {
384
+ const t = peek();
385
+ if (!t) return null;
386
+ if (t.k === "num") {
387
+ at += 1;
388
+ return { t: "num", v: t.v };
389
+ }
390
+ if (t.k === "ref") {
391
+ at += 1;
392
+ return { t: "ref", name: t.name };
393
+ }
394
+ if (eat("(")) {
395
+ const inner = expression();
396
+ if (!inner || !eat(")")) return null;
397
+ return inner;
398
+ }
399
+ return null;
400
+ }
401
+
402
+ function unary(): TsNode | null {
403
+ if (eat("-")) {
404
+ const a = unary();
405
+ return a ? { t: "neg", a } : null;
406
+ }
407
+ if (eat("+")) return unary();
408
+ return primary();
409
+ }
410
+
411
+ function term(): TsNode | null {
412
+ let a = unary();
413
+ if (!a) return null;
414
+ for (;;) {
415
+ const t = peek();
416
+ if (!t || t.k !== "op" || (t.v !== "*" && t.v !== "/")) return a;
417
+ at += 1;
418
+ const b = unary();
419
+ if (!b) return null;
420
+ a = { t: "bin", op: t.v as "*" | "/", a, b };
421
+ }
422
+ }
423
+
424
+ function expression(): TsNode | null {
425
+ let a = term();
426
+ if (!a) return null;
427
+ for (;;) {
428
+ const t = peek();
429
+ if (!t || t.k !== "op" || (t.v !== "+" && t.v !== "-")) return a;
430
+ at += 1;
431
+ const b = term();
432
+ if (!b) return null;
433
+ a = { t: "bin", op: t.v as "+" | "-", a, b };
434
+ }
435
+ }
436
+
437
+ const node = expression();
438
+ return node && at === tokens.length ? node : null;
439
+ }
440
+
441
+ export interface TsEvalResult {
442
+ value: number | null;
443
+ error?: TsFormulaError;
444
+ }
445
+
446
+ /**
447
+ * Evaluate one parsed expression for ONE column.
448
+ *
449
+ * `lookup` answers with the referenced row's value in this column: a number, `null` when that
450
+ * bucket is unanswerable, or `undefined` when there is NO SUCH ROW.
451
+ *
452
+ * The three refusals, and why each is null rather than a number (R2 says "never 0"):
453
+ * - an UNKNOWN reference is a typo or a deleted row. Treating it as 0 turns
454
+ * `[sales] - [returns]` into `[sales]` the day someone removes the returns row: a number
455
+ * that is still plausible, still updates, and is silently wrong.
456
+ * - a CYCLE has no value at all.
457
+ * - DIVISION BY ZERO is undefined, not infinity and not 0 β€” and because sum/count buckets
458
+ * zero-fill, a denominator of 0 is the COMMON path here, exactly as it is for `deltaPct`.
459
+ * An unanswerable INPUT (null) makes the cell unanswerable with NO footnote: that is ordinary
460
+ * missing data, already disclosed by the source row's own em dash.
461
+ */
462
+ export function evalTsNode(
463
+ node: TsNode,
464
+ lookup: (name: string) => number | null | undefined
465
+ ): TsEvalResult {
466
+ let error: TsFormulaError | undefined;
467
+ const walk = (n: TsNode): number | null => {
468
+ switch (n.t) {
469
+ case "num":
470
+ return n.v;
471
+ case "ref": {
472
+ const v = lookup(n.name);
473
+ if (v === undefined) {
474
+ error = error ?? "unknown_ref";
475
+ return null;
476
+ }
477
+ return v;
478
+ }
479
+ case "neg": {
480
+ const a = walk(n.a);
481
+ return a == null ? null : -a;
482
+ }
483
+ case "bin": {
484
+ const a = walk(n.a);
485
+ const b = walk(n.b);
486
+ if (a == null || b == null) return null;
487
+ if (n.op === "+") return a + b;
488
+ if (n.op === "-") return a - b;
489
+ if (n.op === "*") return a * b;
490
+ if (b === 0) {
491
+ error = error ?? "div_zero";
492
+ return null;
493
+ }
494
+ const q = a / b;
495
+ // A finite-input division can still overflow to Infinity. It is not a number this
496
+ // table may print, and `JSON.stringify(Infinity)` is the string "null" β€” so a check
497
+ // that trusted serialisation would never see it (the wave-13 `isNull` scar).
498
+ return Number.isFinite(q) ? q : null;
499
+ }
500
+ }
501
+ };
502
+ const value = walk(node);
503
+ return error ? { value: null, error } : { value };
504
+ }
505
+
506
+ function formulaErrorText(label: string, error: TsFormulaError): string {
507
+ switch (error) {
508
+ case "syntax":
509
+ return `${label}: that formula could not be read β€” use + - * / ( ) with numbers and [row] references.`;
510
+ case "unknown_ref":
511
+ return `${label}: a row it refers to is not on this sheet, so it is left blank rather than treated as zero.`;
512
+ case "cycle":
513
+ return `${label}: it refers back to itself, so it has no value.`;
514
+ case "div_zero":
515
+ return `${label}: divided by zero in at least one period β€” those cells are blank, not zero.`;
516
+ }
517
+ }
518
+
519
+ // ---------------------------------------------------------------- deltas (item 18)
520
+
521
+ /**
522
+ * How many buckets back "the same period last year" is, per bucket kind.
523
+ *
524
+ * ⚠ 52 weeks is 364 days, not a year β€” the standard weekly year-over-year comparison and the
525
+ * only one that lands on a like-for-like bucket boundary. Named here rather than hidden in the
526
+ * caller so the approximation is visible to whoever next reads a weekly YoY figure.
527
+ */
528
+ export const TS_YOY_BACK: Record<TsBucket, number> = {
529
+ week: 52,
530
+ month: 12,
531
+ quarter: 4,
532
+ year: 1,
533
+ };
534
+
535
+ export const TS_DELTA_LABELS: Record<TsDeltaKind, string> = {
536
+ abs: "Change",
537
+ pct: "Change %",
538
+ yoy: "vs last year",
539
+ ytd: "YTD growth",
540
+ };
541
+
542
+ /** A delta expressed as a percentage renders with a % sign; `abs` carries the row's own unit. */
543
+ export function isPercentDelta(kind: TsDeltaKind): boolean {
544
+ return kind !== "abs";
545
+ }
546
+
547
+ export interface TsDeltaSubRow {
548
+ kind: TsDeltaKind;
549
+ label: string;
550
+ percent: boolean;
551
+ values: (number | null)[];
552
+ /** Set when the row cannot answer this delta AT ALL β€” rendered as a footnote, once. */
553
+ refusal?: string;
554
+ }
555
+
556
+ /**
557
+ * The delta sub-rows for one series.
558
+ *
559
+ * Every one of them can REFUSE, and the refusals are the point:
560
+ * - `abs`/`pct` need a prior bucket; `pct` additionally refuses a zero or unanswerable prior
561
+ * (the wave-13 rule, kept verbatim β€” `deltaPct` is unchanged).
562
+ * - `yoy` needs a bucket a whole year back. In a 12-month span there is none, so every cell
563
+ * is "β€”" and the row says why once instead of printing a column of dashes that look like
564
+ * missing data.
565
+ * - `ytd` is offered ONLY on a row whose own window is `ytd`. On a trailing-90 row the same
566
+ * arithmetic would produce a real number that a reader would take for year-to-date growth,
567
+ * which is the misreading item 16 exists to end. Refusing needs the server's `window`, so
568
+ * before C-TSWIN lands every row refuses it β€” honestly, and it lights up on its own.
569
+ */
570
+ export function buildTsDeltas(
571
+ row: Pick<TsTableRow, "cells" | "window">,
572
+ kinds: readonly TsDeltaKind[],
573
+ bucket: TsBucket
574
+ ): TsDeltaSubRow[] {
575
+ const values = row.cells.map((c) => c.value);
576
+ const back = TS_YOY_BACK[bucket] ?? 12;
577
+ const out: TsDeltaSubRow[] = [];
578
+ for (const kind of kinds) {
579
+ const percent = isPercentDelta(kind);
580
+ let refusal: string | undefined;
581
+ let cells: (number | null)[];
582
+ if (kind === "abs") {
583
+ cells = values.map((v, i) =>
584
+ i === 0 || v == null || values[i - 1] == null ? null : v - (values[i - 1] as number)
585
+ );
586
+ } else if (kind === "pct") {
587
+ cells = values.map((v, i) => deltaPct(v, i > 0 ? values[i - 1] : null));
588
+ } else {
589
+ const eligible = kind === "yoy" || row.window?.kind === "ytd";
590
+ if (!eligible) {
591
+ cells = values.map(() => null);
592
+ refusal =
593
+ row.window == null
594
+ ? "Year-to-date growth needs the metric's own period, which this server did not report."
595
+ : `Year-to-date growth is only meaningful on a year-to-date metric β€” this one is "${row.window.label}".`;
596
+ } else {
597
+ cells = values.map((v, i) => deltaPct(v, i >= back ? values[i - back] : null));
598
+ if (values.length <= back)
599
+ refusal = `This span is shorter than a year, so there is no earlier period to compare against.`;
600
+ }
601
+ }
602
+ out.push({ kind, label: TS_DELTA_LABELS[kind], percent, values: cells, refusal });
603
+ }
604
+ return out;
605
+ }
606
+
607
+ // ------------------------------------------------------------------ styles (item 17)
608
+
609
+ /**
610
+ * The emphasis for one cell: the ROW's style, overlaid by the CELL's.
611
+ *
612
+ * The schema keeps CELL grain (`rowId:colKey`) while the wave-14 UI only writes ROW grain β€”
613
+ * so this resolves both from the day it ships. A renderer that read only the grain its own
614
+ * controls emit would silently ignore styles a later editor saves, which is the failure where
615
+ * the data is right and the screen is wrong.
616
+ */
617
+ export function resolveTsStyle(
618
+ styles: Record<string, TsCellStyle> | undefined,
619
+ rowId: string,
620
+ colKey?: string
621
+ ): TsCellStyle {
622
+ if (!styles) return {};
623
+ const rowStyle = styles[rowId];
624
+ const cellStyle = colKey ? styles[`${rowId}:${colKey}`] : undefined;
625
+ if (!rowStyle && !cellStyle) return {};
626
+ return { ...rowStyle, ...cellStyle };
627
+ }
628
+
629
+ // -------------------------------------------------------------- sparkline (item 17)
630
+
631
+ export interface TsSparkSegment {
632
+ points: { x: number; y: number }[];
633
+ }
634
+
635
+ /**
636
+ * A row's values as SVG polyline segments in a `w Γ— h` box.
637
+ *
638
+ * Hand-rolled, no library β€” it is six lines of arithmetic and the alternative is a dependency
639
+ * on the render path of every row.
640
+ *
641
+ * ⚠ Unanswerable buckets BREAK the line into separate segments rather than being skipped over.
642
+ * A line drawn straight across a gap asserts a value for the period it crosses; a gap says the
643
+ * store could not answer. Same law as `tsRowToChartModel`, at 60 pixels wide.
644
+ *
645
+ * A flat series (every value equal) draws down the MIDDLE, not at the top or bottom: with a
646
+ * zero range any normalisation is arbitrary, and the middle is the one that does not imply a
647
+ * direction the data does not have.
648
+ */
649
+ export function sparklineSegments(
650
+ values: (number | null)[],
651
+ w: number,
652
+ h: number
653
+ ): TsSparkSegment[] {
654
+ const real = values.filter((v): v is number => v != null && Number.isFinite(v));
655
+ if (real.length < 2) return [];
656
+ const lo = Math.min(...real);
657
+ const hi = Math.max(...real);
658
+ const span = hi - lo;
659
+ const stepX = values.length > 1 ? w / (values.length - 1) : 0;
660
+ const segments: TsSparkSegment[] = [];
661
+ let current: { x: number; y: number }[] = [];
662
+ values.forEach((v, i) => {
663
+ if (v == null || !Number.isFinite(v)) {
664
+ if (current.length > 1) segments.push({ points: current });
665
+ current = [];
666
+ return;
667
+ }
668
+ const y = span === 0 ? h / 2 : h - ((v - lo) / span) * h;
669
+ current.push({ x: i * stepX, y });
670
+ });
671
+ if (current.length > 1) segments.push({ points: current });
672
+ return segments;
673
+ }
674
+
675
+ /** The `points` attribute of one segment, rounded to a tenth of a pixel. */
676
+ export function sparklinePoints(segment: TsSparkSegment): string {
677
+ return segment.points
678
+ .map((p) => `${Math.round(p.x * 10) / 10},${Math.round(p.y * 10) / 10}`)
679
+ .join(" ");
680
+ }
681
+
682
+ // ------------------------------------------------------------------- the sheet
683
+
684
+ export interface TsSheetRow {
685
+ /** The style/tsStyles key: a measure field key, or a custom row's id. */
686
+ id: string;
687
+ kind: "metric" | "note" | "formula";
688
+ label: string;
689
+ /** R1 β€” the server's window label, so a cumulative row cannot read as a periodic one. */
690
+ sublabel?: string;
691
+ /** A formula row's source text, carried through so the row can edit its own arithmetic. */
692
+ expr?: string;
693
+ agg?: string;
694
+ cells: TsCell[];
695
+ total?: number;
696
+ deltas: TsDeltaSubRow[];
697
+ allUnanswered: boolean;
698
+ }
699
+
700
+ export interface TsSheet {
701
+ columns: TsColumn[];
702
+ rows: TsSheetRow[];
703
+ notes: string[];
704
+ pool: number;
705
+ empty: boolean;
706
+ }
707
+
708
+ /** Match a `[reference]` against a row id (exact) then a row label (case-insensitive). */
709
+ function refKey(name: string): string {
710
+ return name.trim().toLowerCase();
711
+ }
712
+
713
+ /**
714
+ * The rendered sheet: the server's metric rows, then the user's note and formula rows, with
715
+ * delta sub-rows under everything that carries a series.
716
+ *
717
+ * ORDER: metrics in the server's order, then custom rows in the user's. A formula therefore
718
+ * sits below the rows it sums, which is where a spreadsheet puts a subtotal β€” and it means a
719
+ * reference can never point at a row further down that has not been resolved yet, except
720
+ * through another formula, which is the case the cycle guard exists for.
721
+ */
722
+ export function buildTsSheet(
723
+ table: TsTable,
724
+ opts: {
725
+ customRows?: readonly TsCustomRow[];
726
+ deltas?: readonly TsDeltaKind[];
727
+ bucket: TsBucket;
728
+ }
729
+ ): TsSheet {
730
+ const notes = [...table.notes];
731
+ const kinds = opts.deltas ?? [];
732
+ const custom = (opts.customRows ?? []).filter((r) => r && typeof r.id === "string");
733
+
734
+ // Every row a formula may reference, by id and by label. Metric rows resolve straight to
735
+ // their server values; formula rows resolve lazily, through the cycle guard below.
736
+ const byId = new Map<string, { kind: "metric" | "formula"; index: number }>();
737
+ const byLabel = new Map<string, { kind: "metric" | "formula"; index: number }>();
738
+ table.rows.forEach((r, index) => {
739
+ if (!byId.has(r.field)) byId.set(r.field, { kind: "metric", index });
740
+ const lk = refKey(r.label);
741
+ if (lk && !byLabel.has(lk)) byLabel.set(lk, { kind: "metric", index });
742
+ });
743
+ custom.forEach((r, index) => {
744
+ if (r.kind !== "formula") return;
745
+ if (!byId.has(r.id)) byId.set(r.id, { kind: "formula", index });
746
+ const lk = refKey(r.label);
747
+ if (lk && !byLabel.has(lk)) byLabel.set(lk, { kind: "formula", index });
748
+ });
749
+
750
+ const parsed = custom.map((r) =>
751
+ r.kind === "formula" ? parseTsFormula(r.expr ?? "") : null
752
+ );
753
+ const resolved = new Map<number, (number | null)[]>();
754
+ const rowError = new Map<number, TsFormulaError>();
755
+
756
+ /** A formula row's values, memoised, with a visiting set that turns a cycle into a refusal. */
757
+ const formulaValues = (index: number, stack: Set<number>): (number | null)[] => {
758
+ const cached = resolved.get(index);
759
+ if (cached) return cached;
760
+ const width = table.columns.length;
761
+ if (stack.has(index)) {
762
+ rowError.set(index, "cycle");
763
+ return new Array(width).fill(null);
764
+ }
765
+ const node = parsed[index];
766
+ if (!node) {
767
+ rowError.set(index, "syntax");
768
+ const blank = new Array(width).fill(null);
769
+ resolved.set(index, blank);
770
+ return blank;
771
+ }
772
+ stack.add(index);
773
+ const out: (number | null)[] = [];
774
+ for (let c = 0; c < width; c += 1) {
775
+ const res = evalTsNode(node, (name) => {
776
+ const hit = byId.get(name.trim()) ?? byLabel.get(refKey(name));
777
+ if (!hit) return undefined;
778
+ if (hit.kind === "metric") return table.rows[hit.index]?.cells[c]?.value ?? null;
779
+ // A self-reference needs NO special case: it re-enters with its own index already in
780
+ // `stack`, which is the same guard a mutual cycle trips. One guard, tested once β€” a
781
+ // second copy would be defence in depth that quietly defeats its own negative control
782
+ // (the wave-13 rank-gate scar).
783
+ return formulaValues(hit.index, stack)[c] ?? null;
784
+ });
785
+ if (res.error && !rowError.has(index)) rowError.set(index, res.error);
786
+ out.push(res.value);
787
+ }
788
+ stack.delete(index);
789
+ resolved.set(index, out);
790
+ return out;
791
+ };
792
+
793
+ const rows: TsSheetRow[] = table.rows.map((r) => ({
794
+ id: r.field,
795
+ kind: "metric" as const,
796
+ label: r.label,
797
+ sublabel: r.window?.label,
798
+ agg: r.agg,
799
+ cells: r.cells,
800
+ total: r.total,
801
+ deltas: buildTsDeltas(r, kinds, opts.bucket),
802
+ allUnanswered: r.allUnanswered,
803
+ }));
804
+
805
+ custom.forEach((r, index) => {
806
+ if (r.kind === "note") {
807
+ // A note row is a LABEL and nothing else β€” its cells are deliberately empty rather than
808
+ // dashed, because "β€”" in this table means "the store could not answer", and a note was
809
+ // never asking.
810
+ rows.push({
811
+ id: r.id,
812
+ kind: "note",
813
+ label: r.label,
814
+ cells: table.columns.map((c) => ({ value: null, delta: null, partial: c.partial === true })),
815
+ deltas: [],
816
+ allUnanswered: false,
817
+ });
818
+ return;
819
+ }
820
+ const values = formulaValues(index, new Set());
821
+ const cells: TsCell[] = table.columns.map((c, i) => ({
822
+ value: values[i] ?? null,
823
+ delta: deltaPct(values[i] ?? null, i > 0 ? (values[i - 1] ?? null) : null),
824
+ partial: c.partial === true,
825
+ }));
826
+ const err = rowError.get(index);
827
+ if (err) notes.push(formulaErrorText(r.label || r.id, err));
828
+ rows.push({
829
+ id: r.id,
830
+ kind: "formula",
831
+ label: r.label,
832
+ expr: r.expr,
833
+ cells,
834
+ deltas: buildTsDeltas({ cells, window: undefined }, kinds, opts.bucket),
835
+ allUnanswered: cells.length > 0 && cells.every((c) => c.value == null),
836
+ });
837
+ });
838
+
839
+ // One refusal line per delta kind, not per row: "this span is shorter than a year" is a
840
+ // property of the span, and twelve copies of it would bury the notes that are not.
841
+ const refusals = new Set<string>();
842
+ for (const row of rows)
843
+ for (const d of row.deltas) if (d.refusal) refusals.add(d.refusal);
844
+ for (const line of refusals) notes.push(line);
845
+
846
+ return {
847
+ columns: table.columns,
848
+ rows,
849
+ notes,
850
+ pool: table.pool,
851
+ empty: rows.length === 0,
852
+ };
853
+ }
854
+
855
+ // ------------------------------------------------------------------- chart
856
+
857
+ /**
858
+ * One metric row β†’ a `ChartModel` the `viz/vega` adapter can draw.
859
+ *
860
+ * ⚠ Built HERE rather than through `viz/chartData.buildChartData`, and that is the whole
861
+ * point of the function. `buildChartData` applies `MAX_BUCKETS = 12` β€” a cap that is right for
862
+ * a categorical bar chart of the top groups and CATASTROPHIC for a time series, where dropping
863
+ * buckets means dropping PERIODS. HOST's amendment makes 120 buckets legal, so routing 120
864
+ * months through the 12-cap would silently amputate a decade and still print a total that
865
+ * covered it.
866
+ *
867
+ * The server already decided the column set and refuses past `TS_MAX_BUCKETS`, so there is
868
+ * nothing left to cap: every column the panel holds is drawn. The disclosure fields on
869
+ * `ChartModel` are therefore all zero, honestly β€” nothing was omitted.
870
+ *
871
+ * Unanswerable buckets are SKIPPED, not zeroed: a line must break where the data does.
872
+ */
873
+ export function tsRowToChartModel(row: TsTableRow, columns: TsColumn[]): ChartModel {
874
+ const points = row.cells
875
+ .map((cell, i) => ({ cell, col: columns[i] }))
876
+ .filter((p) => p.col && p.cell.value != null)
877
+ .map((p) => ({
878
+ key: p.col.key,
879
+ label: p.col.label,
880
+ value: p.cell.value as number,
881
+ n: 1,
882
+ seriesKey: row.field,
883
+ seriesLabel: row.label,
884
+ }));
885
+ return {
886
+ points,
887
+ xOrder: columns.map((c) => c.key),
888
+ seriesOrder: [row.field],
889
+ // Nothing was capped, so nothing is omitted. Reporting a non-zero here would make the
890
+ // card claim a truncation that did not happen.
891
+ omitted: 0,
892
+ omittedValue: 0,
893
+ omittedSeries: 0,
894
+ omittedSeriesValue: 0,
895
+ blanks: row.cells.filter((c) => c.value == null).length,
896
+ missingY: 0,
897
+ rows: points.length,
898
+ nonPositive: 0,
899
+ nonPositiveValue: 0,
900
+ };
901
+ }
902
+
903
+ // --------------------------------------------------------------------- CSV
904
+
905
+ function csvCell(v: string): string {
906
+ return /[",\r\n]/.test(v) ? `"${v.replace(/"/g, '""')}"` : v;
907
+ }
908
+
909
+ /**
910
+ * RFC-4180 CSV of the sheet AS SHOWN, matching `export.ts`'s shape (CRLF rows, quoted only
911
+ * where needed) so a time-series export opens like every other export this app makes.
912
+ *
913
+ * "As shown" is the rule and it decides the awkward cases: custom rows and delta sub-rows are
914
+ * ON the sheet, so they are IN the file β€” an export that quietly held back the reader's own
915
+ * formula rows would be a different document with the same name.
916
+ *
917
+ * An unanswerable cell exports as an EMPTY field, not as "β€”" and not as 0: the reader is a
918
+ * spreadsheet, and there `β€”` is text that poisons a column while `0` is a lie that sums.
919
+ * A withheld total exports empty for the same reason. A NOTE row exports its label and nothing
920
+ * else, which is all it ever claimed.
921
+ */
922
+ export function buildTsCsv(sheet: TsSheet): string {
923
+ const head = ["Metric", ...sheet.columns.map((c) => c.label), "Total"];
924
+ const lines = [head.map(csvCell).join(",")];
925
+ for (const r of sheet.rows) {
926
+ lines.push(
927
+ [
928
+ csvCell(r.sublabel ? `${r.label} (${r.sublabel})` : r.label),
929
+ ...r.cells.map((c) => (c.value == null ? "" : String(c.value))),
930
+ r.total == null ? "" : String(r.total),
931
+ ].join(",")
932
+ );
933
+ for (const d of r.deltas)
934
+ lines.push(
935
+ [
936
+ csvCell(`${r.label} β€” ${d.label}${d.percent ? " (%)" : ""}`),
937
+ ...d.values.map((v) => (v == null ? "" : String(v))),
938
+ "",
939
+ ].join(",")
940
+ );
941
+ }
942
+ return lines.join("\r\n") + "\r\n";
943
+ }
944
+
945
+ /** The caps, re-exported so the panel and the gate read ONE source. */
946
+ export const TS_LIMITS = {
947
+ maxBuckets: TS_MAX_BUCKETS,
948
+ maxFields: TS_MAX_FIELDS,
949
+ maxLastN: TS_MAX_LAST_N,
950
+ } as const;
951
+
952
+ export type { ChartAgg };
web/src/customer-grid/types.ts CHANGED
@@ -225,6 +225,23 @@ export interface DisplaySpec {
225
  y?: string;
226
  agg: string;
227
  title?: string;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
  }[];
229
  /**
230
  * Wave 2026-08-02 item 3 (C-DISP) β€” kanban card clamp. **Stored ONLY as the literal `false`.**
@@ -261,6 +278,35 @@ export interface DisplaySpec {
261
  tsSpan?: { from?: string; to?: string; lastN?: number };
262
  /** Item 7 (C-TS) β€” the measure-backed field keys that become rows, max 12. */
263
  tsFields?: string[];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
264
  }
265
 
266
  /**
@@ -286,6 +332,59 @@ export const TS_MAX_FIELDS = 12;
286
  /** C-DISP β€” the cap on a calendar view's summary metrics. */
287
  export const MAX_CALENDAR_METRICS = 4;
288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
  /**
290
  * Client-side normalization of a stored `display`. A ref-less `{mode:'grid'}` normalizes to
291
  * ABSENT so a view that went list-and-back is byte-identical to one that never left the grid
@@ -301,6 +400,43 @@ export const MAX_CALENDAR_METRICS = 4;
301
  * only for non-grid modes (aios_grid._clean_display drops mode 'grid'), so the refs' durable
302
  * home is the non-grid display; the grid-mode carry lives in this browser's draft.
303
  */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
304
  export function cleanDisplay(raw: unknown): DisplaySpec | undefined {
305
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
306
  const d = raw as Record<string, unknown>;
@@ -321,10 +457,17 @@ export function cleanDisplay(raw: unknown): DisplaySpec | undefined {
321
  // size picks instead of feeding the selects their defaults again.
322
  // I19c β€” the chart list rides the same carry as the field refs.
323
  if (Array.isArray(d.charts)) {
324
- const charts = d.charts.filter(
325
- (c): c is DisplaySpec["charts"] extends (infer T)[] | undefined ? T : never =>
326
- !!c && typeof c === "object" && typeof (c as { id?: unknown }).id === "string"
327
- );
 
 
 
 
 
 
 
328
  if (charts.length) out.charts = charts.slice(0, 12);
329
  }
330
  // ── C-DISP / C-TS (2026-08-02) ──────────────────────────────────────────────────────────
@@ -369,6 +512,77 @@ export function cleanDisplay(raw: unknown): DisplaySpec | undefined {
369
  const keys = d.tsFields.filter((k): k is string => typeof k === "string" && k !== "");
370
  if (keys.length) out.tsFields = keys.slice(0, TS_MAX_FIELDS);
371
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
372
  if (
373
  out.mode === "grid" &&
374
  !out.dateField &&
@@ -384,7 +598,17 @@ export function cleanDisplay(raw: unknown): DisplaySpec | undefined {
384
  !out.calendarMetrics &&
385
  !out.tsBucket &&
386
  !out.tsSpan &&
387
- !out.tsFields
 
 
 
 
 
 
 
 
 
 
388
  )
389
  return undefined;
390
  return out;
@@ -1518,6 +1742,20 @@ export interface GridWorkspace {
1518
  derived?: Record<string, Record<string, string | number | null>>;
1519
  viewer?: Viewer;
1520
  userOptions?: string[];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1521
  overlays?: Record<string, Record<string, string>>;
1522
  /**
1523
  * Wave 2026-08-02 item 5 (contract C-LAYOUT) β€” this USER'S field order inside the record
 
225
  y?: string;
226
  agg: string;
227
  title?: string;
228
+ /**
229
+ * Wave-14 R3 β€” the chart's PERIOD. This is deliberately NOT a new chart kind: any card whose
230
+ * field is measure-backed gains bucket/span controls, and a card that HAS a bucket fetches
231
+ * its series over the time-series channel instead of aggregating categories.
232
+ *
233
+ * Loose-typed `string` for exactly the reason `agg` above is: the real vocabulary is
234
+ * `TS_BUCKETS`, and chartData.ts imports THIS module rather than the reverse β€” types.ts stays
235
+ * the leaf it is. `cleanDisplay` is what enforces membership.
236
+ *
237
+ * ⚠ Dropped PER ENTRY (host + client alike) when the chart's field is not measure-backed:
238
+ * one stale card must never cost the user their other eleven. Absent => category behavior,
239
+ * byte-identical to before this key existed.
240
+ */
241
+ bucket?: string;
242
+ /** R3 β€” how far back the trend runs. `lastN` is 1..TS_MAX_LAST_N and is meaningful only
243
+ * beside `bucket`; alone it is inert rather than invalid (the picker writes them together). */
244
+ span?: { lastN?: number };
245
  }[];
246
  /**
247
  * Wave 2026-08-02 item 3 (C-DISP) β€” kanban card clamp. **Stored ONLY as the literal `false`.**
 
278
  tsSpan?: { from?: string; to?: string; lastN?: number };
279
  /** Item 7 (C-TS) β€” the measure-backed field keys that become rows, max 12. */
280
  tsFields?: string[];
281
+ // ── C-TYPES2 (wave 14, items 17+18) β€” the excel-adjacent time-series surface ───────────────
282
+ /** Item 18 β€” the delta SUB-ROWS a metric row carries, in the order the user picked them.
283
+ * ≀4, deduped, vocabulary-checked against `TS_DELTA_KINDS`. Absent = no delta rows. */
284
+ tsDeltas?: TsDeltaKind[];
285
+ /**
286
+ * Item 17 β€” the gridline toggle. **Stored ONLY as the literal `false`**, the `kanbanClamp`
287
+ * construction: absent = gridlines shown (the default), `false` = this view turned them off.
288
+ * `true` is unwritable on purpose β€” a second spelling of the default is how a round trip
289
+ * starts churning, and the literal type makes that a compile error rather than a convention.
290
+ *
291
+ * ⚠ The no-churn branch below must test `=== undefined`, never `!out.tsGridlines`: truthiness
292
+ * is FALSE for both absent and `false`, so it would normalise the user's opt-out away.
293
+ */
294
+ tsGridlines?: false;
295
+ /** Item 17 β€” the trailing sparkline column. **Literal `true` ONLY**, the mirror image of
296
+ * `tsGridlines`: absent = no sparkline (the default), `true` = the user asked for it. */
297
+ tsSparkline?: true;
298
+ /** Item 17 (R2) β€” the user's own rows: free-text NOTE rows and computed FORMULA rows,
299
+ * ≀ TS_MAX_CUSTOM_ROWS. See `TsCustomRow` for the `expr` law. */
300
+ tsRows?: TsCustomRow[];
301
+ /**
302
+ * Item 17 β€” per-row / per-cell emphasis, ≀ TS_MAX_STYLES entries.
303
+ *
304
+ * Key grain is deliberately BOTH: `rowId` styles the whole row, `` `${rowId}:${colKey}` ``
305
+ * styles one cell. The schema keeps cell grain even where the UI ships row-grain first (R2
306
+ * defers the per-CELL formatting UI, not the storage), so a later cell picker needs no
307
+ * migration.
308
+ */
309
+ tsStyles?: Record<string, TsCellStyle>;
310
  }
311
 
312
  /**
 
332
  /** C-DISP β€” the cap on a calendar view's summary metrics. */
333
  export const MAX_CALENDAR_METRICS = 4;
334
 
335
+ // ── C-TYPES2 (wave 14) β€” the time-series surface's vocabulary ────────────────────────────────
336
+ // Same construction as TS_BUCKETS above: const arrays rather than bare unions, so the validator
337
+ // below and the pickers TSREC builds read ONE list. Mirrored by the host's `_clean_display`
338
+ // (contract C-ACC); the two must move together.
339
+
340
+ /**
341
+ * Item 18 β€” the delta SUB-ROWS a metric row can carry.
342
+ *
343
+ * abs β€” this bucket minus the previous one
344
+ * pct β€” the same as a share of the prior bucket. **null on a zero or absent prior** β€” the
345
+ * wave-13 refusal, kept: a percentage of nothing is not 0, it is unanswerable
346
+ * yoy β€” vs the SAME bucket one year back (12 / 4 / 52 / 1 positions, by bucket kind)
347
+ * ytd β€” this bucket's year-to-date against the prior year's same-position year-to-date;
348
+ * offered only when the ROW's own window kind is `ytd` (C-TSWIN), "β€”" otherwise
349
+ */
350
+ export type TsDeltaKind = "abs" | "pct" | "yoy" | "ytd";
351
+ export const TS_DELTA_KINDS: readonly TsDeltaKind[] = ["abs", "pct", "yoy", "ytd"] as const;
352
+
353
+ /**
354
+ * Item 17 (R2) β€” a row the USER added, rather than a metric the table resolved.
355
+ *
356
+ * note β€” free text; its bucket cells are empty by construction (a divider / an annotation)
357
+ * formula β€” computed per COLUMN over the resolved bucket values of the OTHER rows
358
+ *
359
+ * The `expr` law (R2), enforced identically on both sides of the wire:
360
+ * - ≀ `TS_MAX_EXPR` chars, charset `TS_EXPR_CHARSET` β€” and the HOST never parses it. Evaluation
361
+ * is client law; the server stores the string verbatim.
362
+ * - references another row as `[rowId]` or `[row label]`; operators `+ - * / ( )` and numeric
363
+ * literals only.
364
+ * - unknown ref / cycle / divide-by-zero β‡’ **null**, rendered "β€”" with a footnote. Never 0:
365
+ * a fabricated zero is the one answer a reader cannot tell from a real one.
366
+ *
367
+ * ⚠ Consequence of the charset, worth knowing before naming a row: `%`, `,`, `&` and `:` are NOT
368
+ * in it, so a row whose LABEL carries one of them cannot be referenced by label β€” reference it by
369
+ * `[rowId]` instead. (Deliberate: the charset is what lets the host store the string unparsed.)
370
+ */
371
+ export type TsCustomRow = { id: string; kind: "note" | "formula"; label: string; expr?: string };
372
+ export const TS_CUSTOM_ROW_KINDS: readonly TsCustomRow["kind"][] = ["note", "formula"] as const;
373
+
374
+ /** Item 17 β€” per-row / per-cell emphasis. `line` is a TOP border, i.e. the subtotal rule an
375
+ * excel reader expects above a sum; both flags are literal-`true`-only, so "not bold" has
376
+ * exactly one spelling (absent) and cannot churn a round trip. */
377
+ export type TsCellStyle = { bold?: true; line?: true };
378
+
379
+ export const TS_MAX_CUSTOM_ROWS = 12;
380
+ export const TS_MAX_STYLES = 200;
381
+ /** R2 β€” the `expr` bounds. The charset is a WHITELIST: anything outside it is refused. */
382
+ export const TS_MAX_EXPR = 200;
383
+ export const TS_EXPR_CHARSET = /^[A-Za-z0-9_ .+\-*/()[\]]*$/;
384
+ /** R2 β€” `TsCustomRow` id / label bounds. */
385
+ export const TS_ROW_ID_MAX = 40;
386
+ export const TS_ROW_LABEL_MAX = 120;
387
+
388
  /**
389
  * Client-side normalization of a stored `display`. A ref-less `{mode:'grid'}` normalizes to
390
  * ABSENT so a view that went list-and-back is byte-identical to one that never left the grid
 
400
  * only for non-grid modes (aios_grid._clean_display drops mode 'grid'), so the refs' durable
401
  * home is the non-grid display; the grid-mode carry lives in this browser's draft.
402
  */
403
+ type ChartSpecLike = NonNullable<DisplaySpec["charts"]>[number];
404
+
405
+ /**
406
+ * R3 β€” per-entry narrowing of a chart's PERIOD keys, and of nothing else.
407
+ *
408
+ * Returns the SAME object when both keys are already legal (or absent), so a clean read allocates
409
+ * nothing and cannot reorder keys β€” `viewEcho` compares `JSON.stringify(display)`, and key order
410
+ * is part of that string.
411
+ *
412
+ * The drop is per KEY, not per entry: an out-of-vocabulary `bucket` costs the card its trend,
413
+ * never its existence. A `span` with no legal `lastN` is dropped whole β€” `{}` is the absent
414
+ * state's second spelling, and two spellings of one state is how a round trip starts churning.
415
+ */
416
+ function cleanChartPeriod(c: ChartSpecLike): ChartSpecLike {
417
+ const bucketOk =
418
+ c.bucket === undefined || (TS_BUCKETS as readonly string[]).includes(c.bucket);
419
+ const rawSpan = c.span as { lastN?: unknown } | undefined;
420
+ let span: { lastN: number } | undefined;
421
+ if (rawSpan && typeof rawSpan === "object" && !Array.isArray(rawSpan)) {
422
+ const n = rawSpan.lastN;
423
+ if (typeof n === "number" && Number.isFinite(n)) {
424
+ const r = Math.round(n);
425
+ if (r >= 1 && r <= TS_MAX_LAST_N) span = { lastN: r };
426
+ }
427
+ }
428
+ const spanOk =
429
+ c.span === undefined ? span === undefined : !!span && span.lastN === rawSpan?.lastN;
430
+ if (bucketOk && spanOk) return c;
431
+ const next: ChartSpecLike = { ...c };
432
+ if (!bucketOk) delete next.bucket;
433
+ if (!spanOk) {
434
+ if (span) next.span = span;
435
+ else delete next.span;
436
+ }
437
+ return next;
438
+ }
439
+
440
  export function cleanDisplay(raw: unknown): DisplaySpec | undefined {
441
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
442
  const d = raw as Record<string, unknown>;
 
457
  // size picks instead of feeding the selects their defaults again.
458
  // I19c β€” the chart list rides the same carry as the field refs.
459
  if (Array.isArray(d.charts)) {
460
+ const charts = d.charts
461
+ .filter(
462
+ (c): c is DisplaySpec["charts"] extends (infer T)[] | undefined ? T : never =>
463
+ !!c && typeof c === "object" && typeof (c as { id?: unknown }).id === "string"
464
+ )
465
+ // R3 β€” narrow ONLY `bucket`/`span`, leaving every other key exactly as stored. ⚠ This
466
+ // stays a PASS-THROUGH deliberately: rebuilding each entry field-by-field (the
467
+ // `calendarMetrics` shape) would silently drop any chart key not named here, including
468
+ // ones TSREC adds later β€” a whole card losing its axis because a validator was not
469
+ // updated is precisely the failure this list has always been written to avoid.
470
+ .map(cleanChartPeriod);
471
  if (charts.length) out.charts = charts.slice(0, 12);
472
  }
473
  // ── C-DISP / C-TS (2026-08-02) ──────────────────────────────────────────────────────────
 
512
  const keys = d.tsFields.filter((k): k is string => typeof k === "string" && k !== "");
513
  if (keys.length) out.tsFields = keys.slice(0, TS_MAX_FIELDS);
514
  }
515
+ // ── C-TYPES2 (wave 14) ──────────────────────────────────────────────────────────────────
516
+ // Deduped AND vocabulary-checked, which is what actually bounds this at 4 β€” the slice states
517
+ // the cap rather than trusting the loop above it.
518
+ if (Array.isArray(d.tsDeltas)) {
519
+ const seen = new Set<string>();
520
+ const deltas: TsDeltaKind[] = [];
521
+ for (const k of d.tsDeltas) {
522
+ if (typeof k !== "string" || !(TS_DELTA_KINDS as readonly string[]).includes(k)) continue;
523
+ if (seen.has(k)) continue;
524
+ seen.add(k);
525
+ deltas.push(k as TsDeltaKind);
526
+ }
527
+ if (deltas.length) out.tsDeltas = deltas.slice(0, TS_DELTA_KINDS.length);
528
+ }
529
+ // ⚠ Literal-only, both of them, and in OPPOSITE directions β€” see the members' doc comments.
530
+ // `tsGridlines` is `kanbanClamp`'s exact shape and carries the same trap.
531
+ if (d.tsGridlines === false) out.tsGridlines = false;
532
+ if (d.tsSparkline === true) out.tsSparkline = true;
533
+ if (Array.isArray(d.tsRows)) {
534
+ const rows: TsCustomRow[] = [];
535
+ const seenIds = new Set<string>();
536
+ for (const raw2 of d.tsRows) {
537
+ if (!raw2 || typeof raw2 !== "object") continue;
538
+ const r = raw2 as Record<string, unknown>;
539
+ if (typeof r.id !== "string" || !r.id || r.id.length > TS_ROW_ID_MAX) continue;
540
+ if (seenIds.has(r.id)) continue;
541
+ if (
542
+ typeof r.kind !== "string" ||
543
+ !(TS_CUSTOM_ROW_KINDS as readonly string[]).includes(r.kind)
544
+ )
545
+ continue;
546
+ // An EMPTY label is legal (a blank spacer row is a thing an excel reader builds on
547
+ // purpose); an ABSENT one is a malformed row. Hence a type test, not a truthiness one.
548
+ if (typeof r.label !== "string" || r.label.length > TS_ROW_LABEL_MAX) continue;
549
+ seenIds.add(r.id);
550
+ const row: TsCustomRow = { id: r.id, kind: r.kind as TsCustomRow["kind"], label: r.label };
551
+ // AMENDMENT (dated, in the doc): a formula row whose `expr` fails the charset/length check
552
+ // keeps the ROW and loses the EXPR β€” it then renders "β€”", which is honest. Dropping the
553
+ // whole row would delete the user's label to punish their arithmetic. `expr` on a NOTE row
554
+ // is dropped for the same no-churn reason `{}` spans are: a note has no expression, so a
555
+ // dead one left over from a kind change is a second spelling of "no formula".
556
+ if (
557
+ row.kind === "formula" &&
558
+ typeof r.expr === "string" &&
559
+ r.expr.length <= TS_MAX_EXPR &&
560
+ TS_EXPR_CHARSET.test(r.expr)
561
+ )
562
+ row.expr = r.expr;
563
+ rows.push(row);
564
+ }
565
+ if (rows.length) out.tsRows = rows.slice(0, TS_MAX_CUSTOM_ROWS);
566
+ }
567
+ if (d.tsStyles && typeof d.tsStyles === "object" && !Array.isArray(d.tsStyles)) {
568
+ const styles: Record<string, TsCellStyle> = {};
569
+ let kept = 0;
570
+ for (const [key, raw2] of Object.entries(d.tsStyles as Record<string, unknown>)) {
571
+ if (kept >= TS_MAX_STYLES) break;
572
+ if (!key || !raw2 || typeof raw2 !== "object" || Array.isArray(raw2)) continue;
573
+ const s = raw2 as Record<string, unknown>;
574
+ const style: TsCellStyle = {};
575
+ if (s.bold === true) style.bold = true;
576
+ if (s.line === true) style.line = true;
577
+ // AMENDMENT (dated, in the doc): an entry that reduces to `{}` is dropped ENTIRELY and does
578
+ // NOT count against the cap. An empty style is the absent state's second spelling, and
579
+ // letting it consume a slot would let 200 no-ops evict the user's real emphasis.
580
+ if (!style.bold && !style.line) continue;
581
+ styles[key] = style;
582
+ kept += 1;
583
+ }
584
+ if (kept) out.tsStyles = styles;
585
+ }
586
  if (
587
  out.mode === "grid" &&
588
  !out.dateField &&
 
598
  !out.calendarMetrics &&
599
  !out.tsBucket &&
600
  !out.tsSpan &&
601
+ !out.tsFields &&
602
+ !out.tsDeltas &&
603
+ // ⚠ PRESENCE, not truthiness, for both literals. `tsGridlines` is `false | undefined`, so
604
+ // `!out.tsGridlines` is true for BOTH states and would normalise the opt-out away β€” the
605
+ // `kanbanClamp` trap, arriving by a second route. `tsSparkline` is `true | undefined` and is
606
+ // therefore safe under truthiness by accident; it is written the same way on purpose, so the
607
+ // next key added here inherits the correct habit rather than the lucky one.
608
+ out.tsGridlines === undefined &&
609
+ out.tsSparkline === undefined &&
610
+ !out.tsRows &&
611
+ !out.tsStyles
612
  )
613
  return undefined;
614
  return out;
 
1742
  derived?: Record<string, Record<string, string | number | null>>;
1743
  viewer?: Viewer;
1744
  userOptions?: string[];
1745
+ /**
1746
+ * C-AVATAR (wave 14, item 11) β€” username β†’ avatar data URL, served BESIDE `userOptions` so the
1747
+ * grid's `user` cells, the record modal and every people picker read one map rather than three
1748
+ * conventions. Absent, or a username absent from it, = paint the initials fallback; there is
1749
+ * no broken-image state anywhere in this feature.
1750
+ *
1751
+ * ⚠ DATA URLs ONLY (`data:image/png;base64,…` / jpeg, ≀64 KB decoded, validated host-side).
1752
+ * Never an external URL: those are neither same-origin nor CSP-safe here, and one image request
1753
+ * per assignee would hand a third party the tenant's user list a row at a time.
1754
+ *
1755
+ * Workspace, not view config β€” a photo is a property of the PERSON, so it rides `workspace_wire`
1756
+ * and is deliberately outside `config.display` (where it would be copied per view and go stale).
1757
+ */
1758
+ userAvatars?: Record<string, string>;
1759
  overlays?: Record<string, Record<string, string>>;
1760
  /**
1761
  * Wave 2026-08-02 item 5 (contract C-LAYOUT) β€” this USER'S field order inside the record
web/src/customer-grid/useGetCellContent.ts CHANGED
@@ -19,6 +19,7 @@ import type { GridCell, GridColumn, Item } from "@glideapps/glide-data-grid";
19
  import type { Field, Row, VisibleRow } from "./types";
20
  import type { OverlayEdits } from "./useCustomerData";
21
  import { makeCell } from "./cells";
 
22
 
23
  const EMPTY_CELL: GridCell = {
24
  kind: GridCellKind.Text,
@@ -36,20 +37,44 @@ type GroupFooterRow = Extract<VisibleRow, { kind: "group-footer" }>;
36
  * it only on col 0 and it draws blank the instant you scroll right). Only col 0
37
  * carries the text; the rest are the same spanned cell with empty displayData.
38
  * span is in DATA-column space [0, N-1] β€” glide adds the row-marker offset.
 
 
 
 
 
 
 
 
 
 
39
  */
40
- function groupHeaderCell(vr: GroupHeaderRow, col: number, n: number): GridCell {
41
- const text = `${vr.collapsed ? "β–Ά" : "β–Ό"} ${vr.label} (${vr.count.toLocaleString()})`;
 
 
 
 
 
 
 
 
 
 
 
 
42
  return {
43
  kind: GridCellKind.Text,
44
- data: text,
45
- displayData: col === 0 ? text : "",
46
  allowOverlay: false,
47
  span: [0, Math.max(0, n - 1)],
48
  themeOverride: {
49
  bgCell: "#eef0f3",
50
  bgCellMedium: "#eef0f3",
51
  textDark: "#33333d",
52
- baseFontStyle: "600 13px",
 
 
53
  },
54
  };
55
  }
@@ -87,7 +112,26 @@ export function useGetCellContent(
87
  * two copies of a permission rule is how a cell stays editable after the menu says it
88
  * is not.
89
  */
90
- canEdit: (field: Field) => boolean
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  ) {
92
  return useCallback(
93
  ([col, row]: Item): GridCell => {
@@ -100,15 +144,21 @@ export function useGetCellContent(
100
 
101
  // Synthetic grouping rows branch BEFORE the data path.
102
  if (vr.kind === "group-header")
103
- return groupHeaderCell(vr, col, visibleCols.length);
104
  if (vr.kind === "group-footer") return groupFooterCell(vr, field);
105
 
106
  if (!field) return EMPTY_CELL;
107
  const pid = (vr.record as Row).pid;
108
  // Overlay edits win over the raw record (edit shows immediately).
109
  const raw = overlayEdits[pid]?.[field.key] ?? vr.record[field.key];
110
- return makeCell(field, raw, canEdit(field));
111
  },
112
- [visibleRows, visibleCols, fieldByKey, overlayEdits, canEdit]
 
 
 
 
 
 
113
  );
114
  }
 
19
  import type { Field, Row, VisibleRow } from "./types";
20
  import type { OverlayEdits } from "./useCustomerData";
21
  import { makeCell } from "./cells";
22
+ import { fitGroupLabel, GROUP_HEADER_FONT } from "./overlayPlacement";
23
 
24
  const EMPTY_CELL: GridCell = {
25
  kind: GridCellKind.Text,
 
37
  * it only on col 0 and it draws blank the instant you scroll right). Only col 0
38
  * carries the text; the rest are the same spanned cell with empty displayData.
39
  * span is in DATA-column space [0, N-1] β€” glide adds the row-marker offset.
40
+ *
41
+ * ⚠ Wave-14 item 15 made the freeze interaction load-bearing, and it works out
42
+ * exactly right β€” but only because of the two rules above. glide SPLITS a span
43
+ * that straddles `freezeColumns` into a frozen half and a scrollable half
44
+ * (`getSpanBounds` β†’ `[frozenRect, contentRect]`), keys its handled-span set on
45
+ * `c.sticky` so both halves draw, and sets `skipContents` on the scrollable one.
46
+ * So the bar's TEXT is painted by the FROZEN column β€” which is col 0, the only
47
+ * one carrying `displayData` β€” and its background continues across the scroll
48
+ * region. Returning the span only on col 0 would leave the scrollable half with
49
+ * an ordinary blank cell and the bar would stop at the freeze line.
50
  */
51
+ function groupHeaderCell(
52
+ vr: GroupHeaderRow,
53
+ col: number,
54
+ n: number,
55
+ /** Item 15 β€” the frozen strip's usable width, or null when nothing clips the label. */
56
+ labelSpace: number | null,
57
+ measure: ((text: string) => number) | undefined
58
+ ): GridCell {
59
+ const marker = vr.collapsed ? "β–Ά" : "β–Ό";
60
+ const count = vr.count.toLocaleString();
61
+ const full = `${marker} ${vr.label} (${count})`;
62
+ // ⚠ `data` keeps the FULL text and only `displayData` is fitted: `data` is what a copy takes,
63
+ // and a copied group label must not carry the ellipsis the canvas needed.
64
+ const shown = measure ? fitGroupLabel(marker, vr.label, count, labelSpace, measure) : full;
65
  return {
66
  kind: GridCellKind.Text,
67
+ data: full,
68
+ displayData: col === 0 ? shown : "",
69
  allowOverlay: false,
70
  span: [0, Math.max(0, n - 1)],
71
  themeOverride: {
72
  bgCell: "#eef0f3",
73
  bgCellMedium: "#eef0f3",
74
  textDark: "#33333d",
75
+ // ⚠ THE SAME CONSTANT the fit is measured with. A literal here is how the label ends up
76
+ // measured at one weight and painted at another β€” see GROUP_HEADER_FONT.
77
+ baseFontStyle: GROUP_HEADER_FONT,
78
  },
79
  };
80
  }
 
112
  * two copies of a permission rule is how a cell stays editable after the menu says it
113
  * is not.
114
  */
115
+ canEdit: (field: Field) => boolean,
116
+ /** C-AVATAR (wave-14 item 11) β€” `GridWorkspace.userAvatars`, username β†’ data URL. */
117
+ userAvatars?: Record<string, string>,
118
+ /**
119
+ * ⚠ THE REPAINT KEY, and it is not decoration. An avatar's `Image` decodes ASYNCHRONOUSLY, and
120
+ * glide repaints only when THIS callback's identity changes β€” it cannot know about an
121
+ * `onload` three frames later. CustomerGrid bumps this from `setAvatarRepaint`, which is the
122
+ * whole mechanism by which a photo ever replaces its initials. Without it the fallback paints
123
+ * once and stays, and because the fallback is deliberate and correct-looking, nothing on
124
+ * screen would say the photo never arrived.
125
+ */
126
+ avatarTick = 0,
127
+ /**
128
+ * Item 15 β€” the FROZEN STRIP's usable width, and a measurer for it. glide clips a group bar's
129
+ * text to the frozen columns (see `fitGroupLabel`), so without these the label is cut
130
+ * mid-glyph with no ellipsis. `null` = nothing clips it (no grouping); `undefined` measurer =
131
+ * no canvas, so nothing is fitted, which is the safe direction.
132
+ */
133
+ groupLabelSpace: number | null = null,
134
+ measureText?: (text: string) => number
135
  ) {
136
  return useCallback(
137
  ([col, row]: Item): GridCell => {
 
144
 
145
  // Synthetic grouping rows branch BEFORE the data path.
146
  if (vr.kind === "group-header")
147
+ return groupHeaderCell(vr, col, visibleCols.length, groupLabelSpace, measureText);
148
  if (vr.kind === "group-footer") return groupFooterCell(vr, field);
149
 
150
  if (!field) return EMPTY_CELL;
151
  const pid = (vr.record as Row).pid;
152
  // Overlay edits win over the raw record (edit shows immediately).
153
  const raw = overlayEdits[pid]?.[field.key] ?? vr.record[field.key];
154
+ return makeCell(field, raw, canEdit(field), userAvatars);
155
  },
156
+ // ⚠ `avatarTick` is a dependency that is deliberately never READ in the body. Bumping it is
157
+ // the ONLY way an async avatar decode reaches the canvas β€” glide repaints on this callback's
158
+ // identity and on nothing else. The linter can only see that it is unused and calls it
159
+ // unnecessary; removing it would silently strand every photo behind its initials.
160
+ // eslint-disable-next-line react-hooks/exhaustive-deps
161
+ [visibleRows, visibleCols, fieldByKey, overlayEdits, canEdit, userAvatars, avatarTick,
162
+ groupLabelSpace, measureText]
163
  );
164
  }
web/src/customer-grid/useGridColumns.ts CHANGED
@@ -3,8 +3,8 @@ import type { GridColumn, Theme } from "@glideapps/glide-data-grid";
3
  import type { Field, FilterNode, ViewConfig } from "./types";
4
  import { isFilterGroup, isRuleActive } from "./types";
5
  import { typeIconName } from "./iconShapes";
6
- import { fitHeaderTitle, headerLabelSpace } from "./overlayPlacement";
7
- import { COLUMN_TONE_THEME, CUSTOM_FIELD_HEADER, lightTheme } from "./theme";
8
  import type { ControlTone } from "./theme";
9
 
10
  const DEFAULT_WIDTH = 150;
@@ -12,24 +12,41 @@ const DEFAULT_WIDTH = 150;
12
  /**
13
  * Owner item 16 β€” measure header text in GLIDE'S OWN HEADER FONT.
14
  *
15
- * ⚠ NOT the cell font. Glide's `headerFontStyle` is **"600 13px"** and its `baseFontStyle` is
16
  * "13px" (`common/styles.js:73-75`); semibold is materially wider, so measuring with the cell
17
  * font under-measures, under-truncates, and leaves the label running under the (i) β€” the exact
18
  * defect this item is about, surviving a fix that looked correct in the diff.
19
  *
20
- * One lazily-built offscreen context for the module, the same shape as CustomerGrid's
 
 
 
 
 
 
 
21
  * `measureCellText`. A context can legitimately be null (a headless canvas, a locked-down
22
  * embed); 0 then measures as "everything fits" and no title is truncated, which is the safe
23
  * direction to fail β€” a title that slightly overlaps beats one silently cut to "C…".
24
  */
25
- let _hdrCtx: CanvasRenderingContext2D | null | undefined;
26
- function measureHeaderText(text: string): number {
27
- if (_hdrCtx === undefined) {
28
- _hdrCtx = document.createElement("canvas").getContext("2d");
29
- if (_hdrCtx)
30
- _hdrCtx.font = `600 13px ${lightTheme.fontFamily ?? "Inter, sans-serif"}`;
 
 
 
 
 
 
 
 
 
31
  }
32
- return _hdrCtx ? _hdrCtx.measureText(text).width : 0;
 
33
  }
34
 
35
  /** The (i) is drawn for exactly this condition β€” `CustomerGrid.drawGridHeader` resolves the
@@ -60,15 +77,22 @@ function filteredKeys(nodes: FilterNode[], out: Set<string>): void {
60
  * doing two jobs the header names the most consequential one. Blending two tints would produce
61
  * a third colour that matches no chip in the toolbar, which is worse than picking.
62
  */
63
- /** Both overrides, or whichever exists, or `undefined` β€” glide's fast path for "no override" is
64
- * an absent object, so an empty `{}` would cost a ~35-key theme merge per column per frame. */
65
- function mergeColumnTheme(
66
- cell: Partial<Theme> | undefined,
67
- tone: ControlTone | undefined
68
- ): Partial<Theme> | undefined {
69
- const control = tone ? COLUMN_TONE_THEME[tone] : undefined;
70
- if (!cell && !control) return undefined;
71
- return { ...cell, ...control };
 
 
 
 
 
 
 
72
  }
73
 
74
  function columnTones(config: ViewConfig): Map<string, ControlTone> {
@@ -175,6 +199,13 @@ export function useGridColumns(
175
  .map((key) => {
176
  const field = fieldByKey.get(key)!;
177
  const width = config.widths[key] ?? DEFAULT_WIDTH;
 
 
 
 
 
 
 
178
  return {
179
  id: key,
180
  // Owner item 16 β€” ELLIPSISED so the title can never run under the (i). Glide
@@ -186,8 +217,8 @@ export function useGridColumns(
186
  // this returns something shorter than `field.label`.
187
  title: fitHeaderTitle(
188
  field.label,
189
- headerLabelSpace(width, hasInfoMark(field)),
190
- measureHeaderText
191
  ),
192
  width,
193
  hasMenu: true,
@@ -204,13 +235,11 @@ export function useGridColumns(
204
  // `field.note || field.description` condition from the field itself.
205
  // The hover text is still CustomerGrid's floating tip (pointer-events: none β€”
206
  // a tooltip must never swallow the next click, [[ui-invisible-to-assertions]]).
207
- // Custom/editable ownership is a HEADER signal. Active filter/group/sort controls
208
- // also tint the RECORD cells they govern; their stronger semantic tone wins when
209
- // a column is both custom and involved in a control.
210
- themeOverride: mergeColumnTheme(
211
- field.source === "overlay" ? CUSTOM_FIELD_HEADER : undefined,
212
- tones.get(key)
213
- ),
214
  };
215
  }),
216
  [order, visible, config.widths, fieldByKey, tones]
 
3
  import type { Field, FilterNode, ViewConfig } from "./types";
4
  import { isFilterGroup, isRuleActive } from "./types";
5
  import { typeIconName } from "./iconShapes";
6
+ import { fitHeaderTitle, headerLabelSpace, headerMarkSizes } from "./overlayPlacement";
7
+ import { COLUMN_TONE_THEME, INVOLVED_COLUMN_THEME, lightTheme } from "./theme";
8
  import type { ControlTone } from "./theme";
9
 
10
  const DEFAULT_WIDTH = 150;
 
12
  /**
13
  * Owner item 16 β€” measure header text in GLIDE'S OWN HEADER FONT.
14
  *
15
+ * ⚠ NOT the cell font. Glide's `headerFontStyle` is "600 13px" and its `baseFontStyle` is
16
  * "13px" (`common/styles.js:73-75`); semibold is materially wider, so measuring with the cell
17
  * font under-measures, under-truncates, and leaves the label running under the (i) β€” the exact
18
  * defect this item is about, surviving a fix that looked correct in the diff.
19
  *
20
+ * ⚠⚠ Wave-14 item 2 adds the SAME trap one weight up. An involved column now paints its header
21
+ * at **700** (`INVOLVED_COLUMN_THEME.headerFontStyle`), so measuring every column at 600 would
22
+ * under-truncate exactly the filtered/sorted/grouped columns β€” the ones the owner is looking at.
23
+ * Hence TWO cached contexts, and both font strings are read off the theme objects rather than
24
+ * retyped here: a literal in this file is a copy that can drift from the one glide actually
25
+ * paints with, which is the whole failure mode above.
26
+ *
27
+ * One lazily-built offscreen context per weight, the same shape as CustomerGrid's
28
  * `measureCellText`. A context can legitimately be null (a headless canvas, a locked-down
29
  * embed); 0 then measures as "everything fits" and no title is truncated, which is the safe
30
  * direction to fail β€” a title that slightly overlaps beats one silently cut to "C…".
31
  */
32
+ const _hdrCtx: Record<"base" | "bold", CanvasRenderingContext2D | null | undefined> = {
33
+ base: undefined,
34
+ bold: undefined,
35
+ };
36
+ function measureHeaderText(text: string, bold = false): number {
37
+ const slot = bold ? "bold" : "base";
38
+ if (_hdrCtx[slot] === undefined) {
39
+ const ctx = document.createElement("canvas").getContext("2d");
40
+ if (ctx) {
41
+ const style =
42
+ (bold ? INVOLVED_COLUMN_THEME.headerFontStyle : lightTheme.headerFontStyle) ??
43
+ "600 13px";
44
+ ctx.font = `${style} ${lightTheme.fontFamily ?? "Inter, sans-serif"}`;
45
+ }
46
+ _hdrCtx[slot] = ctx;
47
  }
48
+ const ctx = _hdrCtx[slot];
49
+ return ctx ? ctx.measureText(text).width : 0;
50
  }
51
 
52
  /** The (i) is drawn for exactly this condition β€” `CustomerGrid.drawGridHeader` resolves the
 
77
  * doing two jobs the header names the most consequential one. Blending two tints would produce
78
  * a third colour that matches no chip in the toolbar, which is worse than picking.
79
  */
80
+ /**
81
+ * The column's theme override, or `undefined` β€” glide's fast path for "no override" is an absent
82
+ * object, so an empty `{}` would cost a ~35-key theme merge per column per frame.
83
+ *
84
+ * ⚠ Wave-14 item 1 (R11): a user-created field NO LONGER contributes a theme at all. Its yellow
85
+ * header wash is dead and its replacement is a painted DOT, not a background β€” so the only thing
86
+ * that can put a themeOverride on a column now is being INVOLVED in a control, and the returned
87
+ * object is the one shared `INVOLVED_COLUMN_THEME` reference (stable across columns and frames,
88
+ * which is what keeps glide's merge cache-friendly).
89
+ *
90
+ * That the tone is resolved and then discarded is deliberate, not dead code: `columnTones`'
91
+ * filter > group > sort precedence still names WHICH control owns the column for anything that
92
+ * wants it, and R4 is a decision about paint, not about the model.
93
+ */
94
+ function columnTheme(tone: ControlTone | undefined): Partial<Theme> | undefined {
95
+ return tone ? COLUMN_TONE_THEME[tone] : undefined;
96
  }
97
 
98
  function columnTones(config: ViewConfig): Map<string, ControlTone> {
 
199
  .map((key) => {
200
  const field = fieldByKey.get(key)!;
201
  const width = config.widths[key] ?? DEFAULT_WIDTH;
202
+ // Wave-14 item 2 β€” an INVOLVED column's header paints at 700, so it must be MEASURED
203
+ // at 700. `tones` is already a dep of this memo, so this costs nothing.
204
+ const involved = tones.has(key);
205
+ // R11 β€” the marks this header carries, in the strip's canonical order. Both this
206
+ // reserve and `CustomerGrid.drawGridHeader`'s painting read `headerMarkSizes`, so a
207
+ // column can never reserve room for one mark and then be given two.
208
+ const marks = headerMarkSizes(hasInfoMark(field), field.source === "overlay");
209
  return {
210
  id: key,
211
  // Owner item 16 β€” ELLIPSISED so the title can never run under the (i). Glide
 
217
  // this returns something shorter than `field.label`.
218
  title: fitHeaderTitle(
219
  field.label,
220
+ headerLabelSpace(width, marks),
221
+ (text) => measureHeaderText(text, involved)
222
  ),
223
  width,
224
  hasMenu: true,
 
235
  // `field.note || field.description` condition from the field itself.
236
  // The hover text is still CustomerGrid's floating tip (pointer-events: none β€”
237
  // a tooltip must never swallow the next click, [[ui-invisible-to-assertions]]).
238
+ // Wave-14 R4 β€” being INVOLVED in a filter/sort/group is the only thing that tints a
239
+ // column now, and all three tint it the same faint warm grey; the hue that says
240
+ // WHICH control lives on the toolbar chip. User-created ownership moved out of the
241
+ // theme entirely and is the dot drawn in the mark strip (R11).
242
+ themeOverride: columnTheme(tones.get(key)),
 
 
243
  };
244
  }),
245
  [order, visible, config.widths, fieldByKey, tones]
web/src/customer-grid/viewModes.tsx CHANGED
@@ -40,6 +40,7 @@ import { formatDisplay } from "./cells";
40
  import { optionTint } from "./choiceColors";
41
  import { CREATABLE_MODES, MODE_LABELS } from "./iconShapes";
42
  import { LockMark, ModeIcon } from "./icons";
 
43
  import { Popover } from "./Toolbar";
44
 
45
  /** Stacks render this many cards before offering "Show all" β€” a stated cap,
@@ -155,33 +156,28 @@ export function ModeSwitch({
155
  )}
156
  </Popover>
157
  )}
 
 
 
 
 
158
  {mode === "calendar" && dateChoices.length > 0 && (
159
- <select
160
- className="cg-select cg-mode-field"
161
- value={dateField?.key ?? ""}
162
- aria-label="Calendar date field"
163
- onChange={(e) => e.target.value && onPickField("dateField", e.target.value)}
164
- >
165
- {dateChoices.map((f) => (
166
- <option key={f.key} value={f.key}>
167
- {f.label}
168
- </option>
169
- ))}
170
- </select>
171
  )}
172
  {mode === "kanban" && stackChoices.length > 0 && (
173
- <select
174
- className="cg-select cg-mode-field"
175
- value={stackField?.key ?? ""}
176
- aria-label="Kanban stack field"
177
- onChange={(e) => e.target.value && onPickField("stackField", e.target.value)}
178
- >
179
- {stackChoices.map((f) => (
180
- <option key={f.key} value={f.key}>
181
- {f.label}
182
- </option>
183
- ))}
184
- </select>
185
  )}
186
  {/* Owner item 3 (C-DISP) β€” the card-length toggle, beside the stack-field select the
187
  contract names. Cards are CLAMPED by default now (that is the "standardized" the
@@ -297,35 +293,43 @@ export function ModeSwitch({
297
  )}
298
  </Popover>
299
  )}
 
 
 
 
 
 
300
  {mode === "map" && colorChoices.length > 0 && (
301
- <select
302
- className="cg-select cg-mode-field"
 
 
 
 
303
  value={colorField?.key ?? ""}
304
- aria-label="Colour pins by"
305
- onChange={(e) => onPickField("colorField", e.target.value)}
306
- >
307
- <option value="">Colour: none</option>
308
- {colorChoices.map((f) => (
309
- <option key={f.key} value={f.key}>
310
- Colour: {f.label}
311
- </option>
312
- ))}
313
- </select>
314
  )}
315
  {mode === "map" && sizeChoices.length > 0 && (
316
- <select
317
- className="cg-select cg-mode-field"
 
 
318
  value={sizeField?.key ?? ""}
319
- aria-label="Size pins by"
320
- onChange={(e) => onPickField("sizeField", e.target.value)}
321
- >
322
- <option value="">Size: none</option>
323
- {sizeChoices.map((f) => (
324
- <option key={f.key} value={f.key}>
325
- Size: {f.label}
326
- </option>
327
- ))}
328
- </select>
329
  )}
330
  </span>
331
  );
 
40
  import { optionTint } from "./choiceColors";
41
  import { CREATABLE_MODES, MODE_LABELS } from "./iconShapes";
42
  import { LockMark, ModeIcon } from "./icons";
43
+ import { FieldSelectButton } from "./FieldSelect";
44
  import { Popover } from "./Toolbar";
45
 
46
  /** Stacks render this many cards before offering "Show all" β€” a stated cap,
 
156
  )}
157
  </Popover>
158
  )}
159
+ {/* Item 20 (C-FLDSEL) β€” the mode bar's field pickers wear the type mark, same control
160
+ as the filter and sort rows. These two have no "none" state: a calendar without a
161
+ date field and a board without a stack field are not modes, so the picker is never
162
+ in its placeholder state here unless the view names a field the table has lost β€”
163
+ which it now SHOWS rather than silently replacing with the first choice. */}
164
  {mode === "calendar" && dateChoices.length > 0 && (
165
+ <FieldSelectButton
166
+ className="cg-mode-field"
167
+ ariaLabel="Calendar date field"
168
+ value={dateField?.key}
169
+ onChange={(key) => onPickField("dateField", key)}
170
+ fields={dateChoices.map((f) => ({ key: f.key, label: f.label, type: f.type }))}
171
+ />
 
 
 
 
 
172
  )}
173
  {mode === "kanban" && stackChoices.length > 0 && (
174
+ <FieldSelectButton
175
+ className="cg-mode-field"
176
+ ariaLabel="Kanban stack field"
177
+ value={stackField?.key}
178
+ onChange={(key) => onPickField("stackField", key)}
179
+ fields={stackChoices.map((f) => ({ key: f.key, label: f.label, type: f.type }))}
180
+ />
 
 
 
 
 
181
  )}
182
  {/* Owner item 3 (C-DISP) β€” the card-length toggle, beside the stack-field select the
183
  contract names. Cards are CLAMPED by default now (that is the "standardized" the
 
293
  )}
294
  </Popover>
295
  )}
296
+ {/* The map's two encodings are OPTIONAL, so "none" is a real choice and not merely the
297
+ absence of one: it is a row in the list AND the placeholder the button falls back to,
298
+ which is the same state said twice on purpose β€” you can see what you would return to
299
+ before you pick it. The "Colour: " prefix lived on every option because a native
300
+ select had nowhere else to say which encoding it was; the aria-label and the row
301
+ carry that now, so the labels are just the field names. */}
302
  {mode === "map" && colorChoices.length > 0 && (
303
+ <FieldSelectButton
304
+ className="cg-mode-field"
305
+ ariaLabel="Colour pins by"
306
+ placeholder="Colour: none"
307
+ // `?? ""` on purpose: "" is the key of the explicit "No colour" row, so the none
308
+ // state MARKS itself in the list instead of leaving every row unmarked.
309
  value={colorField?.key ?? ""}
310
+ onChange={(key) => onPickField("colorField", key)}
311
+ fields={[
312
+ { key: "", label: "No colour", type: undefined },
313
+ ...colorChoices.map((f) => ({
314
+ key: f.key, label: `Colour: ${f.label}`, type: f.type,
315
+ })),
316
+ ]}
317
+ />
 
 
318
  )}
319
  {mode === "map" && sizeChoices.length > 0 && (
320
+ <FieldSelectButton
321
+ className="cg-mode-field"
322
+ ariaLabel="Size pins by"
323
+ placeholder="Size: none"
324
  value={sizeField?.key ?? ""}
325
+ onChange={(key) => onPickField("sizeField", key)}
326
+ fields={[
327
+ { key: "", label: "No size", type: undefined },
328
+ ...sizeChoices.map((f) => ({
329
+ key: f.key, label: `Size: ${f.label}`, type: f.type,
330
+ })),
331
+ ]}
332
+ />
 
 
333
  )}
334
  </span>
335
  );
web/src/index.css CHANGED
@@ -414,6 +414,65 @@ body {
414
  white-space: nowrap;
415
  }
416
  .cg-type-check { color: var(--lp-blue-deep); flex: 0 0 auto; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
417
  .cg-views-head {
418
  min-height: 44px;
419
  display: flex;
@@ -550,7 +609,15 @@ body {
550
  }
551
  .cg-view-menu {
552
  z-index: var(--cg-z-menu);
553
- width: 126px;
 
 
 
 
 
 
 
 
554
  padding: 4px;
555
  border: 1px solid var(--lp-line);
556
  border-radius: var(--lp-r-lg);
@@ -610,6 +677,12 @@ body {
610
  }
611
  .cg-form-actions {
612
  display: flex;
 
 
 
 
 
 
613
  gap: 6px;
614
  margin-top: 8px;
615
  }
@@ -622,6 +695,10 @@ body {
622
  color: var(--cg-text);
623
  font: inherit;
624
  font-size: var(--lp-fs-2xs);
 
 
 
 
625
  cursor: pointer;
626
  }
627
  .cg-btn:hover:not(:disabled) {
@@ -721,6 +798,46 @@ body {
721
  min-width: 0;
722
  }
723
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
724
  /* The formula-measure create flow reuses the condition builder's WindowPicker; inside the
725
  column menu its controls stack in the narrow panel, so let them wrap on one line. */
726
  .cg-measure-window {
@@ -1030,6 +1147,14 @@ body {
1030
  text-align: left;
1031
  font: inherit;
1032
  color: var(--lp-ink);
 
 
 
 
 
 
 
 
1033
  }
1034
  .cg-pick-row:hover,
1035
  /* Item 6 (2026-07-31) β€” the picker is keyboard-run now (arrows move focus, Enter picks):
@@ -1110,28 +1235,53 @@ body {
1110
  align-items: center;
1111
  gap: 6px;
1112
  }
 
 
 
 
 
1113
  .cg-option-color {
1114
  width: 24px;
1115
  height: 24px;
1116
- padding: 2px;
1117
  border: 1px solid var(--lp-line);
1118
  border-radius: 50%;
1119
  background: #fff;
1120
  cursor: pointer;
1121
  }
1122
- .cg-option-color::-webkit-color-swatch-wrapper { padding: 0; }
1123
- .cg-option-color::-webkit-color-swatch {
1124
- border: 0;
1125
- border-radius: 50%;
1126
- }
1127
- .cg-option-color::-moz-color-swatch {
1128
- border: 0;
1129
- border-radius: 50%;
1130
  }
1131
  .cg-option-color:disabled {
1132
  cursor: default;
1133
  opacity: 0.35;
1134
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1135
  .cg-option-name {
1136
  min-width: 0;
1137
  height: 31px;
@@ -1214,6 +1364,15 @@ body {
1214
  .cg-check-row.is-locked:hover {
1215
  background: transparent;
1216
  }
 
 
 
 
 
 
 
 
 
1217
 
1218
  /* ---- owner item 23 β€” the six-dot reorder grip in the Hide-fields panel -------------------
1219
  Quiet until the row is hovered: a column of grips down a 20-field list competes with the
@@ -1291,6 +1450,22 @@ body {
1291
  overflow: hidden;
1292
  text-overflow: ellipsis;
1293
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1294
  .cg-lock-tag {
1295
  font-size: var(--lp-fs-3xs);
1296
  font-weight: 600;
@@ -1318,11 +1493,31 @@ body {
1318
  color: var(--lp-ink);
1319
  font: inherit;
1320
  font-size: var(--lp-fs-xs);
 
 
 
 
1321
  cursor: pointer;
1322
  }
1323
  .cg-link-btn:hover {
1324
  background: var(--lp-blue-tint);
1325
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1326
 
1327
  /* search */
1328
  .cg-search {
@@ -1335,7 +1530,13 @@ body {
1335
  search is the one control that degrades gracefully when narrowed, so it absorbs the
1336
  pressure instead of the count. */
1337
  min-width: 0;
1338
- flex: 1 1 auto;
 
 
 
 
 
 
1339
  }
1340
  .cg-search-icon {
1341
  position: absolute;
@@ -1345,8 +1546,11 @@ body {
1345
  pointer-events: none;
1346
  }
1347
  .cg-search-input {
1348
- width: 100%;
1349
- max-width: 210px;
 
 
 
1350
  min-width: 0;
1351
  height: 30px;
1352
  padding: 0 26px 0 30px;
@@ -1825,6 +2029,35 @@ body {
1825
  flex: 0 0 auto;
1826
  padding: 0 8px;
1827
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1828
  .cg-link-btn:disabled {
1829
  color: #b6b6bf;
1830
  cursor: not-allowed;
@@ -1850,6 +2083,44 @@ body {
1850
  padding: 0 8px;
1851
  }
1852
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1853
  /* ------------------------------------------------------------------------- */
1854
  /* Record DETAIL panel (Batch 3). Right-side fixed slide-in, ~380px, hairline */
1855
  /* border, navy/gold. Header = Prev/Next + position + close; body scrolls. */
@@ -2852,6 +3123,10 @@ body {
2852
  resize: vertical;
2853
  }
2854
  .cg-formula-insert { margin: 4px 0 0; }
 
 
 
 
2855
  .cg-formula-error { color: #8b1a14; }
2856
 
2857
  /* Item 11 β€” rating stars (picker buttons + static rows). */
@@ -3177,12 +3452,40 @@ body {
3177
 
3178
  /* ===== Wave 7 (2026-07-28) β€” CLIENT items (customer-grid only) ============= */
3179
 
3180
- /* Item W4 (contract C6) β€” column-menu action icons + thin-divider grouping. */
3181
- .cg-column-actions button {
 
 
 
3182
  display: flex;
3183
  align-items: center;
3184
  gap: 8px;
3185
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3186
  .cg-mi-ic {
3187
  display: inline-flex;
3188
  align-items: center;
@@ -4753,10 +5056,15 @@ a.cg-map-ctl-b { text-decoration: none; }
4753
  words, and this says it before the words are read. */
4754
  .set-danger { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--lp-red-deep); }
4755
 
 
4756
  /* ------------------------------------------------------------------------- */
4757
  /* Owner item 7 (2026-08-02, contract C-TS): the TIME SERIES view β€” metric */
4758
  /* rows x time-bucket columns. Also mounted inside the record modal for item */
4759
  /* 13, so nothing here may depend on the grid's own layout. */
 
 
 
 
4760
  /* ------------------------------------------------------------------------- */
4761
 
4762
  .cg-ts {
@@ -4766,13 +5074,23 @@ a.cg-map-ctl-b { text-decoration: none; }
4766
  padding: 12px 14px 18px;
4767
  gap: 10px;
4768
  }
4769
- .cg-ts-bar,
4770
- .cg-ts-fields {
4771
  display: flex;
4772
  align-items: center;
4773
  flex-wrap: wrap;
4774
  gap: 8px;
4775
  }
 
 
 
 
 
 
 
 
 
 
 
4776
  .cg-ts-ctl { display: inline-flex; align-items: center; gap: 6px; }
4777
  .cg-ts-ctl-k {
4778
  font-size: var(--lp-fs-2xs);
@@ -4788,27 +5106,32 @@ a.cg-map-ctl-b { text-decoration: none; }
4788
  color: var(--lp-muted);
4789
  font-variant-numeric: tabular-nums;
4790
  }
4791
- /* A metric chip. Tint FILLS and the -deep weight carries the text, per the brand rule β€”
4792
- the base pastel is 1.88:1 and would not be readable as ink at this size. */
4793
- .cg-ts-chip {
4794
- height: 26px;
4795
- padding: 0 10px;
 
 
 
4796
  border: 1px solid var(--lp-line);
4797
- border-radius: var(--lp-r-lg);
4798
  background: var(--lp-surface);
4799
  color: var(--lp-muted);
4800
- font: inherit;
4801
  font-size: var(--lp-fs-2xs);
 
4802
  cursor: pointer;
4803
  }
4804
- .cg-ts-chip.is-on {
4805
  border-color: var(--lp-blue-deep);
4806
  background: var(--lp-blue-tint);
4807
  color: var(--lp-blue-deep);
4808
  font-weight: 600;
4809
  }
4810
- .cg-ts-chip:disabled { cursor: default; opacity: 0.55; }
4811
- .cg-ts-chip:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 1px; }
 
4812
 
4813
  .cg-ts-scroll {
4814
  overflow: auto;
@@ -4893,6 +5216,143 @@ a.cg-map-ctl-b { text-decoration: none; }
4893
  }
4894
  .cg-ts-notes li { margin-top: 3px; }
4895
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4896
  /* ------------------------------------------------------------------------- */
4897
  /* Owner items 3 + 4 (2026-08-02, contract C-DISP): standardized kanban card */
4898
  /* height, and calendar days that can show totals instead of records. */
@@ -4991,14 +5451,14 @@ a.cg-map-ctl-b { text-decoration: none; }
4991
  border-top: 1px solid var(--lp-line);
4992
  color: var(--lp-muted);
4993
  }
4994
- /* Item 4 β€” one row of the Totals picker: the field checkbox, and (once picked) how to total
4995
- it. The select only appears for a chosen field, so the panel does not present four dead
4996
- dropdowns for fields nobody selected. */
4997
- .cg-cal-pick {
4998
- display: flex;
4999
- align-items: center;
5000
- gap: 8px;
5001
- padding: 2px 8px;
5002
- }
5003
- .cg-cal-pick .cg-check-row { flex: 1 1 auto; min-width: 0; }
5004
- .cg-cal-pick .cg-select { flex: 0 0 auto; }
 
414
  white-space: nowrap;
415
  }
416
  .cg-type-check { color: var(--lp-blue-deep); flex: 0 0 auto; }
417
+
418
+ /* ---- item 20 (C-FLDSEL): the field picker that can show a mark ---------------------------
419
+ The BUTTON keeps `.cg-select`'s box verbatim, so every sizing class already written for a
420
+ native select (`.cg-cond-field`, `.cg-mode-field`, `.cg-swap-select`) applies unchanged.
421
+ It gains 10px of readable width in the bargain: the native picker arrow measured 20.1px
422
+ (see the width derivation beside `.cg-cond-field`) and this caret is 10. */
423
+ .cg-fsel {
424
+ display: inline-flex;
425
+ align-items: center;
426
+ gap: 6px;
427
+ text-align: left;
428
+ /* a <button>'s default is `center`; every select it replaces reads left-aligned */
429
+ justify-content: flex-start;
430
+ }
431
+ .cg-fsel:hover:not(:disabled) { border-color: var(--lp-blue-deep); }
432
+ .cg-fsel:disabled { color: var(--lp-muted); cursor: default; opacity: 0.6; }
433
+ .cg-fsel .cg-type-icon { color: var(--lp-muted); flex: 0 0 auto; }
434
+ .cg-fsel-label {
435
+ flex: 1 1 auto;
436
+ min-width: 0;
437
+ overflow: hidden;
438
+ text-overflow: ellipsis;
439
+ white-space: nowrap;
440
+ }
441
+ /* UNSET reads as a prompt, not as a field: the whole point of the placeholder state is that
442
+ it cannot be mistaken for the first row of the list. */
443
+ .cg-fsel.is-empty .cg-fsel-label { color: var(--lp-muted); }
444
+ /* SET to something this table cannot offer. Amber, not red: the reference is broken, the row
445
+ is not β€” you can still open the list and choose again, which is exactly what the muted
446
+ `is-empty` state would have hidden by showing a plausible field instead. */
447
+ .cg-fsel.is-missing {
448
+ border-color: var(--lp-yellow);
449
+ }
450
+ .cg-fsel.is-missing .cg-fsel-label {
451
+ color: var(--lp-yellow-deep);
452
+ font-variant-numeric: tabular-nums;
453
+ }
454
+ .cg-fsel-caret { color: var(--lp-muted); flex: 0 0 auto; }
455
+ /* Keeps the label column aligned across rows whose mark is absent. */
456
+ .cg-fsel-nomark { width: 14px; height: 14px; flex: 0 0 auto; }
457
+ .cg-fsel-pop {
458
+ min-width: 220px;
459
+ max-width: 320px;
460
+ padding: 4px;
461
+ }
462
+ .cg-fsel-body { display: flex; flex-direction: column; min-width: 0; }
463
+ .cg-fsel-search { border: 1px solid var(--lp-line); border-radius: var(--lp-r-md); }
464
+ .cg-fsel-group {
465
+ padding: 6px 8px 2px;
466
+ font-size: var(--lp-fs-3xs);
467
+ font-weight: 600;
468
+ color: var(--lp-muted);
469
+ }
470
+ .cg-fsel-hint {
471
+ display: block;
472
+ font-size: var(--lp-fs-3xs);
473
+ color: var(--lp-muted);
474
+ font-weight: 400;
475
+ }
476
  .cg-views-head {
477
  min-height: 44px;
478
  display: flex;
 
609
  }
610
  .cg-view-menu {
611
  z-index: var(--cg-z-menu);
612
+ /* ⚠ item 19 (2026-08-02): was a FIXED `width: 126px`, which is where the owner's "the rows
613
+ overlay downward" came from β€” "Change cohort lock…" and "Lock as Time series" both wrap to
614
+ two lines at that width, and a wrapped menu row reads as two rows. The panel is
615
+ shrink-to-fit now with a floor that clears the longest CLOSED-vocabulary label (every
616
+ string in this menu is one of ours; no tenant content lands here, so max-content cannot
617
+ run away) and a ceiling in case that stops being true. `nowrap` below is the other half:
618
+ without it a narrow viewport would re-create the same wrap inside the ceiling. */
619
+ min-width: 186px;
620
+ max-width: 260px;
621
  padding: 4px;
622
  border: 1px solid var(--lp-line);
623
  border-radius: var(--lp-r-lg);
 
677
  }
678
  .cg-form-actions {
679
  display: flex;
680
+ align-items: center;
681
+ /* R7 (2026-08-02) β€” when the row genuinely cannot fit, WHOLE BUTTONS move to a second line.
682
+ Without this the flex line squeezes each button instead and every label breaks in half:
683
+ "Create and change" over two lines inside a 318px column menu, which reads as two
684
+ controls. A wrapped ROW is a layout; a wrapped LABEL is a defect. */
685
+ flex-wrap: wrap;
686
  gap: 6px;
687
  margin-top: 8px;
688
  }
 
695
  color: var(--cg-text);
696
  font: inherit;
697
  font-size: var(--lp-fs-2xs);
698
+ /* R7 β€” the other half of the rule above. Every label here is a CLOSED vocabulary of ours
699
+ ("Save", "Create and change", "Copy configuration", "Delete permanently?"), so it is
700
+ always readable at its natural width; there is nothing to gain by letting it break. */
701
+ white-space: nowrap;
702
  cursor: pointer;
703
  }
704
  .cg-btn:hover:not(:disabled) {
 
798
  min-width: 0;
799
  }
800
 
801
+ /* ---- item 21: the metric PERIOD, stated on the menu and edited in the Edit-field pane ----
802
+ The menu row is a BUTTON that opens Edit field β€” the menu pane edits nothing inline β€” and
803
+ it reads as one line: label, then the window in the reader's own words. `nowrap` on the
804
+ label with the value free to ellipsis, so "in the last 90 days" can never push "Period"
805
+ onto a second line (R7). */
806
+ .cg-column-periodline {
807
+ display: flex;
808
+ align-items: center;
809
+ gap: 8px;
810
+ width: 100%;
811
+ min-height: 30px;
812
+ margin: 4px 0 2px;
813
+ padding: 0 8px;
814
+ border: 0;
815
+ border-radius: var(--lp-r-sm);
816
+ background: var(--lp-surface-2);
817
+ color: var(--lp-ink);
818
+ font: inherit;
819
+ font-size: var(--lp-fs-xs);
820
+ text-align: left;
821
+ cursor: pointer;
822
+ }
823
+ .cg-column-periodline:hover { background: var(--lp-blue-tint); }
824
+ .cg-column-periodline:focus-visible {
825
+ outline: 2px solid var(--lp-blue-deep);
826
+ outline-offset: -1px;
827
+ }
828
+ .cg-column-periodval {
829
+ flex: 1 1 auto;
830
+ min-width: 0;
831
+ overflow: hidden;
832
+ text-overflow: ellipsis;
833
+ white-space: nowrap;
834
+ text-align: right;
835
+ color: var(--lp-muted);
836
+ }
837
+ /* In the Edit-field pane the period is one of the field's properties, laid out like the
838
+ others (`.cg-column-create label` is the column-stack this joins). */
839
+ .cg-edit-period .cg-measure-window { width: 100%; }
840
+
841
  /* The formula-measure create flow reuses the condition builder's WindowPicker; inside the
842
  column menu its controls stack in the narrow panel, so let them wrap on one line. */
843
  .cg-measure-window {
 
1147
  text-align: left;
1148
  font: inherit;
1149
  color: var(--lp-ink);
1150
+ /* R7 (2026-08-02) β€” these rows carry TENANT CONTENT (cohort names), so unlike the closed
1151
+ vocabularies elsewhere they get the ellipsis treatment rather than a bare `nowrap`: a
1152
+ three-line cohort name in the lock picker turned a list of choices into a paragraph, and
1153
+ truncating a name you can still hover beats reflowing the list around it. */
1154
+ min-width: 0;
1155
+ overflow: hidden;
1156
+ text-overflow: ellipsis;
1157
+ white-space: nowrap;
1158
  }
1159
  .cg-pick-row:hover,
1160
  /* Item 6 (2026-07-31) β€” the picker is keyboard-run now (arrows move focus, Enter picks):
 
1235
  align-items: center;
1236
  gap: 6px;
1237
  }
1238
+ /* ⚠ item 22 (2026-08-02): this is a <button> now, not an `<input type="color">`. The
1239
+ ::-webkit-color-swatch / ::-moz-color-swatch rules that used to strip the native chrome are
1240
+ GONE with the input β€” a dead vendor pseudo-element is the kind of thing that reads as
1241
+ load-bearing to the next person. Same 24px circle in the same slot; the fill arrives as an
1242
+ inline style because it is DATA (the option's colour), not a token. */
1243
  .cg-option-color {
1244
  width: 24px;
1245
  height: 24px;
1246
+ padding: 0;
1247
  border: 1px solid var(--lp-line);
1248
  border-radius: 50%;
1249
  background: #fff;
1250
  cursor: pointer;
1251
  }
1252
+ .cg-option-color:focus-visible {
1253
+ outline: 2px solid var(--lp-blue-deep);
1254
+ outline-offset: 1px;
 
 
 
 
 
1255
  }
1256
  .cg-option-color:disabled {
1257
  cursor: default;
1258
  opacity: 0.35;
1259
  }
1260
+
1261
+ /* The ten brand swatches (R5): each hue's `-tint` on the top row, its `-pastel` beneath, so
1262
+ the grid reads as five columns of one hue rather than ten unrelated dots. */
1263
+ .cg-swatch-pop { padding: 8px; }
1264
+ .cg-swatch-grid {
1265
+ display: grid;
1266
+ grid-template-columns: repeat(5, 28px);
1267
+ gap: 6px;
1268
+ }
1269
+ .cg-swatch {
1270
+ display: inline-grid;
1271
+ place-items: center;
1272
+ width: 28px;
1273
+ height: 28px;
1274
+ padding: 0;
1275
+ border: 1px solid rgba(20, 24, 40, 0.12);
1276
+ border-radius: var(--lp-r-md);
1277
+ cursor: pointer;
1278
+ }
1279
+ .cg-swatch:hover { border-color: rgba(20, 24, 40, 0.34); }
1280
+ .cg-swatch.is-on { border-color: var(--lp-ink); }
1281
+ .cg-swatch:focus-visible {
1282
+ outline: 2px solid var(--lp-blue-deep);
1283
+ outline-offset: 1px;
1284
+ }
1285
  .cg-option-name {
1286
  min-width: 0;
1287
  height: 31px;
 
1364
  .cg-check-row.is-locked:hover {
1365
  background: transparent;
1366
  }
1367
+ /* Item 12 (2026-08-02) β€” a HIDDEN field's row reads as hidden. The checkbox already carried
1368
+ the state; at 15px it is the smallest thing in the row and you have to look for it, so a
1369
+ list with four columns hidden looked identical to one with none. Muted ink only β€” never a
1370
+ strike-through or a fill: the row is still a live control and both of those read as
1371
+ "disabled", which the locked row genuinely is. */
1372
+ .cg-check-row.is-off .cg-check-label,
1373
+ .cg-check-row.is-off .cg-type-icon {
1374
+ color: var(--lp-muted);
1375
+ }
1376
 
1377
  /* ---- owner item 23 β€” the six-dot reorder grip in the Hide-fields panel -------------------
1378
  Quiet until the row is hovered: a column of grips down a 20-field list competes with the
 
1450
  overflow: hidden;
1451
  text-overflow: ellipsis;
1452
  }
1453
+ /* R7 (2026-08-02) β€” the RADIO rows never got the treatment their checkbox twins have had
1454
+ since wave 2, and they are the ones that list FIELD LABELS (the Group-by popover): a
1455
+ two-line "Estimated missed revenue, last 12 months" pushed the row below it out of the
1456
+ rhythm and made the radio look mis-aligned with its own text.
1457
+ ⚠ `:not([class])` is load-bearing, not tidiness. `.cg-radio-row > span` alone is (0,1,1)
1458
+ and therefore OUTRANKS `.cg-perm-label` (0,1,0) β€” the view-permission rows whose span
1459
+ deliberately stacks a LABEL over a two-line blurb. That rule would have clipped every
1460
+ explanation in the permissions pane to one ellipsised line. Caught by walking every
1461
+ `cg-radio-row` call site rather than by an assertion; all eleven others are bare spans. */
1462
+ .cg-radio-row > span:not([class]) {
1463
+ flex: 1 1 auto;
1464
+ min-width: 0;
1465
+ overflow: hidden;
1466
+ text-overflow: ellipsis;
1467
+ white-space: nowrap;
1468
+ }
1469
  .cg-lock-tag {
1470
  font-size: var(--lp-fs-3xs);
1471
  font-weight: 600;
 
1493
  color: var(--lp-ink);
1494
  font: inherit;
1495
  font-size: var(--lp-fs-xs);
1496
+ /* R7 β€” a fixed 28px height with a label free to wrap is the worst of both: the second line
1497
+ is CLIPPED rather than shown. Every label here is ours ("Show all", "+ Add condition
1498
+ group", "Copy from another view"), so one line is always the right answer. */
1499
+ white-space: nowrap;
1500
  cursor: pointer;
1501
  }
1502
  .cg-link-btn:hover {
1503
  background: var(--lp-blue-tint);
1504
  }
1505
+ /* Item 12 (2026-08-02) β€” the Hide-fields panel's bulk row, boxed. `--lp-surface-2` is the
1506
+ app's one "quiet slot" fill (the record modal's read-only rows use it for the same reason),
1507
+ so the pair reads as a tray under the list rather than as two more rows of it. The box
1508
+ replaces the hairline: keeping both would draw two separators for one boundary. */
1509
+ .cg-fields-footer {
1510
+ margin-top: 6px;
1511
+ padding: 4px;
1512
+ border-top: 0;
1513
+ border-radius: var(--lp-r-md);
1514
+ background: var(--lp-surface-2);
1515
+ }
1516
+ .cg-fields-footer .cg-link-btn:hover {
1517
+ /* on the grey tray the blue-tint hover reads as a selection; white reads as "this is the
1518
+ button", which is what a hover on a tray needs to say. */
1519
+ background: var(--lp-surface);
1520
+ }
1521
 
1522
  /* search */
1523
  .cg-search {
 
1530
  search is the one control that degrades gracefully when narrowed, so it absorbs the
1531
  pressure instead of the count. */
1532
  min-width: 0;
1533
+ /* ⚠ item 14 (2026-08-02): was `flex: 1 1 auto` while this sat AFTER `.cg-tb-spacer`, where
1534
+ growing was harmless β€” it and the spacer were the only two flexible items and the input's
1535
+ own `max-width` capped the result. Now that it sits INSIDE the left cluster, growing would
1536
+ split the slack with the spacer and strand the count mid-strip. It never grows and still
1537
+ shrinks first, which is the sentence above, unchanged in intent. */
1538
+ flex: 0 1 auto;
1539
+ margin-left: 4px;
1540
  }
1541
  .cg-search-icon {
1542
  position: absolute;
 
1546
  pointer-events: none;
1547
  }
1548
  .cg-search-input {
1549
+ /* item 14: `width: 100%` measured the (previously growing) wrapper; now the INPUT carries
1550
+ the size and the wrapper is content-sized around it, so the two cannot disagree about
1551
+ where the control ends and leave a dead strip after the box. */
1552
+ width: 210px;
1553
+ max-width: 100%;
1554
  min-width: 0;
1555
  height: 30px;
1556
  padding: 0 26px 0 30px;
 
2029
  flex: 0 0 auto;
2030
  padding: 0 8px;
2031
  }
2032
+ /* Item 13 (2026-08-02) β€” the add-links read as ACTIONS. They were 400-weight ink on a
2033
+ transparent background, i.e. typographically indistinguishable from the "Where"/"and" text
2034
+ they sit under, so the one thing in the popover you are meant to click looked like a label.
2035
+ 600 + the product blue is what `.cg-option-add` already uses for the identical job one panel
2036
+ over; this is that decision applied to the pair the owner pointed at, not a new one. */
2037
+ .cg-builder-add .cg-link-btn,
2038
+ .cg-builder-footer .cg-link-btn {
2039
+ font-weight: 600;
2040
+ color: var(--lp-blue-solid);
2041
+ }
2042
+ /* R9 β€” "the one you have been using", held while the popover is open and gone the next time
2043
+ it opens (the popover unmounts its children, so nothing has to clear this). `-deep` on the
2044
+ text with the `-tint` fill, per the palette law; a solid blue chip here would outweigh the
2045
+ Save-shaped primary buttons elsewhere in the same panel. */
2046
+ .cg-builder-add .cg-link-btn.is-on,
2047
+ .cg-builder-footer .cg-link-btn.is-on {
2048
+ background: var(--lp-blue-tint);
2049
+ border-color: var(--lp-blue-deep);
2050
+ color: var(--lp-blue-deep);
2051
+ }
2052
+ .cg-builder-add .cg-link-btn:disabled,
2053
+ .cg-builder-footer .cg-link-btn:disabled {
2054
+ color: #b6b6bf;
2055
+ }
2056
+ /* The copy door sits at the far end of the footer: it acts on the WHOLE view, not on the
2057
+ conditions beside it, and the gap says so without a divider. */
2058
+ .cg-copy-link {
2059
+ margin-left: auto;
2060
+ }
2061
  .cg-link-btn:disabled {
2062
  color: #b6b6bf;
2063
  cursor: not-allowed;
 
2083
  padding: 0 8px;
2084
  }
2085
 
2086
+ /* ---- item 13 (C-COPYVIEW): copy configuration from another view ------------------------- */
2087
+ .cg-copycfg-pop {
2088
+ width: min(360px, calc(100vw - 16px));
2089
+ padding: 8px;
2090
+ }
2091
+ .cg-copycfg-head {
2092
+ display: flex;
2093
+ align-items: center;
2094
+ flex-wrap: wrap;
2095
+ gap: 6px;
2096
+ padding: 2px 4px 8px;
2097
+ font-size: var(--lp-fs-xs);
2098
+ font-weight: 600;
2099
+ }
2100
+ /* The picker is the object of the sentence, so it takes the slack; the two text fragments
2101
+ never wrap away from it because the row is allowed to wrap as a whole (R7: a control that
2102
+ breaks its own sentence in half is worse than a two-line sentence). */
2103
+ .cg-copycfg-source {
2104
+ flex: 1 1 150px;
2105
+ min-width: 140px;
2106
+ }
2107
+ .cg-copycfg .cg-pop-list { max-height: 260px; }
2108
+ .cg-copycfg .cg-mi-ic {
2109
+ display: inline-flex;
2110
+ flex: 0 0 auto;
2111
+ color: var(--lp-muted);
2112
+ }
2113
+ .cg-copycfg-bulk {
2114
+ justify-content: flex-start;
2115
+ gap: 4px;
2116
+ }
2117
+ /* R7 β€” padding only. The gap, the wrap and the alignment are `.cg-form-actions`', so this
2118
+ button row cannot drift from every other Save/Cancel pair in the app; an 8px gap here
2119
+ against 6px everywhere else was the asymmetry the sweep is for, and I had just written it. */
2120
+ .cg-copycfg-actions {
2121
+ padding: 8px 4px 2px;
2122
+ }
2123
+
2124
  /* ------------------------------------------------------------------------- */
2125
  /* Record DETAIL panel (Batch 3). Right-side fixed slide-in, ~380px, hairline */
2126
  /* border, navy/gold. Header = Prev/Next + position + close; body scrolls. */
 
3123
  resize: vertical;
3124
  }
3125
  .cg-formula-insert { margin: 4px 0 0; }
3126
+ /* Item 20 β€” the reference inserter replaced a bare `<select>`, which stretched to the flex
3127
+ line on its own. A button is content-sized, so it needs telling: full width, and the
3128
+ `.cg-fsel-label` ellipsis carries "Insert a field reference…" at the narrow end. */
3129
+ .cg-formula-insert .cg-fsel { flex: 1 1 auto; min-width: 0; }
3130
  .cg-formula-error { color: #8b1a14; }
3131
 
3132
  /* Item 11 β€” rating stars (picker buttons + static rows). */
 
3452
 
3453
  /* ===== Wave 7 (2026-07-28) β€” CLIENT items (customer-grid only) ============= */
3454
 
3455
+ /* Item W4 (contract C6) β€” column-menu action icons + thin-divider grouping.
3456
+ Item 19 (2026-08-02) extends the same row shape to the VIEW menu: one icon column, one
3457
+ line, no wraps. Two menus that do the same kind of thing now look like each other. */
3458
+ .cg-column-actions button,
3459
+ .cg-view-menu button {
3460
  display: flex;
3461
  align-items: center;
3462
  gap: 8px;
3463
  }
3464
+ /* R7 β€” a menu row is ONE LINE. `.cg-mi-text` may ellipsis (it never should at these widths;
3465
+ it is the backstop that keeps a long label from growing the panel past its ceiling). */
3466
+ .cg-column-actions button,
3467
+ .cg-view-menu button {
3468
+ white-space: nowrap;
3469
+ }
3470
+ /* ⚠ The export pane's title is "Export <view name>" β€” TENANT CONTENT under the same nowrap,
3471
+ which without this would run straight out of the panel's 260px ceiling. Caught by walking
3472
+ my own item-19 change rather than by an assertion; the menu rows beside it are all closed
3473
+ vocabulary and genuinely need nothing. */
3474
+ .cg-view-menu .cg-pop-title {
3475
+ overflow: hidden;
3476
+ text-overflow: ellipsis;
3477
+ white-space: nowrap;
3478
+ }
3479
+ .cg-mi-text {
3480
+ flex: 1 1 auto;
3481
+ min-width: 0;
3482
+ overflow: hidden;
3483
+ text-overflow: ellipsis;
3484
+ }
3485
+ .cg-view-menu button:hover:not(:disabled) .cg-mi-ic,
3486
+ .cg-view-menu button.is-danger .cg-mi-ic {
3487
+ color: inherit;
3488
+ }
3489
  .cg-mi-ic {
3490
  display: inline-flex;
3491
  align-items: center;
 
5056
  words, and this says it before the words are read. */
5057
  .set-danger { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--lp-red-deep); }
5058
 
5059
+ /* ═══ TSREC REGION (wave 14) β€” PANEL keep out ═══ */
5060
  /* ------------------------------------------------------------------------- */
5061
  /* Owner item 7 (2026-08-02, contract C-TS): the TIME SERIES view β€” metric */
5062
  /* rows x time-bucket columns. Also mounted inside the record modal for item */
5063
  /* 13, so nothing here may depend on the grid's own layout. */
5064
+ /* */
5065
+ /* Wave 14 (items 16c/17/18) rebuilds the panel as an excel-adjacent sheet: */
5066
+ /* metric ROWS with an add-row at the bottom, delta sub-rows, custom note + */
5067
+ /* formula rows, a sparkline column and an optional gridline grain. */
5068
  /* ------------------------------------------------------------------------- */
5069
 
5070
  .cg-ts {
 
5074
  padding: 12px 14px 18px;
5075
  gap: 10px;
5076
  }
5077
+ .cg-ts-bar {
 
5078
  display: flex;
5079
  align-items: center;
5080
  flex-wrap: wrap;
5081
  gap: 8px;
5082
  }
5083
+ /* R7 β€” the bar may wrap BETWEEN groups at a narrow width; a control's own label may never
5084
+ wrap. A two-line "vs last year" button is the thing the sweep is about, and it is also what
5085
+ makes a row of buttons stop looking like a row. */
5086
+ .cg-ts-group {
5087
+ display: inline-flex;
5088
+ align-items: center;
5089
+ gap: 4px;
5090
+ padding-left: 8px;
5091
+ border-left: 1px solid var(--lp-line);
5092
+ }
5093
+ .cg-ts-bar > * { white-space: nowrap; }
5094
  .cg-ts-ctl { display: inline-flex; align-items: center; gap: 6px; }
5095
  .cg-ts-ctl-k {
5096
  font-size: var(--lp-fs-2xs);
 
5106
  color: var(--lp-muted);
5107
  font-variant-numeric: tabular-nums;
5108
  }
5109
+ /* A bar toggle (a comparison, gridlines, the trend column).
5110
+ ⚠ This REPLACES `.cg-ts-chip`, the metric chip row wave 14 deleted: metrics are ROWS now,
5111
+ added and removed on the sheet itself, so the only chips left are display switches.
5112
+ Tint FILLS and the -deep weight carries the text, per the brand rule β€” the base pastel is
5113
+ 1.88:1 and would not be readable as ink at this size. */
5114
+ .cg-ts-tog {
5115
+ height: 24px;
5116
+ padding: 0 9px;
5117
  border: 1px solid var(--lp-line);
5118
+ border-radius: var(--lp-r-md);
5119
  background: var(--lp-surface);
5120
  color: var(--lp-muted);
5121
+ font-family: inherit;
5122
  font-size: var(--lp-fs-2xs);
5123
+ white-space: nowrap;
5124
  cursor: pointer;
5125
  }
5126
+ .cg-ts-tog.is-on {
5127
  border-color: var(--lp-blue-deep);
5128
  background: var(--lp-blue-tint);
5129
  color: var(--lp-blue-deep);
5130
  font-weight: 600;
5131
  }
5132
+ .cg-ts-tog:hover:enabled { border-color: var(--lp-blue-deep); }
5133
+ .cg-ts-tog:disabled { cursor: default; opacity: 0.55; }
5134
+ .cg-ts-tog:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 1px; }
5135
 
5136
  .cg-ts-scroll {
5137
  overflow: auto;
 
5216
  }
5217
  .cg-ts-notes li { margin-top: 3px; }
5218
 
5219
+ /* ------------------------------------------------------------------------- */
5220
+ /* Wave 14 items 17 + 18 β€” the SHEET: rows you build, comparisons you name. */
5221
+ /* ------------------------------------------------------------------------- */
5222
+
5223
+ /* Item 17 β€” the gridline toggle. Removing the rules leaves the numbers held only by their
5224
+ own alignment, which is how a printed financial statement reads and why the owner asked
5225
+ for it. The STICKY column and the totals rule stay: those are structure, not grain. */
5226
+ .cg-ts-table.is-nogrid th,
5227
+ .cg-ts-table.is-nogrid td { border-bottom-color: transparent; }
5228
+ .cg-ts-table.is-nogrid thead th { border-bottom-color: var(--lp-line); }
5229
+
5230
+ /* Item 17 β€” the emphasis a reader adds. `is-bold` on the row weights the whole line;
5231
+ `is-ruled` draws the rule ABOVE it, which is where a subtotal rule belongs β€” under the
5232
+ inputs it is summarising, above the answer. */
5233
+ .cg-ts-table tr.is-bold td,
5234
+ .cg-ts-table tr.is-bold .cg-ts-stick,
5235
+ .cg-ts-table td.is-bold { font-weight: 700; color: var(--lp-ink); }
5236
+ .cg-ts-table tr.is-ruled th,
5237
+ .cg-ts-table tr.is-ruled td { border-top: 1px solid var(--lp-ink); }
5238
+
5239
+ /* The row's head: its name (and, for a formula, its arithmetic) on the left, its controls on
5240
+ the right. `min-width` because the sticky column now holds inputs β€” without it a formula
5241
+ box would collapse to nothing on a narrow panel and the sheet would look broken. */
5242
+ .cg-ts-stick { min-width: 208px; }
5243
+ .cg-ts-rowhead {
5244
+ display: flex;
5245
+ align-items: flex-start;
5246
+ justify-content: space-between;
5247
+ gap: 8px;
5248
+ }
5249
+ .cg-ts-rowmain { min-width: 0; display: flex; flex-direction: column; gap: 1px; }
5250
+ .cg-ts-rowlabel { font-weight: 500; }
5251
+ /* R1 β€” the metric's OWN window, and the reason this line exists: under identical month
5252
+ headings a cumulative year-to-date row and a trailing-90 row look like the same kind of
5253
+ number. Muted and small, because it qualifies the name rather than competing with it. */
5254
+ .cg-ts-rowsub {
5255
+ font-size: var(--lp-fs-3xs);
5256
+ font-weight: 400;
5257
+ color: var(--lp-muted);
5258
+ white-space: nowrap;
5259
+ overflow: hidden;
5260
+ text-overflow: ellipsis;
5261
+ }
5262
+ /* A row that names itself. Borderless until touched β€” 12 boxed inputs down the left edge
5263
+ would be louder than every number on the sheet. */
5264
+ .cg-ts-rowinput {
5265
+ width: 100%;
5266
+ min-width: 0;
5267
+ padding: 1px 3px;
5268
+ border: 1px solid transparent;
5269
+ border-radius: var(--lp-r-sm);
5270
+ background: transparent;
5271
+ color: var(--lp-ink);
5272
+ font-family: inherit;
5273
+ font-size: inherit;
5274
+ font-weight: 500;
5275
+ }
5276
+ .cg-ts-rowinput:hover { border-color: var(--lp-line); }
5277
+ .cg-ts-rowinput:focus {
5278
+ outline: none;
5279
+ border-color: var(--lp-blue-deep);
5280
+ background: var(--lp-surface);
5281
+ }
5282
+ .cg-ts-rowinput::placeholder { color: var(--lp-muted); opacity: 1; }
5283
+ /* The arithmetic reads as arithmetic: monospace, so `[a] / [b]` lines up and a stray bracket
5284
+ is visible. Smaller and muted β€” it is how the row was made, not what it says. */
5285
+ .cg-ts-rowexpr {
5286
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
5287
+ font-size: var(--lp-fs-3xs);
5288
+ font-weight: 400;
5289
+ color: var(--lp-muted);
5290
+ }
5291
+
5292
+ /* Per-row controls: bold, rule, remove. Hover-revealed like the record modal's grips β€” a
5293
+ permanent column of three buttons per row would out-shout the data β€” but always in the tab
5294
+ order, so the keyboard never loses them. */
5295
+ .cg-ts-rowtools {
5296
+ flex: 0 0 auto;
5297
+ display: inline-flex;
5298
+ gap: 1px;
5299
+ opacity: 0;
5300
+ transition: opacity 90ms ease;
5301
+ }
5302
+ .cg-ts-table tr:hover .cg-ts-rowtools,
5303
+ .cg-ts-rowtools:focus-within { opacity: 1; }
5304
+ .cg-ts-rowtool {
5305
+ width: 18px;
5306
+ height: 18px;
5307
+ display: grid;
5308
+ place-items: center;
5309
+ padding: 0;
5310
+ border: 0;
5311
+ border-radius: var(--lp-r-sm);
5312
+ background: transparent;
5313
+ color: var(--lp-muted);
5314
+ font-family: inherit;
5315
+ font-size: var(--lp-fs-3xs);
5316
+ font-weight: 700;
5317
+ line-height: 1;
5318
+ cursor: pointer;
5319
+ }
5320
+ .cg-ts-rowtool:hover { background: var(--lp-surface-2); color: var(--lp-ink); }
5321
+ .cg-ts-rowtool.is-on { background: var(--lp-blue-tint); color: var(--lp-blue-deep); }
5322
+ .cg-ts-rowtool:focus-visible { outline: 2px solid var(--lp-blue-deep); outline-offset: 1px; }
5323
+
5324
+ /* A NOTE row spans the sheet β€” a section heading in a financial model. Spanning is what stops
5325
+ twelve blank cells from reading as twelve unanswerable ones ("β€”" means something else in
5326
+ this table). */
5327
+ .cg-ts-noterow .cg-ts-stick {
5328
+ background: var(--lp-wash);
5329
+ border-right: 0;
5330
+ color: var(--lp-ink);
5331
+ font-weight: 600;
5332
+ }
5333
+
5334
+ /* The sheet grows from its bottom edge, the way a spreadsheet does. */
5335
+ .cg-ts-addrow .cg-ts-stick {
5336
+ background: var(--lp-surface);
5337
+ border-right: 0;
5338
+ font-weight: 400;
5339
+ }
5340
+ .cg-ts-addbar {
5341
+ display: flex;
5342
+ align-items: center;
5343
+ gap: 6px;
5344
+ white-space: nowrap;
5345
+ }
5346
+ .cg-ts-addsel { max-width: 220px; }
5347
+
5348
+ /* Item 17 β€” the trend column. Narrow on purpose: it answers "which way" at a glance and hands
5349
+ the exact question back to the numbers beside it. */
5350
+ .cg-ts-sparkhead { width: 84px; text-align: center; }
5351
+ .cg-ts-spark { text-align: center; color: var(--lp-blue-deep); }
5352
+ .cg-ts-sparksvg { display: block; margin: 0 auto; overflow: visible; }
5353
+ .cg-ts-sparkempty { color: var(--lp-muted); }
5354
+ /* ═══ end TSREC region ═══ */
5355
+
5356
  /* ------------------------------------------------------------------------- */
5357
  /* Owner items 3 + 4 (2026-08-02, contract C-DISP): standardized kanban card */
5358
  /* height, and calendar days that can show totals instead of records. */
 
5451
  border-top: 1px solid var(--lp-line);
5452
  color: var(--lp-muted);
5453
  }
5454
+ /* Item 4 β€” one row of the Totals picker: the field checkbox, and (once picked) how to total
5455
+ it. The select only appears for a chosen field, so the panel does not present four dead
5456
+ dropdowns for fields nobody selected. */
5457
+ .cg-cal-pick {
5458
+ display: flex;
5459
+ align-items: center;
5460
+ gap: 8px;
5461
+ padding: 2px 8px;
5462
+ }
5463
+ .cg-cal-pick .cg-check-row { flex: 1 1 auto; min-width: 0; }
5464
+ .cg-cal-pick .cg-select { flex: 0 0 auto; }
web/src/settings/SettingsModal.tsx CHANGED
@@ -19,15 +19,17 @@
19
  // would not open.
20
  // ---------------------------------------------------------------------------
21
 
22
- import { useCallback, useEffect, useState } from "react";
23
  import type { SessionUser } from "../shell/session";
24
- import { isAdmin } from "../shell/session";
25
  import type { AdminUser, SettingsPayload, UserPatch } from "./settingsApi";
26
  import {
 
27
  createUser,
28
  getSettings,
29
  listUsers,
30
  patchUser,
 
31
  setPassword,
32
  } from "./settingsApi";
33
 
@@ -407,6 +409,164 @@ function AddUser({
407
  );
408
  }
409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
410
  // ------------------------------------------------------------------ the modal
411
 
412
  export function SettingsModal({
@@ -414,11 +574,15 @@ export function SettingsModal({
414
  section,
415
  onSection,
416
  onClose,
 
417
  }: {
418
  user: SessionUser;
419
  section: SettingsSection;
420
  onSection: (s: SettingsSection) => void;
421
  onClose: () => void;
 
 
 
422
  }) {
423
  const [settings, setSettings] = useState<SettingsPayload | null>(null);
424
  const admin = isAdmin(user);
@@ -491,6 +655,7 @@ export function SettingsModal({
491
  <span className="pg-drill-key">Role</span>
492
  <span className="pg-drill-val">{admin ? "Admin" : "Member"}</span>
493
  </div>
 
494
  </div>
495
  ) : null}
496
 
 
19
  // would not open.
20
  // ---------------------------------------------------------------------------
21
 
22
+ import { useCallback, useEffect, useRef, useState } from "react";
23
  import type { SessionUser } from "../shell/session";
24
+ import { isAdmin, parseUserEnvelope } from "../shell/session";
25
  import type { AdminUser, SettingsPayload, UserPatch } from "./settingsApi";
26
  import {
27
+ clearAvatar,
28
  createUser,
29
  getSettings,
30
  listUsers,
31
  patchUser,
32
+ setAvatar,
33
  setPassword,
34
  } from "./settingsApi";
35
 
 
409
  );
410
  }
411
 
412
+ // ------------------------------------------------------------------ profile photo (wave 14)
413
+
414
+ /** Downscale + centre-crop to a <=128px JPEG data URL. JPEG at this size lands ~5-10KB,
415
+ * comfortably under the server's 64KB decoded wall; the server re-validates regardless. */
416
+ async function fileToAvatarDataUrl(file: File): Promise<string | null> {
417
+ const url = URL.createObjectURL(file);
418
+ try {
419
+ const img = new Image();
420
+ await new Promise<void>((res, rej) => {
421
+ img.onload = () => res();
422
+ img.onerror = () => rej(new Error("unreadable image"));
423
+ img.src = url;
424
+ });
425
+ if (!img.width || !img.height) return null;
426
+ const side = Math.min(128, Math.max(img.width, img.height));
427
+ const canvas = document.createElement("canvas");
428
+ canvas.width = side;
429
+ canvas.height = side;
430
+ const ctx = canvas.getContext("2d");
431
+ if (!ctx) return null;
432
+ const s = Math.min(img.width, img.height);
433
+ ctx.drawImage(img, (img.width - s) / 2, (img.height - s) / 2, s, s, 0, 0, side, side);
434
+ return canvas.toDataURL("image/jpeg", 0.85);
435
+ } catch {
436
+ return null;
437
+ } finally {
438
+ URL.revokeObjectURL(url);
439
+ }
440
+ }
441
+
442
+ /** Inline-styled on purpose: the `.set-*`/`.shell-*` stylesheet is another wave-14 session's
443
+ * file (index.css), so the preview carries its own three declarations. */
444
+ function AvatarPreview({ user, size }: { user: SessionUser; size: number }) {
445
+ if (user.avatar) {
446
+ return (
447
+ <img
448
+ src={user.avatar}
449
+ alt=""
450
+ aria-hidden="true"
451
+ style={{
452
+ width: size,
453
+ height: size,
454
+ borderRadius: "50%",
455
+ objectFit: "cover",
456
+ display: "block",
457
+ flex: "none",
458
+ }}
459
+ />
460
+ );
461
+ }
462
+ const initial = (user.name.match(/[\p{L}\p{N}]/u)?.[0] ?? "?").toUpperCase();
463
+ return (
464
+ <span
465
+ aria-hidden="true"
466
+ style={{
467
+ width: size,
468
+ height: size,
469
+ borderRadius: "50%",
470
+ background: "var(--lp-blue-tint)",
471
+ color: "var(--lp-blue-deep)",
472
+ display: "inline-flex",
473
+ alignItems: "center",
474
+ justifyContent: "center",
475
+ fontWeight: 600,
476
+ fontSize: Math.round(size * 0.42),
477
+ flex: "none",
478
+ }}
479
+ >
480
+ {initial}
481
+ </span>
482
+ );
483
+ }
484
+
485
+ function ProfilePhotoBlock({
486
+ user,
487
+ onUser,
488
+ }: {
489
+ user: SessionUser;
490
+ onUser?: (u: SessionUser) => void;
491
+ }) {
492
+ const [busy, setBusy] = useState(false);
493
+ const [error, setError] = useState("");
494
+ const fileRef = useRef<HTMLInputElement>(null);
495
+
496
+ const upload = useCallback(
497
+ async (file: File) => {
498
+ setBusy(true);
499
+ setError("");
500
+ const dataUrl = await fileToAvatarDataUrl(file);
501
+ if (!dataUrl) {
502
+ setBusy(false);
503
+ setError("That file could not be read as an image.");
504
+ return;
505
+ }
506
+ const r = await setAvatar(dataUrl);
507
+ setBusy(false);
508
+ if (r.ok) {
509
+ const fresh = parseUserEnvelope(r.data);
510
+ if (fresh) onUser?.(fresh);
511
+ } else {
512
+ setError(r.message);
513
+ }
514
+ },
515
+ [onUser]
516
+ );
517
+
518
+ const remove = useCallback(async () => {
519
+ setBusy(true);
520
+ setError("");
521
+ const r = await clearAvatar();
522
+ setBusy(false);
523
+ if (r.ok) {
524
+ const fresh = parseUserEnvelope(r.data);
525
+ if (fresh) onUser?.(fresh);
526
+ } else {
527
+ setError(r.message);
528
+ }
529
+ }, [onUser]);
530
+
531
+ return (
532
+ <>
533
+ <h4 className="set-h4">Profile photo</h4>
534
+ <p className="set-help">
535
+ Shown on Assignee fields and your account chip. Square images look best; large ones
536
+ are scaled down automatically.
537
+ </p>
538
+ {error ? <p className="set-error">{error}</p> : null}
539
+ <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
540
+ <AvatarPreview user={user} size={56} />
541
+ <input
542
+ ref={fileRef}
543
+ type="file"
544
+ accept="image/png,image/jpeg"
545
+ style={{ display: "none" }}
546
+ onChange={(e) => {
547
+ const f = e.target.files?.[0];
548
+ e.target.value = "";
549
+ if (f) void upload(f);
550
+ }}
551
+ />
552
+ <button
553
+ type="button"
554
+ className="set-primary"
555
+ disabled={busy}
556
+ onClick={() => fileRef.current?.click()}
557
+ >
558
+ {user.avatar ? "Change photo" : "Upload photo"}
559
+ </button>
560
+ {user.avatar ? (
561
+ <button type="button" className="set-secondary" disabled={busy} onClick={remove}>
562
+ Remove
563
+ </button>
564
+ ) : null}
565
+ </div>
566
+ </>
567
+ );
568
+ }
569
+
570
  // ------------------------------------------------------------------ the modal
571
 
572
  export function SettingsModal({
 
574
  section,
575
  onSection,
576
  onClose,
577
+ onUser,
578
  }: {
579
  user: SessionUser;
580
  section: SettingsSection;
581
  onSection: (s: SettingsSection) => void;
582
  onClose: () => void;
583
+ /** Wave 14 C-AVATAR β€” the shell's session setter, so a photo change updates the account
584
+ * chip live instead of on the next full reload. Optional: absent, the photo still saves. */
585
+ onUser?: (u: SessionUser) => void;
586
  }) {
587
  const [settings, setSettings] = useState<SettingsPayload | null>(null);
588
  const admin = isAdmin(user);
 
655
  <span className="pg-drill-key">Role</span>
656
  <span className="pg-drill-val">{admin ? "Admin" : "Member"}</span>
657
  </div>
658
+ <ProfilePhotoBlock user={user} onUser={onUser} />
659
  </div>
660
  ) : null}
661
 
web/src/settings/settingsApi.ts CHANGED
@@ -122,3 +122,16 @@ export function setPassword(username: string, password: string): Promise<ApiResu
122
  body: JSON.stringify({ password }),
123
  });
124
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  body: JSON.stringify({ password }),
123
  });
124
  }
125
+
126
+ /** Wave 14 C-AVATAR β€” own-profile photo. The server returns the refreshed `{user}` envelope;
127
+ * the caller parses it with `session.parseUserEnvelope` so the shell chip updates live. */
128
+ export function setAvatar(dataUrl: string): Promise<ApiResult<{ user: unknown }>> {
129
+ return call<{ user: unknown }>("/auth/me/avatar", {
130
+ method: "POST",
131
+ body: JSON.stringify({ dataUrl }),
132
+ });
133
+ }
134
+
135
+ export function clearAvatar(): Promise<ApiResult<{ user: unknown }>> {
136
+ return call<{ user: unknown }>("/auth/me/avatar", { method: "DELETE" });
137
+ }
web/src/shell/NavExtras.tsx CHANGED
@@ -26,18 +26,6 @@ function DotsIcon() {
26
  );
27
  }
28
 
29
- function ChevronIcon({ open }: { open: boolean }) {
30
- return (
31
- <svg
32
- viewBox="0 0 16 16"
33
- aria-hidden="true"
34
- className={"shell-folder-chev" + (open ? " is-open" : "")}
35
- >
36
- <path d="M5.5 3.5 10.5 8l-5 4.5" fill="none" strokeWidth="1.6" />
37
- </svg>
38
- );
39
- }
40
-
41
  function FolderIcon() {
42
  return (
43
  <svg viewBox="0 0 16 16" aria-hidden="true" className="shell-nav-icon">
@@ -97,32 +85,18 @@ function MenuShell({
97
 
98
  export function RowMenu({
99
  entryLabel,
100
- folders,
101
- placedIn,
102
  canSchema,
103
- onMove,
104
- onCreateFolder,
105
  onSchema,
106
  }: {
107
  entryLabel: string;
108
- folders: NavFolder[];
109
- placedIn?: string;
110
  canSchema: boolean;
111
- onMove: (folderId: string | null) => void;
112
- onCreateFolder: (name: string) => void;
113
  onSchema: () => void;
114
  }) {
 
 
 
115
  const { at, ref, openFrom, close } = useMenu();
116
- const [naming, setNaming] = useState(false);
117
- const [name, setName] = useState("");
118
- const submitNew = () => {
119
- const clean = name.trim().replace(/\s+/g, " ");
120
- if (!clean) return;
121
- onCreateFolder(clean);
122
- setName("");
123
- setNaming(false);
124
- close();
125
- };
126
  return (
127
  <>
128
  <button
@@ -133,7 +107,6 @@ export function RowMenu({
133
  onClick={(e) => {
134
  e.preventDefault();
135
  e.stopPropagation();
136
- setNaming(false);
137
  openFrom(e.currentTarget);
138
  }}
139
  >
@@ -141,82 +114,74 @@ export function RowMenu({
141
  </button>
142
  {at && (
143
  <MenuShell at={at} menuRef={ref}>
144
- {canSchema && (
145
- <button
146
- type="button"
147
- className="shell-navmenu-item"
148
- onClick={() => {
149
- close();
150
- onSchema();
151
- }}
152
- >
153
- View schema
154
- </button>
155
- )}
156
- <div className="shell-navmenu-kicker">Move to folder</div>
157
- {folders.map((f) => (
158
- <button
159
- key={f.id}
160
- type="button"
161
- className={
162
- "shell-navmenu-item" + (placedIn === f.id ? " is-current" : "")
163
- }
164
- onClick={() => {
165
- close();
166
- if (placedIn !== f.id) onMove(f.id);
167
- }}
168
- >
169
- {f.name}
170
- {placedIn === f.id ? <span className="shell-navmenu-tick">Current</span> : null}
171
- </button>
172
- ))}
173
- {placedIn && (
174
- <button
175
- type="button"
176
- className="shell-navmenu-item"
177
- onClick={() => {
178
- close();
179
- onMove(null);
180
- }}
181
- >
182
- Remove from folder
183
- </button>
184
- )}
185
- {naming ? (
186
- <form
187
- className="shell-navmenu-form"
188
- onSubmit={(e) => {
189
- e.preventDefault();
190
- submitNew();
191
- }}
192
- >
193
- <input
194
- className="shell-navmenu-input"
195
- autoFocus
196
- maxLength={40}
197
- placeholder="Folder name"
198
- value={name}
199
- onChange={(e) => setName(e.target.value)}
200
- />
201
- <button type="submit" className="shell-navmenu-go" disabled={!name.trim()}>
202
- Add
203
- </button>
204
- </form>
205
- ) : (
206
- <button
207
- type="button"
208
- className="shell-navmenu-item is-new"
209
- onClick={() => setNaming(true)}
210
- >
211
- New folder…
212
- </button>
213
- )}
214
  </MenuShell>
215
  )}
216
  </>
217
  );
218
  }
219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
  export function FolderHead({
221
  folder,
222
  count,
@@ -225,6 +190,8 @@ export function FolderHead({
225
  onToggle,
226
  onRename,
227
  onDelete,
 
 
228
  }: {
229
  folder: NavFolder;
230
  count: number;
@@ -233,6 +200,10 @@ export function FolderHead({
233
  onToggle: () => void;
234
  onRename: (name: string) => void;
235
  onDelete: () => void;
 
 
 
 
236
  }) {
237
  const { at, ref, openFrom, close } = useMenu();
238
  const [renaming, setRenaming] = useState(false);
@@ -249,14 +220,18 @@ export function FolderHead({
249
  return null;
250
  }
251
  return (
252
- <div className="shell-nav-folder">
 
 
 
 
 
253
  <button
254
  type="button"
255
  className="shell-nav-folderbtn"
256
  aria-expanded={open}
257
  onClick={onToggle}
258
  >
259
- <ChevronIcon open={open} />
260
  <FolderIcon />
261
  <span className="shell-nav-label">{folder.name}</span>
262
  <span className="shell-nav-foldercount">{count}</span>
@@ -315,7 +290,6 @@ export function FolderHead({
315
  >
316
  Delete folder
317
  </button>
318
- <div className="shell-navmenu-note">Databases inside fall back to the list.</div>
319
  </MenuShell>
320
  )}
321
  </div>
 
26
  );
27
  }
28
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  function FolderIcon() {
30
  return (
31
  <svg viewBox="0 0 16 16" aria-hidden="true" className="shell-nav-icon">
 
85
 
86
  export function RowMenu({
87
  entryLabel,
 
 
88
  canSchema,
 
 
89
  onSchema,
90
  }: {
91
  entryLabel: string;
 
 
92
  canSchema: boolean;
 
 
93
  onSchema: () => void;
94
  }) {
95
+ // Wave 14 C-NAVFOLD (ruling R10): the three-dots keeps "View schema" ONLY. Folder
96
+ // placement is a DRAG now (the Views-rail gesture, items 4/6), folder ops live on the
97
+ // folder rows, and "New folder" is the quiet + at the list's bottom.
98
  const { at, ref, openFrom, close } = useMenu();
99
+ if (!canSchema) return null;
 
 
 
 
 
 
 
 
 
100
  return (
101
  <>
102
  <button
 
107
  onClick={(e) => {
108
  e.preventDefault();
109
  e.stopPropagation();
 
110
  openFrom(e.currentTarget);
111
  }}
112
  >
 
114
  </button>
115
  {at && (
116
  <MenuShell at={at} menuRef={ref}>
117
+ <button
118
+ type="button"
119
+ className="shell-navmenu-item"
120
+ onClick={() => {
121
+ close();
122
+ onSchema();
123
+ }}
124
+ >
125
+ View schema
126
+ </button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  </MenuShell>
128
  )}
129
  </>
130
  );
131
  }
132
 
133
+ /** Wave 14 C-NAVFOLD β€” the quiet "+ New folder" affordance at the list's bottom (the
134
+ * Views-rail precedent), replacing the RowMenu's creator. */
135
+ export function NewFolderRow({ onCreate }: { onCreate: (name: string) => void }) {
136
+ const [naming, setNaming] = useState(false);
137
+ const [name, setName] = useState("");
138
+ const submit = () => {
139
+ const clean = name.trim().replace(/\s+/g, " ");
140
+ if (!clean) return;
141
+ onCreate(clean);
142
+ setName("");
143
+ setNaming(false);
144
+ };
145
+ if (!naming) {
146
+ return (
147
+ <button
148
+ type="button"
149
+ className="shell-newfolder"
150
+ onClick={() => setNaming(true)}
151
+ >
152
+ + New folder
153
+ </button>
154
+ );
155
+ }
156
+ return (
157
+ <form
158
+ className="shell-navmenu-form shell-newfolder-form"
159
+ onSubmit={(e) => {
160
+ e.preventDefault();
161
+ submit();
162
+ }}
163
+ >
164
+ <input
165
+ className="shell-navmenu-input"
166
+ autoFocus
167
+ maxLength={40}
168
+ placeholder="Folder name"
169
+ value={name}
170
+ onChange={(e) => setName(e.target.value)}
171
+ onKeyDown={(e) => {
172
+ if (e.key === "Escape") {
173
+ setName("");
174
+ setNaming(false);
175
+ }
176
+ }}
177
+ />
178
+ <button type="submit" className="shell-navmenu-go" disabled={!name.trim()}>
179
+ Add
180
+ </button>
181
+ </form>
182
+ );
183
+ }
184
+
185
  export function FolderHead({
186
  folder,
187
  count,
 
190
  onToggle,
191
  onRename,
192
  onDelete,
193
+ isDrop,
194
+ dropProps,
195
  }: {
196
  folder: NavFolder;
197
  count: number;
 
200
  onToggle: () => void;
201
  onRename: (name: string) => void;
202
  onDelete: () => void;
203
+ /** Wave 14 C-NAVFOLD β€” a database row is being dragged over this folder. */
204
+ isDrop?: boolean;
205
+ /** dragover/drop handlers, owned by the Shell (it holds the placement writer). */
206
+ dropProps?: React.HTMLAttributes<HTMLDivElement>;
207
  }) {
208
  const { at, ref, openFrom, close } = useMenu();
209
  const [renaming, setRenaming] = useState(false);
 
220
  return null;
221
  }
222
  return (
223
+ <div
224
+ className={"shell-nav-folder" + (isDrop ? " is-drop" : "")}
225
+ {...(dropProps ?? {})}
226
+ >
227
+ {/* R3: no chevron β€” the Views-rail folder look. Open state reads from the members
228
+ below it (and aria-expanded says it aloud); the mark + bold label ARE the row. */}
229
  <button
230
  type="button"
231
  className="shell-nav-folderbtn"
232
  aria-expanded={open}
233
  onClick={onToggle}
234
  >
 
235
  <FolderIcon />
236
  <span className="shell-nav-label">{folder.name}</span>
237
  <span className="shell-nav-foldercount">{count}</span>
 
290
  >
291
  Delete folder
292
  </button>
 
293
  </MenuShell>
294
  )}
295
  </div>
web/src/shell/Shell.tsx CHANGED
@@ -43,7 +43,7 @@ import { Brand } from "./Brand";
43
  import LoginPage from "./LoginPage";
44
  import { EMPTY_NAV_PREFS, ENVELOPE_KEYS, MAX_NAV_FOLDERS, appLink, defaultRoute, fetchNav, fetchNavPrefs, foldNav, resolveRoute, saveNavPrefs, shapeNav, splitChrome } from "./nav";
45
  import type { NavEntry, NavPage, NavPrefs } from "./nav";
46
- import { FolderHead, RowMenu, SchemaDrawer } from "./NavExtras";
47
  import { isAdmin, logout, me } from "./session";
48
  import type { SessionUser } from "./session";
49
 
@@ -56,6 +56,10 @@ const APP_BASE =
56
 
57
  /** X5's hash route. Also the route an unauthenticated shell is pinned to. */
58
  const LOGIN_ROUTE = "login";
 
 
 
 
59
 
60
  /** A stable identity for "no nav yet" β€” see its use below. */
61
  const NO_ENTRIES: NavEntry[] = [];
@@ -273,7 +277,20 @@ function AccountMenu({
273
  aria-expanded={open}
274
  onClick={() => setOpen((v) => !v)}
275
  >
276
- <span className="shell-avatar" aria-hidden="true">{initial}</span>
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  <span className="shell-account-who">
278
  <span className="shell-account-name">{user.name}</span>
279
  <span className="shell-account-role">{isAdmin(user) ? "Admin" : "Member"}</span>
@@ -452,21 +469,6 @@ export default function Shell() {
452
  },
453
  [commitPrefs]
454
  );
455
- const createFolderFor = useCallback(
456
- (key: string, name: string) => {
457
- const cur = navPrefsRef.current;
458
- if (cur.folders.length >= MAX_NAV_FOLDERS) {
459
- setToast(`At most ${MAX_NAV_FOLDERS} folders.`);
460
- return;
461
- }
462
- const id = `nf_${Date.now().toString(36)}${Math.floor(Math.random() * 1e6).toString(36)}`;
463
- commitPrefs({
464
- folders: [...cur.folders, { id, name }],
465
- placement: { ...cur.placement, [key]: id },
466
- });
467
- },
468
- [commitPrefs]
469
- );
470
  const renameFolder = useCallback(
471
  (id: string, name: string) => {
472
  const cur = navPrefsRef.current;
@@ -497,6 +499,23 @@ export default function Shell() {
497
  return next;
498
  });
499
  }, []);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
500
 
501
  // Keep the URL honest in both directions: an anonymous shell sits on
502
  // `#/login`, and a signed-in one never does.
@@ -597,7 +616,29 @@ export default function Shell() {
597
  </a>
598
  ) : null}
599
 
600
- <div className="shell-nav-list">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
601
  {/* C-SCHEMA: the list folds under the user's folders. The collapsed
602
  rail renders FLAT (folder chrome has no room at 44px) β€” members
603
  stay reachable, the folders wait for the rail to open. */}
@@ -614,6 +655,25 @@ export default function Shell() {
614
  onToggle={() => toggleFolder(row.folder.id)}
615
  onRename={(name) => renameFolder(row.folder.id, name)}
616
  onDelete={() => deleteFolder(row.folder.id)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
617
  />
618
  );
619
  }
@@ -629,9 +689,8 @@ export default function Shell() {
629
  {/* A hand-off opens the current application in a new tab; the
630
  arrow declares that before the click finds out. */}
631
  {item.kind === "handoff" ? <ExtIcon /> : null}
632
- {/* The provenance badge, right-aligned and quiet β€” wave-9 I8's
633
- "light grey subtle label 'Odoo'", same as the host nav. */}
634
- {item.source ? <span className="shell-nav-badge">{item.source}</span> : null}
635
  </>
636
  );
637
  if (item.kind === "group") {
@@ -672,17 +731,27 @@ export default function Shell() {
672
  return (
673
  <div
674
  key={item.key}
675
- className={"shell-nav-row" + (row.folderId ? " is-foldered" : "")}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
676
  >
677
  {link}
678
  {!navCollapsed && item.depth === 0 && (
679
  <RowMenu
680
  entryLabel={item.label}
681
- folders={navPrefs.folders}
682
- placedIn={navPrefs.placement[item.key]}
683
  canSchema
684
- onMove={(fid) => movePage(item.key, fid)}
685
- onCreateFolder={(name) => createFolderFor(item.key, name)}
686
  onSchema={() => setSchemaFor(item.key)}
687
  />
688
  )}
@@ -690,6 +759,10 @@ export default function Shell() {
690
  );
691
  }
692
  )}
 
 
 
 
693
  </div>
694
  {nav.phase === "loading" ? <div className="shell-nav-note">Loading…</div> : null}
695
  {/* Honest, and it names the fix. Inventing a nav here would show
@@ -794,6 +867,7 @@ export default function Shell() {
794
  section={settings}
795
  onSection={setSettings}
796
  onClose={() => setSettings(null)}
 
797
  />
798
  ) : null}
799
 
 
43
  import LoginPage from "./LoginPage";
44
  import { EMPTY_NAV_PREFS, ENVELOPE_KEYS, MAX_NAV_FOLDERS, appLink, defaultRoute, fetchNav, fetchNavPrefs, foldNav, resolveRoute, saveNavPrefs, shapeNav, splitChrome } from "./nav";
45
  import type { NavEntry, NavPage, NavPrefs } from "./nav";
46
+ import { FolderHead, NewFolderRow, RowMenu, SchemaDrawer } from "./NavExtras";
47
  import { isAdmin, logout, me } from "./session";
48
  import type { SessionUser } from "./session";
49
 
 
56
 
57
  /** X5's hash route. Also the route an unauthenticated shell is pinned to. */
58
  const LOGIN_ROUTE = "login";
59
+ /** Wave 14 C-NAVFOLD β€” the nav drag's PRIVATE dataTransfer MIME. Private so a drop on any
60
+ * text-editable surface types nothing (a textarea is a native drop target for text/plain β€”
61
+ * the wave-13 C-LAYOUT scar). */
62
+ const NAV_DRAG_TYPE = "application/x-loopable-nav";
63
 
64
  /** A stable identity for "no nav yet" β€” see its use below. */
65
  const NO_ENTRIES: NavEntry[] = [];
 
277
  aria-expanded={open}
278
  onClick={() => setOpen((v) => !v)}
279
  >
280
+ {user.avatar ? (
281
+ // Wave 14 C-AVATAR β€” the chip wears the photo. Inline-styled: `.shell-avatar`'s
282
+ // stylesheet is another wave-14 session's file (index.css), so the img carries
283
+ // its own fit rules and inherits the span's box from the class.
284
+ <img
285
+ className="shell-avatar"
286
+ src={user.avatar}
287
+ alt=""
288
+ aria-hidden="true"
289
+ style={{ objectFit: "cover", padding: 0 }}
290
+ />
291
+ ) : (
292
+ <span className="shell-avatar" aria-hidden="true">{initial}</span>
293
+ )}
294
  <span className="shell-account-who">
295
  <span className="shell-account-name">{user.name}</span>
296
  <span className="shell-account-role">{isAdmin(user) ? "Admin" : "Member"}</span>
 
469
  },
470
  [commitPrefs]
471
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
472
  const renameFolder = useCallback(
473
  (id: string, name: string) => {
474
  const cur = navPrefsRef.current;
 
499
  return next;
500
  });
501
  }, []);
502
+ // ── Wave 14 C-NAVFOLD (items 4/6): drag replaces the menu's Move-to-folder. A PRIVATE
503
+ // dataTransfer MIME so a drop anywhere text-editable types nothing (the wave-13 C-LAYOUT
504
+ // scar); `dropTarget` is a folder id or "__root__" (drag out = drop on the list itself).
505
+ const [dragKey, setDragKey] = useState<string | null>(null);
506
+ const [dropTarget, setDropTarget] = useState<string | null>(null);
507
+ const createFolder = useCallback(
508
+ (name: string) => {
509
+ const cur = navPrefsRef.current;
510
+ if (cur.folders.length >= MAX_NAV_FOLDERS) {
511
+ setToast(`At most ${MAX_NAV_FOLDERS} folders.`);
512
+ return;
513
+ }
514
+ const id = `nf_${Date.now().toString(36)}${Math.floor(Math.random() * 1e6).toString(36)}`;
515
+ commitPrefs({ folders: [...cur.folders, { id, name }], placement: cur.placement });
516
+ },
517
+ [commitPrefs]
518
+ );
519
 
520
  // Keep the URL honest in both directions: an anonymous shell sits on
521
  // `#/login`, and a signed-in one never does.
 
616
  </a>
617
  ) : null}
618
 
619
+ <div
620
+ className={
621
+ "shell-nav-list" + (dropTarget === "__root__" ? " is-drop-root" : "")
622
+ }
623
+ onDragOver={(e) => {
624
+ if (!e.dataTransfer.types.includes(NAV_DRAG_TYPE)) return;
625
+ e.preventDefault();
626
+ e.dataTransfer.dropEffect = "move";
627
+ setDropTarget("__root__");
628
+ }}
629
+ onDragLeave={(e) => {
630
+ if (e.currentTarget.contains(e.relatedTarget as Node)) return;
631
+ setDropTarget(null);
632
+ }}
633
+ onDrop={(e) => {
634
+ const key = e.dataTransfer.getData(NAV_DRAG_TYPE);
635
+ setDropTarget(null);
636
+ setDragKey(null);
637
+ if (!key) return;
638
+ e.preventDefault();
639
+ movePage(key, null);
640
+ }}
641
+ >
642
  {/* C-SCHEMA: the list folds under the user's folders. The collapsed
643
  rail renders FLAT (folder chrome has no room at 44px) β€” members
644
  stay reachable, the folders wait for the rail to open. */}
 
655
  onToggle={() => toggleFolder(row.folder.id)}
656
  onRename={(name) => renameFolder(row.folder.id, name)}
657
  onDelete={() => deleteFolder(row.folder.id)}
658
+ isDrop={dropTarget === row.folder.id}
659
+ dropProps={{
660
+ onDragOver: (e) => {
661
+ if (!e.dataTransfer.types.includes(NAV_DRAG_TYPE)) return;
662
+ e.preventDefault();
663
+ e.stopPropagation();
664
+ e.dataTransfer.dropEffect = "move";
665
+ setDropTarget(row.folder.id);
666
+ },
667
+ onDrop: (e) => {
668
+ const key = e.dataTransfer.getData(NAV_DRAG_TYPE);
669
+ setDropTarget(null);
670
+ setDragKey(null);
671
+ if (!key) return;
672
+ e.preventDefault();
673
+ e.stopPropagation();
674
+ movePage(key, row.folder.id);
675
+ },
676
+ }}
677
  />
678
  );
679
  }
 
689
  {/* A hand-off opens the current application in a new tab; the
690
  arrow declares that before the click finds out. */}
691
  {item.kind === "handoff" ? <ExtIcon /> : null}
692
+ {/* Wave 14 item 6: the "Odoo" provenance badge is GONE β€” the schema
693
+ drawer still names the source for whoever asks. */}
 
694
  </>
695
  );
696
  if (item.kind === "group") {
 
731
  return (
732
  <div
733
  key={item.key}
734
+ className={
735
+ "shell-nav-row" +
736
+ (row.folderId ? " is-foldered" : "") +
737
+ (dragKey === item.key ? " is-dragging" : "")
738
+ }
739
+ draggable={!navCollapsed && item.depth === 0}
740
+ onDragStart={(e) => {
741
+ e.dataTransfer.setData(NAV_DRAG_TYPE, item.key);
742
+ e.dataTransfer.effectAllowed = "move";
743
+ setDragKey(item.key);
744
+ }}
745
+ onDragEnd={() => {
746
+ setDragKey(null);
747
+ setDropTarget(null);
748
+ }}
749
  >
750
  {link}
751
  {!navCollapsed && item.depth === 0 && (
752
  <RowMenu
753
  entryLabel={item.label}
 
 
754
  canSchema
 
 
755
  onSchema={() => setSchemaFor(item.key)}
756
  />
757
  )}
 
759
  );
760
  }
761
  )}
762
+ {/* Wave 14 C-NAVFOLD β€” the folder creator moved here from the row menu (R10). */}
763
+ {!navCollapsed && nav.phase === "ready" && entries.length > 0 ? (
764
+ <NewFolderRow onCreate={createFolder} />
765
+ ) : null}
766
  </div>
767
  {nav.phase === "loading" ? <div className="shell-nav-note">Loading…</div> : null}
768
  {/* Honest, and it names the fix. Inventing a nav here would show
 
867
  section={settings}
868
  onSection={setSettings}
869
  onClose={() => setSettings(null)}
870
+ onUser={(u) => setSession({ phase: "authed", user: u })}
871
  />
872
  ) : null}
873
 
web/src/shell/navExtras.css CHANGED
@@ -73,6 +73,8 @@
73
  color: var(--lp-ink);
74
  font: inherit;
75
  font-size: var(--lp-fs-xs);
 
 
76
  cursor: pointer;
77
  text-align: left;
78
  }
@@ -81,22 +83,55 @@
81
  background: var(--lp-wash);
82
  }
83
 
84
- .shell-folder-chev {
85
- width: 11px;
86
- height: 11px;
87
- flex: 0 0 auto;
88
- stroke: var(--lp-muted);
89
- transition: transform 0.14s ease;
 
90
  }
91
 
92
- .shell-folder-chev.is-open {
93
- transform: rotate(90deg);
 
 
94
  }
95
 
96
- .shell-nav-foldercount {
97
- margin-left: auto;
98
- font-size: var(--lp-fs-3xs);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  color: var(--lp-muted);
 
 
 
 
 
 
 
 
 
 
 
 
100
  }
101
 
102
  /* ── the fixed popover menu ───────────────────────────────────────────────── */
@@ -127,6 +162,8 @@
127
  color: var(--lp-ink);
128
  cursor: pointer;
129
  text-align: left;
 
 
130
  }
131
 
132
  .shell-navmenu-item:hover {
 
73
  color: var(--lp-ink);
74
  font: inherit;
75
  font-size: var(--lp-fs-xs);
76
+ /* Wave 14 R3 β€” the Views-rail folder look: BOLD label, no chevron. */
77
+ font-weight: 600;
78
  cursor: pointer;
79
  text-align: left;
80
  }
 
83
  background: var(--lp-wash);
84
  }
85
 
86
+ .shell-nav-foldercount {
87
+ margin-left: auto;
88
+ /* Wave 14 item 7 β€” the count wears the LABEL's size, muted; nothing "all over the
89
+ place with regards to symmetry". */
90
+ font-size: var(--lp-fs-xs);
91
+ font-weight: 400;
92
+ color: var(--lp-muted);
93
  }
94
 
95
+ /* ── wave 14 C-NAVFOLD: drag placement (items 4/6) ───────────────────────── */
96
+
97
+ .shell-nav-row.is-dragging {
98
+ opacity: 0.45;
99
  }
100
 
101
+ .shell-nav-folder.is-drop {
102
+ background: var(--lp-blue-tint);
103
+ border-radius: 7px;
104
+ box-shadow: inset 0 0 0 1px var(--lp-blue-deep);
105
+ }
106
+
107
+ .shell-nav-list.is-drop-root {
108
+ border-radius: 9px;
109
+ box-shadow: inset 0 0 0 1px var(--lp-line);
110
+ }
111
+
112
+ .shell-newfolder {
113
+ display: block;
114
+ width: 100%;
115
+ border: 0;
116
+ background: transparent;
117
+ padding: 6px 8px;
118
+ margin-top: 2px;
119
+ border-radius: 7px;
120
+ font: inherit;
121
+ font-size: var(--lp-fs-2xs);
122
  color: var(--lp-muted);
123
+ text-align: left;
124
+ cursor: pointer;
125
+ white-space: nowrap;
126
+ }
127
+
128
+ .shell-newfolder:hover {
129
+ background: var(--lp-wash);
130
+ color: var(--lp-ink);
131
+ }
132
+
133
+ .shell-newfolder-form {
134
+ padding: 4px 2px 2px;
135
  }
136
 
137
  /* ── the fixed popover menu ───────────────────────────────────────────────── */
 
162
  color: var(--lp-ink);
163
  cursor: pointer;
164
  text-align: left;
165
+ /* Wave 14 R7 β€” every menu action occupies ONE line, app-wide. */
166
+ white-space: nowrap;
167
  }
168
 
169
  .shell-navmenu-item:hover {
web/src/shell/session.ts CHANGED
@@ -45,6 +45,9 @@ export interface SessionUser {
45
  bus: string[];
46
  /** Granted registry keys, or the literal `'all'` β€” `core/users`' own encoding. */
47
  modules: string[] | "all";
 
 
 
48
  }
49
 
50
  export function isAdmin(user: SessionUser | null): boolean {
@@ -75,7 +78,11 @@ export function parseUser(raw: unknown): SessionUser | null {
75
  : Array.isArray(r.modules)
76
  ? r.modules.filter((m): m is string => typeof m === "string")
77
  : [];
78
- return { username, name, role, bus, modules };
 
 
 
 
79
  }
80
 
81
  /** The `{user: {...}}` envelope both `/auth/login` and `/auth/me` return. */
 
45
  bus: string[];
46
  /** Granted registry keys, or the literal `'all'` β€” `core/users`' own encoding. */
47
  modules: string[] | "all";
48
+ /** Wave 14 C-AVATAR β€” the user's OWN profile photo as a data URL, or absent. Everyone
49
+ * else's photos ride `workspace.userAvatars`, keyed by display name. */
50
+ avatar?: string | null;
51
  }
52
 
53
  export function isAdmin(user: SessionUser | null): boolean {
 
78
  : Array.isArray(r.modules)
79
  ? r.modules.filter((m): m is string => typeof m === "string")
80
  : [];
81
+ // Defensive like the display fields: only a data: image URL is carried; anything
82
+ // else renders the initials disc rather than a broken <img>.
83
+ const avatar =
84
+ typeof r.avatar === "string" && r.avatar.startsWith("data:image/") ? r.avatar : null;
85
+ return { username, name, role, bus, modules, avatar };
86
  }
87
 
88
  /** The `{user: {...}}` envelope both `/auth/login` and `/auth/me` return. */
web/src/viz/DashboardView.css CHANGED
@@ -40,8 +40,46 @@
40
  font-size: var(--lp-fs-3xs);
41
  }
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  @media (max-width: 820px) {
44
  .cg-ch-card {
45
  grid-column: span 12 !important;
46
  }
 
 
 
 
 
 
 
47
  }
 
40
  font-size: var(--lp-fs-3xs);
41
  }
42
 
43
+ /* ==========================================================================
44
+ Wave 14 items 18 + R7 β€” the chart editor's label column.
45
+ ==========================================================================
46
+ The base rule pins every editor label to `flex: 0 0 54px` (index.css:3917),
47
+ which was sized for "Measure" / "Of" / "By". Item 18 replaces those with
48
+ words a non-analyst can act on β€” "Which number", "Grouped by", "Break down
49
+ by", "How far back", "Bottom axis label" β€” and every one of them WRAPS to two
50
+ lines in 54px, which is exactly the failure R7 is a sweep for: a wrapped
51
+ label breaks the row rhythm the whole pane is read by.
52
+
53
+ Overridden from HERE rather than at the base rule because `index.css` is
54
+ another session's fence this wave. `.cg-ch-cfgbody .cg-ch-row > span` is
55
+ (0,2,1) against the base's (0,1,1), so this wins on SPECIFICITY and never on
56
+ bundle order β€” a tie decided by import sequence is not a thing to bet a
57
+ layout on ([[loopable-nav-logo-toggle]]).
58
+
59
+ `nowrap` is the assertion, not the width: if a future label outgrows this
60
+ column it will overflow visibly instead of quietly reflowing, which is the
61
+ failure mode you can see. */
62
+ .cg-ch-cfgbody .cg-ch-row > span {
63
+ flex: 0 0 104px;
64
+ white-space: nowrap;
65
+ }
66
+
67
+ /* The checkbox row reads left-to-right β€” box, then sentence β€” so its label is
68
+ not a column head and must not take the column width. */
69
+ .cg-ch-cfgbody .cg-ch-check > span {
70
+ flex: 1 1 auto;
71
+ white-space: normal;
72
+ }
73
+
74
  @media (max-width: 820px) {
75
  .cg-ch-card {
76
  grid-column: span 12 !important;
77
  }
78
+
79
+ /* Below the card's own breakpoint the pane is narrow enough that a 104px
80
+ label column starves the control beside it. The labels stay unwrapped and
81
+ the row scrolls its control instead. */
82
+ .cg-ch-cfgbody .cg-ch-row > span {
83
+ flex-basis: 88px;
84
+ }
85
  }
web/src/viz/DashboardView.tsx CHANGED
@@ -7,9 +7,9 @@
7
  // the search and the cohort scope apply by construction. Change a condition and
8
  // every chart moves with the grid's count, because it IS the grid's count.
9
  //
10
- // Rendering crosses one adapter boundary into Vega-Lite. Saved views and the
11
- // arithmetic remain renderer-neutral, so the renderer can be replaced without
12
- // migrating persisted chart definitions.
13
  //
14
  // Honesty (rule 8b) is rendered, not just computed: every card states its
15
  // denominator, says when it dropped buckets past the cap and what they were
@@ -18,7 +18,7 @@
18
  // instead of rendering an empty frame that reads as "no data".
19
  // ---------------------------------------------------------------------------
20
 
21
- import { lazy, Suspense, useMemo, useState } from "react";
22
  import type { Field, Row } from "./types";
23
  import {
24
  CHART_AGGS,
@@ -28,31 +28,49 @@ import {
28
  CHART_KINDS,
29
  CHART_PALETTES,
30
  MAX_AXIS_LABEL,
31
- MAX_BUCKETS,
32
- MAX_CHARTS,
33
- chartModel,
34
- chartValueText,
35
- defaultChart,
36
- groupableForChart,
37
- measurableForChart,
38
- } from "./chartData";
39
- import type {
40
- ChartAgg,
41
- ChartAxisSide,
42
- ChartModel,
 
 
 
43
  ChartFormat,
44
  ChartKind,
45
  ChartPalette,
46
  ChartSpec,
47
- } from "./chartData";
48
- import { toVegaLiteSpec } from "./vega/toVegaLiteSpec";
49
  // ⚠ Still customer-grid's (Y3 amendment, 2026-07-30): the icon layer is ONE
50
  // system with its own gate (verify_icons.py's token-parity leg), and a second
51
  // set of chart-kind glyphs is exactly the drift that gate exists to catch.
52
- import { ChartKindIcon } from "../customer-grid/icons";
53
- import "./DashboardView.css";
54
-
55
- const VegaLiteChart = lazy(() => import("./vega/VegaLiteChart"));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
  /**
58
  * Wave-9 I11 (C2) β€” what each palette NAME means, in the user's words. The stored value is a
@@ -119,7 +137,38 @@ const AGG_LABELS: Record<ChartAgg, string> = {
119
  max: "Largest",
120
  };
121
 
122
- function niceNumber(v: number): string {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  if (!Number.isFinite(v)) return "β€”";
124
  const abs = Math.abs(v);
125
  if (abs >= 1e9) return (v / 1e9).toFixed(1) + "B";
@@ -128,7 +177,7 @@ function niceNumber(v: number): string {
128
  return Number.isInteger(v) ? v.toLocaleString() : v.toFixed(2);
129
  }
130
 
131
- /** One card: the picture, the title, the honesty footer and (when `onChange`
132
  * is wired) the edit pane. Exported since W2-5/Y3 names it a public viz export
133
  * β€” the Y1 `chart` block renders one of these per spec. Behaviour is unchanged;
134
  * only the `export` keyword is new. */
@@ -138,35 +187,54 @@ export function ChartCard({
138
  fields,
139
  yField,
140
  onChange,
141
- onRemove,
142
- }: {
143
- spec: ChartSpec;
144
- data: ChartModel;
 
145
  fields: Field[];
146
  yField?: Field;
147
  onChange: (next: ChartSpec) => void;
148
  onRemove: () => void;
 
 
 
 
 
 
 
 
 
 
149
  }) {
150
  const [editing, setEditing] = useState(false);
151
  const groupable = useMemo(() => groupableForChart(fields), [fields]);
152
  const measurable = useMemo(() => measurableForChart(fields), [fields]);
153
- const xLabel = spec.x ? fields.find((f) => f.key === spec.x)?.label : undefined;
154
- const auto =
155
- spec.agg === "count"
156
- ? `Count of records${xLabel ? ` by ${xLabel}` : ""}`
157
- : `${AGG_LABELS[spec.agg]} ${yField?.label ?? "…"}${xLabel ? ` by ${xLabel}` : ""}`;
158
- const rendererSpec = useMemo(
159
- () =>
160
- toVegaLiteSpec({
161
- spec,
162
- model: data,
163
- xTitle: spec.axis?.x?.label ?? xLabel,
164
- yTitle: spec.axis?.y?.label ?? (spec.agg === "count" ? "Records" : yField?.label),
165
- formatValue: (value) =>
166
- chartValueText(value, yField, spec.axis?.y?.format, niceNumber),
167
- }),
168
- [data, spec, xLabel, yField]
169
- );
 
 
 
 
 
 
 
 
170
 
171
  return (
172
  <div
@@ -243,8 +311,11 @@ export function ChartCard({
243
  ))}
244
  </div>
245
  </div>
 
 
 
246
  <label className="cg-ch-row">
247
- <span>Measure</span>
248
  <select
249
  className="cg-select"
250
  value={spec.agg}
@@ -259,11 +330,23 @@ export function ChartCard({
259
  </label>
260
  {spec.agg !== "count" && (
261
  <label className="cg-ch-row">
262
- <span>Of</span>
263
  <select
264
  className="cg-select"
265
  value={spec.y ?? ""}
266
- onChange={(e) => onChange({ ...spec, y: e.target.value || undefined })}
 
 
 
 
 
 
 
 
 
 
 
 
267
  >
268
  <option value="">Choose a number…</option>
269
  {measurable.map((f) => (
@@ -274,9 +357,62 @@ export function ChartCard({
274
  </select>
275
  </label>
276
  )}
277
- {spec.kind !== "kpi" && (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
278
  <label className="cg-ch-row">
279
- <span>By</span>
280
  <select
281
  className="cg-select"
282
  value={spec.x ?? ""}
@@ -303,9 +439,9 @@ export function ChartCard({
303
  </label>
304
 
305
  {/* ── I11 (C2): colour and stacking β€” the two the owner named, first. ────────── */}
306
- {spec.kind !== "kpi" && spec.kind !== "donut" && (
307
  <label className="cg-ch-row">
308
- <span>Split by</span>
309
  <select
310
  className="cg-select"
311
  value={spec.splitBy ?? ""}
@@ -322,7 +458,7 @@ export function ChartCard({
322
  >
323
  {/* An explicit empty option, never a bare first one β€” a <select> missing its
324
  value renders the FIRST option and silently claims a choice. */}
325
- <option value="">One series</option>
326
  {groupable
327
  .filter((f) => f.key !== spec.x)
328
  .map((f) => (
@@ -340,11 +476,11 @@ export function ChartCard({
340
  checked={spec.stacked === true}
341
  onChange={(e) => onChange({ ...spec, stacked: e.target.checked || undefined })}
342
  />
343
- <span>Stack the series</span>
344
  </label>
345
  )}
346
  <label className="cg-ch-row">
347
- <span>Colour</span>
348
  <select
349
  className="cg-select"
350
  value={spec.palette ?? ""}
@@ -365,7 +501,7 @@ export function ChartCard({
365
  {spec.kind !== "kpi" && (
366
  <>
367
  <label className="cg-ch-row">
368
- <span>X axis</span>
369
  <input
370
  className="cg-input"
371
  value={spec.axis?.x?.label ?? ""}
@@ -375,7 +511,7 @@ export function ChartCard({
375
  />
376
  </label>
377
  <label className="cg-ch-row">
378
- <span>Y axis</span>
379
  <input
380
  className="cg-input"
381
  value={spec.axis?.y?.label ?? ""}
@@ -387,7 +523,7 @@ export function ChartCard({
387
  </>
388
  )}
389
  <label className="cg-ch-row">
390
- <span>Numbers</span>
391
  <select
392
  className="cg-select"
393
  value={spec.axis?.y?.format ?? "auto"}
@@ -405,42 +541,42 @@ export function ChartCard({
405
  </div>
406
  )}
407
 
408
- {data.problem ? (
409
- <div className="cg-ch-empty">{data.problem}</div>
410
- ) : data.points.length === 0 ? (
411
- <div className="cg-ch-empty">No records match this view, so there is nothing to chart.</div>
412
- ) : (
413
- <div className={`cg-ch-viz cg-ch-viz--${spec.kind}`}>
414
- <Suspense fallback={<div className="cg-ch-loading">Loading chart…</div>}>
415
- <VegaLiteChart spec={rendererSpec} label={spec.title || auto} />
416
- </Suspense>
417
- </div>
418
- )}
419
 
420
  {/* The card's footnotes β€” every one of them is a disclosure, not decoration. */}
421
  <div className="cg-ch-foot">
422
  <span>{data.rows.toLocaleString()} records</span>
423
- {data.omitted > 0 && (
424
- <span title={`The ${data.omitted.toLocaleString()} smallest groups are not drawn. Together they account for ${niceNumber(data.omittedValue)}.`}>
425
- Β· top {MAX_BUCKETS} of {(data.xOrder.length + data.omitted).toLocaleString()} groups
426
- shown (+{niceNumber(data.omittedValue)} not drawn)
427
- </span>
428
- )}
429
- {data.omittedSeries > 0 && (
430
- <span
431
- title={`${data.omittedSeries.toLocaleString()} smaller series are not drawn. Together they account for ${niceNumber(data.omittedSeriesValue)}.`}
432
- >
433
- Β· {data.omittedSeries.toLocaleString()} series not drawn
434
- </span>
435
- )}
436
- {data.nonPositive > 0 && (
437
- <span
438
- title={`Donut slices require positive values. These groups have a combined value of ${niceNumber(data.nonPositiveValue)} and are not included in the circle.`}
439
- >
440
- Β· {data.nonPositive.toLocaleString()} zero/negative group
441
- {data.nonPositive === 1 ? "" : "s"} not drawn
442
- </span>
443
- )}
444
  {data.blanks > 0 && <span>Β· {data.blanks.toLocaleString()} with no value grouped as blank</span>}
445
  {data.missingY > 0 && (
446
  <span title="These records carry no number for the measured field, so they are counted in the group but excluded from the aggregate.">
@@ -523,6 +659,7 @@ export function DashboardView({
523
  fieldByKey,
524
  charts,
525
  onCharts,
 
526
  }: {
527
  /** DISTINCT data rows from the full pipeline β€” the same set the grid counts. */
528
  rows: Row[];
@@ -530,12 +667,112 @@ export function DashboardView({
530
  fieldByKey: Map<string, Field>;
531
  charts: ChartSpec[];
532
  onCharts: (next: ChartSpec[]) => void;
 
 
 
 
 
 
 
 
 
 
 
533
  }) {
534
- const datas = useMemo(
535
- () => charts.map((c) => chartModel(c, rows, fieldByKey)),
536
  [charts, rows, fieldByKey]
537
  );
538
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
539
  return (
540
  <div className="cg-dashview">
541
  <div className="cg-dash-bar">
@@ -552,10 +789,10 @@ export function DashboardView({
552
  ? `A view holds at most ${MAX_CHARTS} charts.`
553
  : undefined
554
  }
555
- onClick={() => {
556
- const id = `ch_${Math.random().toString(36).slice(2, 10)}`;
557
- onCharts([...charts, defaultChart(id, fields)]);
558
- }}
559
  >
560
  + Add chart
561
  </button>
@@ -571,9 +808,10 @@ export function DashboardView({
571
  <ChartCard
572
  key={c.id}
573
  spec={c}
574
- data={datas[i]}
575
  fields={fields}
576
  yField={c.y ? fieldByKey.get(c.y) : undefined}
 
577
  onChange={(next) => onCharts(charts.map((o) => (o.id === c.id ? next : o)))}
578
  onRemove={() => onCharts(charts.filter((o) => o.id !== c.id))}
579
  />
 
7
  // the search and the cohort scope apply by construction. Change a condition and
8
  // every chart moves with the grid's count, because it IS the grid's count.
9
  //
10
+ // Rendering crosses one adapter boundary into Vega-Lite. Saved views and the
11
+ // arithmetic remain renderer-neutral, so the renderer can be replaced without
12
+ // migrating persisted chart definitions.
13
  //
14
  // Honesty (rule 8b) is rendered, not just computed: every card states its
15
  // denominator, says when it dropped buckets past the cap and what they were
 
18
  // instead of rendering an empty frame that reads as "no data".
19
  // ---------------------------------------------------------------------------
20
 
21
+ import { lazy, Suspense, useEffect, useMemo, useRef, useState } from "react";
22
  import type { Field, Row } from "./types";
23
  import {
24
  CHART_AGGS,
 
28
  CHART_KINDS,
29
  CHART_PALETTES,
30
  MAX_AXIS_LABEL,
31
+ MAX_BUCKETS,
32
+ MAX_CHARTS,
33
+ chartModel,
34
+ PERIOD_KINDS,
35
+ chartValueText,
36
+ defaultChart,
37
+ groupableForChart,
38
+ isMetricKey,
39
+ isPeriodChart,
40
+ measurableForChart,
41
+ } from "./chartData";
42
+ import type {
43
+ ChartAgg,
44
+ ChartAxisSide,
45
+ ChartModel,
46
  ChartFormat,
47
  ChartKind,
48
  ChartPalette,
49
  ChartSpec,
50
+ } from "./chartData";
51
+ import { toVegaLiteSpec } from "./vega/toVegaLiteSpec";
52
  // ⚠ Still customer-grid's (Y3 amendment, 2026-07-30): the icon layer is ONE
53
  // system with its own gate (verify_icons.py's token-parity leg), and a second
54
  // set of chart-kind glyphs is exactly the drift that gate exists to catch.
55
+ import { ChartKindIcon } from "../customer-grid/icons";
56
+ // R3 β€” the trend path. The SAME channel the time-series view uses, deliberately: two
57
+ // implementations of "sales by month" that could disagree is the thing worth avoiding here,
58
+ // not the shared import. `TS_BUCKETS` is a value (a vocabulary), not a layering violation β€”
59
+ // viz already imports the grid's icon layer for the identical "one system, one gate" reason.
60
+ import { fetchTimeseries } from "../customer-grid/apiBridge";
61
+ import type { SurfaceScope } from "../customer-grid/apiBridge";
62
+ import {
63
+ DEFAULT_TS_LAST_N,
64
+ buildTsRequest,
65
+ buildTsTable,
66
+ tsRowToChartModel,
67
+ } from "../customer-grid/timeSeriesData";
68
+ import type { TsPayload } from "../customer-grid/timeSeriesData";
69
+ import { TS_BUCKETS } from "../customer-grid/types";
70
+ import type { TsBucket } from "../customer-grid/types";
71
+ import "./DashboardView.css";
72
+
73
+ const VegaLiteChart = lazy(() => import("./vega/VegaLiteChart"));
74
 
75
  /**
76
  * Wave-9 I11 (C2) β€” what each palette NAME means, in the user's words. The stored value is a
 
137
  max: "Largest",
138
  };
139
 
140
+ /**
141
+ * ── R3 (item 18): a chart card may be a TREND over time buckets ────────────────────────────
142
+ *
143
+ * Not a new chart kind β€” the same bar/line/area, drawn over PERIODS instead of over a
144
+ * category. A chart whose number is a metric gains a Period control; setting one routes its
145
+ * series through the time-series channel (`fetchTimeseries`) rather than through
146
+ * `chartData`'s grouping, and clearing it puts the card back exactly where it was.
147
+ *
148
+ * ⚠ The 12-bucket cap in `chartData` stays CATEGORY law and is never applied here. That cap is
149
+ * right for "the top 12 groups" and catastrophic for periods, where dropping buckets means
150
+ * dropping MONTHS while the axis still reads like a complete run.
151
+ *
152
+ * Offered on bar / line / area only, and that is a judgment worth stating: a donut of months
153
+ * is a part-of-whole claim about time that nobody makes, and a single-number card has no axis
154
+ * to put periods on. The host narrows the same key from the other side β€” it keeps `bucket`
155
+ * only when the chart's `y` is measure-backed (C-ACC).
156
+ */
157
+ const PERIOD_LABELS: Record<TsBucket, string> = {
158
+ week: "Weekly",
159
+ month: "Monthly",
160
+ quarter: "Quarterly",
161
+ year: "Yearly",
162
+ };
163
+
164
+ const PERIOD_SPANS = [6, 12, 24, 36];
165
+
166
+ /** Charts sharing a period AND a span share ONE request; the endpoint takes many fields. */
167
+ function periodGroupKey(spec: ChartSpec): string {
168
+ return `${spec.bucket}|${spec.span?.lastN ?? DEFAULT_TS_LAST_N}`;
169
+ }
170
+
171
+ function niceNumber(v: number): string {
172
  if (!Number.isFinite(v)) return "β€”";
173
  const abs = Math.abs(v);
174
  if (abs >= 1e9) return (v / 1e9).toFixed(1) + "B";
 
177
  return Number.isInteger(v) ? v.toLocaleString() : v.toFixed(2);
178
  }
179
 
180
+ /** One card: the picture, the title, the honesty footer and (when `onChange`
181
  * is wired) the edit pane. Exported since W2-5/Y3 names it a public viz export
182
  * β€” the Y1 `chart` block renders one of these per spec. Behaviour is unchanged;
183
  * only the `export` keyword is new. */
 
187
  fields,
188
  yField,
189
  onChange,
190
+ onRemove,
191
+ canPeriod,
192
+ }: {
193
+ spec: ChartSpec;
194
+ data: ChartModel;
195
  fields: Field[];
196
  yField?: Field;
197
  onChange: (next: ChartSpec) => void;
198
  onRemove: () => void;
199
+ /**
200
+ * R3 β€” may this card offer a PERIOD? False (the default) hides the control entirely.
201
+ *
202
+ * Absent means the trend channel is not wired where this card is mounted β€” no surface scope,
203
+ * so no fetch. Offering the control anyway would let a user set a period and then read an
204
+ * error message about the host, which is a dead end they were walked into. Hidden rather
205
+ * than disabled: a dead control invites the click that does nothing, and the wave-13
206
+ * Insights precedent this follows hid the whole tab for exactly this reason.
207
+ */
208
+ canPeriod?: boolean;
209
  }) {
210
  const [editing, setEditing] = useState(false);
211
  const groupable = useMemo(() => groupableForChart(fields), [fields]);
212
  const measurable = useMemo(() => measurableForChart(fields), [fields]);
213
+ // R3 β€” a trend's x axis is TIME, so the "by <field>" clause is replaced by the period. A
214
+ // card titled "Sum of Sales" that is actually monthly reads as a single total.
215
+ const period = isPeriodChart(spec) ? PERIOD_LABELS[spec.bucket as TsBucket] : undefined;
216
+ const xLabel = period
217
+ ? "Period"
218
+ : spec.x
219
+ ? fields.find((f) => f.key === spec.x)?.label
220
+ : undefined;
221
+ const by = period ? `, ${period.toLowerCase()}` : xLabel ? ` by ${xLabel}` : "";
222
+ const auto =
223
+ spec.agg === "count"
224
+ ? `Count of records${by}`
225
+ : `${AGG_LABELS[spec.agg]} ${yField?.label ?? "…"}${by}`;
226
+ const rendererSpec = useMemo(
227
+ () =>
228
+ toVegaLiteSpec({
229
+ spec,
230
+ model: data,
231
+ xTitle: spec.axis?.x?.label ?? xLabel,
232
+ yTitle: spec.axis?.y?.label ?? (spec.agg === "count" ? "Records" : yField?.label),
233
+ formatValue: (value) =>
234
+ chartValueText(value, yField, spec.axis?.y?.format, niceNumber),
235
+ }),
236
+ [data, spec, xLabel, yField]
237
+ );
238
 
239
  return (
240
  <div
 
311
  ))}
312
  </div>
313
  </div>
314
+ {/* Item 18's wording sweep β€” "Measure" was the internal word for the mechanism
315
+ (wave-13 C-NAME: the wire says measure, the screen says Metric), and this row
316
+ does not pick one: it picks what to DO with the numbers. */}
317
  <label className="cg-ch-row">
318
+ <span>Show</span>
319
  <select
320
  className="cg-select"
321
  value={spec.agg}
 
330
  </label>
331
  {spec.agg !== "count" && (
332
  <label className="cg-ch-row">
333
+ <span>Which number</span>
334
  <select
335
  className="cg-select"
336
  value={spec.y ?? ""}
337
+ onChange={(e) =>
338
+ onChange({
339
+ ...spec,
340
+ y: e.target.value || undefined,
341
+ // R3 β€” a period belongs to a METRIC. Moving the card onto an ordinary
342
+ // number must take the period with it, or the spec keeps a key the host
343
+ // drops and the control reads set for a chart that cannot use it (the
344
+ // `stacked`-beside-`splitBy` precedent two rows down).
345
+ ...(isMetricKey(e.target.value)
346
+ ? {}
347
+ : { bucket: undefined, span: undefined }),
348
+ })
349
+ }
350
  >
351
  <option value="">Choose a number…</option>
352
  {measurable.map((f) => (
 
357
  </select>
358
  </label>
359
  )}
360
+
361
+ {/* ── R3 (item 18): the period controls. Present on every card whose number is a
362
+ metric; absent everywhere else, where they would promise a time axis the
363
+ field does not have. */}
364
+ {canPeriod && isMetricKey(spec.y) && PERIOD_KINDS.includes(spec.kind) && (
365
+ <>
366
+ <label className="cg-ch-row">
367
+ <span>Over time</span>
368
+ <select
369
+ className="cg-select"
370
+ value={spec.bucket ?? ""}
371
+ onChange={(e) =>
372
+ onChange({
373
+ ...spec,
374
+ bucket: e.target.value || undefined,
375
+ span: e.target.value ? spec.span : undefined,
376
+ })
377
+ }
378
+ >
379
+ {/* An explicit empty option, never a bare first one β€” a <select> missing
380
+ its value renders the FIRST option and silently claims a choice. */}
381
+ <option value="">No β€” group by a field</option>
382
+ {TS_BUCKETS.map((b) => (
383
+ <option key={b} value={b}>
384
+ {PERIOD_LABELS[b]}
385
+ </option>
386
+ ))}
387
+ </select>
388
+ </label>
389
+ {!!spec.bucket && (
390
+ <label className="cg-ch-row">
391
+ <span>How far back</span>
392
+ <select
393
+ className="cg-select"
394
+ value={String(spec.span?.lastN ?? DEFAULT_TS_LAST_N)}
395
+ onChange={(e) =>
396
+ onChange({ ...spec, span: { lastN: Number(e.target.value) } })
397
+ }
398
+ >
399
+ {PERIOD_SPANS.map((n) => (
400
+ <option key={n} value={n}>
401
+ Last {n}
402
+ </option>
403
+ ))}
404
+ </select>
405
+ </label>
406
+ )}
407
+ </>
408
+ )}
409
+
410
+ {/* A trend's x axis IS time, so the grouping picker would be a second, contradictory
411
+ answer to the same question. Hidden rather than disabled: a dead control invites
412
+ the click that does nothing. */}
413
+ {spec.kind !== "kpi" && !(canPeriod && spec.bucket) && (
414
  <label className="cg-ch-row">
415
+ <span>Grouped by</span>
416
  <select
417
  className="cg-select"
418
  value={spec.x ?? ""}
 
439
  </label>
440
 
441
  {/* ── I11 (C2): colour and stacking β€” the two the owner named, first. ────────── */}
442
+ {spec.kind !== "kpi" && spec.kind !== "donut" && !(canPeriod && spec.bucket) && (
443
  <label className="cg-ch-row">
444
+ <span>Break down by</span>
445
  <select
446
  className="cg-select"
447
  value={spec.splitBy ?? ""}
 
458
  >
459
  {/* An explicit empty option, never a bare first one β€” a <select> missing its
460
  value renders the FIRST option and silently claims a choice. */}
461
+ <option value="">Don't break it down</option>
462
  {groupable
463
  .filter((f) => f.key !== spec.x)
464
  .map((f) => (
 
476
  checked={spec.stacked === true}
477
  onChange={(e) => onChange({ ...spec, stacked: e.target.checked || undefined })}
478
  />
479
+ <span>Stack them on top of each other</span>
480
  </label>
481
  )}
482
  <label className="cg-ch-row">
483
+ <span>Colours</span>
484
  <select
485
  className="cg-select"
486
  value={spec.palette ?? ""}
 
501
  {spec.kind !== "kpi" && (
502
  <>
503
  <label className="cg-ch-row">
504
+ <span>Bottom axis label</span>
505
  <input
506
  className="cg-input"
507
  value={spec.axis?.x?.label ?? ""}
 
511
  />
512
  </label>
513
  <label className="cg-ch-row">
514
+ <span>Side axis label</span>
515
  <input
516
  className="cg-input"
517
  value={spec.axis?.y?.label ?? ""}
 
523
  </>
524
  )}
525
  <label className="cg-ch-row">
526
+ <span>Number format</span>
527
  <select
528
  className="cg-select"
529
  value={spec.axis?.y?.format ?? "auto"}
 
541
  </div>
542
  )}
543
 
544
+ {data.problem ? (
545
+ <div className="cg-ch-empty">{data.problem}</div>
546
+ ) : data.points.length === 0 ? (
547
+ <div className="cg-ch-empty">No records match this view, so there is nothing to chart.</div>
548
+ ) : (
549
+ <div className={`cg-ch-viz cg-ch-viz--${spec.kind}`}>
550
+ <Suspense fallback={<div className="cg-ch-loading">Loading chart…</div>}>
551
+ <VegaLiteChart spec={rendererSpec} label={spec.title || auto} />
552
+ </Suspense>
553
+ </div>
554
+ )}
555
 
556
  {/* The card's footnotes β€” every one of them is a disclosure, not decoration. */}
557
  <div className="cg-ch-foot">
558
  <span>{data.rows.toLocaleString()} records</span>
559
+ {data.omitted > 0 && (
560
+ <span title={`The ${data.omitted.toLocaleString()} smallest groups are not drawn. Together they account for ${niceNumber(data.omittedValue)}.`}>
561
+ Β· top {MAX_BUCKETS} of {(data.xOrder.length + data.omitted).toLocaleString()} groups
562
+ shown (+{niceNumber(data.omittedValue)} not drawn)
563
+ </span>
564
+ )}
565
+ {data.omittedSeries > 0 && (
566
+ <span
567
+ title={`${data.omittedSeries.toLocaleString()} smaller series are not drawn. Together they account for ${niceNumber(data.omittedSeriesValue)}.`}
568
+ >
569
+ Β· {data.omittedSeries.toLocaleString()} series not drawn
570
+ </span>
571
+ )}
572
+ {data.nonPositive > 0 && (
573
+ <span
574
+ title={`Donut slices require positive values. These groups have a combined value of ${niceNumber(data.nonPositiveValue)} and are not included in the circle.`}
575
+ >
576
+ Β· {data.nonPositive.toLocaleString()} zero/negative group
577
+ {data.nonPositive === 1 ? "" : "s"} not drawn
578
+ </span>
579
+ )}
580
  {data.blanks > 0 && <span>Β· {data.blanks.toLocaleString()} with no value grouped as blank</span>}
581
  {data.missingY > 0 && (
582
  <span title="These records carry no number for the measured field, so they are counted in the group but excluded from the aggregate.">
 
659
  fieldByKey,
660
  charts,
661
  onCharts,
662
+ scope,
663
  }: {
664
  /** DISTINCT data rows from the full pipeline β€” the same set the grid counts. */
665
  rows: Row[];
 
667
  fieldByKey: Map<string, Field>;
668
  charts: ChartSpec[];
669
  onCharts: (next: ChartSpec[]) => void;
670
+ /**
671
+ * Wave-14 R3 β€” which surface these rows came from, for the trend channel's fetch.
672
+ *
673
+ * ⚠ ABSENT DISABLES THE PERIOD CONTROLS, and there is no default. Asking the customer
674
+ * endpoint about a cohort's pids succeeds β€” a cohort's customers are usually in the
675
+ * reader's customer book too β€” and returns customer-scope numbers under a cohort-scope
676
+ * card: no 403, no marker, a plausible wrong answer. That is the wave-13 Insights scar
677
+ * exactly, and the answer is the same one: render nothing rather than answer a question
678
+ * nobody asked.
679
+ */
680
+ scope?: SurfaceScope;
681
  }) {
682
+ const datas = useMemo(
683
+ () => charts.map((c) => chartModel(c, rows, fieldByKey)),
684
  [charts, rows, fieldByKey]
685
  );
686
 
687
+ // ── R3: the trend channel. Charts sharing a period AND a span share ONE request, because
688
+ // the endpoint takes many fields and runs one grouped query per field regardless β€” twelve
689
+ // monthly cards on a board should cost one round trip, not twelve.
690
+ const pids = useMemo(() => rows.map((r) => Number(r.pid)).filter(Number.isFinite), [rows]);
691
+ const periodSpecs = useMemo(() => charts.filter(isPeriodChart), [charts]);
692
+ const groups = useMemo(() => {
693
+ const map = new Map<string, { bucket: TsBucket; lastN: number; fields: string[] }>();
694
+ for (const spec of periodSpecs) {
695
+ const key = periodGroupKey(spec);
696
+ const entry = map.get(key) ?? {
697
+ bucket: spec.bucket as TsBucket,
698
+ lastN: spec.span?.lastN ?? DEFAULT_TS_LAST_N,
699
+ fields: [],
700
+ };
701
+ if (spec.y && !entry.fields.includes(spec.y)) entry.fields.push(spec.y);
702
+ map.set(key, entry);
703
+ }
704
+ return map;
705
+ }, [periodSpecs]);
706
+ // The dependency is the GROUP SHAPE, not the array identity β€” a card resized or retitled
707
+ // must not re-issue every trend request on the board.
708
+ const groupSig = useMemo(
709
+ () =>
710
+ JSON.stringify(
711
+ [...groups.entries()].map(([k, g]) => [k, [...g.fields].sort()])
712
+ ),
713
+ [groups]
714
+ );
715
+ const [series, setSeries] = useState<Record<string, TsPayload | null>>({});
716
+ const [pending, setPending] = useState(false);
717
+ const reqRef = useRef(0);
718
+
719
+ useEffect(() => {
720
+ if (!scope || !groups.size || !pids.length) {
721
+ setSeries({});
722
+ setPending(false);
723
+ return;
724
+ }
725
+ const seq = ++reqRef.current;
726
+ setPending(true);
727
+ Promise.all(
728
+ [...groups.entries()].map(([key, g]) =>
729
+ fetchTimeseries(
730
+ buildTsRequest({ pids, bucket: g.bucket, span: { lastN: g.lastN }, fields: g.fields }),
731
+ scope
732
+ ).then(({ payload }) => [key, payload] as const)
733
+ )
734
+ ).then((pairs) => {
735
+ // The board the user is waiting on is the LAST one they asked for, not the last set of
736
+ // responses to arrive.
737
+ if (seq !== reqRef.current) return;
738
+ setSeries(Object.fromEntries(pairs));
739
+ setPending(false);
740
+ });
741
+ }, [scope, groupSig, pids, groups]);
742
+
743
+ /** The model for one card: the trend payload when it asked for one, else the category one. */
744
+ const modelFor = (spec: ChartSpec, fallback: ChartModel): ChartModel => {
745
+ if (!isPeriodChart(spec)) return fallback;
746
+ if (!scope)
747
+ return {
748
+ ...fallback,
749
+ points: [],
750
+ problem:
751
+ "This chart is a trend over periods, but the host has not said which surface this view is, so it cannot be loaded.",
752
+ };
753
+ const payload = series[periodGroupKey(spec)];
754
+ if (!payload)
755
+ return {
756
+ ...fallback,
757
+ points: [],
758
+ problem: pending
759
+ ? "Loading the periods…"
760
+ : "The periods could not be loaded, so nothing is drawn rather than a guess.",
761
+ };
762
+ const table = buildTsTable(payload);
763
+ const row = table.rows.find((r) => r.field === spec.y);
764
+ if (!row)
765
+ return {
766
+ ...fallback,
767
+ points: [],
768
+ problem:
769
+ "The server returned no series for this metric β€” a composite metric has no single aggregate to bucket.",
770
+ };
771
+ // ⚠ `tsRowToChartModel`, never `buildChartData`: the 12-bucket cap is category law, and
772
+ // applying it here would silently delete PERIODS off a run that still looks complete.
773
+ return tsRowToChartModel(row, table.columns);
774
+ };
775
+
776
  return (
777
  <div className="cg-dashview">
778
  <div className="cg-dash-bar">
 
789
  ? `A view holds at most ${MAX_CHARTS} charts.`
790
  : undefined
791
  }
792
+ onClick={() => {
793
+ const id = `ch_${Math.random().toString(36).slice(2, 10)}`;
794
+ onCharts([...charts, defaultChart(id, fields)]);
795
+ }}
796
  >
797
  + Add chart
798
  </button>
 
808
  <ChartCard
809
  key={c.id}
810
  spec={c}
811
+ data={modelFor(c, datas[i])}
812
  fields={fields}
813
  yField={c.y ? fieldByKey.get(c.y) : undefined}
814
+ canPeriod={!!scope}
815
  onChange={(next) => onCharts(charts.map((o) => (o.id === c.id ? next : o)))}
816
  onRemove={() => onCharts(charts.filter((o) => o.id !== c.id))}
817
  />
web/src/viz/chartData.ts CHANGED
@@ -37,7 +37,12 @@ import type { Field, Row } from "./types";
37
  // definition; `viz/types.ts` pins the vocabulary in lock-step so a drift is a
38
  // red build rather than a silently mis-typed axis.
39
  import { formatDisplay } from "../customer-grid/display";
40
- import { isDateFamilyType, isNumericFieldType } from "../customer-grid/types";
 
 
 
 
 
41
 
42
  export const CHART_KINDS = ["bar", "line", "area", "donut", "kpi"] as const;
43
  export type ChartKind = (typeof CHART_KINDS)[number];
@@ -93,6 +98,23 @@ export interface ChartSpec {
93
  axis?: { x?: ChartAxisSide; y?: ChartAxisSide };
94
  /** I10 β€” the drag. `{w}` in grid columns, `{h}` in px. Clamped at both ends. */
95
  size?: { w?: number; h?: number };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  }
97
 
98
  /** C2: at most 12 charts per view. */
@@ -100,6 +122,38 @@ export const MAX_CHARTS = 12;
100
  /** Buckets drawn per chart before the card states what it left out. */
101
  export const MAX_BUCKETS = 12;
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  export interface Bucket {
104
  key: string;
105
  label: string;
@@ -634,6 +688,31 @@ export function cleanCharts(raw: unknown): ChartSpec[] | undefined {
634
  one.h = clampRange(Math.round(sz.h), CHART_H_RANGE);
635
  if (one.w !== undefined || one.h !== undefined) spec.size = one;
636
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
637
  out.push(spec);
638
  if (out.length >= MAX_CHARTS) break;
639
  }
 
37
  // definition; `viz/types.ts` pins the vocabulary in lock-step so a drift is a
38
  // red build rather than a silently mis-typed axis.
39
  import { formatDisplay } from "../customer-grid/display";
40
+ import {
41
+ TS_BUCKETS,
42
+ TS_MAX_LAST_N,
43
+ isDateFamilyType,
44
+ isNumericFieldType,
45
+ } from "../customer-grid/types";
46
 
47
  export const CHART_KINDS = ["bar", "line", "area", "donut", "kpi"] as const;
48
  export type ChartKind = (typeof CHART_KINDS)[number];
 
98
  axis?: { x?: ChartAxisSide; y?: ChartAxisSide };
99
  /** I10 β€” the drag. `{w}` in grid columns, `{h}` in px. Clamped at both ends. */
100
  size?: { w?: number; h?: number };
101
+ /**
102
+ * Wave-14 R3 (item 18) β€” this card is a TREND over time buckets, not a category chart.
103
+ *
104
+ * Present β‡’ the series comes from the time-series channel (one `date_trunc` query per
105
+ * metric, the metric's own window slid across bucket ends) instead of from `chartData`'s
106
+ * grouping of the view's rows. Absent β‡’ every path below behaves byte-identically to
107
+ * before, which is the property that makes this safe to add to a shipped renderer.
108
+ *
109
+ * Typed as a plain `string` for the same reason `agg` is: the vocabulary is `TS_BUCKETS` in
110
+ * `customer-grid/types.ts`, and that module is a deliberate LEAF β€” importing it here to
111
+ * nominally type one key would invert the dependency the whole viz layer is arranged
112
+ * around. The host validates it against the real vocabulary (C-ACC) and keeps it only when
113
+ * `y` is measure-backed.
114
+ */
115
+ bucket?: string;
116
+ /** R3 β€” how many buckets back. Meaningful only beside `bucket`; 1..120, host-clamped. */
117
+ span?: { lastN?: number };
118
  }
119
 
120
  /** C2: at most 12 charts per view. */
 
122
  /** Buckets drawn per chart before the card states what it left out. */
123
  export const MAX_BUCKETS = 12;
124
 
125
+ /**
126
+ * Wave-14 R3 β€” the chart kinds a PERIOD may be drawn over.
127
+ *
128
+ * A donut of months is a part-of-whole claim about time that nobody makes, and a
129
+ * single-number card has no axis to put periods on. Narrowing is a design call, so it is
130
+ * stated here rather than left implicit in a JSX condition.
131
+ */
132
+ export const PERIOD_KINDS: readonly ChartKind[] = ["bar", "line", "area"];
133
+
134
+ /** A metric field β€” the only kind with a time dimension of its own (C-TS v1 eligibility). */
135
+ export function isMetricKey(key: string | undefined): boolean {
136
+ return !!key && key.startsWith("measure_");
137
+ }
138
+
139
+ /**
140
+ * Does this spec ask for a TREND over time buckets?
141
+ *
142
+ * ⚠ THIS PREDICATE DECIDES WHICH CAP APPLIES, which is why it lives here beside the cap and
143
+ * not in the component. `true` routes the card's series through the time-series channel, where
144
+ * `MAX_BUCKETS` must NEVER be applied: dropping the 13th of 24 months leaves an axis that
145
+ * still reads like a complete run while two years of history quietly become one. `false` is
146
+ * the category path, unchanged, where the same cap is correct and the card discloses it.
147
+ *
148
+ * The bucket vocabulary is checked by the caller and by the host (C-ACC keeps `bucket` only
149
+ * when `y` is measure-backed); what is checked HERE is everything this module can see, so a
150
+ * spec that is half-a-trend β€” a bucket on a donut, a bucket on a plain number column β€” takes
151
+ * the category path rather than a broken one.
152
+ */
153
+ export function isPeriodChart(spec: ChartSpec): boolean {
154
+ return !!spec.bucket && isMetricKey(spec.y) && PERIOD_KINDS.includes(spec.kind);
155
+ }
156
+
157
  export interface Bucket {
158
  key: string;
159
  label: string;
 
688
  one.h = clampRange(Math.round(sz.h), CHART_H_RANGE);
689
  if (one.w !== undefined || one.h !== undefined) spec.size = one;
690
  }
691
+ // ── Wave-14 R3 (item 18): the PERIOD. ⚠ This branch is not optional decoration β€” THIS
692
+ // FUNCTION IS A REBUILDER. It constructs `{id, kind, agg}` and copies named keys, so a
693
+ // key it does not name is DROPPED on every read (`CustomerGrid.tsx:2566` runs it over the
694
+ // stored display). Without these lines the host would store the period faithfully and the
695
+ // client would throw it away one layer later β€” the control would simply look like it does
696
+ // not save, with nothing anywhere going red. Same law GRID booked from the other side of
697
+ // `cleanDisplay`: when a validator narrows a key inside a collection, every cleaner in the
698
+ // chain has to know the key exists.
699
+ //
700
+ // The rules mirror `aios_grid._clean_chart` (C-ACC) exactly: a period only means something
701
+ // on a metric, and a span only means something beside a period.
702
+ if (
703
+ typeof d.bucket === "string" &&
704
+ (TS_BUCKETS as readonly string[]).includes(d.bucket) &&
705
+ isMetricKey(spec.y)
706
+ ) {
707
+ spec.bucket = d.bucket;
708
+ if (d.span && typeof d.span === "object" && !Array.isArray(d.span)) {
709
+ const n = (d.span as Record<string, unknown>).lastN;
710
+ if (typeof n === "number" && Number.isFinite(n)) {
711
+ const lastN = Math.round(n);
712
+ if (lastN >= 1 && lastN <= TS_MAX_LAST_N) spec.span = { lastN };
713
+ }
714
+ }
715
+ }
716
  out.push(spec);
717
  if (out.length >= MAX_CHARTS) break;
718
  }