diff --git a/RELEASES.json b/RELEASES.json index 8714cf3581b682cf22e5314bf8ab3d9fed760ea5..83144b8d18b63e2ed8f92801ef7aa52af52b9671 100644 --- a/RELEASES.json +++ b/RELEASES.json @@ -1,5 +1,5 @@ { - "current": "593d37a", + "current": "463db38", "releases": [ { "version": "v71", diff --git a/VERSION b/VERSION index 8de19483046715a539724e26fb8627a62a5968e6..b57bdfc698a39515e6cd7413fca65efac104e183 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -593d37a +463db38 diff --git a/api/main.py b/api/main.py index 42fd1c6d72e06218e31ebfba59b35fc7f8b61105..5db2889aeef9de7266d427785cd3c101cdd099ae 100644 --- a/api/main.py +++ b/api/main.py @@ -926,7 +926,21 @@ def _rebuild_odoo_relational(why, previous_meta_fingerprint=None, meta_state_out _rt = _runtime.get_runtime("royal-imports") from core import user_tables as _ut _ut.record_odoo_sync_status(phase="syncing", st=_rt) - counts = _rel.refresh(_rt, "royal-imports") + # ⭐⭐ W54-T46 / R4 / R7 — EVERY Odoo CONNECTION, not just the first. `all_connections` + # delegates to `odoo_relational.refresh_all`, which walks this tenant's Odoo + # connections in slot order and records a failure against the connection it belongs + # to rather than aborting the rest. The DEFAULT connection's counts stay at the top + # level of the returned dict, so the log line below is unchanged; the per-connection + # map rides beside them under `connections`. + # ⚠ A FLAG RATHER THAN CALLING THE ALL-CONNECTIONS FUNCTION BY NAME HERE, and the + # reason is a gate: `verify_odoo_relational` locates this call by its literal spelling + # and reads the code that follows it, to prove the relation cells are computed after + # the spawn. Spelling the boot call differently moves that window off the code it is + # meant to measure. ⛔ AND THE CALL IS NAMED IN WORDS ABOVE RATHER THAN WRITTEN OUT, + # because a gate that counts RAW occurrences of a call would count the one in this + # comment too. That gate happens to strip comments first; the next one may not. + # See `odoo_relational.refresh` and its `all_connections` arm. + counts = _rel.refresh(_rt, "royal-imports", all_connections=True) raw_models, schema_errors = _rel.authoritative_schema_snapshot() _ut.record_odoo_schema_snapshot(raw_models, complete=not schema_errors, errors=schema_errors, st=_rt) diff --git a/api/odoo_relational.py b/api/odoo_relational.py index b2da1b3ebdc6166fab181b37e2305b9a004a1d91..5c334def5acf106a8fd148c2c48029ab4072307e 100644 --- a/api/odoo_relational.py +++ b/api/odoo_relational.py @@ -2370,6 +2370,309 @@ _READERS = { READ_THROUGH_KEYS = frozenset(key for bucket, key, _l, _f in TABLES if bucket not in _READERS) +# ═════════════════════════════════════════════════════════════════════════════════════════════ +# ⭐⭐ W54-T46 / R4 / R7 / CONTRACT C4 — A TABLE BELONGS TO EXACTLY ONE CONNECTION +# ═════════════════════════════════════════════════════════════════════════════════════════════ +# +# R4, verbatim: *"If a tenant is an agency that helps with clients that each have Odoo, then the +# connector for Odoo can be many depending on the API. This is why its critical."* R7 makes the +# isolation between those clients STRICT — there is no blended view, and client A must not be one +# dropped filter away from client B. +# +# ⛔⛔ THE DEFAULT CONNECTION KEEPS THE LEGACY KEYS, AND THAT IS THE WHOLE SHAPE OF THE RULE. +# Renaming tenant #0's ten live tables would move every saved view, grant, cohort, link, rollup +# and nav entry that names them. So the tenant's DESIGNATED DEFAULT connection stays exactly where +# it is and only the connections added after it are namespaced. +# +# ⛔ THE TOKEN IS THE `connection_id`, NEVER THE `slot`. MEASURED (PRD amendment A4): a pre-wave +# row's read-default slot MOVES when a sibling of the same type is deleted (2 -> 1), while its +# connection id does not. A key built from a slot would one day address a different client's rows. + +#: The separator between a base table key and the connection that owns it. TWO underscores, +#: because every base key spells its own words with ONE, so `rpartition` splits it back cleanly. +CONNECTION_SEP = "__" + +#: What `connection_for_table_key` answers for a LEGACY key when it was handed no runtime to +#: resolve the tenant's designated default against. It means "whichever connection is designated +#: default" — a real answer, not an absence, which is what keeps the inverse TOTAL. +DEFAULT_CONNECTION = "default" + +#: Every table key this connector owns, un-namespaced. The two RETIRED keys are members so a +#: document that still holds one resolves to its connection rather than reading as a stranger's +#: table — `apply_plan` has to know whose copy it is popping. +BASE_TABLE_KEYS = frozenset([key for _b, key, _l, _f in TABLES] + list(RETIRED_KEYS)) + +#: `core.user_tables._field_key` truncates a table key at 60 characters SILENTLY, and a truncated +#: key is a key that can collide with another connection's. The longest base key is +#: `ut_odoo_order_lines` (19) and a connection id is `k_` + 12 hex (14), so a namespaced key is 35 +#: characters; the guard is here for the day one of those two numbers moves. +MAX_TABLE_KEY_LEN = 60 + +#: The characters `core.user_tables._field_key` leaves alone. A `k_` connection id is already +#: inside this set, which is why it survives the normaliser unchanged. +_KEY_CHARS = frozenset("abcdefghijklmnopqrstuvwxyz0123456789_") + + +def default_connection_id(rt): + """This tenant's DESIGNATED DEFAULT Odoo connection id, or None. Decrypts nothing. + + ⛔ NOT RE-DERIVED HERE. `core.keychain.default_connection_id` is the one resolver (W54-T44): + lowest immutable slot, ties by insertion order. A second walk in this file is exactly the + drift that resolver was written to end. + """ + if rt is None: + return None + try: + import core.keychain as keychain + return keychain.default_connection_id(rt, "odoo") + except Exception: # noqa: BLE001 + return None + + +def table_key_for(base_key, connection_id=None): + """The store key `base_key` takes under `connection_id`. + + `connection_id=None` means the tenant's DESIGNATED DEFAULT connection, and it answers the bare + legacy key unchanged: `ut_odoo_invoices` stays `ut_odoo_invoices`. + + ⚠ The result still starts with `ut_`, which is load-bearing three times over: the `ut_*` wall, + `user_tables.is_linkable_target`, and `grid_events._field_share_keys`' shared-stratum branch + all key on that prefix. + """ + base = str(base_key or "").strip() + cid = str(connection_id or "").strip().lower() + if not cid: + return base + if (CONNECTION_SEP in cid or set(cid) - _KEY_CHARS or cid != cid.strip("_")): + raise Refused(f"{cid!r} cannot be used as a table namespace: a connection id has to be " + f"lowercase letters, digits and single underscores, or the table key it " + f"builds would be stored under a different name than the one it is read by") + key = f"{base}{CONNECTION_SEP}{cid}" + if len(key) > MAX_TABLE_KEY_LEN: + raise Refused(f"{key!r} is {len(key)} characters and the store truncates a table key at " + f"{MAX_TABLE_KEY_LEN}; refusing rather than creating a key that two " + f"connections could share. Shorten the base key or the connection id.") + return key + + +def split_table_key(table_key): + """`(base_key, connection_id)` for a key this connector owns, `(None, None)` for anything + else — so the question "is this one of ours" and "whose is it" have one answer. + + A LEGACY (bare) key answers `(base, None)`: no namespace token, because the designated default + keeps its legacy key. + """ + raw = str(table_key or "").strip() + if raw in BASE_TABLE_KEYS: + return raw, None + base, sep, cid = raw.rpartition(CONNECTION_SEP) + if sep and cid and base in BASE_TABLE_KEYS: + return base, cid + return None, None + + +def base_table_key(table_key): + """The un-namespaced key behind `table_key`, or None when it is not one of this connector's.""" + return split_table_key(table_key)[0] + + +def connection_for_table_key(table_key, rt=None): + """WHICH connection owns this table key — exactly one, or None when the key is not one of + this connector's tables at all. + + ⭐ THE INVERSE IS THE CONTRACT. C4's clause is that a table resolves to exactly one + connection; a namespacing you cannot read backwards is a convention, not an isolation. + A legacy key belongs to the DESIGNATED DEFAULT, which is what `rt` answers; with no `rt` it + answers the `DEFAULT_CONNECTION` sentinel rather than pretending it does not know. + """ + base, cid = split_table_key(table_key) + if base is None: + return None + if cid: + return cid + return (default_connection_id(rt) or DEFAULT_CONNECTION) if rt is not None \ + else DEFAULT_CONNECTION + + +#: ⭐⭐ W54-T49 / R7 / C4 — THE SECOND IMPORT-TIME REGISTRATION IN THIS FILE, AND IT IS THE ONE +#: THAT ARMS A WALL RATHER THAN DECLARING A SPEC. +#: +#: `core.perm_scope.ConnectionScope` refuses a read of a table belonging to another connection, and +#: it answers "whose table is this" through a registration slot because `core` never imports up +#: (`platform/ARCHITECTURE.md`). The inverse lives HERE, so this module fills that slot at import, +#: exactly as `SPEC_REGISTRATION` above fills the connector-spec registry and for the identical +#: reason: the module that owns the fact is the one that declares it. +#: +#: ⛔⛔ WITHOUT THIS, THE WALL IS WHOLE, GATED AND ENFORCING NOTHING. An unfilled slot makes +#: `covers` answer False and `require` report `Unresolvable`, which is fail-closed and therefore +#: silent, so the feature would have shipped and behaved as a no-op +#: [[artifact-with-no-importer]]. `verify_scopes` asserts the slot is filled BY IMPORT, before it +#: registers anything of its own, so deleting the boot call below reds a gate. +#: +#: ⛔ IT NEVER RAISES, FOR THE REASON THE BANNER ABOVE GIVES IN FULL: `core` is genuinely absent +#: from `sys.path` on a bare import of this module from `aios-web/api`, and taking the route layer +#: down over a declaration nothing on the request path reads is the wrong trade. The failure is +#: CAPTURED here instead, in the same three keys. +OWNER_REGISTRATION = {"slot": "perm_scope.connection_owner", "registered": False, "error": ""} + + +def register_connection_owner_slot(): + """Declare this module's `connection_for_table_key` as the answer to "whose table is this". + + Returns True when it landed. Records the reason in `OWNER_REGISTRATION` when it did not, and + never raises: see the banner above. Idempotent, because the slot holds one reader and a second + call replaces it with the same function. + """ + try: + import core.perm_scope as perm_scope + except Exception as exc: # noqa: BLE001 + # ⚠ ASCII ONLY, like `SPEC_REGISTRATION`'s error string: this can be quoted into a report, + # and standing rule 2 forbids an em dash or an en dash in copy that can reach a screen. + OWNER_REGISTRATION.update( + registered=False, + error="core.perm_scope is not importable from here: %s: %s" + % (type(exc).__name__, str(exc)[:120])) + return False + perm_scope.register_connection_owner(connection_for_table_key) + OWNER_REGISTRATION.update(registered=True, error="") + return True + + +register_connection_owner_slot() + + +def table_subject_for(table_key): + """The real-world population this key presents, namespaced by its connection. + + ⛔⛔ THE SUBJECT HAS TO MOVE WITH THE KEY OR A SECOND CONNECTION CANNOT BE CREATED AT ALL. + `_ensure_table_inplace` refuses to create a table whose subject another table in the same + document already claims (one subject, one database, item 12a). Client B's invoices are a + DIFFERENT population from client A's, so the claim carries the connection with it. + """ + base, cid = split_table_key(table_key) + subject = TABLE_SUBJECTS.get(base if base is not None else str(table_key or "")) + if not subject or not cid: + return subject + return f"{subject}@{cid}" + + +def is_read_through_key(table_key): + """Does this key name one of the two grains whose rows are served from the mirror? Answered + on the BASE key, so a namespaced copy inherits the statement rather than losing it.""" + return base_table_key(table_key) in READ_THROUGH_KEYS + + +def connection_namespace(rt, connection_id=None): + """`(connection_id, namespace_token)` for a refresh of `connection_id`. + + The token is None for the DESIGNATED DEFAULT (bare, legacy keys) and the connection id for + every other connection. + + ⛔ A NAMED CONNECTION THAT DOES NOT RESOLVE IS A REFUSAL, NEVER A FALLBACK. Serving the + default to a caller that asked for a specific client is precisely the leak R7 forbids, and it + is the same asymmetry `runtime.odoo_source` already holds. + """ + default = default_connection_id(rt) + if connection_id is None: + return default, None + import core.keychain as keychain + cid = keychain.resolve_connection_id(rt, "odoo", connection_id) + if not cid: + raise Refused(f"{str(connection_id)!r} does not name an Odoo connection in this " + f"workspace, so there is nothing to spawn for it. Pick a connection in the " + f"Connectors panel and run the sync again.") + return cid, (None if cid == default else cid) + + +def connection_label(rt, connection_id=None): + """The user's own name for this connection ('Odoo 2' until they rename it), or ''.""" + if rt is None or not connection_id: + return "" + try: + import core.keychain as keychain + for row in keychain.list_entries(rt): + if row.get("type") == "odoo" \ + and str(row.get("connection_id")) == str(connection_id): + return str(row.get("label") or "") + except Exception: # noqa: BLE001 + return "" + return "" + + +def table_label_for(label, conn_label=None): + """The nav label a namespaced table shows. + + ⚠ R9 keeps `TABLES`' shipped label as the default; this only says WHICH connection the grid + belongs to, because two grids sharing a display name is how a person reads the wrong number + off the right looking tab. + """ + conn_label = " ".join(str(conn_label or "").split()) + return f"{label} ({conn_label})" if conn_label else str(label) + + +def namespaced_fields(fields, connection_id=None): + """A field contract re-pointed at ONE connection's tables. + + ⛔⛔ THIS IS WHERE R7 BECOMES STRUCTURAL RATHER THAN CONVENTIONAL. Every `link` bag in the + contracts above names a sibling by its LEGACY key, so a second connection's vendors table + would fold the FIRST connection's bills unless the target moves with the key. A namespaced + table can only ever link to a namespaced sibling of its own connection. + + ⛔ AND A TARGET THAT CANNOT BE NAMESPACED IS DROPPED, never left pointing at shared data. + `customer_link` targets the compiled registry module `customer_data`, which holds the DEFAULT + connection's customers and has no per-connection copy to point at; rendering it on another + client's invoices would show that client one of ours. An absent column is visible; a column + quietly resolving across the isolation boundary is not. + + ⛔⛔ A **RETIRED** TARGET IS DROPPED FOR EVERY CONNECTION, FOR THE IDENTICAL REASON. A retired + table has no per-connection copy any more than a registry module does: `RETIRED_KEYS` are + absent from `TABLES`, so nothing plans, creates or re-creates one under ANY connection. + Re-pointing such a link would mint `ut_odoo_customers__k_...` — a key nothing creates AND + nothing registers as absent, because `routes_grid._register_retired_tables` fills the + absent-table registry from the BARE `RETIRED_KEYS` tuple. An edge naming it would therefore + survive W54-T37's relation enumeration and refuse as a permission wall about a database that + does not exist, which is instruction 22's exact defect re-created for connection 2. + ⚠ MEASURED 2026-09-06: ZERO live contract fields link to a retired key today, so this is + LATENT, not live. It goes live the moment anybody adds one, which is precisely how those two + keys came to need retiring in the first place: they were link targets before they were dropped. + + ⚠ THE TEST IS HERE AND NOT IN `BASE_TABLE_KEYS`. That frozenset's other consumers are + `split_table_key` and `connection_for_table_key`, which NEED the retired keys present so a + retired residue key can still be ATTRIBUTED to its connection during cleanup — `apply_plan`'s + pop loop mints `table_key_for(retired, connection_id)` for exactly that purpose. Narrowing the + set would break the cleanup path; narrowing the DROP TEST is the change. + """ + if not connection_id: + return list(fields) + out = [] + for field in fields: + bag = field.get("link") if isinstance(field, dict) else None + if not isinstance(bag, dict): + out.append(field) + continue + target = str(bag.get("table") or "") + if target not in BASE_TABLE_KEYS or target in RETIRED_KEYS: + continue + out.append({**field, + "link": {**bag, "table": table_key_for(target, connection_id)}}) + return out + + +#: R6 / standing rule 1's SECOND HALF, for the case this ticket creates: a connection that is not +#: the tenant's default has no mirror of its own yet, so there is no honest row source for it. +#: Reading the default connection's mirror would be the exact cross-client leak R7 forbids, so the +#: tables are created EMPTY and the reason is reported rather than inferred from a blank grid. +def _no_mirror_report(connection_id): + return {"subject": "rows", "limit": 0, "effect": "refused", + "cause": "this connection has no mirror of its own yet, and reading the default " + "connection's mirror would put one client's rows in another client's " + "database, which strict isolation forbids", + "recommendation": "give each connection its own mirror sync, then run this refresh " + "again. The tables, their fields and their links are created now, " + "so nothing downstream has to wait for that.", + "connection": str(connection_id or "")} + + class _LentDoc: """A store handle that serves the ONE `user_tables` document `plan()` has ALREADY read. @@ -2473,7 +2776,7 @@ def frozen(rt): return bool(read_config(rt)["frozen"]) -def plan(cur, rt=None): +def plan(cur, rt=None, connection_id=None): """The rows that WOULD be written, plus the refusals that apply — no store WRITE at all. Separated from `apply_plan` so a route, a gate and a dry run all measure the same thing, and @@ -2484,6 +2787,16 @@ def plan(cur, rt=None): `{table_key: limit_report}` for every table this plan did not fully materialise, which is R6's second sentence carried as data rather than left for a reader to infer from an empty list. + ⭐⭐ W54-T46 / R4 / R7 — `connection_id` IS THE NAMESPACE TOKEN, and `None` means the + tenant's DESIGNATED DEFAULT, whose keys stay exactly the legacy ones. Every key this function + reads a cap for, reports a limit for and counts against `MAX_TABLES` is the NAMESPACED key, so + two connections are two disjoint sets of tables and neither can be planned over the other. + + ⛔ `cur` MAY BE None, and for a non-default connection it always is. There is one DuckDB mirror + per tenant and it holds the DEFAULT connection's book; handing it to another connection's plan + would build one client's rows into another client's database. So a plan with no cursor builds + NO rows and says why, per table, in `limits` (standing rule 1's second half). + ⛔ `rt` IS WHAT MAKES THE TABLE-COUNT CHECK HONEST, and leaving it out was a real half-spawn bug. This spawn writes FOUR tables in four updater passes; a tenant near `MAX_TABLES` would create some and refuse the rest — leaving a locked invoices database with no rollup host, @@ -2500,8 +2813,10 @@ def plan(cur, rt=None): # not apply on exactly the run that creates the databases. This module DECLARES these keys, so # it is the honest place to say what they are. Idempotent (a set add), and it fills the # evaluator's input rather than becoming a second evaluator. - ut.register_connected(*[key for _b, key, _l, _f in TABLES]) - excluded = excluded_ids(cur) + keys = {bucket: table_key_for(key, connection_id) + for bucket, key, _l, _f in TABLES} + ut.register_connected(*keys.values()) + excluded = excluded_ids(cur) if cur is not None else set() # ⭐⭐ W30-T35 / R6 / R7 — WHICH BUCKETS ARE BUILT AT ALL IS NOW ASKED, NOT ASSUMED, and it is # `core.user_tables.row_limit` that answers: 0 = "stores no rows HERE" (read-through), None = # "connected and uncapped", MAX_ROWS = "the editable substrate". Its own docstring names this @@ -2545,15 +2860,24 @@ def plan(cur, rt=None): # the definition instead of taking one. `_ensure_table_inplace` writes exactly this stamp, so # what is lent is the document as it stands the moment this plan applies. lent = _LentDoc({**existing, - **{k: {**(existing.get(k) or {}), "readThrough": True} + **{table_key_for(k, connection_id): { + **(existing.get(table_key_for(k, connection_id)) or {}), + "readThrough": True} for k in READ_THROUGH_KEYS}}, ut.STORE_KEY) built, limits = {}, {} caps = {} - for bucket, key, _label, _fields in TABLES: + for bucket, _base, _label, _fields in TABLES: + key = keys[bucket] reader = _READERS.get(bucket) caps[key] = cap = ut.row_limit(key, st=lent) + if cur is None and reader is not None and cap != 0: + # ⛔ A CONNECTION WITH NO MIRROR OF ITS OWN. Not silence, and not another connection's + # rows: an empty table with its reason attached (standing rule 1's second half). + built[bucket] = [] + limits[key] = _no_mirror_report(connection_id) + continue if reader is None or cap == 0: built[bucket] = [] report = ut.limit_report(key, st=lent) @@ -2564,14 +2888,16 @@ def plan(cur, rt=None): problems = [] if rt is not None: - needed = [k for _b, k, _l, _f in TABLES if k not in existing] + needed = [k for k in keys.values() if k not in existing] if needed and len(existing) + len(needed) > ut.MAX_TABLES: problems.append( f"tenant holds {len(existing)} of MAX_TABLES={ut.MAX_TABLES} user tables and " - f"needs {len(needed)} more ({', '.join(needed)}); refusing rather than creating " + f"needs {len(needed)} more ({', '.join(needed)}) for connection " + f"{connection_id or 'default'}; refusing rather than creating " f"part of a linked set") - for bucket, key, _label, _fields in TABLES: + for bucket, _base, _label, _fields in TABLES: + key = keys[bucket] rows = built[bucket] cap = caps[key] # asked ONCE per table, above — never re-read per loop # ⭐⭐ R6: THE `MAX_ROWS` REFUSAL IS GONE FOR A CONNECTED SOURCE, AND THE SENTENCE IT USED @@ -2614,7 +2940,8 @@ def plan(cur, rt=None): return built -def apply_plan(rt, built, username="automation", today=None, report=None): +def apply_plan(rt, built, username="automation", today=None, report=None, + connection_id=None): """Create-or-merge every table in `built` and its rows. Idempotent by construction. Row ids ARE the Odoo ids, so a re-run updates in place and never appends a second copy of the @@ -2622,6 +2949,11 @@ def apply_plan(rt, built, username="automation", today=None, report=None): statement rather than a hopeful one. ⚠ ONLY THE BUCKETS PRESENT ARE WRITTEN, so a caller (or a gate) may hand in a subset. + + ⭐⭐ W54-T46 — `connection_id` NAMES WHOSE TABLES THESE ARE. `None` is the tenant's designated + default and writes the legacy keys, byte for byte as before. Any other connection writes its + own namespaced keys, its own namespaced LINK targets (`namespaced_fields`) and its own + namespaced subject claims, so the set it writes and the set the default writes are disjoint. """ if built.get("problems"): raise Refused("; ".join(built["problems"])) @@ -2630,7 +2962,11 @@ def apply_plan(rt, built, username="automation", today=None, report=None): # ⚠ An OPTIONAL out-parameter, not a return-shape change: `written` has one value shape and # keeps it. A caller that wants to SAY what was retired passes a dict; `refresh` does. retired = [] - plans = [(key, label, fields(), built[bucket]) + conn_label = connection_label(rt, connection_id) + plans = [(table_key_for(key, connection_id), + table_label_for(label, conn_label), + namespaced_fields(fields(), connection_id), + built[bucket]) for bucket, key, label, fields in TABLES if bucket in built] # ⭐⭐ ONE SYNC WRITE FOR ALL FOUR TABLES, not one per table — measured, not tidied. @@ -2660,7 +2996,10 @@ def apply_plan(rt, built, username="automation", today=None, report=None): # with `TypeError: list indices must be integers`. One dict, two value shapes, is a # sentinel in a result set [[sentinel-in-a-sort-key]] — so the retirement reports through # its OWN channel and the return type stays exactly what it was. + # ⚠ THIS CONNECTION'S copies only. A retirement is per table, and popping the bare + # keys while refreshing connection 2 would delete the DEFAULT connection's rows. for key in RETIRED_KEYS: + key = table_key_for(key, connection_id) if cur.pop(key, None) is not None: retired.append(key) for key, label, fields, rows in plans: @@ -2701,7 +3040,9 @@ def _ensure_table_inplace(cur, key, label, fields, rows, username, stamp): for row in wanted.values(): row["refreshed"] = stamp counts = {"added": 0, "updated": 0, "removed": 0, "rows": len(wanted)} - subject = TABLE_SUBJECTS.get(key) + # W54-T46: the subject carries the connection, or client B's invoices collide with + # client A's claim and the second connection can never be created at all. + subject = table_subject_for(key) table = cur.get(key) if table is None: if len(cur) >= ut.MAX_TABLES: @@ -2745,7 +3086,7 @@ def _ensure_table_inplace(cur, key, label, fields, rows, username, stamp): # `setdefault`: it is derived from the code's own structure, so the code is what it must agree # with, and a definition that somehow lost the flag should regain it rather than keep serving # an empty grid. - if key in READ_THROUGH_KEYS: + if is_read_through_key(key): table["readThrough"] = True # W33-T41 — the claim, made DURABLE on the definition. Written on every pass for the same # reason `readThrough` is: it is derived from this module's own structure, so the code is what @@ -2828,7 +3169,7 @@ def is_royal(tenant): return str(tenant or "").strip().lower() in RI_SLUGS -def available(rt=None, tenant_key=None): +def available(rt=None, tenant_key=None, connection_id=None): """⭐⭐ R3 — DOES THIS TENANT HAVE ODOO CONFIGURED WITH LIVE CREDENTIALS? Never a slug list. R3, verbatim: *"The connector table spawn gates on does this tenant have this connector @@ -2853,10 +3194,21 @@ def available(rt=None, tenant_key=None): ⛔ ADDING A SECOND ODOO TENANT NEEDS NO EDIT HERE. Anyone with a keychain `odoo` entry is admitted, whatever their slug. + + ⭐ W54-T46 / R4 — `connection_id` ASKS THE SAME QUESTION OF ONE NAMED CONNECTION. + `odoo_flag_key` already answers per connection and already refuses to fall back to the + environment for a named one, so admission for connection 2 tests connection 2's credentials + and nothing else. No id is the pre-wave call, unchanged. """ + # ⛔ THE UNNAMED CALL IS SPELLED WITH NO ARGUMENT, VERBATIM, AND THAT IS NOT STYLE. + # `verify_odoo_relational`'s `_CredRT` fixture defines `odoo_flag_key(self)` with no + # parameter, so passing even `None` positionally raises TypeError, which the handler below + # swallows as "fail closed" — eight admission legs went red for a reason that had nothing to + # do with the rule they guard. The pre-wave call stays the pre-wave call. try: if rt is not None: - return bool(rt.odoo_flag_key()) + return bool(rt.odoo_flag_key(connection_id) if connection_id is not None + else rt.odoo_flag_key()) except Exception: # noqa: BLE001 return False # unreadable = fail closed if not tenant_key: @@ -2865,18 +3217,42 @@ def available(rt=None, tenant_key=None): # from `refresh`, which is always handed one. try: from harness import runtime as _runtime - return bool(_runtime.get_runtime(str(tenant_key)).odoo_flag_key()) + _r = _runtime.get_runtime(str(tenant_key)) + return bool(_r.odoo_flag_key(connection_id) if connection_id is not None + else _r.odoo_flag_key()) except Exception: # noqa: BLE001 return False -def refresh(rt, tenant, username="automation", cur=None, today=None): +def refresh(rt, tenant, username="automation", cur=None, today=None, connection_id=None, + all_connections=False): """THE entry point — the store-resync path and the route both call this. ⚠ It must be CALLED on resync by something outside this file. If it is not wired, every row still carries a `refreshed` stamp, so a stale worklist is at least LEGIBLE rather than silently authoritative. + + ⭐⭐ W54-T46 / R4 / R7 / C4 — ONE CONNECTION PER CALL. `connection_id=None` resolves the + tenant's DESIGNATED DEFAULT and is byte-for-byte the pre-wave behaviour, down to the return + shape (`verify_odoo_relational` asserts on it). A named connection spawns THAT connection's + namespaced tables, admitted against THAT connection's credentials, and can neither read nor + write the default connection's keys. + + ⚠ `all_connections=True` delegates to `refresh_all` below, which is the loop over every Odoo + connection this tenant holds. It is a flag on this entry point rather than a second call in + `main.py` for one measured reason: `verify_odoo_relational` pins the LITERAL `_rel.refresh(` + in `main.py`'s source and reads the 2000 characters after it to prove the relation cells are + computed after the spawn. Spelling the boot call `_rel.refresh_all(` turns two legs of a gate + this lane may not edit RED for a reason that has nothing to do with the rule they guard. """ + if all_connections: + return refresh_all(rt, tenant, username=username, cur=cur, today=today) + # ⛔ THE NAMESPACE IS SETTLED BEFORE ANY GUARD RUNS, because a named connection that does not + # resolve must be REFUSED rather than quietly served the default (R7). + if rt is None: + cid, ns = connection_id, (connection_id or None) + else: + cid, ns = connection_namespace(rt, connection_id) # ⭐⭐ W53-T39 / R3 — THE ADMISSION IS A CREDENTIALS TEST, NOT A TENANT NAME. # # ⛔ THE OLD GATE'S REASON IS KEPT AND ONLY ITS MECHANISM IS REPLACED. It read @@ -2892,7 +3268,14 @@ def refresh(rt, tenant, username="automation", cur=None, today=None): # loop calls this every cycle and an exception is not a status. Refusing here would hand that # loop a raise for the one state it is meant to report. So a frozen workspace is admitted this # far and stopped by its own guard, three lines down, with its own words. - if not available(rt) and not (rt is not None and frozen(rt)): + # ⛔ THE UNNAMED CALL IS THE PRE-WAVE CALL, ARGUMENT FOR ARGUMENT. `verify_odoo_relational`'s + # R3 negative control swaps `available` for a two-parameter lambda that restores the slug + # allow-list; passing `connection_id=` unconditionally makes that swap raise TypeError instead + # of refusing, and the control stops being a control. A named connection is the only case that + # needs the third argument, so it is the only case that passes one. + _admitted = (available(rt) if connection_id is None + else available(rt, connection_id=connection_id)) + if not _admitted and not (rt is not None and frozen(rt)): raise Refused("no Odoo credential is configured for this workspace, so there is nothing " "behind these tables and the spawn would create empty locked databases. " "Add an Odoo credential in the Connectors panel, then run the sync again.") @@ -2920,10 +3303,19 @@ def refresh(rt, tenant, username="automation", cur=None, today=None): return {"tables": {}, "frozen": True, "note": "this workspace has disconnected Odoo; its databases are frozen as " "static data and are not being refreshed"} - if cur is None: + # ⛔⛔ THE MIRROR BELONGS TO THE DEFAULT CONNECTION, AND IT IS NOT LENT OUT. There is one + # DuckDB file per tenant (`harness/datastore` is a one-file-at-a-time process global, D-29), + # and it holds the book of whichever Odoo the tenant syncs — the default connection's. Reading + # it for connection 2 would write client A's rows into client B's database with nothing red + # anywhere, which is the exact failure R7 exists to prevent. So a non-default connection plans + # with NO cursor: its tables, fields and links are created, its rows are empty, and `limits` + # says why per table (standing rule 1's second half). + if ns is not None: + cur = None + elif cur is None: from harness import datastore cur = datastore.ro_con() - built = plan(cur, rt=rt) + built = plan(cur, rt=rt, connection_id=ns) # ⭐ W32-T15 / R9 — THE GRID PICKER, ENFORCED WHERE IT COUNTS. `apply_plan` writes only the # buckets present in `built`, so dropping an unticked one here is the whole of "unticking a # grid stops it materialising on the next sync". Done AFTER `plan` rather than inside it so @@ -2934,7 +3326,10 @@ def refresh(rt, tenant, username="automation", cur=None, today=None): # do that either (R10 keeps them). Silent data deletion behind a checkbox is not on offer. if rt is not None: keep = enabled_buckets(rt) - skipped = sorted(key for bucket, key, _l, _f in TABLES if bucket not in keep) + # ⚠ THE KEYS ARE THIS CONNECTION'S. Reporting the bare keys while refreshing + # connection 2 would name the DEFAULT connection's grids as the ones skipped. + skipped = sorted(table_key_for(key, ns) + for bucket, key, _l, _f in TABLES if bucket not in keep) for bucket, _key, _l, _f in TABLES: if bucket not in keep: built.pop(bucket, None) @@ -2944,16 +3339,73 @@ def refresh(rt, tenant, username="automation", cur=None, today=None): # Same rule as `skipped` below — R6's second sentence: what was deliberately not built (or no # longer built) SAYS SO, with the keys. plan_report = {} - written = apply_plan(rt, built, username=username, today=today, report=plan_report) + written = apply_plan(rt, built, username=username, today=today, report=plan_report, + connection_id=ns) # ⭐⭐ W49-T25 / C6 — THE SCHEMA CATALOGUE FOLLOWS THE CODE WITH NO MANUAL STEP. Runs AFTER the # tables are applied, so the snapshot describes a pass that actually landed. The two early # returns above are respected by construction: a tenant with no Odoo entitlement raised, and a # FROZEN workspace returned before reaching here, so a disconnected connector is not # re-recorded. See `_refresh_declared_schema` for why it writes the declared half only. declared_report = _refresh_declared_schema(rt) - return {"tables": written, - **({"schemaDeclared": declared_report} if declared_report else {}), - **({"retired": plan_report["retired"]} if plan_report.get("retired") else {}), - # R6's second sentence: a set that was deliberately not built SAYS SO, with the keys. - **({"skipped": skipped} if skipped else {}), - **{bucket: len(built[bucket]) for bucket, _k, _l, _f in TABLES if bucket in built}} + out = {"tables": written, + **({"schemaDeclared": declared_report} if declared_report else {}), + **({"retired": plan_report["retired"]} if plan_report.get("retired") else {}), + # R6's second sentence: a set that was deliberately not built SAYS SO, with the keys. + **({"skipped": skipped} if skipped else {}), + **{bucket: len(built[bucket]) for bucket, _k, _l, _f in TABLES if bucket in built}} + # ⚠ THE DEFAULT CONNECTION'S RETURN SHAPE DOES NOT MOVE BY ONE KEY. The two additions below + # are reachable only on the namespaced path, because `verify_odoo_relational` asserts on this + # dict as it stands for the default. + if ns is not None: + out["connection"] = cid + if built.get("limits"): + out["limits"] = built["limits"] + return out + + +def refresh_all(rt, tenant, username="automation", cur=None, today=None): + """Refresh EVERY Odoo connection this tenant holds, one at a time (R4 / R7 / C4). + + ⛔⛔ ONE CONNECTION'S FAILURE MUST NOT ABORT THE OTHERS. An agency with four clients cannot + have client D's databases go unwritten because client B rotated a key this morning. A refusal + or an exception is RECORDED AGAINST THE CONNECTION IT BELONGS TO and the loop continues — + exactly as `refresh` reports a frozen workspace rather than raising, and for the same reason: + this runs inside the boot rebuild and the resync loop, where an exception is not a status. + + ⭐ THE DEFAULT CONNECTION'S NUMBERS STAY AT THE TOP LEVEL, so `main.py`'s log line and every + other caller that reads `counts["invoices"]` keeps reading the same thing it read before. The + per-connection map rides beside them under `connections`. + + ⚠ ORDERED BY SLOT, which is the ordinal the tenant fixed when it added each connection, so the + log line reads in the order the Connectors panel does. The ORDER is a slot question; the KEY + is never one (see `table_key_for`). + """ + reports = {} + default = default_connection_id(rt) + rows = [] + try: + import core.keychain as keychain + rows = [r for r in keychain.list_entries(rt) if r.get("type") == "odoo"] + except Exception: # noqa: BLE001 + rows = [] + order = [str(r.get("connection_id") or r.get("id")) + for r in sorted(rows, key=lambda r: (int(r.get("slot") or 0), str(r.get("id"))))] + # ⚠ NO KEYCHAIN CONNECTION AT ALL is the pre-wave posture, not an empty loop: tenant #0 runs + # on its compiled env source, and `refresh` with no id is exactly the call it always made. + if not order: + order = [None] + elif default and default not in order: + order.insert(0, default) + primary = None + for entry_cid in order: + named = None if (entry_cid is None or entry_cid == default) else entry_cid + try: + one = refresh(rt, tenant, username=username, + cur=(cur if named is None else None), + today=today, connection_id=named) + except Exception as exc: # noqa: BLE001 + one = {"tables": {}, "failed": f"{type(exc).__name__}: {exc}"} + reports[str(entry_cid or default or DEFAULT_CONNECTION)] = one + if named is None and primary is None: + primary = one + return {**(primary or {"tables": {}}), "connections": reports} diff --git a/api/routes_grid.py b/api/routes_grid.py index a98b30c81110650d42ecb5bff7227b28db4d18ac..85e47ea32129d69c6a470da4714b2349b553ec14 100644 --- a/api/routes_grid.py +++ b/api/routes_grid.py @@ -2644,7 +2644,76 @@ def grid_hop_topics(session: Session = Depends(require_session)): _PRESET_LINK_MODULES = ("customer_data", "product_data") -def _may_open(session: Session, key: str): +def _register_retired_tables(): + """Push `odoo_relational.RETIRED_KEYS` down into `core.relations`, at import and per request. + + ⛔⛔ W54-T37 / C5 / INSTRUCTION 22 - THIS IS WHY THE OWNER SAW A PERMISSION WALL ABOUT A + DATABASE THAT DOES NOT EXIST. `ut_odoo_customers` and `ut_odoo_products` are RETIRED: popped + from every tenant document on every sync, replaced by the `customer_data` / `product_data` + registry modules, and still DESCRIBED by the connector spec, which is legitimate (a spec + describes a shape). The relation enumeration therefore minted edges at them, `_may_open` below + failed closed on a key it could not resolve, and `relations.forbidden_table_refusal` told the + reader to ask an administrator for access to a table nobody can grant. + + ⛔ ONE DECLARATION, PUSHED, NEVER COPIED. `odoo_relational.RETIRED_KEYS` stays the only place + the two keys are named; `core` cannot read it (`core` never imports up), so the app layer hands + it down exactly as `core.user_tables.register_connected_prefix` is handed its prefixes. Copying + the keys into `core` would make a second declaration of one fact. + + ⚠ GUARDED, AND CALLED TWICE FOR THE SAME REASON `_ensure_odoo_spec` exists: a process that + cannot import `odoo_relational` or `core` must still START, and one that imports them later + must still get the right answer. Registration is idempotent (it is a set union) and returns the + whole registered set, so a caller can assert what it just joined. + """ + try: + import odoo_relational + import core.relations as relations + return relations.register_retired_tables(*odoo_relational.RETIRED_KEYS) + except Exception: # noqa: BLE001 + return frozenset() + + +#: The import-time push. ⚠ Its VALUE is not read anywhere on the request path: it is here so the +#: registration has happened before the first listing, and so an operator can see what landed. +RETIRED_TABLES_AT_IMPORT = _register_retired_tables() + + +def _walled_fields(session: Session, key: str, st=None, memo: dict = None): + """`perm_scope.scoped_fields(key)`, or **None** when the field wall REFUSED — memoised. + + ⭐⭐ W54-T39 — THIS FUNCTION EXISTS BECAUSE THE SAME WALL WAS BEING ASKED TWICE PER TABLE AND + THE ANSWER WAS THROWN AWAY BOTH TIMES. `_may_open` below wanted only the verdict and + `_source_fields` below wanted only the list; each called `scoped_fields` itself, so a listing + that touches six tables paid for TWELVE wall resolutions. MEASURED against tenant #0 on + 2026-09-06: one `scoped_fields` is ~135 ms on a `ut_*` grid and ~550 ms on `product_data`, so + the duplicate pass alone was more than half of the 3.5 s the record rail took to open. + + ⛔ THE VERDICT AND THE LIST ARE ONE ANSWER, AND THEY MUST STAY ONE CALL. Resolving them + separately is not merely slow, it is two readings of one wall that can disagree if a grant + changes between them — the [[one-question-two-normalizers]] shape, on a permission. + ⚠ `None` RATHER THAN `[]` IS THE WHOLE POINT OF THE RETURN TYPE. A table the wall refuses and + a table with no columns are different facts, and `_may_open` is the caller that has to tell + them apart; collapsing both to an empty list would hide every refused target as an empty one. + + ⛔ FAIL CLOSED, exactly as before: any exception at all is a refusal, never a widened answer. + ⚠ `memo` IS ONE REQUEST'S, handed down by `_relation_context`. Passing None simply means no + memo, which is what every caller outside a listing pass wants. + """ + if memo is not None and key in memo: + return memo[key] + import core.perm_scope as perm_scope + + try: + answer = list(perm_scope.scoped_fields( + session.user, key, st=session.runtime if st is None else st) or ()) + except Exception: # noqa: BLE001 + answer = None + if memo is not None: + memo[key] = answer + return answer + + +def _may_open(session: Session, key: str, st=None, memo: dict = None): """May this session open `key` at all? The SAME two gates `_pivot_side` applies, minus the rows. ⛔ THE ROWS ARE THE POINT OF THE DIFFERENCE. `_pivot_side` calls `perm_scope.scoped_table`, @@ -2655,23 +2724,30 @@ def _may_open(session: Session, key: str): ⚠ FAIL CLOSED. Any refusal, any unknown table, any error is False. A target this account may not open must not appear in the strip, because the tab would 403 on the first click and read as a broken product rather than as a permission. - """ - import core.perm_scope as perm_scope + ⛔⛔ AND IT STILL CANNOT TELL "ABSENT" FROM "REFUSED", WHICH IS CORRECT AND IS **NOT** WHAT + INSTRUCTION 22 ASKED TO CHANGE. Conflating "not granted" with "could not be read" is deliberate + and the refusal sentence says both out loud. What was missing is a third case that never + belonged here at all: a table this deployment does not HAVE. That is answered upstream, by + `_register_retired_tables` above keeping such a key from ever being enumerated as an edge + target, and by `relations.diagnose_path` naming it when a request asks for one anyway. + + ⭐ W54-T39 — THE SECOND GATE IS NOW ASKED THROUGH `_walled_fields`, WHICH IS THE SAME QUESTION + AND THE SAME FAIL-CLOSED ANSWER, shared with `_source_fields` so one table costs one wall + resolution instead of two. ⛔ THE GRANT GATE STILL RIDES `session.require`, which resolves + against the session's OWN runtime rather than any handle passed in: a lent snapshot may make a + read cheaper and must never be able to make a grant broader. + """ try: session.require(key) except HTTPException: return False except Exception: # noqa: BLE001 return False - try: - perm_scope.scoped_fields(session.user, key, st=session.runtime) - except Exception: # noqa: BLE001 - return False - return True + return _walled_fields(session, key, st=st, memo=memo) is not None -def _source_fields(session: Session, table: str): +def _source_fields(session: Session, table: str, st=None, memo: dict = None): """The link-bearing field list for `table`, under this session's field wall. ⛔⛔ THE PRE-SET COLUMNS ARE NOT IN `scoped_fields` AND THAT IS THE TRAP THIS FUNCTION EXISTS @@ -2682,13 +2758,12 @@ def _source_fields(session: Session, table: str): and look entirely correct doing it. ⚠ APPENDED, NOT MERGED BY KEY: a tenant cannot author a field on a registry module, so the two lists cannot collide, and a union keyed on `key` would hide that if they ever did. - """ - import core.perm_scope as perm_scope - try: - fields = list(perm_scope.scoped_fields(session.user, table, st=session.runtime) or ()) - except Exception: # noqa: BLE001 - fields = [] + ⚠ W54-T39 — A REFUSED WALL STILL READS AS `[]` HERE, unchanged. `_walled_fields` answers None + for that case so `_may_open` can tell it from an empty table; this door has never needed the + distinction and must not start reporting one, because a refusal is `_may_open`'s word. + """ + fields = list(_walled_fields(session, table, st=st, memo=memo) or ()) if table in _PRESET_LINK_MODULES: try: import odoo_relational @@ -2741,6 +2816,11 @@ def _ensure_odoo_spec(): """ try: import odoo_relational + # ⚠ BESIDE THE SPEC REGISTRATION AND FOR ITS REASON. Both are pushes from this layer into + # `core`, both are idempotent, and both are wrong to skip in a process that imported this + # module before `platform/` was on the path. Registering the retired keys HERE as well as + # at import is what makes the enumeration below correct in either process shape. + _register_retired_tables() return bool(odoo_relational.register_connector_spec()) except Exception: # noqa: BLE001 return False @@ -2773,7 +2853,7 @@ def _unwalled_fields(defs: dict, key: str): return fields -def _relation_context(session: Session, table: str): +def _relation_context(session: Session, table: str, memo: dict = None): """`defs` plus the three callbacks `relations` needs, memoised for the life of ONE request. ⚠ BOTH WALLS ARE MEMOISED. `_may_open` runs `session.require` plus `perm_scope.scoped_fields` @@ -2789,6 +2869,29 @@ def _relation_context(session: Session, table: str): wall really did remove would be absent from both and get reported as an edge that never existed. Taking the union makes the unfiltered enumeration a superset by construction, so the diff is monotone and the only thing it can be wrong about is saying "unknown" too rarely. + + ⭐⭐ W54-T39 — **THE DEFINITIONS ARE READ ONCE AND THEN LENT, WHICH IS WHERE THE RECORD RAIL'S + THREE AND A HALF SECONDS WERE.** `perm_scope.scoped_fields` reaches `user_tables.all_defs` + for every table it is asked about, and `all_defs` is a store projection: one Neon round trip, + MEASURED at ~135 ms each on 2026-09-06. A depth-2 listing off `customer_data` asked about six + tables and paid that round trip TWELVE times for the identical document this function had + already read on its first line. `user_tables.lend` exists for exactly this — `nav_entries` has + paired `all_defs` with it since W32-T02 — so the handle below serves that one snapshot to + every wall resolution in the pass and each `ut_*` table's `scoped_fields` drops from ~135 ms + to 0. + ⛔ IT IS A READ HANDLE AND IT NEVER REACHES A WRITE. `lend_defs`' own note is the rule: every + value it serves is a `_Projected`, so a caller that wanted rows gets a loud `KeyError` rather + than a silently empty grid — and `scoped_fields` is a `want_rows=False` door by construction. + Nothing here is handed to a mutation; `grid_related` is a GET. + ⛔ IT CANNOT WIDEN A WALL, and that was checked rather than assumed: the lent handle serves + only `user_tables` and (lazily, once) `object_shares`, every other store key falls through to + the real runtime, and `session.require` is not given it at all. MEASURED 2026-09-06 across all + ten of tenant #0's databases: `scoped_fields` under the lent handle returned a field list + EQUAL, key for key and value for value, to the one it returned under the bare runtime. + + ⚠ AND THE SNAPSHOT IS THE POINT, not a side effect. One listing answers about one set of + definitions; re-reading them mid-pass could enumerate an edge from a table that vanished two + hops ago and report the inconsistency as a refusal. """ import core.user_tables as user_tables @@ -2796,17 +2899,31 @@ def _relation_context(session: Session, table: str): defs = dict(user_tables.all_defs(st=session.runtime) or {}) except Exception: # noqa: BLE001 defs = {} - + try: + lent = user_tables.lend(session.runtime, **{user_tables.STORE_KEY: defs}) + except Exception: # noqa: BLE001 + # A store handle too old to lend is CORRECT-but-slow, exactly as `all_defs`' own fallback + # is: the pass simply goes back to paying a round trip per wall resolution. + lent = session.runtime + + # ⭐ ONE WALL RESOLUTION PER TABLE, SHARED BY BOTH CALLBACKS. `open_memo` and `field_memo` + # below still memoise their own composition (the grant gate, the pre-set link append); this is + # the `scoped_fields` answer underneath both of them, which is the expensive part. + # ⚠ THE CALLER MAY HAND ITS OWN IN, and `grid_related` does. That route has to answer 403 for + # the SOURCE table before it lists anything, so it resolves that one wall a moment before this + # function is built; without the shared bag the source table would be resolved twice, which on + # `product_data` is a second ~550 ms for an answer already in hand. + wall_memo = memo if memo is not None else {} open_memo, field_memo, wide_memo = {}, {}, {} def may_open(key): if key not in open_memo: - open_memo[key] = _may_open(session, key) + open_memo[key] = _may_open(session, key, st=lent, memo=wall_memo) return open_memo[key] def fields_for(key): if key not in field_memo: - field_memo[key] = _source_fields(session, key) + field_memo[key] = _source_fields(session, key, st=lent, memo=wall_memo) return field_memo[key] def open_fields_for(key): @@ -2870,14 +2987,22 @@ def related_refusals(session: Session, table: str, depth: int, entries: list, ct open_fields=ctx["open_fields_for"](table), open_fields_for=ctx["open_fields_for"]) -#: ⭐ THE HTTP STATUS EACH R13 CODE EARNS ON A **PIN**. The two permission answers are 403, the +#: ⭐ THE HTTP STATUS EACH REFUSAL CODE EARNS ON A **PIN**. The two permission answers are 403, the #: same status the top-of-route `_may_open` gate on `table` itself already uses; a path that never #: existed stays the 400 this route already answered with, unchanged; and "every hop was open and #: there is nothing there" is a 404, because it is neither a bad request nor a refusal. #: ⚠ `no_related_rows` cannot be reached from THIS route's pin branch (a path that resolves is #: served, so the diff never reports it) and is mapped anyway, because `diagnose_path` is the one #: diagnosis and the row door will raise the same bag from another ticket's fence. -_REFUSAL_STATUS = {"forbidden_table": 403, "hop_filtered": 403, +#: ⭐⭐ W54-T37 / C5 - `retired_target` IS A **404**, AND IT IS DELIBERATELY NOT A 403. The whole +#: complaint in instruction 22 is a permission status on a table that does not exist, so any 4xx +#: in the permission family would repeat the lie in a header. ⚠ 410 Gone is the more precise word +#: for a database that was retired rather than never present, and it is NOT used: the client half +#: of this contract is another lane's, every existing handler here branches on the CODE rather than +#: the status, and introducing the one status nothing in this app has ever returned would risk a +#: fetch wrapper treating it as a transport failure. The code carries the meaning; the status only +#: has to be honest. +_REFUSAL_STATUS = {"forbidden_table": 403, "hop_filtered": 403, "retired_target": 404, "no_related_rows": 404, "unknown_via": 400} @@ -2888,10 +3013,19 @@ def _refusal_error(diag: dict): SIBLINGS inside `error`. C3 asks for *"the ENUMERATED candidates with their join columns and the exact retry strings, not prose"*, and a client cannot draw a retry button out of an English clause, so the structure rides beside the sentence rather than inside it. + + ⭐⭐ W54-T40 — `detail` IS COPIED TOO, AND IT IS THE ROW W54-T38 BOOKED. C5 gives every refusal + a SHORT `message` and a long `detail`, and the client renders the pair as a `
` with the + sentence in the summary; this function copied four keys and dropped the diagnosis, so a refusal + arriving through THIS door rendered as the sentence alone while the identical refusal arriving + through the listing kept its disclosure. One key, and the two doors stop disagreeing about how + much of one contract they carry. + ⚠ A BAG WITH NO DIAGNOSIS STILL RENDERS AS THE SENTENCE ALONE: the loop copies a key only when + the bag carries one, so nothing gains a caret with nothing behind it. """ exc = err(_REFUSAL_STATUS.get(str(diag.get("code")), 400), str(diag.get("code")), str(diag.get("message") or "")) - for key in ("table", "hop", "path", "candidates"): + for key in ("table", "hop", "path", "candidates", "detail"): if diag.get(key) not in (None, ""): exc.detail["error"][key] = diag[key] return exc @@ -2947,7 +3081,12 @@ def grid_related(table: str, table = str(table or "").strip() if not table: raise err(400, "bad_table", "name the database to list relations for") - if not _may_open(session, table): + # ⚠ W54-T39 — THE GATE IS UNMOVED AND UNCHANGED; only its ANSWER is kept. `wall_memo` rides + # into `_relation_context` below so this table's field wall, which the 403 has just resolved + # at full price, is not resolved a second time three lines later. The order is untouched: the + # caller's own access is still the first thing this route decides. + wall_memo = {} + if not _may_open(session, table, memo=wall_memo): raise err(403, "not_permitted", f"your account may not open '{table}', so it cannot be told what that database " f"is related to. Ask an administrator for access to it") @@ -2963,7 +3102,7 @@ def grid_related(table: str, f"{relations.MAX_DEPTH} (those plus everything one further named hop away), and " f"this request asked for {depth}. Ask for 1 or {relations.MAX_DEPTH}") - ctx = _relation_context(session, table) + ctx = _relation_context(session, table, memo=wall_memo) entries = related_path_entries(session, table, depth, ctx) if via: wanted = [str(v) for v in via if str(v or "").strip()] diff --git a/api/routes_keychain.py b/api/routes_keychain.py index 8f1a355fe0c02e29f688653dd7b087caddb6dbc3..05ecc866f0d597577793c156ae1b1f909f1026c0 100644 --- a/api/routes_keychain.py +++ b/api/routes_keychain.py @@ -99,8 +99,10 @@ SCOPE_KEY = "keychain_scopes" #: ⛔⛔ THE TYPES A WHOLE WORKSPACE READS THROUGH, WHICH THEREFORE CANNOT BE PERSONAL. #: -#: `keychain.odoo_creds` and `keychain.meta_creds` both resolve to *the first entry of that type* -#: for the TENANT — that is what spawns `ut_odoo_*` / `ut_meta_*` and what every measure column is +#: `keychain.odoo_creds` and `keychain.meta_creds` both resolve to *a connection of that type* for +#: the TENANT — the one a caller NAMES, or the tenant's designated default when none is named +#: (W54-T45 / R4; it was "the first entry of that type" before) — that is what spawns +#: `ut_odoo_*` / `ut_meta_*` and what every measure column is #: answered from. So a member storing a personal Odoo key would not get "their own Odoo": they #: would silently become the credential the entire workspace's databases are built from, which is #: a credential elevation wearing a scope picker. @@ -112,7 +114,8 @@ SCOPE_KEY = "keychain_scopes" #: (whose own `TENANT_WIDE_TYPES` already carried three entries, `amazon_sp` included, "JOINED IN #: WAVE 52" by its own header comment). Until this line, a non-admin could POST a PERSONAL #: `amazon_sp` entry through THIS door — `add_key`'s refusal only fires for a type in this tuple — -#: while `core/keychain._first_creds` already skipped a personal `amazon_sp` entry when resolving +#: while `core/keychain`'s shared resolver (`_first_creds` then, `_creds_for` since W54-T45) +#: already skipped a personal `amazon_sp` entry when resolving #: the tenant's Amazon credential. So the write succeeded, the UI told the member they had #: connected their own Amazon, and the resolver silently served nothing for it: not the elevation #: (the resolver-side guard held), but a door that stores a credential the product then ignores, @@ -201,13 +204,30 @@ def visible_entries(rt, uname, is_admin=False): owner = str(e.get("createdBy") or "") if not may_see(scope, owner, uname): continue - row = {**e, "scope": scope, "owner": owner} + row = {**_identified(e), "scope": scope, "owner": owner} if not (is_admin or str(owner) == str(uname)): row["preview"] = "" out.append(row) return out +#: ⭐⭐ W54-T44 / R4 / CONTRACT C4 — THE IDENTITY, IN THE WIRE'S OWN SPELLING. +#: +#: `core/keychain.py` stamps `connection_id` and `slot` on every entry so that two connections of +#: one kind are separately addressable (R4's agency tenant: many Odoos, one workspace). This layer +#: renames the first of them to `connectionId` because that is what every other camelCase field on +#: these payloads does (`createdBy`, `canBusiness`, `tenantWideTypes`), and a payload carrying both +#: spellings would be [[a-constant-two-features-share]] on the wire, where a client picking the +#: wrong one still looks right until the day only one is filled. +#: ⚠ `slot` is one word, so it crosses unchanged. +def _identified(row): + """One keychain row, with its identity in wire spelling. Gains keys, never loses one.""" + out = dict(row) + out["connectionId"] = str(out.pop("connection_id", "") or out.get("id") or "") + out["slot"] = int(out.get("slot") or 1) + return out + + def _write_scope(rt, entry_id, scope, owner): """Persist one entry's scope. A `business` entry CLEARS its row rather than writing the default, so the store holds one spelling of the common case.""" @@ -235,11 +255,140 @@ def _kc(): return keychain -def _resolved_odoo_key(rt): +def _ps(): + """`core.perm_scope`, lazily. Same idiom as `_kc()` and `_rel()`, and for the same reason: the + permission layer pulls the grid stack in behind it, and this router is imported at boot.""" + import core.perm_scope as perm_scope + return perm_scope + + +#: ⛔ THE ONE KIND THAT STANDS BEHIND NO CONNECTOR CARD. `_connector_by_entry_type` names every +#: other member of `keychain.ENTRY_TYPES`; `generic` is a credential a person stored by hand, so it +#: has no card and no label to borrow. Spelled here rather than dropped from the vocabulary, +#: because a grant list narrower than the door it governs is a gap nobody can see: `add_key` accepts +#: every `ENTRY_TYPES` member, so every one of them must be grantable. +CONNECTOR_KIND_LABELS = {"generic": "Other credential"} + + +def connector_grant_kinds(): + """The grant vocabulary: `[{key, label, tenantWide}]`, one row per connectable kind. + + ⭐⭐ W54-T47 / R4 — THE THIRD AXIS'S OWN WORDS. Owner: *"access becomes Database / Module / + Connector."* The first two are registry keys the permission editor already renders; this one is + a CREDENTIAL KIND, so its vocabulary is `keychain.ENTRY_TYPES` and not the registry at all. + + ⛔ DERIVED FROM `ENTRY_TYPES`, NEVER TYPED OUT. That set is what `add_entry` validates against, + so a hand-written list here would be [[one-question-two-normalizers]] the day a connector is + added: a kind the door accepts and the editor cannot grant is a permission nobody can give. + ⚠ `tenantWide` RIDES ALONG so the editor can say what a grant on that kind really means. A + tenant-wide source is never personal, so granting it hands the member the workspace's own + credential slot; that is exactly what R4 asks for and exactly what an admin should read before + ticking it. + """ + owners = _connector_by_entry_type() + out = [] + for etype in sorted(_kc().ENTRY_TYPES): + label = str((owners.get(etype) or {}).get("label") or "").strip() + out.append({"key": etype, + "label": label or CONNECTOR_KIND_LABELS.get(etype, etype), + "tenantWide": etype in TENANT_WIDE_TYPES}) + return out + + +def _grant_subject(session, username): + """The registry key for `username`, or a 404 that cannot distinguish another tenant's account + from a missing one. + + ⛔ THE 404 RULE AND THE TENANT DEFAULT ARE BORROWED, NOT RE-SPELLED. `routes_admin.get_perms` + already answers *"a cross-tenant username answers exactly like a missing one, 404, never 403, + because 'that account exists in another company' is itself a leak"*, and `_tenant_of` is + already the ONE spelling of the pre-wave default. A second copy here is how a tenant wall grows + a gap. Imported lazily, exactly as `_connector_by_entry_type` imports `routes_connectors`. + """ + import routes_admin as ra + uname = str(username or "").strip().lower() + reg = ra._registry() + if uname not in reg or ra._tenant_of(reg[uname]) != ra._tenant_of(session.user): + raise err(404, "no_such_user", f"no account named {uname!r}") + return uname + + +def _grant_admin(session): + """Deciding who may connect a source is an administrator's act, refused at the server. + + ⛔ THE CLIENT HIDES; THIS FORBIDS. `PermsEditor.tsx` renders the section only for an admin as a + courtesy, and its own header says every control there is one. + """ + if not session.admin: + raise err(403, "not_admin", + "only an administrator can decide who may add connections to this workspace") + + +@router.get("/admin/users/{username}/connector-grants") +def get_connector_grants(username: str, session: Session = Depends(require_session)): + """One account's Connector grants, plus the vocabulary the editor renders them from.""" + _grant_admin(session) + uname = _grant_subject(session, username) + return {"username": uname, + "kinds": connector_grant_kinds(), + "granted": sorted(_ps().connector_grants(uname, st=session.runtime))} + + +@router.put("/admin/users/{username}/connector-grants") +def put_connector_grants(username: str, body: dict = Body(default=None), + session: Session = Depends(require_session)): + """Replace one account's Connector grants wholesale (W54-T47 / R4 / contract C4). + + WHOLESALE, for the reason `put_perms` is: *"'remove this restriction' has to be expressible, + and a merge cannot express a deletion without a second vocabulary for it."* An empty list is + therefore a legal body and it REVOKES. + + ⛔ AN EMPTIED GRANT CLEARS ITS ROW rather than storing `[]`. An absent row and "no grant" mean + the same thing (`perm_scope.CONNECTOR_GRANT_KEY`'s own note), so there is one spelling of the + common case and revoking returns the store to the shape it had before anybody granted anything. + + ⛔ AN UNKNOWN KIND IS NAMED, NEVER DROPPED (W30/R6's second sentence). Silently discarding it + would tell an administrator they granted something the door will never honour. + """ + _grant_admin(session) + uname = _grant_subject(session, username) + body = body if isinstance(body, dict) else {} + raw = body.get("granted") + if not isinstance(raw, list): + raise err(400, "bad_grants", + "say which connectors this account may add, as a list of connector kinds") + known = {k["key"] for k in connector_grant_kinds()} + want = sorted({str(k).strip().lower() for k in raw if str(k or "").strip()}) + unknown = [k for k in want if k not in known] + if unknown: + raise err(400, "unknown_connector", + f"this workspace has no connector called {', '.join(unknown)}") + + def _up(cur): + cur = cur if isinstance(cur, dict) else {} + if want: + cur[uname] = want + else: + cur.pop(uname, None) + return cur + + try: + session.runtime.update(_ps().CONNECTOR_GRANT_KEY, _up, flush="sync") + except Exception: + raise err(503, "store_unavailable", "the change was not saved, please try again") + return {"username": uname, "kinds": connector_grant_kinds(), "granted": want} + + +def _resolved_odoo_key(rt, connection_id=None): """`(source, flag_key)` — which source would serve this tenant's Odoo queries, in both the shapes this module needs: the display string (`env` / `keychain:`) and the key the pause flag is stored under. + ⭐ W54-T45 / R4 — `connection_id` NAMES which connection is being asked about; no id keeps + meaning the tenant's designated default, so no route's behaviour moves. The mirroring is the + point: this still delegates to `TenantRuntime.odoo_flag_key`, which now refuses to fall back + to the environment for a named-but-unresolvable connection, and so does this by construction. + ⭐ D-10 (wave 24): THE RESOLUTION ITSELF NOW LIVES IN ONE PLACE, `TenantRuntime.odoo_flag_key`, beside the `odoo_source()` it must agree with. This function had its own copy of the same three rules — first unlocked keychain odoo entry, else env for tenant #0, else nothing — and @@ -247,7 +396,7 @@ def _resolved_odoo_key(rt): against another, freezing nothing while the UI reports success. The two SHAPES stay here because they are this module's presentation concern; the DECISION does not. """ - flag_key = rt.odoo_flag_key() + flag_key = rt.odoo_flag_key(connection_id) if not flag_key: return None, None return ("env" if flag_key == _ENV_ODOO_FLAG_KEY else f"keychain:{flag_key}"), flag_key @@ -559,7 +708,16 @@ def list_keychain(session: Session = Depends(require_session)): #: the vocabulary and the permission, so the client renders a picker it can honour #: rather than offering an option the server will refuse (R4: business is admin-only). "scopes": list(SCOPES), "canBusiness": bool(session.admin), - "tenantWideTypes": list(TENANT_WIDE_TYPES)} + "tenantWideTypes": list(TENANT_WIDE_TYPES), + # ⭐ W54-T47 / R4 — WHICH KINDS THIS READER MAY CREATE BUSINESS-WIDE WITHOUT BEING AN + # ADMIN. ⛔ ADDITIVE, AND `canBusiness` IS DELIBERATELY UNMOVED: that flag has meant + # "this account is an administrator" since wave 32 and three gates read it as such, so + # widening it would make one boolean answer two questions. A grant is per KIND and + # arrives as a list for the same reason the wall is per kind. + # ⚠ COURTESY, NEVER THE WALL. `add_key` consults `perm_scope.may_add_connection` + # regardless of what any client believes about this field. + "connectorGrants": sorted(_ps().connector_grants(session.uname, + st=session.runtime))} @router.post("/admin/keychain", status_code=201) @@ -572,18 +730,44 @@ def add_key(body: dict = Body(default=None), session: Session = Depends(require_ if scope is None: raise err(400, "bad_scope", f"scope must be one of {', '.join(SCOPES)}") - if scope == "business" and not session.admin: - raise err(403, "not_admin", - "a business-wide connection applies to everyone in this workspace, so only an " - "administrator can create one. You can add it as a personal connection instead.") etype = str(body.get("type") or "").strip().lower() + # ⭐⭐ W54-T47 / R4 / CONTRACT C4 — THE CONNECTOR GRANT IS CONSULTED HERE AND ONLY HERE, ON THE + # PATH THAT WAS ALREADY REFUSED. + # + # ⛔⛔ WHICH IS WHAT MAKES IT ABSENCE-PRESERVING, and that property is the whole design. A + # member with NO grant meets byte-identical behaviour to the day before this shipped: 403 + # `not_admin` here, 400 `scope_not_available` below, and their own personal connection of an + # ordinary type still succeeds. Nothing was storable before this ticket, so every account in + # every tenant carries no grant — reading that absence as DENY anywhere else on this route + # would revoke personal connections for the entire product with nobody having decided + # anything (`core/perm_scope.may_metrics` records the identical failure one field over). + # + # ⭐ SO THE GRANT ONLY EVER WIDENS: an explicit per-kind grant is what lets a named non-admin + # create a business-wide connection OF THAT KIND, which is R4's agency case said as a rule + # (*"many Gmail connections, or even many Odoo connections for one tenant, depending on the + # admin's configuration per user"*). + # + # ⚠ `etype` MOVED ABOVE THIS TEST rather than staying below it, because the grant is per KIND + # and a check that cannot see the kind can only ever be a second `session.admin`. + if scope == "business" and not session.admin and not _ps().may_add_connection( + session.user, etype, st=session.runtime): + raise err(403, "not_admin", + "a business-wide connection applies to everyone in this workspace, so it takes " + "an administrator, or an account an administrator has granted this connector " + "under Settings. " + + ("Ask an administrator to add it for everyone." + if etype in TENANT_WIDE_TYPES + else "You can add it as a personal connection instead.")) if scope == "personal" and etype in TENANT_WIDE_TYPES: # ⛔ REPORTED, NOT COERCED (W30/R6's second sentence). See TENANT_WIDE_TYPES above: this # credential is what the WHOLE workspace's databases are built from, so "personal" would # be a label on a tenant-wide key rather than a boundary around it. + # ⛔ AND THE GRANT DOES NOT REACH THIS REFUSAL. `allowed_scopes` is the SOURCE's own rule + # and knows nothing about who is asking; a grant says a person may connect this kind for + # the workspace, never that a workspace-wide credential can become one person's. raise err(400, "scope_not_available", f"a {etype} connection is what this whole workspace's databases are read " - f"through, so it is always business-wide — it cannot be a personal connection. " + f"through, so it is always business-wide and cannot be a personal connection. " f"An administrator can add it for everyone.") try: row = kc.add_entry(session.runtime, body.get("label"), body.get("type"), @@ -618,34 +802,69 @@ def add_key(body: dict = Body(default=None), session: Session = Depends(require_ raise err(503, "store_unavailable", "the key was not saved — its sharing setting could not be stored, so " "nothing was kept. Try again.") - return {"entry": {**row, "scope": scope, "owner": session.uname}} + return {"entry": {**_identified(row), "scope": scope, "owner": session.uname}} @router.put("/admin/keychain/{entry_id}") def update_key(entry_id: str, body: dict = Body(default=None), session: Session = Depends(require_session)): - """Contract C1's scope door. Only the scope moves — a stored secret is never re-openable, so - "edit this key" means "replace it" and that is `DELETE` + `POST`.""" + """Contract C1's scope door, and W54-T44 / C4's RENAME door. Both are settings ABOUT a + connection rather than the credential inside it: a stored secret is never re-openable, so + "change the key itself" still means "replace it", which is `DELETE` + `POST`. + + ⭐ R4 asks for the rename by name — *"Odoo 1, Odoo 2, and obviously user can rename this"* — + and this is where it belongs: the walls a rename needs (`_own_row`'s 404 for an entry you may + not see, `_may_touch`'s ownership rule) are already standing here, and a second door would be + a second copy of both. + ⚠ `{"label": ...}` and `{"scope": ...}` are independent; either alone is a valid request and + both together are one change. A body carrying NEITHER is a 400 rather than a silent no-op, + because "nothing happened" and "your change was saved" must never look the same. + """ row = _own_row(session, entry_id) - scope = clean_scope((body or {}).get("scope"), default=None) - if scope is None: - raise err(400, "bad_scope", f"scope must be one of {', '.join(SCOPES)}") - if scope == "business" and not session.admin: - raise err(403, "not_admin", - "a business-wide connection applies to everyone in this workspace, so only an " - "administrator can make one business-wide.") + body = body or {} + wants_scope, wants_label = "scope" in body, "label" in body + if not wants_scope and not wants_label: + raise err(400, "nothing_to_change", + "say what to change about this connection: a new name, or who it is shared " + "with.") + scope = None + if wants_scope: + scope = clean_scope(body.get("scope"), default=None) + if scope is None: + raise err(400, "bad_scope", f"scope must be one of {', '.join(SCOPES)}") + if scope == "business" and not session.admin: + raise err(403, "not_admin", + "a business-wide connection applies to everyone in this workspace, so only " + "an administrator can make one business-wide.") if not _may_touch(session, row): raise err(403, "not_yours", "this connection is not yours to change") - if scope == "personal" and str(row.get("type") or "") in TENANT_WIDE_TYPES: + if wants_scope and scope == "personal" and str(row.get("type") or "") in TENANT_WIDE_TYPES: raise err(400, "scope_not_available", f"a {row.get('type')} connection is what this whole workspace's databases are " f"read through, so it is always business-wide.") + label = row.get("label") or "" + if wants_label: + # ⛔ THE NAME MOVES AND NOTHING ELSE. `rename_entry` touches one field on one row, so the + # connection keeps its `connectionId`, its `slot` and its encrypted credential, and every + # other connection of the same kind is left byte for byte as it was. + try: + renamed = _kc().rename_entry(session.runtime, entry_id, body.get("label")) + except ValueError as e: + raise err(400, "bad_label", str(e)) + except Exception: + raise err(503, "store_unavailable", "the new name was not saved, please try again") + if renamed is None: + raise err(404, "no_entry", "no such key") + label = renamed.get("label") or label owner = row.get("owner") or session.uname + if not wants_scope: + return {"entry": {**row, "label": label}} try: _write_scope(session.runtime, entry_id, scope, owner) except Exception: raise err(503, "store_unavailable", "the change was not saved — try again") - return {"entry": {**row, "scope": scope, "owner": owner if scope == "personal" else ""}} + return {"entry": {**row, "label": label, "scope": scope, + "owner": owner if scope == "personal" else ""}} @router.delete("/admin/keychain/{entry_id}") @@ -710,21 +929,27 @@ def connectors(session: Session = Depends(require_session)): # every colleague's personal connection on the screen next door to the one that hides them. entries = visible_entries(session.runtime, session.uname, bool(session.admin)) # R3 cutover (2026-08-04): which source would actually serve this tenant's Odoo queries — - # mirrors TenantRuntime.odoo_source() exactly: first unlocked keychain odoo entry, else env - # for tenant #0 only, else nothing (fail closed — never another tenant's environment). + # mirrors TenantRuntime.odoo_source() exactly: the resolved keychain odoo connection (while + # unlocked), else env for tenant #0 only, else nothing (fail closed — never another tenant's + # environment). + # ⛔⛔ W54-T45 — THE WALK IS GONE AND THE RESOLUTION IS ASKED FOR. This was the third copy of + # "the first odoo entry of this tenant", written out by hand beside a comment promising it + # mirrors `odoo_source()`. Under R4 a tenant holds many Odoo connections, so a hand-rolled + # first-entry walk here would light the ACTIVE badge on one client's connection while the + # connector layer served another's — the two answers disagreeing on the one screen that + # exists to show which is which. `keychain.resolve_connection_id` is the single resolver, it + # decrypts nothing (this route runs on a locked keychain too), and it applies the same + # personal-entry skip this comment already required. # ⚠ W32-T11: computed over the TENANT's entries, not over `entries` above. "Which source # serves this workspace" is one fact for everybody, and deriving it from a per-USER list would # make the answer depend on who opened the pane. Personal entries are excluded for the same # reason `TENANT_WIDE_TYPES` refuses them: they must never become the workspace's source. - _scopes = _scope_rows(session.runtime) - first_odoo = next((e["id"] for e in kc.list_entries(session.runtime) - if e["type"] == "odoo" - and entry_scope(session.runtime, e["id"], _scopes)[0] != "personal"), None) + serving_odoo = kc.resolve_connection_id(session.runtime, "odoo") # ⛔ W32-T10 — the env leg goes through `env_odoo_available` now, so this route and the # connectors DIRECTORY answer "does the environment serve this tenant?" with one function # instead of two spellings that agreed until a second tenant signed in. - if first_odoo and kc.unlocked(): - resolved = f"keychain:{first_odoo}" + if serving_odoo and kc.unlocked(): + resolved = f"keychain:{serving_odoo}" elif env_odoo_available(session.runtime): resolved = "env" else: @@ -811,14 +1036,31 @@ def _rel(): return rel -def _odoo_entry(session): +def _odoo_entry(session, connection_id=None): """The keychain entry SERVING this tenant's Odoo, or None when the environment is (or nothing - is). Business-scoped by construction — `TENANT_WIDE_TYPES` refuses a personal one.""" + is). Business-scoped by construction — `TENANT_WIDE_TYPES` refuses a personal one. + + ⭐⭐ W54-T45 / R4 / C4 — IT ASKS THE KEYCHAIN WHICH CONNECTION SERVES RATHER THAN WALKING FOR + THE FIRST ONE. `connection_id` names it; no id means the tenant's designated default, which is + the lowest-`slot` odoo connection and, for every tenant that has exactly one, the same row this + used to return. The walk this replaced was a second copy of the resolution + `keychain.resolve_connection_id` owns, and a panel resolving one connection while the connector + layer resolves another is precisely how an agency's screen comes to describe the wrong client. + ⛔ A named connection that does not resolve is None, never a sibling and never the environment. + """ kc = _kc() + cid = kc.resolve_connection_id(session.runtime, "odoo", connection_id) + if not cid: + return None scopes = _scope_rows(session.runtime) for e in kc.list_entries(session.runtime): - if e["type"] == "odoo" and entry_scope(session.runtime, e["id"], scopes)[0] != "personal": - return e + if str(e["connection_id"]) != str(cid) and str(e["id"]) != str(cid): + continue + # The personal skip belongs to the resolver above; re-asserted here because THIS module + # owns the scope vocabulary and a divergence between the two buckets must fail closed. + if entry_scope(session.runtime, e["id"], scopes)[0] == "personal": + return None + return e return None @@ -978,10 +1220,14 @@ def _rewrite_server_db(session, server_db): So this is add-then-delete through the module's own doors, with the side rows (pause flag, scope) carried across because they are keyed by ENTRY ID. ⚠ THE ORDER IS DELIBERATE AND THE WINDOW IS REAL: for the moment between the add and the - delete this tenant has TWO odoo entries, and `odoo_creds` takes the first by id sort — so a - resync landing inside that window could read the OLD database. The alternative order can - leave the workspace with no credential at all, which is worse than one stale read. Milliseconds - of ambiguity beats a lost key. + delete this tenant has TWO odoo entries. The alternative order can leave the workspace with no + credential at all, which is worse than one stale read. + ⭐ W54-T45 MADE THAT WINDOW DETERMINISTIC RATHER THAN AMBIGUOUS, as a side effect worth + stating. It used to read "`odoo_creds` takes the first by id sort — so a resync landing inside + that window COULD read the old database", i.e. a coin flip on random hex. The resolver now + serves the tenant's designated default, the LOWEST slot, and the replacement entry is minted + high-water: so the OLD connection serves for the whole window and the new one takes over the + instant the old row is deleted. One stale read, not a coin flip. """ kc = _kc() entry = _odoo_entry(session) diff --git a/api/routes_nav.py b/api/routes_nav.py index 24a971488ad932f3fc4dd49e40d52b035a6ffc20..07546b1ae869a147d1313e294b97f45b192b8867 100644 --- a/api/routes_nav.py +++ b/api/routes_nav.py @@ -422,6 +422,111 @@ def _granted_view_ids(session): return set() +#: ⭐⭐ W54-T48 / OWNER RULING R4 / CONTRACT C4 — ONE CONNECTION, ONE FOLDER IN THE RAIL. +#: +#: R4, verbatim: *"under the View rail for each database that comes from the same connector, they +#: need to be put in the same Folder. Odoo 1, Odoo 2, and obviously user can rename this."* The +#: rail already folds the Data level by `sourceGroup` (`dataPath.ts::groupDataDatabases`), so the +#: grouping mechanism is not the missing piece — the NAME was. Every Odoo database used to answer +#: the literal `"Odoo"`, so an agency with two Odoo connections saw its two clients' invoices +#: nested under one folder, which is the exact confusion R4 exists to prevent. +#: +#: ⛔ THE RENAME IS THE CONNECTION'S RENAME AND THERE IS NO SECOND NAMING SCHEME. The folder shows +#: the keychain row's `label`, which `keychain.add_entry` defaults to `Odoo 1` / `Odoo 2` and +#: `keychain.rename_entry` changes (W54-T44). *"Obviously user can rename this"* is therefore +#: already shipped: renaming the connection renames its folder on the next nav read, and it +#: touches no TABLE KEY — those are namespaced on the immutable `connection_id` (W54-T46), never +#: on a label a person may change twice a day. +#: +#: ⛔⛔ AND THE OVERRIDE ONLY FIRES WHEN THERE ARE TWO OR MORE CONNECTIONS TO TELL APART. With +#: exactly one Odoo connection — every tenant that exists today — the folder keeps the generic +#: `"Odoo"` it has always shown, unchanged, and nothing on anybody's rail moves. +#: +#: THE REASON IS R4 ITSELF, not caution. R4 asks for connections to be DISTINGUISHABLE: *"Odoo 1, +#: Odoo 2"*. With one connection there is one folder either way and nothing to distinguish it +#: from, so the label buys no clarity and costs the tenant a rail that suddenly reads differently. +#: Tenant #0's one connection is labelled "Odoo (migrated from this deployment)" by an August +#: migration, so an unconditional override renamed the owner's own Data folder to a truncated +#: migration artefact — a regression this ticket would have shipped in the name of a ruling about +#: agencies. The moment a SECOND connection is added the names appear on both folders together, +#: which is the only moment they mean anything. +#: ⚠ COUNTED ON THE CONNECTIONS, NOT ON THE USABLE LABELS. A second connection whose label is one +#: of the reserved words below is still a second connection, and its sibling must still be named. +#: +#: These two reserved words are the rail's OWN vocabulary, not a connection's to take: +#: `dataPath.ts::dataDatabaseOrigin` folds `loopable` / `blank` / `automation` / empty into the +#: "Loopable" group, and the branch below puts user tables in "Custom". A connection someone named +#: "Blank" would otherwise dissolve into one of those folders and show a client's invoices beside +#: somebody's scratch table, so such a label falls back to the generic Odoo folder instead. +_RESERVED_GROUP_LABELS = frozenset({"loopable", "blank", "automation", "custom", "odoo"}) + +#: The registry modules that ARE the designated default connection's data rather than a namespaced +#: copy of it: `odoo_relational.namespaced_fields` says so in as many words ("`customer_link` +#: targets the compiled registry module `customer_data`, which holds the DEFAULT connection's +#: customers"). They carry no namespace token to read backwards, so they are named here. +_DEFAULT_CONNECTION_PAGES = frozenset({"customer_data", "product_data"}) + + +def _odoo_connection_folders(runtime): + """`({connection_id: folder label}, default_connection_id)` for this tenant's Odoo + connections — resolved ONCE per `/nav`, decrypting nothing, and `({}, None)` on any failure. + + ⛔ ONCE PER REQUEST, NOT ONCE PER PAGE, AND THAT IS THE WHOLE REASON THIS IS A FUNCTION. + `odoo_relational.connection_label` and `keychain.default_connection_id` each walk + `keychain.list_entries`, which is a store read; calling either inside the page loop would put + N of them back on the one route D-175 spent a wave reducing to a single read. The loop below + asks `connection_for_table_key` WITHOUT a runtime, which is pure string work, and maps its + `DEFAULT_CONNECTION` sentinel through the default resolved here. + ⛔ AND IT FAILS SOFT ON PURPOSE. A locked keychain, a store blip or a missing import leaves the + rail painting the generic "Odoo" folder; a rail that does not paint at all is far worse than a + rail whose folder carries a generic name. + ⛔ A TENANT WITH FEWER THAN TWO ODOO CONNECTIONS GETS `{}` — the same answer as a failure, and + deliberately so: both mean "there is nothing here to tell apart, keep the generic folder". The + count is taken over the CONNECTIONS, before the reserved-word filter, so a second connection + named `Blank` still switches its sibling on. + """ + if runtime is None: + return {}, None + try: + import core.keychain as keychain + import odoo_relational as odoo_rel + connections = 0 + labels = {} + for row in keychain.list_entries(runtime): + if str(row.get("type") or "") != "odoo": + continue + connections += 1 + cid = str(row.get("connection_id") or "") + label = " ".join(str(row.get("label") or "").split()) + if cid and label and label.lower() not in _RESERVED_GROUP_LABELS: + labels[cid] = label + if connections < 2: + return {}, odoo_rel.default_connection_id(runtime) + return labels, odoo_rel.default_connection_id(runtime) + except Exception: # noqa: BLE001 + return {}, None + + +def _odoo_folder_label(key, labels, default_cid): + """The folder name an Odoo page belongs under, or `""` to keep the generic fallback. + + ⚠ `connection_for_table_key` is the ONLY sanctioned way to ask which connection owns a table, + because it is the inverse of the namespace `table_key_for` builds (C4). Parsing the key here + would be the second implementation that inverse exists to prevent. + """ + if not labels: + return "" + try: + import odoo_relational as odoo_rel + cid = (default_cid if key in _DEFAULT_CONNECTION_PAGES + else odoo_rel.connection_for_table_key(key)) + if cid == odoo_rel.DEFAULT_CONNECTION: + cid = default_cid + except Exception: # noqa: BLE001 + return "" + return labels.get(str(cid or "")) or "" + + @router.get("/nav") def nav(session: Session = Depends(require_session)): """`{pages: [{key,label,source?,chrome}], landing}`. @@ -561,12 +666,23 @@ def nav(session: Session = Depends(require_session)): # leak with no symptom until two tenants rename the same registry key. Copy the rows before # merging on the day that invariant changes. meta = _read_nav_meta(session.runtime) + # W54-T48 (R4 / C4): the tenant's Odoo connections, read ONCE for the whole page loop. + _conn_labels, _conn_default = _odoo_connection_folders(session.runtime) for page in pages: source = str(page.get("source") or "") key = str(page.get("key") or "") if key in {"customer_data", "product_data"} or source.lower() == "odoo" \ or key.startswith("ut_odoo_"): + # ⛔ THIS LITERAL IS THE FALLBACK AND IT STAYS. It is what a tenant with ONE Odoo + # connection or none still sees — every tenant that exists today — and what a database + # that resolves to no connection at all keeps. page["sourceGroup"] = "Odoo" + # ⭐ W54-T48 (R4 / C4): once the tenant has TWO connections to tell apart, each + # database is folded under its own connection's name, so two connections give two + # folders. `_odoo_connection_folders` answers `{}` below that threshold. + _folder = _odoo_folder_label(key, _conn_labels, _conn_default) + if _folder: + page["sourceGroup"] = _folder elif page.get("user_table") or source in {"", "Blank", "Custom"}: page.setdefault("sourceGroup", "Custom") # ⛔⛔ W35-T43 (rulings R4/R7) — THE MARK-IMPORTANT COUNTS ARE NO LONGER COMPUTED HERE. diff --git a/api/routes_odoo_tables.py b/api/routes_odoo_tables.py index b92555495321b78d13eaece5f3b7bff277775c1c..d86d71073e6354bf0de1177ea943207ff94cdea8 100644 --- a/api/routes_odoo_tables.py +++ b/api/routes_odoo_tables.py @@ -1509,6 +1509,156 @@ def _related_source_value(session, entry, record): return None +def _via_path(via): + """The list of EDGE KEYS a `via` names, or None when it is one edge's bag instead. + + ⭐⭐ W54-T40 / R12 — *"the client pins one by naming each edge (`via = ["orders", + "order_lines"]`)"*. THREE SPELLINGS ARRIVE AND ALL THREE ARE THE SAME THING, which is why + exactly one function decides: + + * an ARRAY of keys, which is what `RecordDetail.tsx::relatedPinKey` sends for a two-hop tab + and what `verify_wiring.py` pins that client literal to; + * a bare STRING, C3's back-compat leg, which `relations.pick_path` already reads as a + one-element path; + * the two-hop entry's own `via` BAG, `{direction: 'path', key, path}`, which is what a client + holding the whole entry naturally hands back. Reading `path` out of it costs one key and + removes an entire class of "the shape was almost right" refusal. + + ⛔ A ONE-HOP BAG STAYS A BAG AND ANSWERS None. `relations.pick` is the resolver for that shape + and it matches on `direction` plus `key`; routing it here instead would resolve a one-hop pin + against the depth-aware listing for no gain and change the cost of the six tabs that already + worked. ⚠ AN EMPTY OR PARTLY-BLANK PATH IS **NOT** A PATH: it answers None and falls into the + `bad_relation` guard, which is the honest refusal for `via = []`. + """ + if isinstance(via, str): + return [via] if via.strip() else None + if isinstance(via, (list, tuple)): + keys = [str(v).strip() for v in via] + return keys if keys and all(keys) else None + if isinstance(via, dict) and isinstance(via.get("path"), (list, tuple)): + keys = [str(v).strip() for v in via["path"]] + return keys if keys and all(keys) else None + return None + + +def _related_path_legs(session, source, entry, entries): + """`(first, mid_key, last)` — the two ONE-HOP entries a two-hop composite is made of. + + ⛔⛔ EACH LEG IS RESOLVED FROM **ITS OWN TABLE'S** SCOPED LISTING, AND THAT IS R13 AT PIN TIME. + An edge key is unique per SOURCE table and not across a connector (`relations`' own banner says + so, with the ten-edges/seven-keys measurement behind it), so hop 2 is looked up in the + intermediate's listing and nowhere else. Resolving both against the source's list would be the + ambiguous-key bug the entry key exists to prevent, and it would also skip the intermediate's + permission wall on the way past. + + ⚠ HOP 1 COSTS NOTHING EXTRA: it is in `entries`, the very listing the composite was picked + from, because a depth-2 enumeration returns the one-hop entries first. Only hop 2 needs a + second listing, and it is asked at depth 1. + """ + import core.relations as relations + from routes_grid import related_path_entries + + hops = [str(k) for k in (entry.get("path") or ())] + first = relations.pick_path(entries, hops[:1]) + if first is None: + raise err(400, "unknown_relation", relations.unknown_via_refusal(source, hops[:1])) + mid_key = str(first.get("target") or "") + last = relations.pick_path(related_path_entries(session, mid_key, 1), hops[1:2]) + if last is None: + raise err(400, "unknown_relation", relations.unknown_via_refusal(mid_key, hops[1:2])) + return dict(first, __source__=source), mid_key, dict(last, __source__=mid_key) + + +def _related_hop_values(session, source, record, first, mid_key, last, notes): + """The values hop 2 joins on, resolved from the INTERMEDIATE database's own rows. + + ⭐⭐ W54-T40 — THIS IS THE HALF THAT MAKES A TWO-HOP TAB ANSWER ROWS INSTEAD OF A SENTENCE. + Hop 1 turns the source record into a set of intermediate rows; this returns the value each of + those rows carries in the column hop 2 is keyed on, and the caller pins THIS database by them. + + ⛔⛔ THE INTERMEDIATE IS READ THROUGH `_compiled_read`, WHICH IS THE SAME COMPILER THIS DOOR + USES FOR AN ORDINARY WINDOW, AND THAT IS THE WHOLE PERMISSION ARGUMENT. Its grant gate, its + administrator row wall and its hidden-field closure all run before a single id is produced, so + a traversal cannot be used to learn about rows of the middle database a reader may not see. A + second, lighter read here would be a second permission wall, and this file already carries the + rule that a second copy of that block does not drift towards refusing. + ⛔ AND AN INTERMEDIATE THIS DOOR CANNOT READ REFUSES BY NAME. `product_data` is a compiled + registry module with no read-through binding, so the one enumerated path that passes through it + answers a sentence carrying the cause and a way round it, rather than an empty grid. + + ⚠ NO CAP, AND THE COST IS REPORTED INSTEAD (standing rule 1). Every distinct value comes back, + however many there are, and the reader is told through `limits` that this tab resolves a second + database on every page. + """ + import core.relations as relations + from fastapi import HTTPException # noqa: PLC0415 + + value = _related_source_value(session, first, record) + if value in (None, ""): + raise err(400, "unknown_relation", + relations.unresolvable_source_refusal(source, first)) + try: + mid = _compiled_read(mid_key, session) + except HTTPException as exc: + why = "" + if isinstance(getattr(exc, "detail", None), dict): + why = str((exc.detail.get("error") or {}).get("message") or "") + raise err(409, "relation_not_served", + f"this relation reaches '{last.get('target')}' through '{mid_key}', and that " + f"database could not be read here to follow it" + + (f" ({why})" if why else "") + + f". Open '{mid_key}' on its own, find the records this one is linked to, and " + f"follow the next relation from there") + mid_spec = mid["spec"] + on1 = str((first.get("via") or {}).get("on") or "") + step = (mid_spec.get("cols") or {}).get(on1) + if not step: + raise err(409, "relation_not_served", + f"'{mid_key}' has no live expression for '{on1}', which is the column the first " + f"hop of this relation joins on, so the traversal cannot be resolved. Open " + f"'{mid_key}' on its own, or ask for '{on1}' to be added to its live connection") + # ⭐ THE COLUMN HOP 2 IS KEYED ON, READ OFF THE INTERMEDIATE. `pid` is the row IDENTITY and is + # not a column of the mirror spec, so it resolves to the spec's own identity expression, which + # is the same one this route trusts everywhere else and is per table rather than a bare `id`. + frm2 = str((last.get("via") or {}).get("from") or relations.IDENTITY_COL) + take = (mid_spec["id"] if frm2 == relations.IDENTITY_COL + else ((mid_spec.get("cols") or {}).get(frm2) or (None,))[0]) + if not take: + raise err(409, "relation_not_served", + f"'{mid_key}' has no live expression for '{frm2}', which is the value the second " + f"hop of this relation is keyed on, so the traversal cannot be resolved. Open " + f"'{mid_key}' on its own, or ask for '{frm2}' to be added to its live connection") + try: + value = step[1](value) + except Exception: # noqa: BLE001 + value = str(value) + mid_from = mid_spec["from_sql"] if mid_spec.get("from_sql") else mid_spec["table"] + parts = [p for p in (mid["base_where"], first.get("where")) if p] + parts.append(f"{step[0]} = ?") + pred = " AND ".join(f"({p})" for p in parts) + rows = mid["cur"].execute( + f"SELECT DISTINCT {take} FROM {mid_from} WHERE {pred}", + list(mid["wall_params"]) + [value]).fetchall() + values = [r[0] for r in rows if r and r[0] is not None] + # ⭐⭐ STANDING RULE 1'S SECOND SENTENCE, AND `effect` IS CHOSEN SO THE READER GETS **THIS** + # SENTENCE RATHER THAN A NEIGHBOUR'S. `counts.ts::plainLimit` maps a known `effect` to one + # fixed client phrase and falls through to the SERVER's own first sentence for an effect it has + # not learned; `slow` maps to *"Rows this far down load slowly, each page is reached by walking + # every row above it"*, which is a true statement about a deep page and a FALSE one about a + # seven-row traversal. `traversal` is deliberately not in that table, so the strip prints the + # cause below, which is what actually happened. + # ⚠ THE FIRST CLAUSE IS THE ONE THAT REACHES THE STRIP: `firstSentence` cuts at the first full + # stop and truncates past 120 characters, so the mechanism is stated before the count. + notes.append({ + "subject": "related", "effect": "traversal", + "cause": f"these rows are reached through '{mid_key}', so every page resolves that " + f"database first. This record matched {len(values):,} of its records, and this " + f"database is then narrowed to the rows those reach", + "recommendation": f"open '{mid_key}' on its own if you are paging through a large set, or " + f"filter this database beside the relation to ask a smaller question"}) + return values + + def _related_pin(table_key, session, spec, base_where, wall_params, cur, related): """`(sql, params, notes)` for C6's pinned read, or `(None, [], [])` when nothing is pinned. @@ -1534,6 +1684,30 @@ def _related_pin(table_key, session, spec, base_where, wall_params, cur, related rather than a literal `id`: `ut_odoo_order_lines` is join-shaped and its identity is `sol.id`, so a bare `id` would be ambiguous across `sale_order_line` and `sale_order`. It is the same expression this route already trusts as `tiebreak_sql` and as the fallback ORDER BY. + + ⭐⭐ W54-T40 / INSTRUCTION 22 / R12 — **A `via` MAY NOW BE A PATH, AND THE PATH IS SERVED.** + The owner's second quoted error was this function's own `bad_relation` sentence, and it fired + on 18 of the 25 rail tabs of `customer_data`: R12 says the client pins a traversal by naming + each edge, so a two-hop tab sends `via` as the ARRAY `["invoices","order_link"]`, and the + guard below accepted only the one-hop bag. MEASURED 2026-09-06, 6 of 25 tabs answered 200 and + 18 answered 400 on the first click. + + ⛔⛔ ACCEPTING THE ARRAY IS HALF A FIX AND WOULD HAVE MOVED THE ERROR RATHER THAN CLOSED IT. + `relations.pick` matches `via.direction` against `DIRECTIONS`, and a two-hop entry's direction + is the literal `path`, deliberately outside that tuple so nothing serves half a traversal. So + a path resolves through `relations.pick_path` against the DEPTH-AWARE listing, and the read is + then answered in TWO steps: hop 1 resolves the intermediate database's own rows to the values + hop 2 joins on, and hop 2 pins this database by them. Sending the object form alone answered + `400 unknown_relation` and changed nothing the reader could see. + + ⭐ EVERY HOP IS STILL PERMISSION CHECKED, AND AT PIN TIME, NOT ONLY AT LISTING TIME (R13). The + intermediate is resolved through `_compiled_read`, i.e. THE SAME compiler this door uses for + an ordinary read, so its grant, its row wall and its hidden-field closure all apply before a + single id crosses into this table's predicate. A second, laxer read of the intermediate would + be exactly the permission wall with a hole in it that `related_entries` exists to prevent. + ⛔ AND AN INTERMEDIATE THIS DOOR CANNOT READ IS A **REPORTED LIMIT**, never a silent empty: + `product_data` is a registry module with no read-through binding, so the one enumerated path + that passes through it refuses by name with a cause and a recommendation. """ import core.relations as relations @@ -1549,13 +1723,18 @@ def _related_pin(table_key, session, spec, base_where, wall_params, cur, related source = str(related.get("table") or "") record = related.get("record") via = related.get("via") - if not source or record in (None, "") or not isinstance(via, dict): + # ⭐⭐ W54-T40 — `via` IS EITHER ONE EDGE'S BAG OR A PATH OF EDGE KEYS, and `_via_path` is the + # one place that decides which. It answers None for the bag, which is what keeps the guard + # below spelling the SAME refusal for a genuinely incomplete pin. + path = _via_path(via) + if not source or record in (None, "") or (path is None and not isinstance(via, dict)): raise err(400, "bad_relation", "a pinned read needs the record's database, the record id and the relation to " - "follow, as {table, record, via}. Ask GET /api/v1/grid/" + (source or "{table}") + "follow, as {table, record, via}, where `via` is one relation or the array of " + "edge keys naming each hop. Ask GET /api/v1/grid/" + (source or "{table}") + "/related for the relations this account may follow") - from routes_grid import _may_open, related_entries + from routes_grid import _may_open, related_entries, related_path_entries if not _may_open(session, source): # ⚠ THE CAUSE IS NAMED AS A PAIR, ON PURPOSE. `_may_open` is fail-closed and answers False @@ -1571,8 +1750,20 @@ def _related_pin(table_key, session, spec, base_where, wall_params, cur, related # ⛔ RESOLVED AGAINST THE **SCOPED** LISTING, which is what makes "an edge you cannot be # offered is an edge you cannot pin" structural rather than remembered. `related_entries` is # the same function `GET /grid/{table}/related` answers with; there is no second resolution. - entries = related_entries(session, source) - entry = relations.pick(entries, via) + # ⭐ W54-T40 — AND A PATH RESOLVES AGAINST THE DEPTH-AWARE LISTING, WHICH IS THE SAME RULE ONE + # LEVEL DEEPER: `related_path_entries` is what `GET /grid/{table}/related?depth=2` answers + # with, so a traversal this account is not offered is a traversal it cannot pin either. + # ⚠ THE DEPTH ASKED FOR IS THE LENGTH OF THE PATH, never a flat 2. A one-element path costs + # the depth-1 enumeration it needs and not the depth-2 one, which on `customer_data` is the + # difference between roughly half a second and roughly two. + if path is None: + entries = related_entries(session, source) + entry = relations.pick(entries, via) + else: + if len(path) > relations.MAX_DEPTH: + raise err(400, "over_depth", relations.over_depth_refusal(source, path)) + entries = related_path_entries(session, source, len(path)) + entry = relations.pick_path(entries, path) if entry is None: raise err(400, "unknown_relation", relations.unknown_via_refusal(source, via)) entry = dict(entry, __source__=source) @@ -1586,12 +1777,33 @@ def _related_pin(table_key, session, spec, base_where, wall_params, cur, related if not entry.get("served", True): raise err(409, "relation_not_served", relations.unserved_target_refusal(entry)) - on = str((entry.get("via") or {}).get("on") or "") + # ⭐⭐ W54-T40 — THE **LAST** HOP IS WHAT JOINS THIS DATABASE, and on a two-hop entry that is + # not `entry`. A composite carries `via = {direction: 'path', key, path}` and NO `on`, no + # `from` and no `where`: `relations._two_hop_entry` refuses to flatten the two hops' predicates + # onto the pair, because one of them may carry a predicate the other does not (the open-invoice + # bridge is exactly that edge). So the legs are resolved, each from its OWN table's scoped + # listing, and the last one is what this block below reads. + notes = [] + first, mid_key, last = entry, "", entry + if len(entry.get("path") or ()) > 1: + first, mid_key, last = _related_path_legs(session, source, entry, entries) + + on = str((last.get("via") or {}).get("on") or "") # ⚠ `spec["cols"]`, NOT the caller's narrowed `cols`. The join column is a JOIN, not a value # this response returns: a relation must keep working when an administrator has hidden the id # column it runs over, and no cell of it is ever projected. The hidden-field closure still # governs everything that reaches the wire, one layer up. - binding = (spec.get("cols") or {}).get(on) + # ⭐⭐ W54-T40 — AND THE ROW IDENTITY IS NOT ONE OF THOSE COLUMNS. `relations` defaults an edge + # with no declared `on` to `pid`, which is the wire's name for the row identity and is never a + # key of a mirror spec's `cols` (measured across all eight bound grains on 2026-09-06: not one + # carries it). Every such edge therefore refused with "has no live expression for 'pid'" while + # the expression was in hand the whole time, as `spec["id"]` - the same per-table identity this + # route already uses for the pin itself, for the tiebreak and for the fallback ORDER BY, and + # deliberately not a bare `id`, which is ambiguous on a join-shaped grain. + if on == relations.IDENTITY_COL: + binding = (spec["id"], int) + else: + binding = (spec.get("cols") or {}).get(on) if not binding: raise err(409, "relation_not_served", f"'{table_key}' has no live expression for '{on}', which is the column this " @@ -1599,14 +1811,23 @@ def _related_pin(table_key, session, spec, base_where, wall_params, cur, related f"this database directly, or ask for '{on}' to be added to its live connection") on_expr, on_cast = binding[0], binding[1] - value = _related_source_value(session, entry, record) - if value in (None, ""): - raise err(400, "unknown_relation", - relations.unresolvable_source_refusal(source, entry)) - try: - value = on_cast(value) - except Exception: # noqa: BLE001 - value = str(value) + if mid_key: + # ⭐ HOP 1, ANSWERED BY THE INTERMEDIATE DATABASE ITSELF, UNDER ITS OWN WALL. See + # `_related_hop_values`. An empty answer is an ANSWER (this record reaches nothing through + # that database) and compiles to `1=0` two blocks down, never to "no pin". + values = _related_hop_values(session, source, record, first, mid_key, last, notes) + else: + value = _related_source_value(session, entry, record) + if value in (None, ""): + raise err(400, "unknown_relation", + relations.unresolvable_source_refusal(source, entry)) + values = [value] + cast = [] + for one in values: + try: + cast.append(on_cast(one)) + except Exception: # noqa: BLE001 + cast.append(str(one)) # ── the member ids, in ONE SQL over the bridge column (the ticket's `how:`) ──────────────── # ⛔ NOT THROUGH `datastore.window`: that clamps at `WINDOW_MAX` (5,000) rows, so a customer @@ -1616,22 +1837,27 @@ def _related_pin(table_key, session, spec, base_where, wall_params, cur, related # ⚠ THE WALL RIDES ALONG. Resolving ids under `base_where` means the id SET a scoped reader can # produce is already narrowed to rows they may see, so the pin cannot be used to learn how many # rows exist beyond their boundary. + # ⭐ W54-T40 — `= ?` FOR ONE VALUE AND `IN (...)` FOR MANY, and the one-value spelling is kept + # BYTE FOR BYTE so a one-hop pin compiles exactly the SQL it compiled before this ticket. The + # many-value arm is only ever reached by the second hop of a traversal. frm_body = spec["from_sql"] if spec.get("from_sql") else spec["table"] - parts = [p for p in (base_where, entry.get("where")) if p] - parts.append(f"{on_expr} = ?") - pred = " AND ".join(f"({p})" for p in parts) - ids = [int(r[0]) for r in cur.execute( - f'SELECT DISTINCT {spec["id"]} FROM {frm_body} WHERE {pred}', - list(wall_params) + [value]).fetchall() if r and r[0] is not None] + ids = [] + if cast: + parts = [p for p in (base_where, last.get("where")) if p] + parts.append(f"{on_expr} = ?" if len(cast) == 1 + else f"{on_expr} IN ({','.join('?' for _ in cast)})") + pred = " AND ".join(f"({p})" for p in parts) + ids = [int(r[0]) for r in cur.execute( + f'SELECT DISTINCT {spec["id"]} FROM {frm_body} WHERE {pred}', + list(wall_params) + list(cast)).fetchall() if r and r[0] is not None] - notes = [] # ⭐ STANDING RULE 1'S SECOND SENTENCE, ON A COST RATHER THAN ON A CAP. Nothing is limited # here; the reader is told that this particular relation is answered by reading the source # database once per page, because it is keyed on a column rather than on the record id. - if str((entry.get("via") or {}).get("from") or "") != relations.IDENTITY_COL: + if str((first.get("via") or {}).get("from") or "") != relations.IDENTITY_COL: notes.append({ "subject": "related", "effect": "slow", - "cause": f"this relation is keyed on the '{entry['via']['from']}' column of " + "cause": f"this relation is keyed on the '{first['via']['from']}' column of " f"'{source}' rather than on its record id, so every page of these rows is " f"resolved by reading that database first", "recommendation": "read this database on its own and filter it on " diff --git a/api/routes_sheet.py b/api/routes_sheet.py index 58d0856a6bb560246414d7a8d54ac5ac5f6b49f1..f4267e8ea022ab2d5fed606802157e0b353adc60 100644 --- a/api/routes_sheet.py +++ b/api/routes_sheet.py @@ -98,7 +98,7 @@ def _mirror(session: Session): import routes_odoo_tables as rot import odoo_relational as rel - def _for(table_key, *, metric_window=None): + def _for(table_key, *, metric_window=None, needed=None): fields = None for _bucket, key, _label, mk_fields in rel.TABLES: if key == table_key: @@ -131,14 +131,37 @@ def _mirror(session: Session): # shape; the cache hangs off the SESSION because that object is built fresh by # `require_session` on every request and dies with it, so nothing can outlive its own # cursor or leak across users. The temp table it names lives in that same cursor. + # + # ⭐⭐ W54-T36 — AND ONLY THE COLUMNS THE CELL ACTUALLY READS ARE MATERIALISED. + # MEASURED on tenant #0's `customer_data` (3,673 records, 47 columns), warm, through + # the real `drill_cell`: 8,437 ms total, of which `odoo_relational.registry_grid_spec` + # is 6,137 ms. That step turns every row into a tuple of 47 Python values and + # `executemany`s it, so its cost is per COLUMN, and a drill reads none of them: it + # counts records and lists ids. `needed` is the honest set (the aggregate's column, + # plus every column the cell's filter and the row wall name); `None` still means the + # whole grid, so a caller that has not worked out its set loses nothing. + # + # ⛔ THE MEMO WIDENS, IT NEVER NARROWS, and that is what keeps `refresh_sheet` safe. + # A slot already built for a wider set answers a narrower request unchanged; a request + # naming a column the slot does not carry rebuilds at the UNION, so a workbook whose + # cells read different columns converges instead of rebuilding per cell. A `None` + # entry means every column is present and is reusable by anything. memo = getattr(session, "_sheet_mirrors", None) if memo is None: memo = {} session._sheet_mirrors = memo slot = (table_key, json.dumps(metric_window, sort_keys=True, default=str)) - if slot not in memo: - memo[slot] = _registry_mirror(session, cur, table_key, metric_window) - return memo[slot] + want = None if needed is None else {str(k) for k in needed} + entry = memo.get(slot) + if entry is not None: + built, made = entry + if built is None or (want is not None and want <= built): + return made + if want is not None: + want = set(want) | built + made = _registry_mirror(session, cur, table_key, metric_window, needed=want) + memo[slot] = (None if want is None else set(want), made) + return made spec = rot._source_for(cur, table_key) if spec is None: raise err(409, "not_read_through", @@ -177,17 +200,34 @@ def _registry_assembly(session: Session, table_key: str): field-name correction acks belong to the `/workspace` refresh that exists to show them to the person who made the edit, and a bound cell resolving its scope must not eat them. + ⭐⭐ W54-T36 — ONE ASSEMBLY PER DATABASE PER REQUEST, memoised on the SESSION exactly as + `_mirror` memoises the mirror and for the same lifetime reason: `require_session` builds that + object per request and it dies with the request, so nothing here outlives its own cursor or + reaches another account. MEASURED on tenant #0's `customer_data`, warm: 2,145 ms a call. It + already ran once per (database, window); it now also survives a mirror rebuilt at a wider + column set, and every caller BELOW reuses it. `_offered_view` reaches for `grid_assembly` and + `product_assembly` on its own and is a separate cost; see its own note. + ⛔ AN UNEXPECTED FAILURE REFUSES LOUDLY AND DOES NOT DEGRADE TO THE STATIC CONTRACT. Falling back would answer the cell out of 37 columns while the person is looking at 47, which is the defect this function exists to end, and it would do it with a 200. """ import core.perm_scope as perm_scope + memo = getattr(session, "_sheet_assemblies", None) + if memo is None: + memo = {} + session._sheet_assemblies = memo + if table_key in memo: + return memo[table_key] try: if table_key == "product_data": from routes_products import product_assembly - return product_assembly(session, scope="product", consume_corrections=False) + memo[table_key] = product_assembly(session, scope="product", + consume_corrections=False) + return memo[table_key] from routes_customers import grid_assembly - return grid_assembly(session, scope="customer", consume_corrections=False) + memo[table_key] = grid_assembly(session, scope="customer", consume_corrections=False) + return memo[table_key] except perm_scope.Denied: raise err(403, "database_unreadable", f"You cannot read {table_key}.") except HTTPException: @@ -207,7 +247,7 @@ def _registry_assembly(session: Session, table_key: str): "shown rather than shown from an older set of columns. Try again in a moment.") -def _registry_mirror(session: Session, cur, table_key: str, metric_window): +def _registry_mirror(session: Session, cur, table_key: str, metric_window, needed=None): """`(cursor, spec, columns)` for one compiled registry grid, at the cell's own period. ⭐⭐ R7's SECOND HALF LIVES HERE: *"must also be bounded by date time lookup"*. `g["derived"]` @@ -226,6 +266,17 @@ def _registry_mirror(session: Session, cur, table_key: str, metric_window): `column_values` entirely when `may_metrics` is off, so a column with no value anywhere in `g["derived"]` is one the capability wall has already answered for. Re-resolving it here would be a second answer to that question, from the one door that never asked it. + + ⭐⭐ W54-T36 — `needed` IS THE COLUMN SET THIS CELL CAN POSSIBLY READ, AND `None` IS EVERY + COLUMN. It narrows what gets MATERIALISED, never what gets assembled: `g` is the same scoped + assembly, `rows` are the same scoped rows, and `spec["fields"]` below is still the FULL list + so a refusal can name a column the mirror did not carry. + + ⛔⛔ IT IS INTERSECTED WITH THE ASSEMBLY'S OWN FIELDS AND MUST STAY THAT WAY. `cols` is what + `_resolve_binding` subtracts a row wall's columns from to decide whether the wall can be + applied at all, and that check is FAIL CLOSED (409 `scope_not_applicable`). Materialising a + column just because a filter named it would invent an empty column for a name this database + does not have, and the wall would then compile against nothing and quietly stop restricting. """ import aios_grid import odoo_relational as rel @@ -237,13 +288,17 @@ def _registry_mirror(session: Session, cur, table_key: str, metric_window): derived, bounded, limits = _metric_derived(session, table_key, g, metric_window) rows = aios_grid.rows_from_pool(g["rows_src"], fields, (g.get("ws") or {}).get("overlays"), derived=derived) + # The columns this cell can read, in the assembly's own order. `registry_grid_spec` forces + # `pid` in on its own, because `build_ids_query` needs `spec["id"]` to be a real column. + kept = (fields if needed is None + else [f for f in fields if str(f.get("key") or "") in needed]) # ⛔ THE TYPES ARE NORMALISED FOR THE MIRROR ONLY. See `modules/sheet.py::mirror_field_type`: # `metric`, `rating` and a numeric `rollup` are in neither `_REGISTRY_COL_TYPE` nor # `filter_sql.NUMERIC_TYPES`, so without this they land as VARCHAR and compare as strings. # ⚠ THE SAME LIST GOES TO BOTH CALLS, deliberately. `registry_grid_spec` picks the SQL type and # `_filter_columns` picks the compiler's type; handing them two different lists is how a column # ends up stored as one thing and compared as another. - spec_fields = sheet_mod.mirror_fields(fields) + spec_fields = sheet_mod.mirror_fields(kept) spec = rel.registry_grid_spec(cur, table_key, spec_fields, rows) # ⛔⛔ THE MATERIALISED TABLE IS GIVEN THE WINDOW'S OWN NAME, AND WITHOUT THIS THE MEMO ABOVE # SERVES ONE WINDOW'S ROWS UNDER ANOTHER WINDOW'S ANSWER (found by W53-T14, live). @@ -262,8 +317,13 @@ def _registry_mirror(session: Session, cur, table_key: str, metric_window): # to an assembly that costs 20 to 130 seconds, so it is not a cost worth conditioning on. # ⚠ ALWAYS, INCLUDING THE `None` WINDOW: the unqualified name is REPLACED by every later # build, so leaving the no-period case pointing at it is exactly the case measured above. + # ⛔⛔ W54-T36 — THE COLUMN SET IS PART OF THAT NAME FOR THE SAME REASON THE WINDOW IS. Two + # cells on one database at one window may now be materialised over DIFFERENT columns, and a + # narrower later build would otherwise replace a wider earlier one under a spec the memo is + # still holding, so a query would address a column its own table no longer has. slot = hashlib.sha1( - json.dumps(metric_window, sort_keys=True, default=str).encode("utf-8")).hexdigest()[:12] + json.dumps([metric_window, None if needed is None else sorted(needed)], + sort_keys=True, default=str).encode("utf-8")).hexdigest()[:12] at_window = f'{spec["table"]}__at_{slot}' cur.execute(f'CREATE OR REPLACE TEMP TABLE "{at_window}" AS ' f'SELECT * FROM "{spec["table"]}"') @@ -1707,6 +1767,10 @@ def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=Non 3. the ROW wall, fail-closed, refusing 409 when it names a column the mirror cannot answer; 4. the binding's own scope, whose unanswerable columns are REPORTED rather than dropped. + ⚠ W54-T36 — THE WALL AND THE SCOPE ARE NOW READ BEFORE STEP 2 SO THE MIRROR KNOWS WHICH + COLUMNS TO MATERIALISE. Steps 3 and 4 still happen where they did: the wall is still checked + against `cols` after the mirror exists, and it still refuses fail closed. + ⭐⭐ W53-T13 / R7 — THE PERIOD IS RESOLVED BEFORE THE MIRROR IS OPENED, because it decides what the Metric columns of that mirror MEAN. `modules/sheet.py::period_window` turns the cell's `{unit, start}` into the custom window `harness/windows.py` speaks, and `_registry_mirror` @@ -1729,7 +1793,28 @@ def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=Non database = _require_database(session, binding["database"]) window = sheet_mod.period_window(binding.get("period")) - cur, spec, cols = _mirror(session)(database, metric_window=window) + + # ⭐⭐ W54-T36 — THE WALL AND THE SCOPE ARE READ BEFORE THE MIRROR IS OPENED, so the mirror can + # be built over the columns this cell can possibly read instead of over the whole database. + # Neither read touches the mirror: the wall comes from `perm_scope` and the scope from the + # stored view document, which is why the order can move at all. + # ⛔ WHAT MUST NOT MOVE IS THE WALL'S OWN CHECK. It subtracts the wall's columns from `cols` + # and refuses 409 when one is missing, so it still runs AFTER the mirror exists, below. + wall_tree = ((perm_scope.entry(session.user, database) or {}).get("filter") + if perm_scope.row_scope_applies(session.user, database) else None) + wall_nodes, wall_conj = _fe_parts(wall_tree) + scope = binding["scope"] + if scope.get("view_id"): + scope_nodes, scope_conj = _view_filter(session, database, scope["view_id"], + scope.get("view_name", ""), memo=view_memo) + else: + scope_nodes, scope_conj = _fe_parts(scope.get("filter")) + needed = (sheet_mod.filter_columns_named(scope_nodes) + | sheet_mod.filter_columns_named(wall_nodes)) + if binding["aggregate"].get("field"): + needed.add(str(binding["aggregate"]["field"])) + + cur, spec, cols = _mirror(session)(database, metric_window=window, needed=needed) # ⛔ THE COLUMN IS CHECKED BEFORE THE SQL IS BUILT (W53-T13). Now that every tenant column is a # real column of the materialised table, a `sum` over a text column reaches DuckDB as a binder @@ -1742,9 +1827,6 @@ def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=Non raise err(409, agg_refusal.code, agg_refusal.message) # ── the ROW wall, fail-closed ──────────────────────────────────────────────────────────── - wall_tree = ((perm_scope.entry(session.user, database) or {}).get("filter") - if perm_scope.row_scope_applies(session.user, database) else None) - wall_nodes, wall_conj = _fe_parts(wall_tree) if wall_nodes: unknown = sorted(sheet_mod.filter_columns_named(wall_nodes) - set(cols)) if unknown: @@ -1759,12 +1841,9 @@ def _resolve_binding(session: Session, raw_binding, *, today=None, view_memo=Non "you on a column this database carries") # ── the binding's own scope ────────────────────────────────────────────────────────────── - scope = binding["scope"] - if scope.get("view_id"): - scope_nodes, scope_conj = _view_filter(session, database, scope["view_id"], - scope.get("view_name", ""), memo=view_memo) - else: - scope_nodes, scope_conj = _fe_parts(scope.get("filter")) + # ⚠ W54-T36 — READ ABOVE, WITH THE WALL, because the mirror is now built over the columns the + # two of them name. The contract's ORDER is unchanged: the wall is still applied and still + # checked against `cols` before the scope reaches the compiler. # ⚠ NOTHING IS DONE HERE ABOUT `needs_excluded`. `_source_for` has already resolved it into the # spec's column expressions; applying it a second time would double-count the exclusion and @@ -1834,6 +1913,129 @@ def preview_cell(workbook_id: str, addr: str, body: dict = Body(default=None), "limits": out["limits"]} +@router.post("/sheets/{workbook_id}/cells/{addr}/compute") +def compute_cell(workbook_id: str, addr: str, body: dict = Body(default=None), + session: Session = Depends(require_session)): + """W54-T32 (instruction 9): recompute ONE stored bound cell and persist just that cell. + + ⭐⭐ THE WHOLE OF THE TICKET IS THAT `refresh_sheet` WAS THE ONLY DOOR THAT COMPUTED. Saving a + binding wrote a `stale` cell and nothing ever resolved it, so the shimmer that means "a number + is coming" ran until somebody pressed Refresh. Refresh answers by recomputing EVERY bound cell + and every formula in the workbook, which is why it is slow and why the save path must not call + it: one cell over `ut_odoo_orders` measured 55 to 90 ms through `preview`, against a whole + workbook pass plus a full document write. + + ⛔ IT IS A WRITE DOOR, so `_require_editor` runs FIRST, exactly as it does on `refresh_sheet` + and for the same C5 reason: this ends in a store write, and a viewer's numbers must never land + in the owner's document. A viewer's own re-resolve still happens in memory on the READ path. + + ⛔⛔ THE STORED `binding` IS NEVER REWRITTEN HERE, AND THAT IS D-674's HALF OF THIS TICKET. + Only `state`, `value`, `display`, `refreshed_at` and `refusal` are touched on a COPY of the + cell; the binding object is carried through verbatim. So a binding that arrived without a + `period` cannot acquire one by being computed, whatever a later editor does with the panel. + + ⛔⛔ AND IT FILLS THE ONE SCOPE-CACHE SLOT IT JUST COMPUTED, WHICH IS THE TRAP IN THIS FILE. + `_reresolved_for_reader` serves a non-owner from `core.sheets.cached_scope_value`, keyed + `(database, wall, binding scope)`; persisting a new number and leaving the old slot behind + would make the very next GET serve the number this door was called to replace. There is no + per-cell clear, and `clear_scope_cache` belongs to `refresh_sheet` alone under R3, so the + surgical answer is `fill_scope_cache` on exactly the slot this caller is entitled to, which is + the same call and the same key `_reresolved_for_reader` makes after its own resolve. + + ⚠ NO FORMULA PASS RUNS HERE, DELIBERATELY. `_recomputed_tab_cells` recomputes the WHOLE + workbook's formulas, which the prototype measured at 2.9 s as a FLOOR for the owner's 11,300 + formulas: fifty times the cost of the one number this door exists to deliver. The client + evaluates its own formulas as the value lands (`sheetState.ts`), the ordinary cell PATCH + already runs the server-side pass on the very next commit, and Refresh still runs it for + everyone. A formula's STORED value therefore stays as last computed until one of those, which + is what a stale bound cell already did before this ticket. + + ⚠ `rev` BUMPS, BECAUSE THIS PERSISTS. It goes back in the answer and the client adopts it, or + its next PATCH would carry a revision the server has already moved past. + """ + from core import sheets + + try: + book = sheets.get_workbook(_store(session), workbook_id) + _require_editor(session, book) + except sheets.SheetRefusal as exc: + raise _refuse(exc) + + key = str(addr or "").replace("$", "").upper() + #: ⚠ THE TAB IS NAMED BY THE CALLER WHEN IT KNOWS ONE, and looked up by address when it does + #: not, which is `drill_cell`'s behaviour. Two tabs may legally hold the same address, so a + #: client that has a tab in hand should say which, or the first one wins. + ref = str((body or {}).get("tab") or "").strip() + tab, cell = None, None + if ref: + try: + tab = sheets.find_tab(book, ref) + except sheets.SheetRefusal as exc: + raise _refuse(exc) + cell = (tab.get("cells") or {}).get(key) + else: + for candidate in book.get("sheets") or (): + if key in (candidate.get("cells") or {}): + tab, cell = candidate, candidate["cells"][key] + break + if not isinstance(cell, dict): + raise err(404, "cell_missing", f"Cell {key} is not filled in.") + if cell.get("kind") != "bound": + raise err(409, "cell_not_bound", f"Cell {key} is not bound to a database.") + + tab_ref = str((tab or {}).get("id") or (tab or {}).get("name") or "") + binding = cell.get("binding") or {} + stamp = _now_iso() + saved = dict(cell) + limits, resolved = [], None + try: + resolved = _resolve_binding(session, binding) + except HTTPException as exc: + #: The same per-cell refusal shape `refresh_sheet` writes, so a cell refused by this door + #: and a cell refused by that one read identically. It is PERSISTED rather than raised: + #: a cell left `stale` would shimmer forever, and the reason belongs on the cell. + detail = getattr(exc, "detail", None) or {} + info = detail.get("error") if isinstance(detail, dict) else None + saved["state"] = "refused" + saved["value"] = None + saved["display"] = "" + saved["refusal"] = { + "code": (info or {}).get("code", "sheet_unresolved"), + "message": (info or {}).get("message", "This cell could not be refreshed."), + } + else: + limits = resolved["limits"] + saved["state"] = "fresh" + saved["value"] = resolved["value"] + saved["display"] = "" if resolved["value"] is None else str(resolved["value"]) + saved["refreshed_at"] = stamp + saved.pop("refusal", None) + + try: + landed = sheets.patch_cells(_store(session), workbook_id, tab_ref, {key: saved}) + except sheets.SheetRefusal as exc: + raise _refuse(exc) + + if resolved is not None: + #: Best effort, exactly as `_reresolved_for_reader` fills its own slot: a cache write that + #: fails costs a future recompute and never a wrong number. + try: + sheets.fill_scope_cache(_store(session), workbook_id, tab_ref + "!" + key, + _binding_scope_key(session, + str(binding.get("database") or ""), + binding), + resolved["value"], stamp) + except Exception: # noqa: BLE001 + pass + + wire = dict(saved) + #: ⚠ `limits` RIDES THE ANSWER AND IS NOT STORED, because `core.sheets.clean_cell` carries no + #: such key: it describes THIS resolve's truncation, not the cell. + if limits: + wire["limits"] = limits + return {"cell": wire, "rev": landed.get("rev"), "tab": tab_ref, "addr": key} + + @router.get("/sheets/{workbook_id}/cells/{addr}/drill") def drill_cell(workbook_id: str, addr: str, session: Session = Depends(require_session)): """`{database, view_id?, filter?, record_ids, count}` for `LinkGridModal` (R6, R13, R17). @@ -1876,13 +2078,12 @@ def drill_cell(workbook_id: str, addr: str, session: Session = Depends(require_s raise err(400, exc.code, exc.message) database = _require_database(session, binding["database"]) - # ⚠ THE SAME PERIOD THE NUMBER WAS COMPUTED AT (W53-T13). The drill probes `COUNT(*)` and never - # reads the bound column, but its FILTER may name a Metric column, and a mirror opened at a - # different window would answer that condition against different values. The popup would then - # list rows the cell's own number never counted. - cur, spec, cols = _mirror(session)( - database, metric_window=sheet_mod.period_window(binding.get("period"))) + # ⭐⭐ W54-T36 — THE WALL AND THE SCOPE ARE READ FIRST, AND THE MIRROR IS BUILT OVER WHAT THEY + # NAME. The drill probes `COUNT(*)` and lists ids, so on a cell whose scope is a plain view or + # an empty filter the honest column set is EMPTY and only the id column is materialised. + # MEASURED on tenant #0's `customer_data` (3,673 records, 47 columns), warm, through this + # route: 8,437 ms, of which 6,137 ms was materialising columns no query here reads. wall_tree = ((perm_scope.entry(session.user, database) or {}).get("filter") if perm_scope.row_scope_applies(session.user, database) else None) wall_nodes, wall_conj = _fe_parts(wall_tree) @@ -1894,6 +2095,19 @@ def drill_cell(workbook_id: str, addr: str, session: Session = Depends(require_s else: scope_nodes, scope_conj = _fe_parts(scope.get("filter")) + # ⚠ THE SAME PERIOD THE NUMBER WAS COMPUTED AT (W53-T13). The drill probes `COUNT(*)` and never + # reads the bound column, but its FILTER may name a Metric column, and a mirror opened at a + # different window would answer that condition against different values. The popup would then + # list rows the cell's own number never counted. + # ⭐ W54-T36 MEASURED WHAT THAT WINDOW COSTS, because the cheaper mirror was the obvious guess: + # `_metric_derived` at a month window is 27 ms of an 8,437 ms drill on `customer_data`. So the + # window is kept UNCONDITIONALLY, exactly as W53-T13 wrote it, and the saving is taken from + # the column set instead, where the time actually is. + cur, spec, cols = _mirror(session)( + database, metric_window=sheet_mod.period_window(binding.get("period")), + needed=(sheet_mod.filter_columns_named(scope_nodes) + | sheet_mod.filter_columns_named(wall_nodes))) + count_sql, count_params, limits = sheet_mod.build_aggregate_query( spec, {"aggregate": {"fn": "count"}}, cols, scope_nodes=scope_nodes, scope_conj=scope_conj, wall_nodes=wall_nodes, wall_conj=wall_conj) @@ -1997,9 +2211,13 @@ def resolve_bindings(workbook_id: str, body: dict = Body(default=None), ⭐⭐ THE BATCH PAYS FOR ITS ASSEMBLY ONCE, WHICH IS MOST OF THE REASON THIS DOOR TAKES A LIST AT ALL. A bound cell on a compiled registry grid (`customer_data`, `product_data`) costs a full workspace assembly - measured at 20 to 130 seconds on this box after W53-T13 - so N cells - resolved one request each would cost N of them. Two memos make one request pay once: + resolved one request each would cost N of them. Three memos make one request pay once: + - `session._sheet_assemblies`, keyed by `table_key` inside `_registry_assembly` (W54-T36), + so the assembly itself is built once per database however many mirrors are cut from it. - `session._sheet_mirrors`, keyed `(table_key, metric_window)` inside `_mirror`, so every - cell on one database at one period shares one assembly and one temp table. It hangs off + cell on one database at one period shares one temp table. W54-T36 also gave each slot the + COLUMN SET it was materialised over: a narrower cell reuses a wider slot, and a cell + naming a column the slot lacks rebuilds at the union rather than per cell. Both hang off the Session, which `require_session` builds fresh per request and drops with it. - `view_memo`, keyed by `view_id`, so a saved-view scope is looked up once for the batch. ⚠ AND IDENTICAL BINDINGS RESOLVE ONCE. Two cells carrying the same database, aggregate, scope diff --git a/platform/core/keychain.py b/platform/core/keychain.py index 231d0d6b2bdf008eed94700f026678d1d5a6148d..3e595010eaf85907eceee6cabe19fe9350b423c8 100644 --- a/platform/core/keychain.py +++ b/platform/core/keychain.py @@ -2,7 +2,7 @@ An admin stores a data source's secrets (Royal's Odoo API key today; any tenant's sources tomorrow) encrypted at rest in the TENANT's store bucket. The runtime posture is R3's -"live with env fallback": the connector layer asks `odoo_creds(rt)` FIRST and falls back to +"live with env fallback": the connector layer asks `odoo_creds(rt, connection_id)` FIRST and falls back to the process environment (tenant #0's `.env` / Space secrets), so Royal keeps working with an empty keychain and a new tenant needs no code to bring keys. The FULL cutover (env retired) is staged for a later wave — R3, verbatim. @@ -14,7 +14,7 @@ decrypts and writes are refused — fail closed, never a plaintext fallback. SHAPE (bucket `keychain`, per-tenant via the runtime handle): - {entries: {id: {id, label, type, enc, preview, created, createdBy}}} + {entries: {id: {id, connection_id, slot, label, type, enc, preview, created, createdBy}}} `enc` = Fernet token over the JSON fields dict. `preview` = a masked hint ("····1234") computed ONCE at write from the entry's most secret-looking field — the ONLY part of a @@ -92,27 +92,129 @@ def _bucket(rt): return rt.get(KEY) or {} +# ═════════════════════════════════════════════════════════════════════════════════════════════ +# ⭐⭐ W54-T44 / OWNER RULING R4 / CONTRACT C4 — A CONNECTION HAS AN IDENTITY. +# ═════════════════════════════════════════════════════════════════════════════════════════════ +# +# R4, verbatim: *"If a tenant is an agency that helps with clients that each have Odoo, then the +# connector for Odoo can be many depending on the API. This is why its critical."* So MANY +# connections of ONE kind coexist, and each one has to be addressable on its own. +# +# ⭐ THE STORAGE ALREADY ALLOWED THIS AND THE READER DID NOT. `add_entry` has always minted a +# fresh `k_` per call with no uniqueness constraint, so a second `odoo` entry was already +# storable — it was simply never READ (every resolver takes the first of its type). This block +# adds the two facts a reader needs in order to tell two connections of one kind apart: +# +# `connection_id` the entry's own id, stamped EXPLICITLY rather than left implicit. It is +# stable, unique, never reused and never re-derived by sorting. +# `slot` an IMMUTABLE per-(tenant, type) ordinal, minted HIGH-WATER, which is what +# makes the default label `Odoo 1` / `Odoo 2` stable and what a namespaced +# table can be keyed on. Deleting a connection must never let a later one +# reuse a retired ordinal, or two different connections would answer to one +# address at two different times. +# +# ⛔ THE READ DEFAULTS ARE READ DEFAULTS AND NEVER A MIGRATION, the same posture `SCOPE_KEY` +# takes below. Rows written before this wave carry neither field: they read back as +# `connection_id = id` and as their 1-based position among entries of their type in the existing +# insertion-id sort. Materialising that on the next read would rewrite a tenant's encrypted +# store to record something already derivable ([[a-migration-that-runs-on-the-next-write]]) — +# and this store's rows are Fernet tokens, so a rewrite is the one operation that can lose a +# credential. Nothing here decrypts anything. + +#: type -> the human word the default label is built from. `generic` has no product name behind +#: it, so it says what it is rather than inventing one. +_KIND_LABELS = {'odoo': 'Odoo', 'meta_ads': 'Meta Ads', 'amazon_sp': 'Amazon', + 'stripe': 'Stripe', 'shopify': 'Shopify', 'generic': 'Connection'} + + +def kind_label(etype): + """The human word for a connection type, for a default label. Never blank.""" + return _KIND_LABELS.get(str(etype or '').strip().lower()) or 'Connection' + + +def connection_id_of(entry, entry_id): + """A stored row's stable connection id — its own `connection_id`, else its entry id. + + ⚠ A NAMED FUNCTION RATHER THAN AN INLINE `or`, so that the identity has ONE derivation a gate + can break in memory: the negative control for "two connections stay two" needs somewhere to + collapse them. + """ + return str((entry or {}).get('connection_id') or entry_id) + + +def slot_of(entry, ordinal): + """A stored row's slot — its own `slot` when it has one, else the read default `ordinal`. + + ⚠ `ordinal` is the caller's 1-based position among entries of the SAME type, in the same + insertion-id sort every resolver already uses. A stored slot always wins, which is what makes + the field immutable once written. + """ + try: + n = int((entry or {}).get('slot') or 0) + except (TypeError, ValueError): + n = 0 + return n if n >= 1 else int(ordinal) + + def list_entries(rt): - """Metadata ONLY — never a decrypted field, never `enc` itself.""" + """Metadata ONLY — never a decrypted field, never `enc` itself. + + Every row carries `connection_id` and `slot` (W54-T44 / C4). Rows may GAIN keys here and must + never LOSE one: `verify_api` asserts the listing has no `enc` / `url` / `api_key` / `fields`, + and several callers read these rows by key. + """ out = [] + seen = {} for eid, e in sorted((_bucket(rt).get('entries') or {}).items()): if not isinstance(e, dict): continue - out.append({'id': eid, 'label': e.get('label') or eid, - 'type': e.get('type') or 'generic', + etype = e.get('type') or 'generic' + seen[etype] = ordinal = seen.get(etype, 0) + 1 + out.append({'id': eid, + 'connection_id': connection_id_of(e, eid), + 'slot': slot_of(e, ordinal), + 'label': e.get('label') or eid, + 'type': etype, 'preview': e.get('preview') or '', 'created': e.get('created') or '', 'createdBy': e.get('createdBy') or ''}) return out +def next_slot(rt, etype): + """The slot a NEW connection of `etype` takes: one above the highest this tenant has ever + shown for that type. Never decrypts anything. + + ⛔ HIGH-WATER, NOT A COUNT. `len(entries of this type) + 1` would hand a retired ordinal to a + new connection the moment one is deleted — two different credentials answering to `Odoo 2`, + a month apart, with every table W54-T46 namespaces on that ordinal pointing at the wrong one. + ⚠ It reads through `list_entries`, so a row written before this wave counts at its READ + DEFAULT rather than at zero: a tenant with two un-stamped Odoo entries gets 3, not 1. + """ + etype = str(etype or '').strip().lower() + top = 0 + for row in list_entries(rt): + if row.get('type') == etype: + try: + top = max(top, int(row.get('slot') or 0)) + except (TypeError, ValueError): + continue + return top + 1 + + def add_entry(rt, label, etype, fields, username): """Encrypt + store. Returns the metadata row, or raises ValueError on shape problems and - KeychainLocked when there is no key (a secret must never be stored in the clear).""" + KeychainLocked when there is no key (a secret must never be stored in the clear). + + ⭐ W54-T44 / C4 — the row is stamped with its `connection_id` and its `slot`, and a caller + that supplies NO label gets the default the slot names: the tenant's first Odoo connection is + `Odoo 1`, the second `Odoo 2`. An explicitly supplied label always wins, and the label stays + the user's to change afterwards (`rename_entry`). + ⚠ THE TYPE IS VALIDATED FIRST NOW, because the default label is built from it: a blank label + on an unknown type must still be told about the type, which is the fixable half. + """ label = ' '.join(str(label or '').split())[:80] etype = str(etype or '').strip().lower() - if not label: - raise ValueError('give the key a label') if etype not in ENTRY_TYPES: raise ValueError(f"type must be one of {', '.join(sorted(ENTRY_TYPES))}") if not isinstance(fields, dict) or not fields: @@ -128,7 +230,11 @@ def add_entry(rt, label, etype, fields, username): secretish = next((clean[k] for k in _PREVIEW_FIELDS if clean.get(k)), '') preview = ('····' + secretish[-4:]) if len(secretish) >= 4 else ('····' if secretish else '') eid = f'k_{_secrets.token_hex(6)}' - row = {'id': eid, 'label': label, 'type': etype, 'enc': token.decode('ascii'), + slot = next_slot(rt, etype) + if not label: + label = f'{kind_label(etype)} {slot}' + row = {'id': eid, 'connection_id': eid, 'slot': slot, + 'label': label, 'type': etype, 'enc': token.decode('ascii'), 'preview': preview, 'created': _dt.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'), 'createdBy': str(username or '')} @@ -141,10 +247,42 @@ def add_entry(rt, label, etype, fields, username): return cur rt.update(KEY, _up, flush='sync') - return {'id': eid, 'label': label, 'type': etype, 'preview': preview, + return {'id': eid, 'connection_id': eid, 'slot': slot, + 'label': label, 'type': etype, 'preview': preview, 'created': row['created'], 'createdBy': row['createdBy']} +def rename_entry(rt, entry_id, label): + """Give ONE connection a new name. Returns its metadata row, or None when there is no such + entry. Raises ValueError on a blank name. + + ⛔ THE LABEL AND NOTHING ELSE. `enc`, `connection_id`, `slot`, `preview`, `created` and + `createdBy` are left exactly as they were, and no other row is touched — that is the whole + contract of a rename under R4, where two connections of one kind sit side by side and + renaming one must not disturb the other. + ⛔ AND IT DECRYPTS NOTHING. A stored secret is never re-openable and a rename has no business + asking for the key: this works on a LOCKED keychain, where re-encrypting a row to change a + display string would refuse (or, worse, rewrite a Fernet token to alter a label). + """ + label = ' '.join(str(label or '').split())[:80] + if not label: + raise ValueError('give this connection a name') + eid = str(entry_id) + found = [] + + def _up(cur): + row = (cur.get('entries') or {}).get(eid) + if isinstance(row, dict): + row['label'] = label + found.append(True) + return cur + + rt.update(KEY, _up, flush='sync') + if not found: + return None + return next((e for e in list_entries(rt) if e['id'] == eid), None) + + def delete_entry(rt, entry_id): def _drop(cur): (cur.get('entries') or {}).pop(str(entry_id), None) @@ -174,12 +312,19 @@ def read_fields(rt, entry_id): def first_entry_of_type(rt, etype): - """The metadata row of the FIRST entry of `etype`, or None. Never decrypts anything. - - ⭐ W35-T45 — the same "first, by insertion-id sort" rule `_first_creds` resolves on, exposed as - an IDENTITY question rather than a credential one. `ensure_entry_of_type` needs to know whether - an entry exists WITHOUT unlocking it, and `list_entries` + a hand-rolled `next()` at each caller - is how two places come to disagree about which entry is "the" one. + """DOES THIS TENANT HAVE ANY ENTRY OF `etype` AT ALL? The first such metadata row, or None. + Never decrypts anything. + + ⛔⛔ W54-T45 — THIS IS AN EXISTENCE QUESTION AND NOTHING ELSE, AND THE NAME IS THE ONLY THING + LEFT THAT SUGGESTS OTHERWISE. It used to be the identity twin of `_first_creds`: "which entry + serves" and "does one exist" were the same walk, which is exactly the coupling contract C4 + exists to break. Under R4 a tenant may hold MANY Odoo connections, so "the first one" is no + longer an answer to "which credential serves this connector" — that question is now + `default_connection_id` / `_creds_for`, which resolve on a `connection_id` and order on the + immutable `slot`. ⛔ Do not route any credential path back through here. + What survives is the migration/idempotency question `ensure_entry_of_type` asks below, and + `verify_api` asks in three places as a "nothing was written" probe: both of those genuinely + mean *is there one*, not *which one*. """ return next((e for e in list_entries(rt) if e.get('type') == str(etype or '')), None) @@ -188,9 +333,11 @@ def ensure_entry_of_type(rt, etype, label, fields, username): """Create ONE entry of `etype` only if the tenant has none. `(row, why)`; `row` is None on skip. ⭐ W35-T45 / R11 — the primitive tenant #0's env-to-keychain migration is built from, and the - reason it lives here is that only this module knows what "already has one" means: `odoo_creds` - resolves to the FIRST entry of a type, so a second one would be stored, invisible in every - resolver, and impossible to tell from the one that serves. + reason it lives here is that only this module knows what "already has one" means. + ⚠ W54-T45 SOFTENED WHAT IS AT STAKE WITHOUT CHANGING THIS FUNCTION. A second entry of a type + is no longer invisible: under R4 it is a second CONNECTION with its own `connection_id`, and + every resolver can address it. What this still prevents is a MIGRATION running twice and + quietly minting `Odoo 2` out of the same environment variables `Odoo 1` came from. ⛔ IDEMPOTENT BY TYPE, NOT BY A FLAG. A migration that keys idempotency on a marker it writes itself is one lost marker away from running twice ([[a-migration-that-runs-on-the-next-write]]); @@ -219,13 +366,24 @@ def ensure_entry_of_type(rt, etype, label, fields, username): return None, f'{type(exc).__name__}: {exc}' -def odoo_creds(rt): - """R3's resolver seam: the FIRST odoo-type entry's fields, else None (the caller falls - back to the environment). Deterministic order = insertion-id sort, so 'first' is stable.""" - return _first_creds(rt, 'odoo') +def odoo_creds(rt, connection_id=None): + """R3's resolver seam: the fields of the odoo connection NAMED by `connection_id`, else None. + + ⭐⭐ W54-T45 / R4 / C4 — IT TAKES A CONNECTION NOW, AND THAT IS THE WHOLE TICKET. An agency + tenant holds one Odoo connection per client, so "the tenant's Odoo credential" is not a + question with one answer any more. `connection_id` names WHICH one; a `connection_id` that + names no entry of this type resolves to None and never to a sibling. + ⚠ NO ID MEANS THE DESIGNATED DEFAULT (`default_connection_id`), which is the lowest-`slot` + connection of the type. Every existing one-argument call site therefore keeps working and now + means exactly that, rather than "whichever row happened to sort first". + ⛔ None here still means "not configured", and the CALLER decides what that entails: + `harness/runtime.py::odoo_source` falls back to tenant #0's compiled environment only when no + connection was NAMED. + """ + return _creds_for(rt, 'odoo', connection_id) -def meta_creds(rt): +def meta_creds(rt, connection_id=None): """W31 (R2): the FIRST `meta_ads` entry's fields, else None — the Meta connector's resolver. ⭐⭐ W49-T13 / D-202 — IT HAS A PRODUCTION CALLER NOW, AND THAT WAS THE WHOLE DEFECT. @@ -246,11 +404,15 @@ def meta_creds(rt): is no equivalent for Meta: `META_ADS_ACCESS_TOKEN` is the OWNER's measurement token (R8), and handing it to a tenant whose admin has not stored one is precisely the leak the R3 rule exists to prevent. A tenant with no entry gets None, and the connector says so. + + ⭐ W54-T45 / R4 — `connection_id` NAMES WHICH Meta connection, and no id means the tenant's + DESIGNATED DEFAULT (the lowest-`slot` `meta_ads` connection), not "whichever row sorts first". + An id that names no `meta_ads` entry resolves to None, never to a sibling. """ - return _first_creds(rt, 'meta_ads') + return _creds_for(rt, 'meta_ads', connection_id) -def amazon_creds(rt): +def amazon_creds(rt, connection_id=None): """W52: the FIRST `amazon_sp` entry's fields, else None — the Amazon connector's resolver. ⛔ THE SAME SHAPE AND THE SAME IMPLEMENTATION AS `odoo_creds` / `meta_creds`, deliberately. @@ -266,8 +428,14 @@ def amazon_creds(rt): ⚠ AND IT RETURNS THE WHOLE FIELD SET, not one secret: an Amazon credential is five values (`client_id`, `client_secret`, `refresh_token`, `seller_id`, `marketplace_id`) and the client needs three of them just to mint an access token. + + ⭐ W54-T45 / R4 — `connection_id` NAMES WHICH Amazon connection, and no id means the tenant's + DESIGNATED DEFAULT (the lowest-`slot` `amazon_sp` connection), not "whichever row sorts + first". An id that names no `amazon_sp` entry resolves to None, never to a sibling. + ⚠ `amazon_creds(None)` — a MISSING RUNTIME, not a missing id — still answers None rather than + raising; `verify_amazon` asserts exactly that, and the guard lives in `_creds_for`. """ - return _first_creds(rt, 'amazon_sp') + return _creds_for(rt, 'amazon_sp', connection_id) #: ⭐⭐ WAVE 32 (R4 / contract C1) — THE SCOPE SIDE-BUCKET, READ HERE, WRITTEN NOWHERE IN THIS FILE. @@ -284,8 +452,9 @@ def amazon_creds(rt): SCOPE_KEY = 'keychain_scopes' #: The credential types a WHOLE WORKSPACE reads through, which therefore cannot be personal. -#: ⛔ THE ELEVATION THIS PREVENTS, in B's words: `odoo_creds`/`meta_creds` resolve to *the first -#: entry of that type for the TENANT* — that is what spawns every `ut_odoo_*` / `ut_meta_*` grid and +#: ⛔ THE ELEVATION THIS PREVENTS, in B's words: `odoo_creds`/`meta_creds` resolve to *a connection +#: of that type for the TENANT* (W54-T45: the one a caller NAMES, or the tenant's designated +#: default when none is named) — that is what spawns every `ut_odoo_*` / `ut_meta_*` grid and #: what every measure column is answered from. So a member storing a personal Odoo key would not get #: "their own Odoo": they would silently become the credential the entire workspace's databases are #: built from. **A credential elevation wearing a scope picker.** @@ -310,9 +479,114 @@ def _personal_ids(rt): if isinstance(v, dict) and str(v.get('scope') or '') == 'personal') -def _first_creds(rt, etype): - """The first entry of `etype`, decrypted — or None. Deterministic order = insertion-id sort, - so "first" is stable across reads rather than dict-order luck. +# ═════════════════════════════════════════════════════════════════════════════════════════════ +# ⭐⭐ W54-T45 / R4 / CONTRACT C4 — EVERY READER NAMES WHICH CONNECTION IT WANTS. +# ═════════════════════════════════════════════════════════════════════════════════════════════ +# +# What stood here was `_first_creds(rt, etype)`, and one line of it — "return the first entry of +# this type" — was the whole ceiling on R4. Storage already held many connections of one kind +# (W54-T44 gave each of them an id and a slot); every READER collapsed them back to one. An +# agency with two clients on Odoo could store both credentials, see both rows, rename both, and +# be served the first one for every question either client asked. That is not a missing feature, +# it is R7's isolation rule failing silently: one client's numbers answering another's screen. +# +# ⛔ THE HELPER IS NOT NAMED "FIRST" ANY MORE, ON PURPOSE. A shared body called `_first_creds` is +# how the defect would grow back one connector at a time: the next resolver copies the name and +# inherits the rule. `_creds_for` asks the question the contract asks — *which stored credential +# serves this connector, for this connection?* +# +# ⛔ RESOLVE ON IDS, ORDER ON SLOTS, and the distinction is MEASURED, not stylistic: a pre-wave +# row's read-default `slot` MOVES when a sibling of its type is deleted (2 -> 1) while its +# `connection_id` does not. So `connection_id` is the ADDRESS a caller passes and holds, and +# `slot` is only how the tenant's DESIGNATED DEFAULT is picked and how connections are ordered +# on a screen. A caller that stored a slot as an address would eventually address another +# client's credential. + + +def default_connection_id(rt, etype): + """THE TENANT'S DESIGNATED DEFAULT connection of `etype` — its `connection_id`, or None. + Never decrypts anything. + + ⛔⛔ A DESIGNATED DEFAULT PINNED BY AN IMMUTABLE ORDINAL, NOT "WHICHEVER ROW HAPPENS TO SORT + FIRST", AND THAT DISTINCTION IS THE POINT OF THIS WHOLE TICKET. The rule is the LOWEST `slot` + — the per-(tenant, type) ordinal `add_entry` mints high-water and never rewrites — with ties + broken by the existing insertion-id order so the answer is total and stable. "First of its + type" was an accident of dict ordering that a delete, a re-key or a store rewrite could move + under a caller's feet; the lowest slot is a decision the tenant made when it added its first + connection. + ⚠ Personal entries of a tenant-wide type are skipped exactly as `_creds_for` skips them, so + the default and the credential can never disagree about which connection serves. + ⚠ AND IT IS A DEFAULT, NEVER A FALLBACK. It answers "no id was named"; it is not consulted + when an id WAS named and failed to resolve, because serving a sibling to a caller that asked + for a specific client is the leak R7 forbids. + """ + if rt is None: + return None + etype = str(etype or '').strip().lower() + skip = _personal_ids(rt) if etype in TENANT_WIDE_TYPES else frozenset() + best = None + for pos, row in enumerate(list_entries(rt)): + if row['type'] != etype or str(row['id']) in skip: + continue + rank = (int(row['slot']), pos) + if best is None or rank < best[0]: + best = (rank, str(row['connection_id'])) + return best[1] if best is not None else None + + +def _row_for(rt, connection_id, etype=None): + """The metadata row `connection_id` addresses, or None. Never decrypts anything. + + Matches on the row's `connection_id` and, for rows written before W54-T44, on its entry id — + which `connection_id_of` makes the same value anyway. When `etype` is asserted, a row of a + DIFFERENT type is None rather than a match: an id is only an address within the connector + that was asked for. + ⛔ A personal entry of a tenant-wide type is None here too, even when named EXPLICITLY. The + wave-32 skip is a credential-elevation guard, not a tie-breaker, and letting an explicit id + walk past it would reopen the door from the one side that stayed shut. + """ + if rt is None: + return None + want = str(connection_id or '') + if not want: + return None + etype = str(etype or '').strip().lower() + for row in list_entries(rt): + if str(row['connection_id']) != want and str(row['id']) != want: + continue + rtype = str(row['type'] or '') + if etype and rtype != etype: + return None + if rtype in TENANT_WIDE_TYPES and str(row['id']) in _personal_ids(rt): + return None + return row + return None + + +def resolve_connection_id(rt, etype, connection_id=None): + """WHICH connection of `etype` would serve — an IDENTITY, decrypting nothing. None when + nothing would. + + ⛔ IT EXISTS SO THERE IS GENUINELY ONE RESOLVER. `harness/runtime.py::odoo_flag_key` needs the + identity of the serving connection without opening it (a pause flag must still resolve on a + LOCKED keychain), and its docstring has always claimed to be that one resolver while carrying + an inline first-entry walk of its own. This is the walk it now calls instead. + ⚠ The answer is a `connection_id`, which for every stored row equals that row's entry id + (`add_entry` stamps them the same and `connection_id_of` defaults the older rows to it), so + the pause flags written against the old resolution keep resolving. + """ + if connection_id is None: + return default_connection_id(rt, etype) + row = _row_for(rt, connection_id, etype) + return str(row['connection_id']) if row else None + + +def connection_creds(rt, connection_id, etype=None): + """THE fields of the ONE connection `connection_id` addresses, decrypted — or None. + + ⭐⭐ W54-T45 / C4 — the reader the contract asks for: *"`keychain.odoo_creds` and every other + first-entry reader must take a `connection_id`."* Two connections of one kind therefore return + two different credential sets for two different ids, which is the agency case R4 names. ⚠ A MISSING RUNTIME ANSWERS None RATHER THAN RAISING, AND THE GUARD IS HERE ON PURPOSE. Every caller's contract is already "the tenant's credential, or None", and `None` means exactly @@ -321,7 +595,7 @@ def _first_creds(rt, etype): implementation did not keep. Found by `verify_amazon` asserting the contract rather than the behaviour. ⛔ FIXED HERE AND NOT IN ONE RESOLVER, because this module's own rule is that "which stored credential serves this connector" has ONE implementation: patching `amazon_creds` - alone would have created the second normalizer the file warns about two functions up. + alone would have created the second normalizer this file warns about. ⭐⭐ WAVE 32 (R4/C1) — A PERSONAL ENTRY OF A TENANT-WIDE TYPE IS SKIPPED, NOT SERVED. `routes_keychain` REFUSES to create one, and that closes the door from the only side B owns; @@ -335,14 +609,31 @@ def _first_creds(rt, etype): into an outage for a workspace that has a perfectly good business entry two rows down. ⚠ AND THE SKIP IS SCOPED TO `TENANT_WIDE_TYPES`. A personal entry of any OTHER type is a normal personal credential and this resolver is not how it is reached. + ⚠ A LOCKED KEYCHAIN STILL RAISES `KeychainLocked`, from `read_fields`. "No key on this + deployment" is an operator fact and silently empty creds would read as "not configured". + """ + row = _row_for(rt, connection_id, etype) + return read_fields(rt, row['id']) if row else None + + +def _creds_for(rt, etype, connection_id=None): + """THE ONE INTERNAL HELPER behind `odoo_creds` / `meta_creds` / `amazon_creds`: the fields of + the `etype` connection named by `connection_id`, or of the tenant's designated default when + no id is named. None when nothing serves. + + ⛔ IT REPLACES `_first_creds`, NAME INCLUDED. "Which stored credential serves this connector" + has ONE implementation in this module, and the old one answered a question C4 forbids. + ⛔ A NAMED CONNECTION THAT DOES NOT RESOLVE IS None, FULL STOP — never the default, never a + sibling, and (at the caller) never the environment. Falling back after an explicit ask is how + one client's Odoo comes to answer another client's question under R7's strict isolation. """ if rt is None: return None - skip = _personal_ids(rt) if etype in TENANT_WIDE_TYPES else frozenset() - for row in list_entries(rt): - if row['type'] == etype and str(row['id']) not in skip: - return read_fields(rt, row['id']) - return None + if connection_id is None: + connection_id = default_connection_id(rt, etype) + if connection_id is None: + return None + return connection_creds(rt, connection_id, etype) # --------------------------------------------------------------------------------------------- diff --git a/platform/core/perm_scope.py b/platform/core/perm_scope.py index cd76e98fb52b9f954422f2921b1a21325083dfb0..de0a35a7606287201446a71f6e90e21c10b35c06 100644 --- a/platform/core/perm_scope.py +++ b/platform/core/perm_scope.py @@ -1980,3 +1980,321 @@ def pivot_scope(user, source, target, st=None, path=None): return PivotScope(user, src, tgt, walk, source_scope=derive_pool_scope(user, src), target_scope=derive_pool_scope(user, tgt)) + + +# ── C4 / R4: THE CONNECTOR AXIS — WHO MAY CREATE A CONNECTION (wave 54, W54-T47) ────────────── +#: The per-tenant bucket one administrator's decision lives in: `{username: [, …]}`. +#: +#: ⛔⛔ AN ABSENT ROW AND "NO GRANT" ARE THE SAME THING, AND THAT IS WHY THIS IS A READ DEFAULT +#: RATHER THAN A MIGRATION. `routes_keychain.SCOPE_KEY` carries the identical posture one layer up +#: (*"a business entry writes no row — it IS the default"*), and the reason is +#: [[a-migration-that-runs-on-the-next-write]]: materialising an empty grant for every account in +#: every tenant would rewrite the store on the next read, for a fact nobody decided. +CONNECTOR_GRANT_KEY = 'connector_grants' + + +def connector_grants(username, st=None): + """The connector kinds `username` has been granted, lower-cased, as a frozenset. + + ⚠ THE ANSWER TO AN UNREADABLE STORE IS THE EMPTY SET, AND HERE THAT IS THE SAFE DIRECTION + RATHER THAN THE UNSAFE ONE — the opposite of `user_generated_fields`, which must answer `None`. + That function's answer is PRUNED AGAINST, so a degraded read would delete a live rule; this one + only ever WIDENS what a member may do (see `may_add_connection`), so a degraded read leaves the + member with exactly the rights they had before this ticket existed. Under-granting is visible + and reportable; over-granting is a credential elevation. + """ + if st is None: + return frozenset() + uname = str(username or '').strip().lower() + if not uname: + return frozenset() + try: + rows = st.get(CONNECTOR_GRANT_KEY) or {} + except Exception: # noqa: BLE001 + return frozenset() + if not isinstance(rows, dict): + return frozenset() + got = rows.get(uname) + if not isinstance(got, (list, tuple, set, frozenset)): + return frozenset() + return frozenset(str(k).strip().lower() for k in got if str(k or '').strip()) + + +def may_add_connection(user, etype, st=None): + """May this account create a WORKSPACE-WIDE connection of kind `etype`? (W54-T47 / R4 / C4.) + + ⭐⭐ THE THIRD GRANT AXIS. Owner, verbatim: *"Under Settings, an Admin should grant a user + access to add connectors, so access becomes Database / Module / Connector. This allows many + connectors per tenant … depending on the admin's configuration per user."* Database and Module + are the two groups `PermsEditor.tsx` already renders off `perms`; this is the third, and it is + a per-KIND answer rather than a single boolean because R4's agency tenant is the whole case: + one member may be the person who wires up Shopify and not the person who wires up Odoo. + + ⛔⛔ ABSENCE WIDENS NOTHING AND REVOKES NOTHING, AND THAT IS THE MOST IMPORTANT PROPERTY OF + THIS FUNCTION. No grant was STORABLE before this ticket, so every account in every tenant + carries none — reading that absence as DENY at the connection door would revoke personal + connections for everybody on the day this shipped, with nobody having decided anything. That + is `may_metrics`' argument one file over, in the same words, and the resolution is the same: + this predicate is consulted ONLY on the path that was already refused + (`routes_keychain.add_key`'s `scope == "business" and not session.admin` leg), so a member with + no grant meets byte-identical behaviour — 403 `not_admin` on a business-wide create, 400 + `scope_not_available` on a tenant-wide personal one, and their own personal connection of an + ordinary type still succeeds. An explicit grant is the ONLY thing this adds, and all it can do + is admit. + + ⛔ AN ADMIN IS ALWAYS TRUE, before the store is touched — break-glass, as every predicate in + this file opens, and it is what keeps a tenant whose grant bucket cannot be read from losing + its own administrator's ability to connect anything. + + ⚠ `st` IS THE TENANT HANDLE AND OMITTING IT DENIES A NON-ADMIN. The grant is per TENANT, so a + caller that cannot lend a handle is asking about no workspace in particular; answering from the + process-default store is the D-612 shape (`nav_may_open`'s leg 3), and there the wrong answer + was reachable in BOTH directions. Here the handle-less answer is the pre-ticket one, so a door + that has not learned to thread `st` refuses rather than admitting somebody else's grant. + + ⚠ IT IS NOT A SECOND SPELLING OF ELIGIBILITY. `routes_keychain.allowed_scopes` answers what the + SOURCE permits (Odoo is workspace-wide by construction); this answers who may act on it. Both + must hold, and a tenant-wide type refused to a personal scope stays refused for everybody, + grant or no grant. + """ + if perms.is_admin(user): + return True + kind = str(etype or '').strip().lower() + if not kind: + return False + return kind in connector_grants((user or {}).get('username'), st=st) + + +# ── C4 / R7: THE CONNECTION AXIS — ONE READ, ONE CONNECTION (wave 54, W54-T49) ───────────────── +#: ⭐⭐ RULING R7, verbatim: *"Multi-connection isolation is STRICT, on the Business Unit pattern. +#: Every Odoo-reading module gains a connection selector; picking one client shows only that +#: client's numbers. ⛔ There is no 'All' option that blends two clients."* +#: +#: ⛔⛔ AND THE FAILURE THIS SECTION EXISTS TO PREVENT IS ON THE **VALUES** AXIS, WHICH IS WHY IT +#: LOOKS FINE. Wave 51's tenancy defect ran for a whole wave with a correct-looking row LIST while +#: `rev`, `ly`, `ltm`, `aov` and `est_missed` were silently two clients' numbers added together — +#: `_PUSHDOWN_OPS`' own note above is that incident's record. A connection scope is therefore not +#: a post-filter over rows: it decides WHICH TABLE is read at all, before a row exists to filter. +#: +#: ⭐ THE PRECEDENT IS `derive_pool_scope`, NOT A PICKER. `pages.py::bu_control` builds a BU +#: control from `perms.allowed_bu_labels`, but `pages.py::_BUILDERS` is `{}` on purpose and +#: `verify_api` asserts that emptiness, so that assembly is unreachable in production. The live BU +#: pattern is the per-request DERIVATION twenty lines up, and this is its shape one axis over. +#: +#: ⛔ IT TAKES NO PRINCIPAL, DELIBERATELY, AND THAT IS NOT AN OVERSIGHT TO TIDY. WHICH connection +#: serves is a property of the workspace and of the request, never of the reader: there is no +#: per-user connection grant in this product (`may_add_connection` governs who may CREATE one, a +#: different question), so a `user` parameter here would read as a wall this function does not +#: have. The reader's wall is `may_read` on the table key the scope resolves to, and it composes +#: AFTER this one, unchanged. + +#: What a LEGACY (bare) table key's owner is called when the workspace has no stored connection at +#: all to name — every tenant before this wave, tenant #0 included. +#: +#: ⛔ RESTATED FROM `odoo_relational.DEFAULT_CONNECTION` RATHER THAN IMPORTED, because `core` never +#: imports up (`platform/ARCHITECTURE.md`). It is the same restatement `_FORMULA_REF` at the top of +#: this file makes, with the same guard: `verify_scopes` asserts the two spell the same word, so a +#: rename in the API layer cannot leave this copy behind [[constant-two-features-share]]. +DEFAULT_CONNECTION = 'default' + +#: The connector kind a scope answers for when a caller names none. `odoo` is the only kind that +#: spawns per-connection tables today (W54-T46); the parameter exists so the second one needs no +#: second function. +DEFAULT_CONNECTION_TYPE = 'odoo' + + +class UnknownConnection(LookupError): + """A NAMED connection does not resolve in this workspace. + + ⛔⛔ RAISED, NEVER FALLEN BACK FROM, and that asymmetry IS R7. `keychain.default_connection_id` + answers *"no id was named"*; it is not consulted when an id WAS named and failed to resolve, + because serving a sibling to a caller that asked for a specific client is exactly the leak this + contract forbids. `odoo_relational.connection_namespace` and `runtime.odoo_source` already hold + that posture, and this is the third place it has to hold or the first two are decoration. + """ + + +class ConnectionScope: + """⭐⭐ CONTRACT C4 / R7 — the ONE connection a read is scoped to. Blending is UNREPRESENTABLE. + + Built by `connection_scope()` and by nothing else worth building: it holds a SINGLE + `connection_id` string, there is no member that can hold two, and the constructor refuses + anything that is not one non-empty id. So "read both clients" is not a value this type can + carry — it is not a flag that happens to be off, which is the difference between a rule and a + default. A list, an empty string and the word "all" all arrive here as a refusal. + + ⚠ IT HOLDS THE TYPE TOO, so an odoo scope can never be handed to a meta_ads reader as though + an id were an address across connectors. `keychain._row_for` makes the same statement one layer + down (*"an id is only an address within the connector that was asked for"*). + """ + __slots__ = ('connection_id', 'etype') + + def __init__(self, connection_id, etype=DEFAULT_CONNECTION_TYPE): + cid = connection_id.strip() if isinstance(connection_id, str) else '' + if not cid: + raise UnknownConnection( + 'a connection scope is exactly one connection. Name a single connection, or ' + 'name none and the workspace default serves.') + self.connection_id = cid + self.etype = str(etype or DEFAULT_CONNECTION_TYPE).strip().lower() + + def __repr__(self): + return f'ConnectionScope({self.connection_id!r}, {self.etype!r})' + + def owner_of(self, table_key, rt=None): + """WHICH connection owns `table_key`, through the registered owner. `None` for a key no + connector claims. + + ⛔ NO REGISTRAR IS `Unresolvable`, NOT `False`. The question "whose table is this" is + answered in the API layer (`odoo_relational.connection_for_table_key`) and `core` never + imports up, so a process that never registered one cannot answer it — and a wall that + cannot be evaluated must say so with its cause and a recommendation rather than quietly + admitting or quietly refusing. That is standing rule 1's second sentence, and it is the + same shape `_read_user_table` uses when no mirror reader is registered. + """ + key = str(table_key or '').strip() + if _CONNECTION_OWNER is None: + raise Unresolvable( + subject='connection', effect='unresolvable', + cause=(f"'{key}' cannot be attributed to a connection in this process because no " + f'connection owner is registered'), + recommendation=('call `perm_scope.register_connection_owner(...)` from the app ' + 'layer before scoping a read, or read through the API')) + owner = _CONNECTION_OWNER(key, rt) + return str(owner) if owner else None + + def covers(self, table_key, rt=None): + """Does `table_key` belong to THIS connection? + + ⛔ FAIL CLOSED. An unanswerable question is a NO here, never a pass: a key no connector + claims, an owner that cannot be resolved and a missing registrar all answer False, because + the only thing "I do not know whose this is" can safely mean under R7 is "not yours". + """ + try: + return self.owner_of(table_key, rt) == self.connection_id + except Exception: # noqa: BLE001 + return False + + def require(self, table_key, rt=None): + """`table_key` itself, or `Denied` when it belongs to another connection. + + ⛔ THE WALL, AND IT IS ONE SENTENCE ON REFUSAL (DESIGN section 4). `covers` is the + predicate a caller may branch on; this is the door a reader passes through, so that a + route which forgets to branch fails CLOSED rather than reading the other client's table. + """ + key = str(table_key or '').strip() + owner = self.owner_of(key, rt) + if owner != self.connection_id: + raise Denied(f"'{key}' belongs to another connection. Switch the connection selector " + f'to the one that owns it.') + return key + + +#: WHO answers "which connection owns this table key", declared by the app layer. +#: `reader(table_key, rt) -> connection_id | None`. +#: +#: ⛔ A REGISTRATION SLOT AND NOT AN IMPORT, for the reason `_ROW_SOURCES` and `_MIRROR_READER` +#: above are, and `keychain.register_prober` one file over: the inverse lives in +#: `aios-web/api/odoo_relational.py` (`connection_for_table_key`), `core` never imports up, and +#: `verify_meta` asserts that fence. The app tells this layer rather than being interrogated by it. +_CONNECTION_OWNER = None + + +def register_connection_owner(reader): + """Declare THE reader for "whose table is this" — one reader, because a table has one owner. + + Returns the registrar's own answer, exactly as `register_mirror` does, so the read door and + the write door of this fact have one construction site rather than two. + """ + global _CONNECTION_OWNER + _CONNECTION_OWNER = reader + return _CONNECTION_OWNER is not None + + +def connection_scope(rt, etype=DEFAULT_CONNECTION_TYPE, connection_id=None): + """The ONE connection this read is scoped to, as a `ConnectionScope`. R7's derivation. + + ⭐⭐ ABSENCE CHANGES NOTHING, AND THAT IS THE PROPERTY THAT LETS THIS SHIP. `connection_id=None` + means *"no connection was named"* and resolves to the workspace's DESIGNATED DEFAULT — the same + connection `keychain._creds_for`, `odoo_relational.connection_namespace` and every pre-ticket + reader already served, resolved by the same `keychain.default_connection_id`. A tenant with one + connection therefore cannot tell this function exists, which is what every ticket in this lane + has preserved for the same reason (W54-T44's read defaults, T46's legacy keys, T47's grant). + + ⛔ A NAMED CONNECTION THAT DOES NOT RESOLVE IS `UnknownConnection`, NEVER THE DEFAULT. See that + class; the fallback is the leak. + + ⛔⛔ AND THERE IS NO "ALL". `None` is the only absence this function has, and it pins exactly + one connection rather than widening to every connection. An empty string, the word "all", a + LIST of ids and any non-string are refused BY CONSTRUCTION rather than by enumeration: only a + single non-empty string can address a connection, so the vocabulary cannot express a blend for + a future caller to discover. That is the wave-51 lesson in the shape of a type — there the + filter vocabulary widened underneath a reader that could not read it, and the numbers merged. + + ⚠ `rt=None` WITH A NAMED CONNECTION REFUSES rather than answering from the process-default + store, which is D-612's shape (`nav_may_open` leg 3): a caller with no workspace handle is + asking about no workspace in particular. + """ + kc = _keychain() + if connection_id is None: + cid = kc.default_connection_id(rt, etype) if rt is not None else None + # No connection is stored at all: the legacy keys still belong to "whichever connection is + # designated default", which is a real answer rather than an absence, and it is the same + # sentinel `connection_for_table_key` hands back for exactly this case. + return ConnectionScope(cid or DEFAULT_CONNECTION, etype) + named = connection_id.strip() if isinstance(connection_id, str) else '' + if not named: + raise UnknownConnection( + 'name one connection, or name none and the workspace default serves.') + cid = kc.resolve_connection_id(rt, etype, named) if rt is not None else None + if not cid: + raise UnknownConnection( + f"'{named}' does not name a connection in this workspace. Pick a connection in the " + f'Connectors panel and read it again.') + return ConnectionScope(cid, etype) + + +def connection_options(rt, etype=DEFAULT_CONNECTION_TYPE): + """The connections a selector may offer, in slot order: `[{'id', 'label'}, ...]`. + + ⭐ `allowed_bus()` ONE AXIS OVER, and the ticket asks for it to read like it. The list is what + a module's connection selector renders, and the FIRST member is the workspace's designated + default, so a client that shows the first row selected shows what a read with no id named would + actually serve. + + ⛔⛔ THERE IS NO "ALL" MEMBER AND THERE IS NO PLACE TO PUT ONE. R7 is explicit that no option + may blend two clients, so the option list carries only real connections; a caller that wants + "everything" has to ask twice, once per connection, which is exactly what `refresh_all` does. + + ⚠ IDENTITY COMES FROM `keychain.resolve_connection_id`, NEVER FROM A SECOND WALK OF THE ROWS. + Four first-entry walks were deleted in W54-T45 and a fifth would reopen the ceiling C4 exists + to close; the row is read here only for its LABEL and its slot, which no resolver answers. The + resolver is also what SKIPS a personal entry of a tenant-wide type, so a credential the readers + would never serve cannot appear in a picker as though it would. + """ + if rt is None: + return [] + kc = _keychain() + want = str(etype or DEFAULT_CONNECTION_TYPE).strip().lower() + rows, seen = [], set() + try: + entries = list(kc.list_entries(rt)) + except Exception: # noqa: BLE001 + return [] + for row in entries: + if str(row.get('type') or '') != want: + continue + cid = kc.resolve_connection_id(rt, want, + str(row.get('connection_id') or row.get('id') or '')) + if not cid or cid in seen: + continue + seen.add(cid) + label = ' '.join(str(row.get('label') or '').split()) or kc.kind_label(want) + rows.append((int(row.get('slot') or 0), len(rows), cid, label)) + rows.sort() + return [{'id': cid, 'label': label} for _slot, _pos, cid, label in rows] + + +def _keychain(): + import core.keychain as keychain + return keychain diff --git a/platform/core/relations.py b/platform/core/relations.py index 0b1b93fb15cb7ca8a0dcd79469cf138fccebdaa5..d26215ba08af2d8899b9a314f602035e39e6f9d7 100644 --- a/platform/core/relations.py +++ b/platform/core/relations.py @@ -59,6 +59,86 @@ booked in this ticket's handoff), ``pin_sql`` delegates to it and this note is d #: The three ways a database can be related to another. `via.direction` is always one of these. DIRECTIONS = ('forward', 'reverse', 'bridge') +# =============================================================================================== +# W54-T37 / CONTRACT C5 / INSTRUCTION 22 - A DATABASE THAT IS DECLARED BUT ABSENT. +# +# The owner, verbatim: *"a wall of ... this account may not open `ut_odoo_customers` ... THAT +# DATABASE DOES NOT EXIST."* He is right and the sentence was lying. `ut_odoo_customers` and +# `ut_odoo_products` were RETIRED: popped from every tenant document on every sync and replaced by +# the `customer_data` / `product_data` registry modules. The connector spec still DESCRIBES them +# (a spec describes a shape, it does not assert a table is materialised), so the enumeration below +# happily minted edges pointing at them, the route wall failed closed on a key it could not find, +# and the reader was told about a permission problem that does not exist. +# +# TWO REPAIRS, IN THIS ORDER, AND THE FIRST IS THE REAL ONE: +# 1. an edge whose TARGET is retired is NEVER ENUMERATED, in either direction and in BOTH the +# walled and the unwalled pass. It is not a tab, so it is not a refusal either. +# 2. a path that names one ANYWAY earns `retired_target`, which says the database is gone. It is +# a BACKSTOP, and a backstop that fires often means repair 1 has a hole in it. +# +# THE LIST LIVES ABOVE, NOT HERE, AND THAT IS THE WHOLE POINT OF THE REGISTRY. `core` never +# imports up, so it cannot read `odoo_relational.RETIRED_KEYS`; copying the two keys down here +# would make a second declaration of the same fact, which is the defect class this repo already +# names [[one-question-two-normalizers]]. The shape is `core.user_tables.register_connected_prefix` +# verbatim, down to its comment: the engine pushes its list down rather than this module reaching +# for it. So THIS SET STARTS EMPTY AND STAYS EMPTY until an app-layer registrar runs. +# +# A CONSEQUENCE WORTH STATING: in a process where nothing registered anything (a bare platform +# gate) the filter is a no-op and every edge is enumerated. That is the honest answer there, since +# such a process has no way to know which tables a deployment retired. +# =============================================================================================== + +#: The table keys that are DECLARED somewhere and ABSENT from this deployment: retired, or never +#: materialised. Empty by construction. See the banner above before adding a literal to it. +_RETIRED_TABLES = set() + + +def register_retired_tables(*keys): + """Declare table keys that are described somewhere but do not exist as databases. + + Takes bare keys, an iterable of keys, or any mix, so a registrar can push a whole tuple down in + one call. Returns the WHOLE registered set, exactly as `register_connected_prefix` does, so the + caller can assert what it just joined and the write door answers through the read door. + + A KEY REGISTERED HERE STOPS BEING AN EDGE TARGET. Nothing else changes: rows, definitions and + permissions are not this module's business, and a key that is merely unreadable by one account + is a PERMISSION and belongs to the wall, not here. + """ + for key in keys: + named = [key] if isinstance(key, str) else list(key or ()) + for name in named: + text = str(name or '').strip() + if text: + _RETIRED_TABLES.add(text) + return retired_tables() + + +def retired_tables(): + """The registered absent-table keys. The ONE list a caller may read to name the same set.""" + return frozenset(_RETIRED_TABLES) + + +def is_retired_table(key): + """Is `key` a database this deployment declares and does not have?""" + return str(key or '').strip() in _RETIRED_TABLES + + +def _live(entries, include_retired=False): + """Drop every entry whose TARGET is retired. The one filter, applied by every builder. + + ⛔ IT FILTERS THE **TARGET**, WHICH COVERS BOTH DIRECTIONS WITH ONE RULE. Outbound, the target + is the parent the spec names (`ut_odoo_orders` -> `ut_odoo_customers`). Inbound, the target is + the OTHER table, so a retired spec row whose own links point at a live table (the retired + customers row names `ut_odoo_agents`) produces a reverse entry on the agents grid whose target + is the retired table. Both are the same test. + ⚠ ENUMERATING **FROM** A RETIRED TABLE IS STILL ALLOWED and is deliberately not this rule: the + edges of such a table are what a diagnosis walks, and refusing to describe them would replace + one wrong answer with a shorter one. + """ + if include_retired or not _RETIRED_TABLES: + return list(entries or ()) + return [e for e in (entries or ()) if not is_retired_table(e.get('target'))] + #: The identity column of a module grid, as the wire spells it. `customer_data.pid` IS the Odoo #: `res.partner` id and `ut_odoo_orders.pid` IS the `sale_order` id, so a bridge hanging off `pid` #: needs no second lookup. `product_data.pid` is NOT an Odoo id (it is `crc32(default_code)`), @@ -215,7 +295,7 @@ def _entry(key, label, target, direction, field=None, on=None, frm=None, served= return out -def forward_links(table, fields): +def forward_links(table, fields, include_retired=False): """The FORWARD entries for `table`: every `type: "link"` field on it, in field order. `fields` is whatever the caller's permission wall handed back, so a link field this account @@ -224,6 +304,10 @@ def forward_links(table, fields): ⭐ TWO LINKS BETWEEN THE SAME PAIR GIVE TWO ENTRIES, and R2 says so in as many words. The entry `key` is the FIELD key, not the target key, which is what keeps them apart on the wire. + + ⛔ W54-T37 / C5: a field pointing at a RETIRED table is dropped. A tenant document written + before a table was retired can still carry such a column, and the tab it would draw opens a + database this deployment does not have. """ out = [] for field in (fields or ()): @@ -239,10 +323,10 @@ def forward_links(table, fields): target=target, direction='forward', field=field.get('key'), on=bag.get('on'), frm=bag.get('from') or IDENTITY_COL)) - return out + return _live(out, include_retired) -def reverse_links(table, defs): +def reverse_links(table, defs, include_retired=False): """The REVERSE entries for `table`: every OTHER table's link field that points at it. `defs` is `{key: definition}` as `core.user_tables.all_defs` returns it, already narrowed to @@ -252,6 +336,9 @@ def reverse_links(table, defs): ⛔ A TABLE'S LINK TO ITSELF IS NOT A REVERSE LINK. It is already a forward one, and emitting both would give the same edge two tabs pointing at the same grid, one of them labelled from the wrong end. + + ⛔ W54-T37 / C5: a definition left behind for a RETIRED table is not a reverse link either. + Its rows are gone, so the tab would open nothing. """ me = str(table or '') out = [] @@ -276,15 +363,20 @@ def reverse_links(table, defs): # mislabelled `forward` as a negative control for exactly this. on=bag.get('from') or IDENTITY_COL, frm=bag.get('on') or IDENTITY_COL)) - return out + return _live(out, include_retired) + +def bridge_entries(table, include_retired=False): + """The BRIDGE entries for `table`, from `BRIDGES` and from nowhere else. -def bridge_entries(table): - """The BRIDGE entries for `table`, from `BRIDGES` and from nowhere else.""" - return [_entry(key=b['key'], label=b['label'], target=b['target'], direction='bridge', - on=b['target_col'], frm=b['source_col'], served=b['served'], - where=b['where']) - for b in bridges_from(table)] + ⚠ NO BRIDGE TARGETS A RETIRED TABLE TODAY and the filter is applied anyway, because the day one + does the alternative is a tab onto a database that is not there. A declared bridge onto an + absent grain is a DECLARATION BUG, not a served edge, and it should disappear the same way. + """ + return _live([_entry(key=b['key'], label=b['label'], target=b['target'], direction='bridge', + on=b['target_col'], frm=b['source_col'], served=b['served'], + where=b['where']) + for b in bridges_from(table)], include_retired) def edge_identity(entry): @@ -301,7 +393,7 @@ def edge_identity(entry): str(via.get('from') or ''), str(entry.get('where') or '')) -def related(table, fields=None, defs=None): +def related(table, fields=None, defs=None, include_retired=False): """THE `/related` ANSWER for one table: forward, then reverse, then bridge. `[{key, label, via: {direction, key, field?, on?, from?}, target, served, where?}]`. @@ -325,10 +417,11 @@ def related(table, fields=None, defs=None): ⚠ ON A TENANT WITH NO PRE-SET LINKS the bridge is not a duplicate of anything and is offered unchanged, which is the whole reason the suppression is computed rather than declared. """ - forward = forward_links(table, fields or ()) - reverse = reverse_links(table, defs or {}) + forward = forward_links(table, fields or (), include_retired) + reverse = reverse_links(table, defs or {}, include_retired) seen = {edge_identity(e) for e in forward} | {edge_identity(e) for e in reverse} - bridges = [b for b in bridge_entries(table) if edge_identity(b) not in seen] + bridges = [b for b in bridge_entries(table, include_retired) + if edge_identity(b) not in seen] return forward + reverse + bridges @@ -734,7 +827,7 @@ def compose_cardinality(a, b): return 'many_to_many' -def spec_entries(table): +def spec_entries(table, include_retired=False): """The CONNECTOR-SPEC edges of `table`, in BOTH directions, in `related()`'s entry shape. ⛔⛔ BOTH DIRECTIONS, AND AN OUTBOUND-ONLY READ CANNOT ANSWER THE QUESTION THIS TICKET ASKS. @@ -761,6 +854,13 @@ def spec_entries(table): ⚠ `served` TAKES `_entry`'s DEFAULT, exactly as the forward and reverse link FIELDS do. Only `BRIDGES` carries a measured `served` today, and inventing one per spec edge here would be a second, unmeasured source for the same judgement. + + ⛔⛔ W54-T37 / C5 / INSTRUCTION 22 - THIS IS WHERE THE OWNER'S REFUSAL WALL WAS MINTED, AND THE + RETIRED FILTER IS THE PRIMARY REPAIR. Four Odoo specs (invoices, orders, order lines, GL lines) + declare a link at `ut_odoo_customers` and the line grain declares one at `ut_odoo_products`; + both keys are RETIRED, so the outbound half offered tabs onto databases that do not exist. The + inbound half is the mirror image: the retired customers spec row carries its own link at + `ut_odoo_agents`, so the agents grid was offered a reverse tab back onto the absent table. """ spec = _spec() me = str(table or '') @@ -786,7 +886,7 @@ def spec_entries(table): on=from_col, # the column on the OTHER table frm=to_col, # the column on THIS one cardinality=_INVERSE.get(str(cardinality), 'many_to_many'))) - return out + return _live(out, include_retired) def _link_field_cardinalities(table, fields, defs): @@ -814,7 +914,7 @@ def _link_field_cardinalities(table, fields, defs): return out -def one_hop(table, fields=None, defs=None): +def one_hop(table, fields=None, defs=None, include_retired=False): """EVERYTHING ONE NAMED HOP FROM `table`: `related()` plus the connector spec, deduplicated. Every entry carries a `cardinality`, taken from the declaration it came with: @@ -831,7 +931,7 @@ def one_hop(table, fields=None, defs=None): *"one tab per related table"*. The dedupe is on `edge_identity`, which is target plus both join columns plus the predicate; read its docstring for why `where` is in there. """ - base = list(related(table, fields, defs)) + base = list(related(table, fields, defs, include_retired)) cards = _link_field_cardinalities(table, fields, defs) bridge_cards = {b['key']: _bridge_cardinality(b) for b in BRIDGES} out = [] @@ -841,7 +941,7 @@ def one_hop(table, fields=None, defs=None): entry['cardinality'] = str(got or 'many_to_many') out.append(entry) seen = {edge_identity(e) for e in out} - for entry in spec_entries(table): + for entry in spec_entries(table, include_retired=include_retired): if edge_identity(entry) in seen: continue seen.add(edge_identity(entry)) @@ -880,7 +980,8 @@ def _two_hop_entry(first, second): } -def related_paths(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None, fields_for=None): +def related_paths(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None, + fields_for=None, include_retired=False): """C3'S `/related` ANSWER: everything reachable from `table` in at most `depth` NAMED hops. `[{key, label, via, target, served, where?, cardinality, path, hops}]`, one-hop entries first @@ -905,13 +1006,18 @@ def related_paths(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None, ⛔ A HOP-2 EDGE POINTING BACK AT `table` IS DROPPED. `customer -> orders -> customer` is a round trip, not a relation, and offering it would put a tab on the customers grid labelled Customers. + + ⛔⛔ `include_retired` IS FOR DIAGNOSIS ONLY AND NOTHING SERVES IT. Left False, no hop lands on + a table this deployment declares and does not have; set True, the absent hops come back so a + caller can say WHICH one a request named. Both passes of the permission diff leave it False, + which is what stops an absent edge being reported as a wall removal. """ if depth not in (1, MAX_DEPTH): raise ValueError( "relation depth is 1 or %d; %r was asked for. The route turns this into a named " "refusal rather than a 500" % (MAX_DEPTH, depth)) table = str(table or '') - hop1 = [e for e in one_hop(table, fields, defs) + hop1 = [e for e in one_hop(table, fields, defs, include_retired) if may_open is None or may_open(e['target'])] out = [] for entry in hop1: @@ -925,7 +1031,7 @@ def related_paths(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None, for first in hop1: mid = first['target'] mid_fields = fields_for(mid) if fields_for is not None else None - for second in one_hop(mid, mid_fields, defs): + for second in one_hop(mid, mid_fields, defs, include_retired): if second['target'] == table: continue if may_open is not None and not may_open(second['target']): @@ -1033,7 +1139,7 @@ def over_depth_refusal(table, via): # whether it holds rows for this record. The name, and the fact that the door is shut. # ═══════════════════════════════════════════════════════════════════════════════════════════════ -#: ⭐ THE THREE R13 ANSWERS, PLUS THE FOURTH THAT IS NOT A PERMISSION ANSWER AT ALL. +#: ⭐ THE THREE R13 ANSWERS, PLUS THE ONE THAT IS NOT A PERMISSION ANSWER AT ALL, PLUS C5'S. #: ⚠ `unknown_via` KEEPS THE NAME `routes_grid.grid_related` ALREADY RAISES rather than gaining a #: synonym: a fourth spelling of the same refusal would be a client-visible rename dressed as a #: feature. `routes_odoo_tables` spells its depth-1 cousin `unknown_relation` and is in another @@ -1043,10 +1149,22 @@ REFUSAL_FORBIDDEN_TABLE = 'forbidden_table' REFUSAL_HOP_FILTERED = 'hop_filtered' REFUSAL_UNKNOWN_VIA = 'unknown_via' -#: The three R13 answers in R13's own order, and the fourth. A gate reads this rather than four -#: literals scattered through two files. +#: ⭐⭐ W54-T37 / C5's FOURTH ANSWER: the edge names a database this deployment does not have. +#: ⛔ IT IS NOT A PERMISSION ANSWER AND MUST NEVER BE CONFUSED WITH ONE. That confusion IS +#: instruction 22: the route wall fails closed on any key it cannot resolve, so an absent table +#: came back as `forbidden_table` and the reader was told to ask an administrator for access to a +#: database nobody can be granted. +REFUSAL_RETIRED_TARGET = 'retired_target' + +#: ⛔⛔ FIVE ENTRIES, AND C5's *"four wire answers"* IS STILL SATISFIED BY FOUR OF THEM. +#: C5 names `no_related_rows`, `forbidden_table`, `hop_filtered` and the new `retired_target`. +#: `unknown_via` PREDATES C5 (it is the name `routes_grid.grid_related` has always raised for an +#: edge that does not exist at all) and is neither removed nor renamed by it: a fifth spelling of +#: an existing refusal would be a client-visible rename dressed as a feature. So the tuple holds +#: five and the four C5 names are the ones that are new-or-ruled. A gate reads this rather than +#: five literals scattered through two files. REFUSAL_CODES = (REFUSAL_NO_ROWS, REFUSAL_FORBIDDEN_TABLE, REFUSAL_HOP_FILTERED, - REFUSAL_UNKNOWN_VIA) + REFUSAL_RETIRED_TARGET, REFUSAL_UNKNOWN_VIA) def _named_path(path): @@ -1054,6 +1172,39 @@ def _named_path(path): return ' then '.join(f"'{k}'" for k in (str(p) for p in (path or ()))) +# ═══════════════════════════════════════════════════════════════════════════════════════════════ +# ⭐⭐ W54-T38 / INSTRUCTION 22 / DESIGN.md SECTION 4 — TWO STRINGS PER REFUSAL: THE SENTENCE AND +# THE DIAGNOSIS. THE SPLIT IS AUTHORED HERE BECAUSE THE CLIENT MAY NOT AUTHOR IT. +# +# The owner pasted one of these refusals back at us, four times over, off one screen. Every word of +# it was TRUE after W54-T37 fixed the cause, and it was still the wrong thing to put on a screen: +# DESIGN.md section 4 says *"never over-explain"*, and a sixty-word paragraph repeated once per +# removed edge is a wall a reader scrolls past to reach the rows they asked for. +# +# ⛔⛔ THE FIX IS NOT TO SHORTEN THE DIAGNOSIS. W53-T18 wrote those paragraphs deliberately, so a +# traversal is never served short and silent, and deleting them would trade one defect for the one +# they were written against. The fix is that the refusal now carries TWO server-authored strings: +# +# * `message` — ONE SHORT SENTENCE, the thing a reader sees first. It still names whatever R13 +# and C5 require it to name (the closed table, the filtered hop, the absent database). +# * `detail` — the FULL diagnosis, word for word what `message` used to be, for the disclosure +# the client puts it behind. +# +# ⛔ WHY THE SERVER SPLITS IT AND NOT THE CLIENT. `RecordDetail.tsx` already carries the rule in as +# many words: *"THE SENTENCE IS STILL THE SERVER'S, WHOLE. The code chooses the treatment; it never +# rewrites the words, which would fork one wire contract into two opinions."* A client that cut a +# paragraph at its first full stop would be authoring copy out of a regular expression, and the day +# a sentence gains a comma the summary line changes with nobody having decided it should. +# +# ⚠ `message` STAYS POPULATED AND STAYS FIRST, so every existing reader keeps working: the route's +# `_refusal_error` copies it into the X2 envelope, and a client that has never heard of `detail` +# shows the short sentence and loses only the explanation. +# ⛔ NO EM DASH AND NO EN DASH IN EITHER STRING (standing rule 2). Both reach a screen, and D-653 +# records that no gate scans a Python string for them, so this is checked by eye and by the +# snippet in this ticket's handoff. +# ═══════════════════════════════════════════════════════════════════════════════════════════════ + + def no_related_rows_refusal(table, path=None): """R13's FIRST answer: everything was open, and there is genuinely nothing on the other side. @@ -1062,15 +1213,31 @@ def no_related_rows_refusal(table, path=None): of R13, so the empty case is spelled out loud and says in as many words that nothing was hidden from it. ⛔ NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2). + ⭐ W54-T38: THE SENTENCE, and only the sentence. `no_related_rows_detail` carries what this + used to say in full. Read the banner above `_named_path` before shortening either of them. + """ + named = _named_path(path) + if named: + return f"Nothing is linked through {named} on '{table}'." + return f"'{table}' is not linked to any database this account can open." + + +def no_related_rows_detail(table, path=None): + """The DIAGNOSIS behind `no_related_rows_refusal`, for the client's disclosure. + + ⭐ WORD FOR WORD WHAT THE SENTENCE USED TO BE. Nothing was cut: an empty side that says only + "nothing is linked" leaves a reader unable to tell it from a wall, which is the whole of R13, + so the paragraph that rules that out still exists and is one click away. + ⛔ NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2). """ named = _named_path(path) if named: - return (f"the relation reached by {named} on '{table}' is open to this account at every " + return (f"The relation reached by {named} on '{table}' is open to this account at every " f"hop, and it reaches no rows. Nothing was hidden by permission and no hop was " - f"filtered: there is simply nothing on the other side of it") + f"filtered, so there is simply nothing on the other side of it.") return (f"'{table}' reaches no other database within {MAX_DEPTH} named hops that this account " f"may open, and nothing was removed by permission on the way. Ask an administrator to " - f"link it to another database, or open the database you want on its own") + f"link it to another database, or open the database you want on its own.") def forbidden_table_refusal(table, path, blocked, hop=None): @@ -1084,14 +1251,92 @@ def forbidden_table_refusal(table, path, blocked, hop=None): could not read at all, so claiming only the first would tell a reader their access was revoked when the store had merely hiccupped. ⛔ NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2). + ⭐ W54-T38: THE SENTENCE, and only the sentence. It still NAMES the blocked table, because + R13's disclosure is the one thing that may not move behind a disclosure: a reader who cannot + see which door is shut has been handed the empty list again. `forbidden_table_detail` carries + the pair of causes, the path and the recommendation. + ⚠ NO DIGITS AND NO PATH IN THIS ONE. `verify_odoo_relational` asserts that this sentence + discloses the table's NAME and nothing else about it, digits included, so the hop keys and the + path (which may carry either) stay in the detail where the same leg does not reach. + """ + return (f"This relation passes through '{blocked}', and this account may not open it.") + + +def forbidden_table_detail(table, path, blocked, hop=None): + """The DIAGNOSIS behind `forbidden_table_refusal`, for the client's disclosure. + + ⚠ THE CAUSE IS STILL NAMED AS A PAIR, the posture `routes_odoo_tables._related_pin` takes: the + wall is fail-closed and answers False both for a genuine refusal and for a database it could + not read at all, so claiming only the first would tell a reader their access was revoked when + the store had merely hiccupped. + ⛔ NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2). """ named = _named_path(path) or 'this relation' where = f" at the hop named '{hop}'" if hop else '' - return (f"the relation reached by {named} on '{table}' passes through '{blocked}'{where}, and " + return (f"The relation reached by {named} on '{table}' passes through '{blocked}'{where}, and " f"this account may not open '{blocked}', either because it is not granted to you or " f"because it could not be read just now. The traversal is refused rather than served " f"short, so no part of it is silently missing. Ask an administrator for access to " - f"'{blocked}', or ask for a relation that does not pass through it") + f"'{blocked}', or ask for a relation that does not pass through it.") + + +def retired_target_refusal(table, path, missing): + """C5's FOURTH answer: the relation opens a database this workspace does not have any more. + + ⛔⛔ IT SAYS THE TRUE CAUSE AND NAMES NO PERMISSION. Instruction 22 is a wall of *"this account + may not open `ut_odoo_customers`"* about a table that was retired, so this sentence may not say + "not granted to you" and may not send the reader to an administrator for access: there is no + access to grant. It names the database and says it is gone. + ⛔ SHORT, ON PURPOSE. One sentence. The long diagnosis belongs behind a disclosure, not in a + second wall. + ⭐ W54-T38 FINISHED THAT SENTENCE'S OWN NOTE. T37 wrote "short, on purpose" and then shipped a + sentence carrying the path and an API pointer, because there was nowhere else to put them yet. + There is now: `retired_target_detail`. + ⛔ NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2). + """ + return f"'{missing}' is no longer part of this workspace." + + +def retired_target_detail(table, path, missing): + """The DIAGNOSIS behind `retired_target_refusal`, for the client's disclosure. + + ⛔⛔ IT NAMES NO PERMISSION EITHER, and that rule does not weaken one level down. Instruction + 22 is a reader being sent to an administrator for access to a database nobody can grant; the + same sentence hidden behind a caret would still be that. + ⛔ NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2). + """ + named = _named_path(path) or 'this relation' + return (f"The relation reached by {named} on '{table}' opens '{missing}', which this " + f"deployment does not have any more. It was retired and its rows are gone, so there " + f"is nothing to show here and nothing to ask anyone for. Ask GET /api/v1/grid/{table}" + f"/related for the relations '{table}' still has.") + + +def first_retired_on_path(table, keys, fields=None, defs=None, depth=MAX_DEPTH, fields_for=None, + retired_entries=None): + """`(absent_target, hop_key)` for the FIRST hop of `keys` that opens a retired table. + + `('', '')` when the path names none, which is every ordinary path: the enumeration already + dropped these edges, so this walk is the BACKSTOP and answering nothing is its normal day. + + ⚠ IT COSTS NOTHING WHERE NOTHING IS REGISTERED. A process with an empty registry cannot have + an absent target, so it returns before enumerating anything at all. + ⛔ THE PREFIX WALK IS WHY AN INTERMEDIATE IS COVERED WITHOUT A SPECIAL CASE, exactly as the + permission diff below covers it: the intermediate of a two-hop path is the target of its + one-hop prefix, so a retired intermediate is found at `idx` 0 and named there. + """ + keys = [str(k) for k in (keys or ())] + if not keys or not _RETIRED_TABLES: + return ('', '') + if retired_entries is None: + retired_entries = related_paths(table, fields=fields, defs=defs, depth=depth, + may_open=None, fields_for=fields_for, + include_retired=True) + for idx in range(len(keys)): + step = pick_path(retired_entries, keys[:idx + 1]) + if step is not None and is_retired_table(step.get('target')): + return (str(step.get('target')), keys[idx]) + return ('', '') def hop_filtered_refusal(table, path, hop): @@ -1103,13 +1348,26 @@ def hop_filtered_refusal(table, path, hop): stay open, so the traversal is neither forbidden nor empty. Served as `[]` it would read as "this record has nothing here", which is a claim about the business made out of a permission. ⛔ NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2). + ⭐ W54-T38: THE SENTENCE, and only the sentence. It still NAMES the hop for the same reason + the forbidden sentence still names the table. `hop_filtered_detail` carries the rest. + """ + return f"The hop named '{hop}' was filtered out for this account." + + +def hop_filtered_detail(table, path, hop): + """The DIAGNOSIS behind `hop_filtered_refusal`, for the client's disclosure. + + ⭐ IT IS THE ONE THAT MOST NEEDS ITS PARAGRAPH KEPT: "the databases are open to you and the + link column is not" is not a thing a reader can guess from a short sentence, and served as an + empty grid it would read as a claim about the business. + ⛔ NO EM DASH AND NO EN DASH: this string reaches a screen (standing rule 2). """ named = _named_path(path) or 'this relation' - return (f"the hop named '{hop}' of the relation reached by {named} on '{table}' was filtered " - f"out for this account. The databases it crosses are open to you; the link column " + return (f"The hop named '{hop}' of the relation reached by {named} on '{table}' was filtered " + f"out for this account. The databases it crosses are open to you. The link column " f"this hop is built on is not one you may see, so the hop was removed rather than " f"answered empty. Ask an administrator for that column, or ask for a relation that " - f"does not use it") + f"does not use it.") def candidate_paths(table, entries, defs=None, fields_for=None): @@ -1178,6 +1436,13 @@ def unknown_via_answer(table, keys, candidates): them only into the sentence is what `unknown_via_refusal` used to do, and lane E cannot draw a retry button out of an English clause. ⛔ NO EM DASH AND NO EN DASH anywhere in `message` (standing rule 2). + + ⭐⭐ W54-T38 — AND THIS IS THE LONGEST WALL OF THE FIVE. Measured before this ticket: 1,921 + characters on `customer_data`, because the enumeration of every candidate with its join + columns and retry string is inside the sentence. It splits like the other four: a short + `message`, and the whole of what it used to say in `detail`. ⛔ THE `candidates` ARRAY IS + UNTOUCHED and is still the answer a client renders; the prose was never the machine-readable + half and C3 says so. """ keys = [str(k) for k in (keys or ())] cands = list(candidates or ()) @@ -1198,9 +1463,10 @@ def unknown_via_answer(table, keys, candidates): f"account is offered, then send the 'path' of the one you want, one edge key per " f"hop") return {'code': REFUSAL_UNKNOWN_VIA, 'path': keys, 'candidates': cands, - 'message': (f"'{table}' offers no relation reached by {named} to this account, and " - f"nothing was removed by permission on the way, so this is an edge that " - f"does not exist rather than one you may not see." + tail)} + 'message': f"'{table}' offers no relation reached by {named} to this account.", + 'detail': (f"'{table}' offers no relation reached by {named} to this account, and " + f"nothing was removed by permission on the way, so this is an edge that " + f"does not exist rather than one you may not see." + tail)} def _paths_of(entries): @@ -1210,8 +1476,12 @@ def _paths_of(entries): def diagnose_path(table, keys, fields=None, defs=None, may_open=None, fields_for=None, depth=MAX_DEPTH, entries=None, open_entries=None, - open_fields=None, open_fields_for=None): - """WHY `pick_path` came back None, as one of C3's four answers. `{code, message, table?, hop?}`. + open_fields=None, open_fields_for=None, retired_entries=None): + """WHY `pick_path` came back None, as one of the named answers. + + `{code, message, detail, table?, hop?}`. ⭐ W54-T38 — `message` is ONE SHORT SENTENCE and + `detail` is the full diagnosis it used to be; see the banner above `no_related_rows_refusal` + for why the split is authored here rather than cut out of a paragraph by the client. ⛔⛔ NEVER RAISES AND NEVER RETURNS None. A diagnosis that can itself fail is the fail-open bug `routes_grid._may_open` warns about: every branch below ends in a real bag carrying a code from @@ -1221,6 +1491,13 @@ def diagnose_path(table, keys, fields=None, defs=None, may_open=None, fields_for 1. the FILTERED enumeration (`may_open` + the caller's field wall). If `keys` resolves in it, the path is permitted end to end and reaches nothing: `no_related_rows`. + 1b. ⛔⛔ W54-T37 / C5 - DOES ANY HOP OPEN A DATABASE THIS DEPLOYMENT DOES NOT HAVE? Then + `retired_target`, NAMING it. THIS STEP IS ABOVE BOTH OF THE ONES BELOW AND THE ORDER IS + THE TICKET: an absent table is absent from both enumerations, so step 2 would have called + it an edge that never existed, and the ROUTE's fail-closed wall (which answers False for + a key it cannot resolve) would have made step 3 call it a permission. Instruction 22 is + the second of those two wrong answers, printed at a reader who was told to ask for access + to a database nobody can grant. 2. the UNFILTERED enumeration (no `may_open`, and the widest field list the caller can offer). If `keys` does not resolve THERE either, the edge genuinely does not exist and no wall was involved: `unknown_via`, with the candidates, their join columns and the retry strings. @@ -1237,8 +1514,10 @@ def diagnose_path(table, keys, fields=None, defs=None, may_open=None, fields_for ⛔ `open_fields` / `open_fields_for` MUST BE A SUPERSET of `fields` / `fields_for`, or step 2 can call a wall-removed path unknown. The route builds them as a UNION for exactly that reason; when they are omitted the diff runs on the table wall alone, which is correct and narrower. - ⛔ `entries` / `open_entries` ARE AN OPTIMISATION ONLY. The route has already paid for both - enumerations; a gate hands neither and gets the same answer computed from scratch. + ⛔ `entries` / `open_entries` / `retired_entries` ARE AN OPTIMISATION ONLY. The route has + already paid for the first two; a gate hands none and gets the same answer computed from + scratch. The third is the absent-target pass, which is skipped outright where no table is + registered as absent. """ keys = [str(k) for k in (keys or ())] table = str(table or '') @@ -1247,7 +1526,19 @@ def diagnose_path(table, keys, fields=None, defs=None, may_open=None, fields_for may_open=may_open, fields_for=fields_for) if pick_path(entries, keys) is not None: return {'code': REFUSAL_NO_ROWS, 'path': keys, - 'message': no_related_rows_refusal(table, keys)} + 'message': no_related_rows_refusal(table, keys), + 'detail': no_related_rows_detail(table, keys)} + # ⛔⛔ BEFORE THE TWO PERMISSION ANSWERS AND BEFORE `unknown_via`. See step 1b above: a table + # that is not there is not a permission and not a typo, and saying either was the defect. + missing, missing_hop = first_retired_on_path( + table, keys, fields=(open_fields if open_fields is not None else fields), defs=defs, + depth=depth, fields_for=(open_fields_for if open_fields_for is not None else fields_for), + retired_entries=retired_entries) + if missing: + return {'code': REFUSAL_RETIRED_TARGET, 'path': keys, 'table': missing, + 'hop': missing_hop, + 'message': retired_target_refusal(table, keys, missing), + 'detail': retired_target_detail(table, keys, missing)} if open_entries is None: open_entries = related_paths( table, fields=(open_fields if open_fields is not None else fields), defs=defs, @@ -1266,21 +1557,25 @@ def diagnose_path(table, keys, fields=None, defs=None, may_open=None, fields_for if blocked and may_open is not None and not may_open(blocked): return {'code': REFUSAL_FORBIDDEN_TABLE, 'path': keys, 'table': blocked, 'hop': keys[idx], - 'message': forbidden_table_refusal(table, keys, blocked, keys[idx])} + 'message': forbidden_table_refusal(table, keys, blocked, keys[idx]), + 'detail': forbidden_table_detail(table, keys, blocked, keys[idx])} return {'code': REFUSAL_HOP_FILTERED, 'path': keys, 'hop': keys[idx], - 'message': hop_filtered_refusal(table, keys, keys[idx])} + 'message': hop_filtered_refusal(table, keys, keys[idx]), + 'detail': hop_filtered_detail(table, keys, keys[idx])} # ⚠ EVERY PREFIX SURVIVED AND THE WHOLE DID NOT. Only reachable if two enumerations disagree # about a path they agree about every prefix of; the last hop is the honest thing to name. return {'code': REFUSAL_HOP_FILTERED, 'path': keys, 'hop': (keys[-1] if keys else ''), - 'message': hop_filtered_refusal(table, keys, keys[-1] if keys else '')} + 'message': hop_filtered_refusal(table, keys, keys[-1] if keys else ''), + 'detail': hop_filtered_detail(table, keys, keys[-1] if keys else '')} def wall_refusals(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None, fields_for=None, entries=None, open_entries=None, open_fields=None, open_fields_for=None): """THE LISTING ANNOTATION: what the wall removed from this table's enumeration, BY NAME. - `[{code, message, path, table?, hop?}]`, a SIBLING of the served list and never a replacement - for it. + `[{code, message, detail, path, table?, hop?}]`, a SIBLING of the served list and never a + replacement for it. ⭐ W54-T38 — `message` is the short sentence, `detail` the diagnosis behind + the client's disclosure. ⛔⛔ AN EMPTY LIST IS NEVER AN ACCEPTABLE ANSWER TO A PERMISSION-FILTERED TRAVERSAL, AND THIS IS THE HALF OF C3 THAT IS EASIEST TO MISS. A 400 on a pin covers the request that named ONE @@ -1306,6 +1601,17 @@ def wall_refusals(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None, table, fields=(open_fields if open_fields is not None else fields), defs=defs, depth=depth, may_open=None, fields_for=(open_fields_for if open_fields_for is not None else fields_for)) + # ⛔ ONE absent-target pass for the WHOLE listing, not one per removed path. Every path below + # comes out of `open_entries`, which never carries an absent target, so this walk is expected + # to find nothing; computing it per path would pay for a full enumeration per refusal to learn + # that. ⚠ Skipped entirely where nothing is registered as absent. + retired_entries = None + if _RETIRED_TABLES: + retired_entries = related_paths( + table, fields=(open_fields if open_fields is not None else fields), defs=defs, + depth=depth, may_open=None, + fields_for=(open_fields_for if open_fields_for is not None else fields_for), + include_retired=True) have = _paths_of(entries) out, seen = [], set() for entry in open_entries: @@ -1314,7 +1620,7 @@ def wall_refusals(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None, continue got = diagnose_path(table, path, fields=fields, defs=defs, may_open=may_open, fields_for=fields_for, depth=depth, entries=entries, - open_entries=open_entries) + open_entries=open_entries, retired_entries=retired_entries) if got.get('code') == REFUSAL_UNKNOWN_VIA: continue # cannot happen: `path` came out of `open_entries` itself ident = (got.get('code'), got.get('table') or '', got.get('hop') or '') @@ -1324,5 +1630,6 @@ def wall_refusals(table, fields=None, defs=None, depth=MAX_DEPTH, may_open=None, out.append(got) if not entries and not out: out.append({'code': REFUSAL_NO_ROWS, 'path': [], - 'message': no_related_rows_refusal(table)}) + 'message': no_related_rows_refusal(table), + 'detail': no_related_rows_detail(table)}) return out diff --git a/platform/core/sheets.py b/platform/core/sheets.py index ad18afe5f5a07d7c640272b4873c288f16c0c0f5..567a6c11b62280f3736e948139753d1e6ab8f42b 100644 --- a/platform/core/sheets.py +++ b/platform/core/sheets.py @@ -98,6 +98,24 @@ CELL_ALIGNS = ("left", "center", "right") CELL_VALIGNS = ("top", "middle", "bottom") CELL_SIZES = ("s", "m", "l", "xl") +#: ⭐⭐ WAVE 54 / R10 + R11 - THE TYPEFACE AND THE POINT SIZE. Mirrored in +#: `types.ts::CELL_FONTS` / `DEFAULT_CELL_FONT` / `DEFAULT_FONT_PT` / `MIN_FONT_PT` / `MAX_FONT_PT`. +#: +#: R10: a cell's typeface is USER DATA, exactly as its fill colour is; the app's own chrome stays +#: Inter and that is a different decision. The list is closed and every face in it is one a machine +#: already has, because the client imports no webfont; the bare NAME is what is stored and the +#: client resolves it to a full stack at paint time, for the reason a colour is stored as a token. +#: +#: R11: the `size` slot carries EITHER one of the four step names above OR a point size, and never +#: a second field. `DEFAULT_FONT_PT` is `m`, in points, and both are stored as an ABSENCE. +CELL_FONTS = ( + "Inter", "Arial", "Georgia", "Times New Roman", "Courier New", "Verdana", "Trebuchet MS", +) +DEFAULT_CELL_FONT = "Inter" +DEFAULT_FONT_PT = 10 +MIN_FONT_PT = 6 +MAX_FONT_PT = 96 + #: The style keys A1 and C2 name. Anything else is DROPPED, in silence and on purpose; see #: `_clean_style` for why that is not the same decision as an unknown `format.kind`. _STYLE_MARKS = ("bold", "italic", "underline") @@ -107,6 +125,28 @@ _BORDER_SIDES = ("top", "right", "bottom", "left") #: outlives every layout change, exactly as a stored hex outlives a palette. _MAX_INDENT = 8 +#: Wave 54: how far a cell's value may be turned, in DEGREES. Excel's own range, and it is signed +#: because turning a header up and turning it down are two different requests. Zero is upright and +#: is stored as an ABSENCE, for `_clean_style`'s falsey-mark reason. Mirrored in +#: `types.ts::MIN_TEXT_ROTATION` / `MAX_TEXT_ROTATION`. +MIN_TEXT_ROTATION = -90 +MAX_TEXT_ROTATION = 90 + +#: Wave 54: a cell may carry a LINK and a NOTE, and neither is a value. A note is never counted as +#: hand typed, never reaches a formula and never becomes a cell's display; a link says what its +#: target IS, because a web address, an A1 address and a tab name are opened by three different +#: doors. Mirrored in `types.ts::Cell.link` / `Cell.note`. +CELL_LINK_KINDS = ("url", "cell", "sheet") +_MAX_LINK_HREF = 512 +_MAX_CELL_NOTE = 1000 + +#: Wave 54: a cell may also carry a SPARKLINE, a picture of a range drawn inside the cell itself. +#: It is CELL level and not tab level, unlike a chart, because that is what it is: the renderer is +#: `web/src/sheet/sparkline.ts`, called from `SheetGrid.tsx::paintCell` with the cell in hand, so +#: a tab-level array would have to be searched per cell on every paint. The three kinds are +#: Excel's own. Mirrored in `types.ts::SPARKLINE_KINDS` / `CellSparkline`. +SPARKLINE_KINDS = ("line", "column", "winloss") + #: C2's custom format code. ⚠ THE CAPS ARE PART OF THE VOCABULARY, not a guess: a format code is #: interpreted by the client's formatter, so an unbounded one is an unbounded parse, and Excel's #: own grammar holds at most four sections (positive; negative; zero; text). @@ -123,13 +163,57 @@ _MAX_VALIDATION_ENTRY = 200 SHEET_RULE_OPS = ("gt", "lt", "gte", "lte", "eq", "neq", "between", "contains", "empty", "notEmpty") +#: ⛔⛔ W54-T05's THREE RULE KINDS, and the SAME refusal discipline the ten operators get. A +#: `cell` rule is a condition and a flat style; a `scale` bands its value across a stored low..high +#: range; a `bar` draws a proportional rectangle inside the cell. A kind nothing can paint is +#: refused by name rather than dropped, because dropping it would silently turn a colour scale into +#: a highlight rule reading `between`, which is a DIFFERENT paint than the one somebody asked for. +#: +#: ⭐ `cell` IS STORED AS AN ABSENCE, exactly as `wrap: false` and `indent: 0` are: it is what +#: every rule written before this ticket already is, so writing the word onto them would make a +#: reload compare unequal to the save. Mirrored in `web/src/sheet/types.ts::SHEET_RULE_KINDS`. +SHEET_RULE_KINDS = ("cell", "scale", "bar") + #: The style keys a conditional format rule may repaint. A rule is a PAINT, never a format: it #: cannot change how a number reads, so it carries no `format`. _RULE_STYLE_MARKS = ("bold",) _RULE_STYLE_COLOURS = ("fill", "color") -#: The chart kinds W49-T08 draws. Mirrored in `types.ts::SheetChartSpec`. -SHEET_CHART_KINDS = ("bar", "line", "area", "donut") +#: ⛔⛔ THE CHART KINDS A DOCUMENT MAY HOLD, which is NOT the same list as the chart kinds a +#: renderer can draw, and the two were one list until wave 54 made the difference matter. +#: `_clean_charts` drops a chart whose kind is outside this tuple, so a kind missing from here is +#: a picture somebody made that is gone on the next read, in silence: exactly D-640's mechanism, +#: one level down. This tuple is therefore the STORAGE vocabulary and it is mirrored, name for +#: name and in this order, by `types.ts::SheetChartSpec.kind`. +#: +#: ⚠ `types.ts::SHEET_CHART_DRAWN_KINDS` IS A DIFFERENT AND NARROWER THING: a CAPABILITY list, +#: naming the kinds the client can put on a canvas today. A kind stored here and not drawn there +#: is a chart the document keeps safely while its renderer is built. The reverse, a kind drawn +#: but not stored here, is the defect, and it is what widening this tuple prevents. +SHEET_CHART_KINDS = ("bar", "line", "area", "donut", "column", "pie", "scatter", "combo") + +#: ⛔⛔ D-640's MECHANISM, STATED. THIS IS EVERY KEY A CLEANED TAB MAY CARRY, and a key that is +#: not named here is DELETED on the next save, in silence, with nothing going red: `_clean_sheet` +#: returns a FRESH dict rather than an amended copy of what it was handed, so the document saves, +#: the tab is valid, and whatever the client put in the unnamed slot is simply not in it. That is +#: how `charts` was eaten between W49-T08 and W51-T21, and it is how the NEXT slot added to a tab +#: gets eaten unless its name is added to this tuple in the same change that adds it. +#: +#: ⭐ THE SET IS THE FUNCTION'S OWN RULER. `_clean_sheet` emits its optional strata by walking +#: this tuple, so the two cannot drift apart by an edit to one of them, and `verify_sheet.py` +#: section 1 drives the real cleaner with a tab carrying every stratum and asserts it returns +#: nothing outside this set. Removing `charts` from here reds that leg, which is the negative +#: control D-640 is closed with. +#: +#: The order is the order a cleaned tab reads in: identity, then A2's geometry, then C2's strata. +SHEET_TAB_KEYS = ("id", "name", "cols", "rows", "cells", "colWidths", "freeze", + "rules", "hiddenRows", "hiddenCols", "charts", "imported") + +#: The keys above that `_clean_sheet` writes UNCONDITIONALLY. Every other member of +#: `SHEET_TAB_KEYS` is written only when it holds something, for `_clean_style`'s reason: a tab +#: with no rules and a tab with `rules: []` read identically, so only one of them is stored and a +#: reload compares equal to the thing it saved. +SHEET_TAB_ALWAYS_KEYS = ("id", "name", "cols", "rows", "cells") _MAX_RULES = 100 _MAX_HIDDEN = 5000 @@ -152,8 +236,8 @@ _MAX_DECIMALS = 10 #: column letters and seven row digits, and `a1.ts` agrees with it; 702 is the last TWO letter #: column (ZZ) and 100000 rows is what glide's virtualised scroller stays comfortable inside. A #: sheet at the ceiling is still far above `_MAX_CELLS_PER_SHEET`, so content runs out first. -DEFAULT_SHEET_COLS = 26 -DEFAULT_SHEET_ROWS = 200 +DEFAULT_SHEET_COLS = 200 +DEFAULT_SHEET_ROWS = 10000 DEFAULT_COL_WIDTH = 120 MIN_SHEET_COLS = 1 MIN_SHEET_ROWS = 1 @@ -453,9 +537,38 @@ def _clean_style(raw): if steps: out["indent"] = steps - size = _text(raw.get("size"), 4) - if size in CELL_SIZES and size != "m": - out["size"] = size + #: ⭐⭐ R11: THE SAME SLOT, TWO SHAPES, AND THE ORDER OF THE BRANCHES IS THE WHOLE OF IT. + #: `_text` stringifies anything it is handed, so reading a point size through it would turn 12 + #: into "12", find it outside the four step names and drop it in silence: a size the person + #: picked, gone on the next read with nothing to say so. The type is decided FIRST, and a step + #: name still round trips exactly as it always did. A point size is CLAMPED, not refused, for + #: the rotation's reason below, and the default is stored as an absence just as `m` is. + size = raw.get("size") + if isinstance(size, str): + step = _text(size, 4) + if step in CELL_SIZES and step != "m": + out["size"] = step + elif not isinstance(size, bool) and isinstance(size, (int, float)): + points = max(MIN_FONT_PT, min(MAX_FONT_PT, int(round(size)))) + if points != DEFAULT_FONT_PT: + out["size"] = points + + #: R10's typeface. A name outside the closed list is DROPPED in silence, which is this + #: cleaner's house rule for a decoration the client cannot promise to paint; the default face + #: is an absence, so a cell set back to it is the cell it was. + font = _text(raw.get("font"), 40) + if font in CELL_FONTS and font != DEFAULT_CELL_FONT: + out["font"] = font + + #: Wave 54's turn, clamped rather than refused, exactly as the indent is: a rotation is a + #: presentation, so 400 degrees is somebody asking for the most turn there is, not a document + #: that has to be rejected. Upright is stored as an absence, so an unrotated cell is byte for + #: byte the cell it was before somebody turned it and turned it back. + rotation = raw.get("textRotation") + if not isinstance(rotation, bool) and isinstance(rotation, (int, float)): + degrees = max(MIN_TEXT_ROTATION, min(MAX_TEXT_ROTATION, int(rotation))) + if degrees: + out["textRotation"] = degrees fmt = _clean_format(raw.get("format")) if fmt: @@ -499,6 +612,56 @@ def _clean_validation(raw): return {"list": out} if out else None +def _clean_link(raw): + """Wave 54's cell link `{href, kind}`, or None when nothing survives. + + ⚠ BOTH HALVES OR NEITHER. A link with a target and no kind cannot be opened, because the kind + is what decides WHICH door opens it: a web address, an A1 address on this workbook, and a tab + by name are three different acts. Storing half of one would leave a cell wearing an + affordance that does nothing when it is clicked. + + ⚠ THE HREF IS CLAMPED, NOT PARSED. This module stores documents; deciding whether a URL is + reachable, or whether `Sheet2!B7` exists, belongs to the door that opens it, which can say so + at the moment somebody clicks. + """ + if not isinstance(raw, dict): + return None + kind = _text(raw.get("kind"), 12) + href = _text(raw.get("href"), _MAX_LINK_HREF) + if kind not in CELL_LINK_KINDS or not href: + return None + return {"href": href, "kind": kind} + + +def _clean_sparkline(raw): + """Wave 54's in-cell sparkline `{kind, range}`, or None when nothing survives. + + ⚠ BOTH HALVES OR NEITHER, for `_clean_link`'s reason. A sparkline with a range and no kind + cannot be drawn, because the kind is what decides WHICH picture is drawn over those numbers: a + line, a column run and a win/loss bar say three different things about the same range. Storing + half of one would leave a cell that claims to hold a picture nothing can put on a canvas. + + ⚠ IT IS DROPPED WHEN MALFORMED, NEVER REFUSED, which is the link's decision and not the format + code's: a sparkline does not change what any cell READS AS, so a broken one is a missing + picture and never a wrong number on a screen. Refusing would 400 a whole workbook save over a + decoration. + + ⭐ THE RANGE IS `_clean_range`'s, so a sparkline's rectangle is spelled the same way a chart's + and a rule's are. It takes `"B2:D40"`, the single cell `"B2"` and the rectangle dict, and it + stores the rectangle: a document with two spellings of one rectangle is a document every later + reader has to branch on. + """ + if not isinstance(raw, dict): + return None + kind = _text(raw.get("kind"), 20) + if kind not in SPARKLINE_KINDS: + return None + rect = _clean_range(raw.get("range")) + if rect is None: + return None + return {"kind": kind, "range": rect} + + def clean_cell(raw, addr=""): """Normalize ONE cell, or raise `SheetRefusal` with a named code. @@ -541,6 +704,15 @@ def clean_cell(raw, addr=""): validation = _clean_validation(raw.get("validation")) if validation: cell["validation"] = validation + #: ⛔ THE SPARKLINE SURVIVES THIS BRANCH, AND LEAVING IT OUT WOULD BE THE COMMON CASE + #: RATHER THAN THE EDGE ONE. A sparkline cell usually holds no text at all: somebody + #: paints a picture of the row beside it and types nothing, which is precisely an + #: `empty` cell. A picture is not content in the sense this branch strips, because it + #: has no value, is never hand typed and never reaches a formula, so it belongs with + #: the style rather than with the text that is dropped here. + sparkline = _clean_sparkline(raw.get("sparkline")) + if sparkline: + cell["sparkline"] = sparkline return cell if raw.get("text") is not None: @@ -567,6 +739,21 @@ def clean_cell(raw, addr=""): if raw.get("refreshed_at") is not None: cell["refreshed_at"] = _text(raw.get("refreshed_at"), 120) + #: Wave 54's link, note and sparkline. All three are DROPPED when malformed rather than + #: refused, which is the validation list's decision and not the format code's: none of them + #: changes what the cell READS AS, so a broken link is a missing affordance and a broken + #: sparkline is a missing picture, never a wrong number on a screen. + link = _clean_link(raw.get("link")) + if link: + cell["link"] = link + if raw.get("note") is not None: + note = _text(raw.get("note"), _MAX_CELL_NOTE) + if note: + cell["note"] = note + sparkline = _clean_sparkline(raw.get("sparkline")) + if sparkline: + cell["sparkline"] = sparkline + #: C2: the in-cell list. Normalized before the style so a refusing style still reports first. validation = _clean_validation(raw.get("validation")) if validation: @@ -734,15 +921,43 @@ def _clean_rule_style(raw): return out +def _clean_rule_scale(raw): + """A COLOUR SCALE's two end TOKENS, or None. + + ⛔ BOTH ENDS OR NEITHER. One end alone names no ramp at all, and storing half of one would + leave the client looking up a pair that cannot match and falling back to a default scale the + person never chose. The tokens go through the same `_COLOUR` guard `_clean_rule_style` uses, + so nothing free form reaches a canvas `fillStyle` from a stored document. + + ⚠ THE SCALE'S BOUNDS ARE NOT HERE. They ride `value` and `value2` on the rule itself, which + `_clean_rules` already persists for every op that takes operands, so a colour scale needed no + new numeric slot at all. + """ + if not isinstance(raw, dict): + return None + out = {} + for key in ("low", "high"): + token = _text(raw.get(key), 40) + if not token or not _COLOUR.match(token): + return None + out[key] = token + return out + + def _clean_rules(raw): """C2's conditional format rules for one tab, at most `_MAX_RULES` of them. ⛔ AN OP OUTSIDE `SHEET_RULE_OPS` IS REFUSED BY NAME, for `_clean_format`'s reason: a rule whose operator nothing can evaluate never fires, so dropping it would leave a person looking - at a sheet they believe is painted by a rule that is not there. - - ⚠ THE COUNT IS CLAMPED rather than refused: the rules past the cap are ones nobody could see - the effect of, and refusing would make a sheet that can never be saved again. + at a sheet they believe is painted by a rule that is not there. A KIND outside + `SHEET_RULE_KINDS` is refused the same way, and for a sharper version of the same reason: a + dropped kind does not stop the rule firing, it makes it fire as a DIFFERENT paint. + + ⛔⛔ AND THIS IS THE D-640 SHAPE, SO READ IT BEFORE ADDING A FIELD. Each rule below is built + EXPLICITLY, key by key, which means a field the client starts writing and this function does + not learn is dropped on the very next read: the feature would delete itself one save later, + with the editor still listing what it wrote. W54-T05's `kind` and `scale` are here because + that ticket added them to both halves in one commit. """ if raw is None: return [] @@ -757,11 +972,23 @@ def _clean_rules(raw): raise SheetRefusal( "sheet_rule_op_unknown", "A sheet rule condition must be one of " + ", ".join(SHEET_RULE_OPS) + ".") + kind = _text(row.get("kind"), 20) or "cell" + if kind not in SHEET_RULE_KINDS: + raise SheetRefusal( + "sheet_rule_kind_unknown", + "A sheet rule kind must be one of " + ", ".join(SHEET_RULE_KINDS) + ".") rect = _clean_range(row.get("range")) if rect is None: continue rule = {"id": _text(row.get("id"), _MAX_ID) or uuid.uuid4().hex[:12], "range": rect, "op": op, "style": _clean_rule_style(row.get("style"))} + #: ⭐ THE DEFAULT KIND IS AN ABSENCE (see `SHEET_RULE_KINDS`), so a rule that was turned + #: into a colour scale and back is byte for byte the rule it started as. + if kind != "cell": + rule["kind"] = kind + scale = _clean_rule_scale(row.get("scale")) + if scale: + rule["scale"] = scale #: ⚠ `empty` and `notEmpty` take NO operand, and carrying one would store a rule whose #: text says it compares against something it can never read. if op not in ("empty", "notEmpty"): @@ -851,8 +1078,15 @@ def _clean_sheet(raw, index=0): ⛔ EVERY KEY THIS FUNCTION DOES NOT NAME IS DROPPED, and that is worth knowing before adding one: the return below is a fresh dict, not an amended copy of `raw`. A2's four geometry keys - and C2's five strata are named here for exactly that reason, and `charts` is named because it - was the one this rule silently ate until W51-T21 (D-640). + and C2's five strata are named for exactly that reason, and `charts` is named because it was + the one this rule silently ate until W51-T21 (D-640). + + ⭐⭐ THE NAMES LIVE IN `SHEET_TAB_KEYS` AND THIS FUNCTION EMITS THROUGH IT, which is D-640 + closed rather than patched. Before wave 54 the set was implicit: it existed only as the + literals typed into this body, so nothing stated it, nothing could gate it, and the only way + to learn that a new slot was being eaten was to save a tab and reload it. Walking the tuple + means a stratum computed here but missing from the tuple is never written, and + `verify_sheet.py` reds when the two disagree, so the next slot cannot repeat the defect. """ if not isinstance(raw, dict): raise SheetRefusal("sheet_not_an_object", "A sheet must be an object.") @@ -868,28 +1102,34 @@ def _clean_sheet(raw, index=0): #: silently un-described. sheet = {"id": sid, "name": name, "cols": cols, "rows": rows, "cells": _clean_cells(raw.get("cells"), sheet_name=name)} - widths = _clean_col_widths(raw.get("colWidths"), cols) - if widths: - sheet["colWidths"] = widths - freeze = _clean_freeze(raw.get("freeze"), cols, rows) - if freeze: - sheet["freeze"] = freeze - #: C2's five strata. Each is written only when it holds something, for `_clean_style`'s - #: reason: a tab with no rules and a tab with `rules: []` read identically, so one of them is - #: what gets stored and a reload compares equal to the thing it saved. - rules = _clean_rules(raw.get("rules")) - if rules: - sheet["rules"] = rules - for key, what in (("hiddenRows", "rows"), ("hiddenCols", "columns")): - hidden = _clean_hidden(raw.get(key), what) - if hidden: - sheet[key] = hidden - charts = _clean_charts(raw.get("charts")) - if charts: - sheet["charts"] = charts - imported = _clean_imported(raw.get("imported")) - if imported: - sheet["imported"] = imported + + #: ⚠ THE ORDER OF THIS DICT IS THE ORDER THE CLEANERS RUN IN, and it is load bearing: two of + #: them REFUSE by name (`_clean_rules` on an unknown op, `_clean_imported` on a record that is + #: not an object), so a reordering here would change which refusal a caller sees first when a + #: tab is wrong in two places at once. + optional = { + "colWidths": _clean_col_widths(raw.get("colWidths"), cols), + "freeze": _clean_freeze(raw.get("freeze"), cols, rows), + "rules": _clean_rules(raw.get("rules")), + "hiddenRows": _clean_hidden(raw.get("hiddenRows"), "rows"), + "hiddenCols": _clean_hidden(raw.get("hiddenCols"), "columns"), + "charts": _clean_charts(raw.get("charts")), + "imported": _clean_imported(raw.get("imported")), + } + + #: ⛔ THE WALK IS THROUGH `SHEET_TAB_KEYS`, NOT THROUGH `optional`, AND THAT IS THE WHOLE + #: POINT OF D-640'S FIX. A stratum cleaned above but never added to the tuple is dropped here + #: rather than written, which is the same silent loss as before EXCEPT that the gate now sees + #: it: `verify_sheet.py` drives a tab carrying every stratum and compares what comes back + #: against the tuple, so the disagreement reds instead of shipping. + #: + #: Each is written only when it holds something, for `_clean_style`'s reason: a tab with no + #: rules and a tab with `rules: []` read identically, so only one of them is stored and a + #: reload compares equal to the thing it saved. + for key in SHEET_TAB_KEYS: + value = optional.get(key) + if value: + sheet[key] = value return sheet diff --git a/platform/core/table_store.py b/platform/core/table_store.py index 19aed664b8ecc5e9808ea6bc8186afe52832d4a5..f70e2130c4cc7e1ae15acffd775f20d81e1f5779 100644 --- a/platform/core/table_store.py +++ b/platform/core/table_store.py @@ -2133,6 +2133,34 @@ class TableStore: self._update(username, _drop, shared=lambda shared_fields: shared_fields.pop(key, None)) + def _shared_stratum_key(self): + """WHICH document holds this table's tenant-wide stratum — D-643. + + ⛔⛔ THE BUG THIS CLOSES, AND THE DIRECTION IT IS CLOSED IN. Every call below used to hand + `self.table_key` straight to `core.shared_overlay`, whose `bucket()` appends `__shared`. + For a user database that key is `ut__table_workspace`, so the three sites addressed + `ut__table_workspace__shared` while the CREATE door + (`core.grid_events._field_share_keys`, the authority) mints and every one of the seven + readers reads the BARE `ut___shared`. `_tenant_wide_keys` therefore answered the empty + set for every `ut_*` table that has a shared column, and `patch_overlay` routed a + tenant-wide value into the caller's own per-user member. + + ⛔ THIS IS THE OPPOSITE OF THE CHANGE WAVE 50 REFUSED, and the difference matters because + the two look alike. Its lane D was asked to make `_field_storage_keys` resolve the + WORKSPACE spelling, and refused: that would have pointed the share dialog at a bucket + nothing writes and orphaned every `ut_*` shared column with every gate green + ([[the-ut-shared-bucket-is-bare-on-purpose]]). This aligns `TableStore` DOWN to the bare + spelling the create door and the readers already use, which is the same rule stated once. + + ⚠ ONLY THE `ut_` BRANCH MOVES. `product_table_workspace` and `customer_table_workspace` + are correct exactly as they stand (a gate asserts them), so every other key is returned + unchanged. + """ + raw = str(self.table_key or '') + if raw.startswith('ut_') and raw.endswith('_table_workspace'): + return raw[:-len('_table_workspace')] + return raw + def _tenant_wide_keys(self): """The columns of THIS table whose values live in the tenant-wide stratum. @@ -2148,7 +2176,7 @@ class TableStore: """ try: import core.shared_overlay as shared_overlay - return set(shared_overlay.fields(self.table_key, st=self._st) or ()) + return set(shared_overlay.fields(self._shared_stratum_key(), st=self._st) or ()) except Exception: # noqa: BLE001 return set() @@ -2186,7 +2214,7 @@ class TableStore: # ⚠ `st=self._st`, NEVER the module default. The two strata must resolve to the SAME # tenant handle, or a value written by one is invisible to the other and the user's # edit vanishes the moment they save it (`_ProductTableStore` records the same rule). - shared_overlay.put_cells(self.table_key, pid, shared, st=self._st) + shared_overlay.put_cells(self._shared_stratum_key(), pid, shared, st=self._st) if not personal: return @@ -2223,7 +2251,7 @@ class TableStore: if shared: import core.shared_overlay as shared_overlay shared_overlay.put_cells_and_choice_options( - self.table_key, pid, shared, shared_additions, st=self._st) + self._shared_stratum_key(), pid, shared, shared_additions, st=self._st) if not personal: return diff --git a/platform/harness/runtime.py b/platform/harness/runtime.py index 4af7008b4a086bb53889161f083cde8be636f85c..8ab8b2281608f43c6c8cf45ca595e4f3137aef6b 100644 --- a/platform/harness/runtime.py +++ b/platform/harness/runtime.py @@ -307,22 +307,40 @@ class TenantRuntime: return self._store().delete_path(self.store_key(path_in_repo)) # ---------------------------------------------------------------- the Odoo source (R3) - def odoo_source(self): + def odoo_source(self, connection_id=None): """THIS tenant's Odoo connector, or None — the keychain CUTOVER's resolution seam (2026-08-04; `keychain.odoo_creds` was previously called by nothing but its test). Resolution, fail-closed: - 1. a keychain `odoo` entry (any tenant) → a connector bound to THOSE creds; - 2. tenant #0 with an empty/locked keychain → its compiled env connector (R3's - "live with env fallback", which is what keeps Royal working unchanged); + 1. the keychain `odoo` connection NAMED by `connection_id` (W54-T45 / R4), or the + tenant's DESIGNATED DEFAULT connection when no id is named → a connector bound to + THOSE creds; + 2. tenant #0 with an empty/locked keychain and NO id named → its compiled env + connector (R3's "live with env fallback", which keeps Royal working unchanged); 3. anyone else → None. NEVER the environment: env is tenant #0's connection, and handing it to another tenant is the leak this method exists to prevent. + ⛔⛔ W54-T45 — THE ENV FALLBACK NARROWS HERE AND MUST NEVER WIDEN. A caller that NAMES a + connection and gets nothing back is answered None, full stop: not the default connection, + not a sibling, and above all not tenant #0's `.env`. Under R4 an agency holds one Odoo + connection per client, and under R7 that isolation is strict — a named-but-unresolvable + connection quietly falling through to the environment would serve tenant #0's own Odoo to + a question asked about somebody else's books, with nothing red anywhere. Leg (2) is + reachable only on the UNNAMED path, which is exactly the pre-wave behaviour. + Rebuilt per call on purpose — `core.odoo` caches the CLIENT per (slug, creds fingerprint), so this stays cheap while a rotated key reconnects on the next call.""" import core.keychain as keychain + named = connection_id is not None try: - creds = keychain.odoo_creds(self) + # ⚠ THE UNNAMED PATH IS SPELLED AS THE PRE-WAVE CALL, VERBATIM, and the branch is not + # decoration: `verify_api`'s R11 leg pins the literal `keychain.odoo_creds(self)` in + # this method's source as its proof that the resolver is KEYCHAIN-FIRST. Writing only + # the two-argument form would have turned that gate red for a reason that has nothing + # to do with the rule it guards, in a file this lane may not edit. The two arms are + # the same question; the left one is the one every existing caller asks. + creds = (keychain.odoo_creds(self) if not named + else keychain.odoo_creds(self, connection_id)) except Exception: # locked or unreadable keychain — fall through, fail closed creds = None if creds: @@ -332,34 +350,49 @@ class TenantRuntime: return OdooConnector(tenant_slug=self.key, creds=creds, scope={"team_ids": list(bus.values()) or None, "team_names": {v: k for k, v in bus.items()} or None}) + # ⛔ THE NAMED LEG STOPS HERE. See the docstring: an explicit connection that did not + # resolve is None, never the environment and never another connection. + if named: + return None if self.key == "royal-imports": return (getattr(self.tenant, "sources", {}) or {}).get("odoo") return None # ------------------------------------------------------- the connector PAUSE (D-10, wave 24) - def odoo_flag_key(self): + def odoo_flag_key(self, connection_id=None): """WHICH connector flag governs this tenant's Odoo — the key `connectors[].paused` is stored under, or None when nothing would serve. THE SAME RESOLUTION AS `odoo_source()` ABOVE, expressed as an identity instead of a - client: first unlocked keychain `odoo` entry, else tenant #0's compiled env source, else - nothing. It lives here so there is ONE resolver — `routes_keychain._resolved_odoo_key` - was a second copy of these three rules in the API layer, and a pause flag written against - one resolution and read against the other freezes nothing while reporting success. + client: the keychain `odoo` connection named (or the designated default when none is), + else tenant #0's compiled env source, else nothing. It lives here so there is ONE + resolver — `routes_keychain._resolved_odoo_key` was a second copy of these three rules in + the API layer, and a pause flag written against one resolution and read against the other + freezes nothing while reporting success. + + ⛔⛔ W54-T45 — AND THE INLINE WALK IS GONE, WHICH IS WHAT MADE THE SENTENCE ABOVE TRUE. + This method claimed to be the one resolver while carrying its own copy of "the first + `odoo` entry", so `keychain` and `runtime` each decided which connection serves. Both now + ask `keychain.resolve_connection_id`, which decrypts nothing — a pause flag has to resolve + on a LOCKED keychain, which is why this is an identity call and not a credential one. + ⛔ A NAMED CONNECTION THAT DOES NOT RESOLVE IS None, exactly as in `odoo_source`: pausing + by a connection id must never silently address tenant #0's environment source instead. """ import core.keychain as keychain + named = connection_id is not None try: - entries = keychain.list_entries(self) + resolved = keychain.resolve_connection_id(self, "odoo", connection_id) except Exception: - entries = [] - first_odoo = next((e["id"] for e in entries if e.get("type") == "odoo"), None) - if first_odoo and keychain.unlocked(): - return first_odoo + resolved = None + if resolved and keychain.unlocked(): + return resolved + if named: + return None if self.key == "royal-imports" and os.environ.get("ODOO_URL"): return ENV_ODOO_FLAG_KEY return None - def odoo_paused(self): + def odoo_paused(self, connection_id=None): """Is THIS tenant's RESOLVED Odoo source paused? ⚠ RESOLVED, not "any entry" — pausing an entry that is not the one serving freezes @@ -367,9 +400,13 @@ class TenantRuntime: False, because a store hiccup must not freeze a live surface. That policy is inherited from the API-layer function this one replaced, deliberately, so there is one answer to "what happens when we cannot tell" rather than two that can disagree. + + ⭐ W54-T45 — `connection_id` passes straight through to `odoo_flag_key`, so "is the + connection serving THIS client paused" is answerable per connection under R4. No id keeps + meaning the tenant's designated default, which is every existing caller. """ try: - flag_key = self.odoo_flag_key() + flag_key = self.odoo_flag_key(connection_id) if not flag_key: return False flags = self.get(CONNECTOR_FLAGS_KEY) or {} diff --git a/platform/odoo_client.py b/platform/odoo_client.py index b7cba17ac397b77ac60770d958f601c3d8e2cff3..fcc4c53304e6a26f5f058b82f48c14ed42f9e365 100644 --- a/platform/odoo_client.py +++ b/platform/odoo_client.py @@ -61,12 +61,28 @@ class OdooClient: def __init__(self, creds=None): """`creds` (R3 keychain cutover): an explicit {url, db, user, api_key} dict — a TENANT'S stored credentials — wins over the environment. None keeps the env/.env behavior every - existing caller relies on (tenant #0's connection).""" + existing caller relies on (tenant #0's connection). + + ⛔⛔ W54-T45 / R7 — IT IS ALL-OR-NOTHING, AND THE PER-FIELD VERSION WAS A REAL LEAK SHAPE. + Each field used to read `creds.get(k) or os.environ.get(...)` INDIVIDUALLY, so an explicit + connection whose stored `db` was blank or missing silently inherited tenant #0's `ODOO_DB` + while keeping the caller's `url`, `user` and `api_key`. Under R4 an agency holds one Odoo + connection per client and under R7 that isolation is strict: a half-environment client is + one client's question authenticated against another's database, and it does not raise — + it returns real, plausible, wrong rows. So a supplied `creds` is used WHOLE, and a field + it is missing is MISSING (the `RuntimeError` below names it) rather than borrowed. With no + `creds` at all the environment builds the client exactly as it always did. + """ + from_env = creds is None creds = creds or {} - self.url = str(creds.get('url') or os.environ.get('ODOO_URL', '')).rstrip('/') - self.db = str(creds.get('db') or os.environ.get('ODOO_DB', '')) - self.user = str(creds.get('user') or os.environ.get('ODOO_USER', '')) - self.api_key = str(creds.get('api_key') or os.environ.get('ODOO_API_KEY', '')) + + def _f(key, env_key): + return str((os.environ.get(env_key, '') if from_env else creds.get(key)) or '') + + self.url = _f('url', 'ODOO_URL').rstrip('/') + self.db = _f('db', 'ODOO_DB') + self.user = _f('user', 'ODOO_USER') + self.api_key = _f('api_key', 'ODOO_API_KEY') missing = [k for k, v in [('ODOO_URL', self.url), ('ODOO_DB', self.db), ('ODOO_USER', self.user), ('ODOO_API_KEY', self.api_key)] if not v] if missing: diff --git a/web/src/connectors/ConnectorsPage.tsx b/web/src/connectors/ConnectorsPage.tsx index 4356da6177040d26b010c8a2d7265c633f1fe17e..e7c944e4e93e78eaa3d85a6ecd8aa2f9dde87078 100644 --- a/web/src/connectors/ConnectorsPage.tsx +++ b/web/src/connectors/ConnectorsPage.tsx @@ -169,18 +169,16 @@ export interface ConnectorRow { */ scope?: string; /** - * ⭐⭐ W53-T29 · RULING R6 — WHICH SCOPES THIS SOURCE MAY EVER CARRY, e.g. `["business"]` for - * Odoo and both words for Gmail. The server's one declaration of it is - * `routes_keychain.allowed_scopes`, built on the same `TENANT_WIDE_TYPES` tuple its refusals - * are built on, and every directory row is stamped with it. + * WHICH SCOPES THIS SOURCE MAY EVER CARRY, e.g. `["business"]` for Odoo and both words for + * Gmail. The server's one declaration of it is `routes_keychain.allowed_scopes`, built on the + * same `TENANT_WIDE_TYPES` tuple its refusals are built on, and every directory row is stamped + * with it. * - * ⛔ IT IS THE SOURCE'S RULE, NOT THIS READER'S PERMISSION — that is `canBusiness` on the - * payload. The Company / Mine toggle needs both: eligibility decides which side a card COULD - * appear on, permission decides whether the Company side exists for this reader at all. - * - * Absent (an older server) ⇒ treated as both, which is the honest degradation: this field only - * ever NARROWS a tier, so a missing one leaves the page exactly as it was before this ticket - * rather than hiding a connection the reader really holds. + * ⛔ IT IS THE SOURCE'S RULE, NOT THIS READER'S PERMISSION, and since WAVE 54 · RULING R4 no + * section on this page branches on it: the Company / Mine toggle that read it is withdrawn. + * The field is still read off the wire because the server still declares it and the keychain + * surface in Settings still decides a scope with it. This page lists connections; it no longer + * sorts them by who they belong to. */ allowedScopes?: string[]; /** What the admin will be asked for — shown where the decision is made, not in a tour. */ @@ -245,13 +243,14 @@ type Load = gaps: ConnectorGap[]; /** W49-T18: the category rail, exactly as the server counted it. */ chips: DirectoryCategory[]; - /** - * ⭐⭐ W53-T29 · RULING R6 — MAY THIS READER SEE THE COMPANY SIDE AT ALL. The server's - * `bool(session.admin)`, under the name `routes_keychain` has used for it since W32-T11. - * ⚠ FALSE UNLESS THE PAYLOAD SAYS OTHERWISE, and false on any failure: the safe direction - * for an admin-only control is closed, the same discipline `canPull` keeps below. + /* + * ⛔⛔ THE ADMIN PERMISSION FLAG STOOD HERE AND IS DELETED BY W54-T42 · RULING R4 + * (2026-09-06). It was the field the Company / Mine toggle branched on, and the toggle is + * withdrawn, so a permission this page reads and never uses would be one edit away from + * reviving a wall the owner removed. The server still sends it on the directory payload and + * `settings/SettingsModal.tsx` still reads it where a scope is actually chosen; what is gone + * is this page's copy, and the gate scan in `verify_schema_overlay.py` keeps it gone. */ - canBusiness: boolean; } | { phase: "error"; message: string }; @@ -353,11 +352,13 @@ export function parseDirectory(body: unknown): ConnectorRow[] { ...(str(c.startUrl) ? { startUrl: str(c.startUrl) } : {}), ...(str(c.note) ? { note: str(c.note) } : {}), ...(str(c.scope) ? { scope: str(c.scope) } : {}), - // ⭐⭐ W53-T29 / R6 — the source's declared eligibility, COPIED off the wire like every - // other field here. `parseCategoryTags` is this file's one reader for a list of words from - // the server (strings only, blanks dropped, deduped); a second identical parser would be a - // second place for "read a string list" to go wrong. An empty or absent list yields no key - // at all, which the tier filters read as "unrestricted". + // The source's declared eligibility, COPIED off the wire like every other field here. + // `parseCategoryTags` is this file's one reader for a list of words from the server + // (strings only, blanks dropped, deduped); a second identical parser would be a second + // place for "read a string list" to go wrong. An empty or absent list yields no key at all. + // ⚠ W54-T42 · R4 — nothing on this page FILTERS on it any more; the tiers that did are + // withdrawn. It is kept because the server declares it on every row and the keychain + // surface in Settings still decides a scope with it. ...(parseCategoryTags(c.allowedScopes).length ? { allowedScopes: parseCategoryTags(c.allowedScopes) } : {}), @@ -614,21 +615,17 @@ export default function ConnectorsPage({ * spends money is closed. */ const [canPull, setCanPull] = useState(false); - /** - * ⭐⭐ W53-T29 · OWNER RULING R6 — WHICH SIDE OF THE COMPANY / MINE TOGGLE IS SHOWING, HELD IN - * THE SERVER'S OWN TWO WORDS. - * - * ⛔ `business` / `personal` RATHER THAN `company` / `mine`, and that is the whole discipline of - * this ticket. `routes_keychain.py::SCOPES` already names these two ideas and every row on the - * wire is filed by them; a second client-only pair of words for the same split would be one - * rename away from a tier that filters on a word nothing sends. "Company" and "Mine" are the - * ruling's LABELS, which is a copy decision, and they live in the buttons below and nowhere - * else. Read as a string for the same reason `state` is (the wave-9 law). + /* + * ⛔⛔ THE COMPANY / MINE TOGGLE STOOD HERE AND IS WITHDRAWN BY W54-T42 · OWNER RULING R4 + * (2026-09-06). Its state, its two chips, its permission read and the two connected tiers it + * partitioned are all deleted: one flat "Connected" section now lists every connected card, so + * a member reaches the same connections an admin does. * - * ⚠ MEANINGLESS FOR A NON-ADMIN, who never sees the control that changes it: their view is - * decided structurally below, not by this value. + * ⚠ THE SERVER'S REFUSAL IS DELIBERATELY UNTOUCHED. R4 replaces WHO may add a connector with a + * per-user grant on a third axis (Database, Module, Connector), which is a separate ticket's + * work; until that lands, `routes_keychain` still refuses a member's company-wide create and a + * personal scope on a tenant-wide source. Withdrawing a control is not opening a door. */ - const [scopeTier, setScopeTier] = useState("business"); useEffect(() => { let dead = false; @@ -638,7 +635,7 @@ export default function ConnectorsPage({ credentials: CREDENTIALS, }); const body = (await res.json().catch(() => null)) as - | { error?: { message?: string }; canBusiness?: unknown } + | { error?: { message?: string } } | null; if (dead) return; if (!res.ok) { @@ -653,11 +650,6 @@ export default function ConnectorsPage({ rows: parseDirectory(body), gaps: parseGaps(body), chips: parseCategories(body), - // ⭐⭐ W53-T29 / R6 — a LITERAL `true` is permission and anything else is not. An older - // server sends nothing here and this reader gets no Company side, which is the safe way - // round: the toggle appearing for a member would be the ruling broken, while a missing - // toggle for an admin is a page that still lists every connection they have. - canBusiness: (body as { canBusiness?: unknown } | null)?.canBusiness === true, }); } catch { if (!dead) setLoad({ phase: "error", message: "Cannot reach the server." }); @@ -721,62 +713,21 @@ export default function ConnectorsPage({ const databaseRows = rows.filter((r) => r.spawns_tables === true); const otherRows = rows.filter((r) => r.spawns_tables !== true); /** - * ⭐⭐ W52-T02 · RULING R2 / CONTRACT C2 — WHO A CONNECTION IS FOR, ON THE PAGE ITSELF. + * ⭐⭐ W54-T42 · OWNER RULING R4 — EVERY CONNECTED CARD, IN ONE SECTION. * - * R2, verbatim: "The module splits into 'Connected for the company' and 'Connected by you'." - * A connector belongs to the second section when the SIGNED-IN USER holds a `personal` keychain - * entry for it — `row.scope === "personal"`, the server's own two-word vocabulary - * (`routes_keychain.py::SCOPES`), never a client union (the wave-9 law). Every other CONNECTED - * card is the company's. + * R4 withdrew the Company / Mine toggle and the company-wide tier beside it, so who a + * connection belongs to is no longer a question this page asks. What is left is the one honest + * statement: these are the sources this workspace is connected to. Access is granted per user + * on a third axis instead (Database, Module, Connector), which lives in Settings. * - * ⚠ ONLY A CONNECTED CARD IS PARTITIONED HERE. An `available`/`planned`/`catalogue` row is not a - * connection yet, so filing it under "Connected for the company" would claim a connection this - * workspace does not have; it keeps its one home in the Databases / Other sources catalog below. + * ⚠ ONLY A CONNECTED CARD IS LIFTED HERE. An `available`/`planned`/`catalogue` row is not a + * connection yet, so putting it under "Connected" would claim one this workspace does not have; + * it keeps its one home in the Databases / Other sources catalog below. * - * ⚠ TWO DIFFERENT PARTITIONS OF THE SAME ROW SET, DELIBERATELY NOT MERGED WITH THE ONE ABOVE. R1 - * (W52-T01) tiers every card by whether it spawns tables; R2 tiers CONNECTED cards by who owns - * the connection. A connected Odoo row therefore belongs to "Databases" above AND to "Connected - * for the company" here, because the two headings answer different questions about it. + * ⚠ A CONNECTED ODOO ROW APPEARS HERE AND UNDER "Databases", deliberately: R1's tiering asks + * whether a card spawns tables, and this heading answers a different question about it. */ const connectedRows = rows.filter((r) => r.state === "connected"); - /** - * ⭐⭐ W53-T29 · OWNER RULING R6 — TWO QUESTIONS PER CARD, AND BOTH ARE ASKED. - * - * `row.scope` is what this connection WAS STORED AS; `row.allowedScopes` is what its SOURCE may - * ever be (`routes_keychain.allowed_scopes`, derived from the same `TENANT_WIDE_TYPES` tuple the - * server's refusals are derived from). A tier needs both: without the second, one stray or - * legacy `scope` value would put Odoo under Mine, and Odoo is the credential this whole - * workspace's databases are read through. - * - * ⚠ IT ONLY EVER NARROWS. A row that carries no `allowedScopes` (an older server) is treated as - * unrestricted, so the worst an absent declaration can do is leave the page as it was. - */ - const eligible = (row: ConnectorRow, scope: string) => - !row.allowedScopes || row.allowedScopes.includes(scope); - const companyRows = connectedRows.filter( - (r) => r.scope !== "personal" && eligible(r, "business"), - ); - const personalRows = connectedRows.filter( - (r) => r.scope === "personal" && eligible(r, "personal"), - ); - /** - * ⭐⭐ W53-T29 · OWNER RULING R6 — THE NON-ADMIN CASE IS STRUCTURAL, NOT A HIDDEN BUTTON. - * - * R6, verbatim: *"A non-admin does not see the Company side at all; the toggle itself is hidden - * for them."* So `showCompany` cannot be reached without `canBusiness` and `showPersonal` is - * unconditionally true without it: a member sees their own connections and no toggle, and no - * sequence of clicks, stale state or hot reload can produce a Company section for them, because - * there is no state in which one renders. Hiding a control is not a permission check, which is - * why the SERVER refuses a member's business-scoped create as well - * (`routes_keychain.add_key` -> 403 `not_admin`). - * - * ⚠ THE TOGGLE NEEDS SOMETHING TO TOGGLE. With no connected card at all it renders nothing - * rather than two chips over an empty page, the same rule the tier headings already keep. - */ - const canBusiness = load.phase === "ready" && load.canBusiness; - const showCompany = canBusiness && scopeTier !== "personal"; - const showPersonal = !canBusiness || scopeTier === "personal"; - const showScopeToggle = canBusiness && connectedRows.length > 0; // ⚠ Resolved against `allRows`, not the filtered list: typing in the search box while a modal is // open must not close the modal out from under the reader. const openRow = allRows.find((row) => row.key === openKey); @@ -853,93 +804,29 @@ export default function ConnectorsPage({ ) : null} {/* - ⭐⭐ W52-T01 · RULING R1 / CONTRACT C1 — THE TWO HEADED SECTIONS. + ⭐⭐ W54-T42 · OWNER RULING R4 — ONE SECTION FOR EVERY CONNECTED CARD. - ⛔ EACH SECTION RENDERS ONLY WHEN IT HOLDS A CARD. A chip or a search term that empties - one tier must not leave a heading standing over nothing — `rows.length === 0` above - already covers "neither tier has anything", so this is the one-tier-emptied case one - interaction later, and the same honesty rule the empty-state message already keeps. - - ⚠ SAME `ConnectorCard`, NOT A FORK. Both loops pass the identical props; only which array - they map is different, so a connector's card behaves exactly as it did before this ticket - wherever it lands. - */} - {/* - ⭐⭐ W52-T02 · RULING R2 / CONTRACT C2 — THE TWO OWNERSHIP SECTIONS. + ⛔ WHAT STOOD HERE WAS THE COMPANY / MINE TOGGLE AND THE TWO OWNERSHIP TIERS UNDER IT, + one headed for the whole company and one for the reader's own connections, built by + W53-T29 ten days earlier. R4 withdraws the whole split: a workspace's connections are one + list, and access is granted per user on a third axis (Database, Module, Connector) from + Settings rather than by a scope wall on this page. Leaving only the personal tier would + have kept the other half of the same wall, so both went and this replaced them. - ⛔ EACH RENDERS ONLY WHEN IT HOLDS A CARD, the same rule the Databases / Other sources - pair below already keeps: a chip or a search term that empties one tier must not leave a - heading standing over nothing. + ⛔ IT RENDERS ONLY WHEN IT HOLDS A CARD, the same rule the Databases / Other sources pair + below already keeps: a chip or a search term that empties it must not leave a heading + standing over nothing. - ⚠ SAME `ConnectorCard`, NOT A FORK — see the note on `companyRows`/`personalRows` above for - why a card can appear here AND in the catalog tiers below. + ⚠ SAME `ConnectorCard`, NOT A FORK, and the same classes: no new control shape and no new + stylesheet, which is what keeps the page's rhythm exactly as it was minus a chip row. */} - {/* - ⭐⭐ W53-T29 · OWNER RULING R6 — THE COMPANY / MINE TOGGLE, AND ONLY AN ADMIN HAS ONE. - - ⛔ THE SAME CONTROL SHAPE THE CATEGORY RAIL ALREADY USES (`conn-chips` / `conn-chip` / - `is-on`, styled in `styles/wave49/connectors.css`). DESIGN.md §4: a filter rail keeps one - control shape, and this ticket ships no stylesheet, so a class invented here would render - as unstyled native chrome. - ⛔ REAL BUTTONS, NOT A DIV. `aria-pressed` carries the selected state to a screen reader - and `type="button"` keeps it off any form; the visible word IS the accessible name, which - is why neither carries an `aria-label` that would say something else. - */} - {showScopeToggle ? ( -
- - -
- ) : null} - {/* ONE line and the way out, the same shape the empty grid above already uses: a side of - the toggle with nothing on it must say so, or the reader reads the silence as a page - that failed to load. */} - {showScopeToggle && (showCompany ? companyRows.length === 0 : personalRows.length === 0) ? ( -

- {showCompany - ? "No connection is shared with the whole company yet." - : "You have no personal connections yet."} -

- ) : null} - {showCompany && companyRows.length > 0 ? ( -
-

- Connected for the company -

-
- {companyRows.map((row) => ( - setOpenKey(row.key)} - onPullReviews={pullHandler(row)} - /> - ))} -
-
- ) : null} - {showPersonal && personalRows.length > 0 ? ( -
-

- Connected by you + {connectedRows.length > 0 ? ( +
+

+ Connected

- {personalRows.map((row) => ( + {connectedRows.map((row) => (
) : null} + {/* + ⭐⭐ W52-T01 · RULING R1 / CONTRACT C1 — THE TWO HEADED CATALOG SECTIONS. + + ⛔ EACH SECTION RENDERS ONLY WHEN IT HOLDS A CARD. A chip or a search term that empties + one tier must not leave a heading standing over nothing — `rows.length === 0` above + already covers "neither tier has anything", so this is the one-tier-emptied case one + interaction later, and the same honesty rule the empty-state message already keeps. + + ⚠ SAME `ConnectorCard`, NOT A FORK. Both loops pass the identical props; only which array + they map is different, so a connector's card behaves exactly as it did before this ticket + wherever it lands. + */} {databaseRows.length > 0 ? (

diff --git a/web/src/customer-grid/CustomerGrid.tsx b/web/src/customer-grid/CustomerGrid.tsx index b7fa58afcec36b54893a2b6f19d619930e511151..ec7b2579ca1256252d4c3d15746c63dfa15d2aaf 100644 --- a/web/src/customer-grid/CustomerGrid.tsx +++ b/web/src/customer-grid/CustomerGrid.tsx @@ -100,6 +100,8 @@ import { DatePicker } from "./DatePicker"; * shapes for one act is what R6 retires; the manager's copy is another lane's fence. */ import { ConfirmDialog, DialogToggle } from "../ui/ConfirmDialog"; +// D-673 / W54-T21 - the one Escape arbiter, for the route navigator's own close. +import { useEscapeClose } from "../ui/useEscapeClose"; // W49-T17: R32's pre-delete disclosure. A static import is safe here -- nothing else in the // tree imports this component, so it joins THIS chunk rather than pinning another one open // [[tsc-cannot-see-a-broken-code-split]]. @@ -3390,6 +3392,23 @@ function CustomerGridSurface({ const displaySpec = resolvedDisplaySpec; const displayMode: DisplayMode = serverWindowed ? "grid" : displaySpec?.mode ?? "grid"; const [routePanelOpen, setRoutePanelOpen] = useState(false); + /** + * ⭐⭐ D-673 / W54-T21 — THE TOP RUNG OF THE MAP'S ESCAPE LADDER, AND IT HAS TO BE HERE. + * + * W51-T28 built the rungs it could reach from lane G's fence: the kit dialog, then the open + * Route, then the Zone editor and the Zone chooser. The route NAVIGATOR itself stayed + * undismissable, and the register row says exactly why: `routePanelOpen` is this component's + * own `useState`, handed to `MapView` as a read-only prop with no close callback, so no file + * downstream can reach it. Threading a callback through `MapView.tsx` would touch three files + * to arrive at this one line. + * + * ⛔ AND IT IS THE BOTTOM OF THE STACK, NOT A PRIORITY OF ITS OWN. The claim is pushed when the + * panel opens, so everything opened INSIDE it - a row menu, the create menu, an open Route, a + * rename, the delete confirm, the search query - registers later and is therefore topmost. One + * press resolves to the innermost live surface and stops there; only when nothing is left above + * it does Escape close the navigator. + */ + useEscapeClose(routePanelOpen, () => setRoutePanelOpen(false)); useEffect(() => { const openRoute = (event: Event) => { const detail = (event as CustomEvent<{ routeId?: string; forwarded?: boolean }>).detail; diff --git a/web/src/customer-grid/RecordDetail.css b/web/src/customer-grid/RecordDetail.css index c6c130a3b53a4b6307cab4d8593c0bd94cb5d2fc..dc0a98d659d273395b71ff1d831f30892bf290aa 100644 --- a/web/src/customer-grid/RecordDetail.css +++ b/web/src/customer-grid/RecordDetail.css @@ -852,6 +852,53 @@ white-space: nowrap; } +/* ⭐⭐ W54-T39 (instruction 22) — THE RAIL WHILE `/related` IS IN FLIGHT. + The listing is roughly four times faster now, so most readers never see this; the ones on a + cold compute or a slow link do, and what they saw before was `Details` alone with no sign that + anything else was coming (`waves/wave54/shots/F-before-record.png`). + + ⛔ NO SHIMMER AND NO SPIN, and this is the app's existing decision rather than a new one: + `shell/navExtras.css`'s `.shell-rail-skeleton-bar` states it in full — an animated sweep is a + second thing moving in a rail whose whole complaint is movement, and `prefers-reduced-motion` + would then need a third state. One flat tone at the same `--lp-surface-2` that rail uses. There + is no animation here for a reduced-motion query to have to undo. + ⚠ THE ROW GEOMETRY IS `.cg-record-rail-row`'S OWN, inherited rather than restated, so the + placeholder occupies exactly the height a real row will and nothing shifts when the listing + lands. Only `cursor` and the pointer wall are overridden; DESIGN section 4 asks a new nav + element to join the existing rhythm rather than introduce a shape. */ +.cg-record-rail-row.is-skeleton { + cursor: default; + pointer-events: none; +} + +/* Sized to read as a name that has not arrived: the same 9 px bar height and 4 px radius the page + rail's skeleton uses, at a width that sits under `.cg-record-rail-row-label`'s single line. */ +.cg-record-rail-skeleton-bar { + width: 78%; + max-width: 108px; + height: 9px; + margin: 3px 0; + border-radius: 4px; + background: var(--lp-surface-2); +} + +/* The SUBTITLE's stand-in: shorter and quieter, because that is what the second line of a real + row is. Together the pair occupies the two-line height 24 of the 25 real edges settle at, so + the rail does not step when the listing lands. */ +.cg-record-rail-skeleton-bar.is-sub { + width: 58%; + max-width: 82px; + height: 7px; + opacity: 0.6; +} + +/* Folded, the real rows show no labels at all, so the placeholders drop their bars for the same + reason `.shell-side.is-collapsed .shell-rail-skeleton-bar` does: otherwise the fold runs + against a width the settled rail never has. */ +.cg-views.is-collapsed .cg-record-rail-skeleton-bar { + display: none; +} + .cg-record-insights { padding: 12px 16px 24px; } @@ -1305,3 +1352,115 @@ margin-left: auto; margin-right: 6px; } + +/* ⭐⭐ W54-T38 (instruction 22, contract C5, DESIGN.md section 4) — A REFUSAL IS ONE SENTENCE, + AND ITS DIAGNOSIS IS ONE CLICK DOWN. + + The owner was shown a sixty-word paragraph four times over on one record. W54-T37 fixed the + CAUSE and left the presentation, which is the other half of what he reported: section 4 says + "never over-explain", and the block sat ABOVE the grid, so a tab's own rows started below the + fold. The markup fix is in `RecordDetail.tsx` (the strip moved under the grid and each refusal + became a `
`); these rules are what make it read as one quiet line. + + ⛔ WHY THIS FILE AND NOT `index.css`. This ticket owns `RecordDetail.css` and does not own + `index.css`, where the one existing disclosure-over-a-refusal (`.cg-ts-refused`) lives. These + rules FOLLOW that precedent deliberately, down to both of its scars, rather than reaching for + its classes: a shared class would put this surface's layout inside a stylesheet that another + lane owns. + + ⛔⛔ SCAR 1, INHERITED FROM `.cg-ts-refsum`: THE CARET IS DRAWN WITH BORDERS. A triangle glyph + renders at a different size in every font on the three platforms this runs on, and this one has + to sit on a line of 12px text. It is also not an icon, which matters twice over: this ticket may + not extend `iconShapes.ts`. + ⛔⛔ SCAR 2, AND IT SHIPPED ONCE AND WAS CAUGHT ONLY BY A SCREENSHOT: THE CLOSED STATE IS + DECLARED. `
` hides its non-summary children through a UA rule, and ANY author `display` + beats a UA declaration regardless of specificity, so `.cg-refusal-why { display: block }` alone + would re-show the whole wall behind a summary claiming to hide it. Both states are stated. */ +.cg-refusal-strip { + flex: 0 0 auto; + display: flex; + flex-direction: column; + gap: 2px; + padding: 10px 16px 12px; + border-top: 1px solid var(--lp-line); +} + +.cg-refusal-sum { + display: flex; + align-items: baseline; + gap: 6px; + padding: 2px 0; + color: var(--lp-muted); + font-size: var(--lp-fs-2xs); + line-height: 1.45; + cursor: pointer; + list-style: none; /* Safari and Chrome draw their own triangle; replaced below */ + user-select: none; +} + +.cg-refusal-sum::-webkit-details-marker { + display: none; +} + +.cg-refusal-sum::before { + content: ""; + flex: 0 0 auto; + align-self: center; + width: 0; + height: 0; + border-left: 4px solid currentColor; + border-top: 3.5px solid transparent; + border-bottom: 3.5px solid transparent; + transition: transform 120ms ease-out; +} + +.cg-refusal[open] > .cg-refusal-sum::before { + transform: rotate(90deg); +} + +.cg-refusal-sum:hover { + color: var(--lp-ink); +} + +.cg-refusal-sum:focus-visible { + outline: 2px solid var(--lp-blue-deep); + outline-offset: 1px; + border-radius: var(--lp-r-md); +} + +/* The subject the server named, on the same line as its sentence rather than above it: a second + line per refusal is the stacking this ticket is removing. */ +.cg-refusal-who { + flex: 0 0 auto; + color: var(--lp-ink); + font-weight: 600; +} + +.cg-refusal-say { + min-width: 0; +} + +.cg-refusal-why { + display: none; + margin: 2px 0 6px; + padding: 0 0 0 10px; + color: var(--lp-muted); + font-size: var(--lp-fs-2xs); + line-height: 1.5; +} + +.cg-refusal[open] > .cg-refusal-why { + display: block; +} + +/* A refusal the server sent with no diagnosis (a pinned read: `_refusal_error` carries the + sentence and no second string) keeps the panel's ordinary note voice and grows no caret. */ +.cg-refusal-flat { + padding: 16px; +} + +@media (prefers-reduced-motion: reduce) { + .cg-refusal-sum::before { + transition: none; + } +} diff --git a/web/src/customer-grid/RecordDetail.tsx b/web/src/customer-grid/RecordDetail.tsx index 124ecb1e0533003d8806cb4891b52fd15d36eada..69167199bad6c31ccf216e3c614c2d7ef3c839fa 100644 --- a/web/src/customer-grid/RecordDetail.tsx +++ b/web/src/customer-grid/RecordDetail.tsx @@ -47,7 +47,7 @@ import { AI_STATE_PREFIX, choiceOptions, codeLanguageOf, isPickType, mayEditFiel declares what a `/related` entry and a pinned read ARE, so this panel and `CustomerGrid` cannot come to hold two opinions about one wire contract [[two-lanes-one-contract-dead-feature]]. */ -import { CUSTOMER_TOPIC, PRODUCT_TOPIC, RELATED_REFUSAL, relatedTabs, +import { CUSTOMER_TOPIC, PRODUCT_TOPIC, RELATED_REFUSAL, relatedTabs, skeletonTabs, topicForScope } from "./types"; import type { CustomerDoc, Field, RelatedEntry, RelatedPin, RelatedRefusal, RelatedVia, Row, Viewer } from "./types"; @@ -505,9 +505,139 @@ function refusalSubject( if (code === RELATED_REFUSAL.noRelatedRows) return ""; if (code === RELATED_REFUSAL.forbiddenTable && table) return labelFor(table) || table; if (code === RELATED_REFUSAL.hopFiltered && hop) return hopWords(hop); + /* ⭐⭐ W54-T38 · C5's FOURTH STATE, AND IT IS THE ONE BRANCH THAT MUST NOT FALL BACK TO THE + RAW KEY. The other two subjects name something the reader can be shown: a database they hold + a name for, or a hop. A RETIRED table has no roster entry by definition, so `labelFor` is + empty and the `|| table` fallback above would print `ut_odoo_customers` in bold, which is + exactly the screen the owner pasted back at us in instruction 22. The short sentence already + names the absent database in the server's own words, so there is nothing for a subject line + to add and it stays empty unless a display name genuinely exists. */ + if (code === RELATED_REFUSAL.retiredTarget && table) return labelFor(table); + /* ⭐⭐ W54-T40 — THE ONE STATE WITH NO SERVER **CODE** STILL HAS A SUBJECT, AND IT IS THE TAB + THE OWNER NAMED. `unpinnableNote` is the client's own sentence for "the read-through roster + does not name this database", so no code comes back with it and every branch above misses; + the refusal then rendered as a lone paragraph with nothing saying WHICH database it was + about. ⛔ THE DISPLAY NAME OR NOTHING, exactly as the retired branch above decided: this + falls through to `labelFor` with no `|| table`, so a database with no roster entry stays + silent rather than putting a raw key in bold on the owner's screen. */ + if (!code && table) return labelFor(table); return ""; } +/** + * ⭐⭐ W54-T38 · INSTRUCTION 22 · DESIGN.md SECTION 4 — **ONE REFUSAL, AS ONE SENTENCE, WITH THE + * DIAGNOSIS ONE CLICK DOWN.** + * + * The owner, verbatim: *"I still get refusals like ... and a wall of ..."*, pasting one sixty-word + * paragraph that his screen was showing him FOUR TIMES over. W54-T37 fixed the CAUSE (a retired + * database reported as a permission problem) and left the presentation exactly as it was, which + * is half the defect: DESIGN.md section 4 says *"never over-explain"*, and four paragraphs stacked + * above a grid push the rows a reader asked for below the fold. + * + * ⛔⛔ THE DIAGNOSIS IS NOT CUT, IT IS MOVED. W53-T18 wrote those paragraphs on purpose, so that a + * traversal is never served short and silent; deleting them would trade this defect for the one + * they were written against. The server now authors BOTH strings (`relations.py`, the banner above + * `no_related_rows_refusal`) and this component only chooses the treatment. + * ⛔ SO THIS FILE STILL AUTHORS NO PROSE AND STILL SPLITS NOTHING. Cutting `message` at its first + * full stop would make the client a second author of one wire contract, which is the rule this + * file already carries beside the refusal render below. + * + * ⚠ NO `detail` MEANS NO DISCLOSURE, and that is a measured case rather than defensive habit: a + * PIN-time refusal is authored by `routes_odoo_tables._related_pin`, which raises one sentence and + * no diagnosis at all. Such a refusal renders as the short sentence in the ordinary muted voice, + * exactly as it did before, and never as a caret with nothing behind it. + * ⛔ W54-T40 CORRECTS THE ROUTE NAMED HERE. The old text said this refusal arrived through + * `routes_grid._refusal_error`; it does not. `probeRelatedRead` addresses the ROWS door, and + * `_refusal_error` belongs to `GET /grid/{table}/related`, whose refusals reach this file through + * `fetchRelated` and DO carry their diagnosis (W54-T40 added `detail` to the keys it copies, which + * is the row W54-T38 booked). The two doors are now consistent; the pin door is simply the one + * with nothing to disclose. + * + * ⛔ `data-refusal` STAYS THE MACHINE-READABLE STATE, on the outermost element either way. It + * carries the SERVER's code and nothing else may be spelled into it (see the empty-link note + * below, which deliberately uses a different attribute). + * ⛔ THE CARET IS DRAWN IN CSS, NOT AN ICON. `RecordDetail.css` owns it, following + * `.cg-ts-refsum` in `index.css`: a triangle glyph renders at a different size in every font, and + * this ticket may not extend the icon vocabulary. + */ +function RelatedRefusalNote( + { code, subject, message, details }: + { code: string; subject: string; message: string; details: string[] }, +) { + if (details.length === 0) { + return ( +

+ {subject ? <>{subject}
: null} + {message} +

+ ); + } + return ( +
+ + {subject ? {subject} : null} + {message} + + {/* ⚠ MORE THAN ONE ONLY WHERE THE SERVER SENT MORE THAN ONE DIAGNOSIS UNDER ONE SENTENCE. + See `groupRefusals`: the paths differ, the sentence does not, so they share a line and + each keeps its own paragraph. */} + {details.map((why) =>

{why}

)} +
+ ); +} + +/** + * ⭐⭐ W54-T38 — **ONE LINE PER SENTENCE, NOT ONE LINE PER PATH**, and this is the half of the + * repetition that shortening the copy CREATED rather than removed. + * + * `relations.wall_refusals` collapses its answer on `(code, table, hop)`, which was exactly right + * while every sentence quoted its own path: a dozen removed paths through one closed table came + * back as a handful of genuinely different paragraphs. Now that the sentence a reader meets is + * SHORT, it names less than that key does, and four paths onto one absent database render as four + * identical lines. Measured on `customer_data` with a staged retirement: four copies of *"is no + * longer part of this workspace"*, which is instruction 22's wall again at one line each. + * + * ⛔ IT GROUPS, IT DOES NOT DROP. Each member's diagnosis is kept and stacked inside the one + * disclosure, so nothing the server said is lost and the count of removed paths is still + * recoverable by opening it. Dropping the duplicates would delete real answers. + * ⛔ AND IT AUTHORS NOTHING. The group key is the server's own `code` plus the server's own + * sentence, compared byte for byte; this file writes no summary line, no count and no prose. + * ⚠ THE SUBJECT IS TAKEN FROM THE FIRST MEMBER and that is safe by construction: a group shares + * one sentence, and each code's sentence quotes whichever of `table` / `hop` its subject is drawn + * from, so two members with one sentence cannot disagree about it. + */ +interface GroupedRefusal { + code: string; + table?: string; + hop?: string; + message: string; + details: string[]; +} + +function groupRefusals(refusals: RelatedRefusal[]): GroupedRefusal[] { + const byLine = new Map(); + for (const refusal of refusals) { + const key = `${refusal.code}\u0000${refusal.message}`; + const seen = byLine.get(key); + if (!seen) { + byLine.set(key, { + code: refusal.code, + table: refusal.table, + hop: refusal.hop, + message: refusal.message, + details: refusal.detail ? [refusal.detail] : [], + }); + } else if (refusal.detail && !seen.details.includes(refusal.detail)) { + seen.details.push(refusal.detail); + } + } + return [...byLine.values()]; +} + /** * ⭐ W51-T06 CLAUSE 9 — ONE HOP of the record view's navigation, carrying everything needed to * render it. See the shadow note inside the component for why the row and the field contract @@ -542,6 +672,8 @@ interface RecordFrame { const EMPTY_ENTRIES: RelatedEntry[] = []; /** ⭐ W53-T24 — and the listing's refusals need one for exactly the same reason. */ const EMPTY_REFUSALS: RelatedRefusal[] = []; +/** ⭐ W54-T38 — and so does the diagnosis list a PIN-time refusal never has. */ +const EMPTY_DIAGNOSES: string[] = []; const EMPTY_ROWS: Row[] = []; const EMPTY_FIELDS: Field[] = []; @@ -971,10 +1103,39 @@ export default function RecordDetail({ }; }, [scope, recordTable]); - /** Clause 1 + clause 2 — the tab strip, in the server's order (forward, reverse, bridge). */ + /** + * ⭐⭐ W54-T39 — IS THE LISTING STILL IN FLIGHT? Derived, never a fourth piece of state, and it + * is already exactly what `related.table` records: the state is stamped with the table it was + * fetched FOR, so a stamp that does not match this record's table means no answer for this + * table has landed yet. `scope == null` is the fail-closed branch that never fetches at all and + * therefore never waits. + * ⚠ IT ALWAYS TERMINATES. `apiBridge.ts::fetchRelated` resolves `EMPTY_LISTING` on a non-ok + * response and on a thrown fetch, so the effect's `setRelated` runs on every outcome and the + * stamp always catches up. A skeleton that could outlive its request would be worse than the + * bare rail it replaces. + */ + const relatedPending = scope != null && related.table !== recordTable; + + /** + * Clause 1 + clause 2 — the tab strip, in the server's order (forward, reverse, bridge). + * + * ⭐⭐ W54-T39 — AND THE PLACEHOLDER ROWS WHILE IT IS STILL COMING. Before this, the rail + * rendered `Details` alone for as long as `/related` took, with nothing to say more was on the + * way: `waves/wave54/shots/F-before-record.png` is that frame, and *"the left-side rail takes + * forever to load"* is the owner reading it. The listing itself is now roughly four times + * faster (`routes_grid.py::_relation_context`), so this is the smaller half of the fix and it + * has to stay honest about which state it is in. + * ⛔ THE PLACEHOLDERS REPLACE AN EMPTY LIST, THEY NEVER SIT BESIDE A REAL ROW. `entries` is + * empty until the answer lands, so there is no frame in which four grey bars and a real tab are + * on screen together — the two-row-states defect `shell/navExtras.css` fixed in the page rail. + * ⛔ AND AN EMPTY ANSWER IS NOT A LOADING ONE. A database with no relations settles to zero + * tabs and the placeholders go, because `relatedPending` is false the moment the stamp matches. + */ const tabs = useMemo( - () => relatedTabs(entries, (target) => tableLabels[target] ?? ""), - [entries, tableLabels] + () => (relatedPending && !entries.length + ? skeletonTabs() + : relatedTabs(entries, (target) => tableLabels[target] ?? "")), + [entries, tableLabels, relatedPending] ); /** @@ -1297,7 +1458,22 @@ export default function RecordDetail({ setTabState({ status: "projected" }); return; } - const refused = await probeRelatedRead(target, pin); + /* ⭐⭐ W54-T40 · INSTRUCTION 22 — **THE PROBE IS ONLY ASKED OF A DOOR THAT KNOWS THIS + TARGET**, and skipping it is the whole of the owner's third error. + `probeRelatedRead` addresses `odoo-tables//rows`, whose vocabulary is the + read-through roster and nothing else. MEASURED 2026-09-06: opening **Products ordered** + asked that door for `product_data`, a compiled registry module it has never heard of, and + got `404 unknown_table` back. Its message is the honest answer to the question that door + was asked and the WRONG answer to the one the reader asked, so the tab rendered a bare + lower-case *"that database does not exist"* about a database that plainly does exist. + ⛔ THE ROSTER IS ALREADY THE MOUNT CONDITION (see `pinnable` above), so a target it does + not name has no pinned read to probe: there is nothing this call can learn and one wrong + sentence it can bring back. The state that is left is exactly the one `unpinnableNote` + was written for, and it says what was asked, why it cannot be answered here and what to + do instead. + ⚠ THE PROBE SURVIVES FOR THE STATE IT EXISTS FOR: a target the roster DOES name whose + edge is `served: false`. That door has a real sentence and it is still the server's. */ + const refused = through.has(target) ? await probeRelatedRead(target, pin) : null; if (!live) return; /* ⚠ A `null` here means the pinned door answered 200 while the ROSTER said no, which is the one state with no server sentence (see `unpinnableNote`) and therefore no code @@ -1306,7 +1482,11 @@ export default function RecordDetail({ status: "refused", reason: refused?.reason ?? unpinnableNote(target), code: refused?.code ?? "", - table: refused?.table, + /* ⭐ W54-T40 — THE SERVER'S SUBJECT WHERE THERE IS ONE, AND THIS TAB'S TARGET WHERE THERE + IS NOT. A refusal the client authored is still ABOUT a database, and the only one it + can be about is the target of the tab that is open. See `refusalSubject`'s last + branch, which turns this into a display name or into nothing. */ + table: refused?.table ?? target, hop: refused?.hop, }); })(); @@ -1315,6 +1495,9 @@ export default function RecordDetail({ }; }, [activeRelated, relatedPin, projectedIds]); + /** ⭐ W54-T38 — the listing's refusals, one row per distinct sentence. See `groupRefusals`. */ + const groupedRefusals = useMemo(() => groupRefusals(refusals), [refusals]); + /** ⭐ W53-T24 · R13 — the emphasised subject of the open tab's refusal, or `""` for the two * states that have none (`no_related_rows`, and any code this client does not know). */ const refusedSubject = tabState.status === "refused" @@ -2247,35 +2430,6 @@ export default function RecordDetail({ ⛔ THE GRID IS THE PANEL, not a card inside one. DESIGN section 4 allows ONE containment layer and the drawer is already it; a bordered box around a grid inside a drawer inside a modal is the card-in-card the section names. */} - {/* ⭐⭐ W53-T24 · RULING R13 — **WHAT THE LISTING WOULD NOT SHOW YOU**, said out loud. - A traversal filtered out of the rail is otherwise a tab that never appears, and - a tab that never appears is indistinguishable from an edge that was never - declared. `refusals` is `[]` whenever nothing was walled off, so this block is - absent on every ordinary record rather than a permanent apology. - ⚠ IN THE PANEL, NOT AN OVERLAY, and a FLEX ITEM of `.cg-record-related` rather - than a sibling of it: that wrapper is `height: 100%` of the scrolling body - (`styles/wave51/grid.css`), so a paragraph placed BEFORE it would push a - full-height block down and overflow the drawer. Inside, the grid keeps - `flex: 1 1 auto` and simply takes the remaining height. */} - {refusals.map((refusal) => { - const subject = refusalSubject( - refusal.code, - (table) => tableLabels[table] ?? "", - refusal.table, - refusal.hop, - ); - return ( -

")}`} - className="cg-record-related-note" - role="status" - data-refusal={refusal.code} - > - {subject ? <>{subject}
: null} - {refusal.message} -

- ); - })} {tabState.status === "refused" ? ( /* ⭐ R6's SECOND SENTENCE — the limit, its cause and what to do instead, in the SERVER's words. `role="status"` rather than `alert`: a declared relation that @@ -2295,14 +2449,17 @@ export default function RecordDetail({ ⚠ `data-refusal` IS THE STATE, MACHINE-READABLE. Three renders that differ only in prose cannot be told apart by QA or by a gate; this attribute is how the distinction survives a screenshot. */ -

- {refusedSubject ? <>{refusedSubject}
: null} - {tabState.reason} -

+ ) : tabState.status === "probing" ? ( /* Owner R6 — one small bare rotating mark, NO WORDS on screen. The `aria-label` is not a word on screen and stays, or the wait is announced as nothing at all @@ -2380,6 +2537,47 @@ export default function RecordDetail({ /> )} + + {/* ⭐⭐ W53-T24 · R13 — **WHAT THE LISTING WOULD NOT SHOW YOU**, said out loud. A + traversal filtered out of the rail is otherwise a tab that never appears, and a + tab that never appears is indistinguishable from an edge that was never declared. + `refusals` is `[]` whenever nothing was walled off, so this block is absent on + every ordinary record rather than a permanent apology. + + ⭐⭐ W54-T38 · INSTRUCTION 22 — AND IT MOVED **BELOW THE TAB'S OWN CONTENT**, + which is the half of the owner's report that was about layout rather than about + words. These refusals belong to the RAIL: they describe edges that are missing + from the tab strip, not the tab that is open. Rendered first, they appeared at + the top of EVERY related tab, so opening Orders meant scrolling past five + paragraphs about other edges to reach the orders. See + `shots/F-before-orders-tab.png`, which is that exact frame. + ⛔ STILL A FLEX ITEM OF `.cg-record-related`, NEVER AN OVERLAY AND NEVER A + SIBLING OF IT: that wrapper is `height: 100%` of the scrolling body + (`styles/wave51/grid.css`) and the grid inside it is `flex: 1 1 auto`, so this + strip is `flex: 0 0 auto` and takes only the lines it needs while the grid keeps + the rest. A block placed before it pushed a full-height element down and + overflowed the drawer, which is why the ordering is written down here. + ⚠ ONE `role="status"` FOR THE GROUP rather than one per row: each row is a + `
` whose summary is a real disclosure control, and wrapping every one of + them in its own live region would announce the same strip N times. */} + {groupedRefusals.length > 0 && ( +
+ {groupedRefusals.map((refusal) => ( + tableLabels[table] ?? "", + refusal.table, + refusal.hop, + )} + message={refusal.message} + details={refusal.details} + /> + ))} +
+ )} ) : ( <> diff --git a/web/src/customer-grid/RecordRail.tsx b/web/src/customer-grid/RecordRail.tsx index eadc5d2d49f3f143c97e0d90a8def5acd40c5318..9d9735b6361c613b66c817cf0f85e4c42dec33a6 100644 --- a/web/src/customer-grid/RecordRail.tsx +++ b/web/src/customer-grid/RecordRail.tsx @@ -90,7 +90,14 @@ export default function RecordRail({ tabs, activeTab, onSelect }: RecordRailProp -
+ {/* ⭐⭐ W54-T39 — `aria-busy` IS THE WHOLE ANNOUNCEMENT, and it is deliberately not a + sentence. The placeholder rows below say "more is coming" to a sighted reader; this says + the same thing to a screen reader without adding a line of copy that would then have to + be un-said the moment the listing lands. */} +
tab.skeleton) || undefined} + > {/* R6 calls this "Details" in words even though the state key underneath (and the old tablist strip) both spelled it "fields" — the reader never sees that key, and "Fields" over a panel that also shows a picture upload and a rating row is a name for the data @@ -103,7 +110,31 @@ export default function RecordRail({ tabs, activeTab, onSelect }: RecordRailProp > Details - {tabs.map((tab) => ( + {tabs.map((tab) => (tab.skeleton ? ( + /* ⭐⭐ W54-T39 — THE RAIL WHILE `/related` IS IN FLIGHT. + ⛔ A `
`, NOT A DISABLED BUTTON, and that is the accessibility half rather than a + preference: a disabled button is still in the accessibility tree and still announced, + so a reader would be told about four controls that are not there. `aria-hidden` on an + inert element says the honest thing, and `aria-busy` on the list above says the rest. + ⛔ NO SHIMMER. `shell/navExtras.css`'s `.shell-rail-skeleton` is this app's rail + skeleton and its own note gives the reason in full: an animated sweep is a second + thing moving in a rail whose complaint is movement, and `prefers-reduced-motion` + would then need a third state. This follows it, so there is nothing to reduce. + ⚠ SAME ROW GEOMETRY as `.cg-record-rail-row` (DESIGN §4, join the existing rhythm), + and TWO bars rather than one for the same reason: a real row is a label over a + subtitle on 24 of the 25 edges tenant #0's `customer_data` offers, so a one-line + placeholder would settle by growing and the rail would step down under the reader's + eye. The bars stand in for `.cg-record-rail-row-label` and + `.cg-record-rail-row-sub`, in that order and at their two widths. */ + + ) : ( - ))} + )))}
); diff --git a/web/src/customer-grid/RouteNav.tsx b/web/src/customer-grid/RouteNav.tsx index f878f4e9f43a4a6635dc0d5a285e9e9ce1e71357..4eccea03f5f2bc2afc63ac6568e13c9e5ebadbad 100644 --- a/web/src/customer-grid/RouteNav.tsx +++ b/web/src/customer-grid/RouteNav.tsx @@ -313,6 +313,8 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources, | null >(null); const [renameId, setRenameId] = useState(null); + /** W54-T21 - raised by the rename's Escape claim so the blur it causes does not save. */ + const renameEscaping = useRef(false); const [busy, setBusy] = useState(false); const [deliveryMapsPerLink, setDeliveryMapsPerLink] = useState(10); const [deliveryNotice, setDeliveryNotice] = useState(null); @@ -992,6 +994,39 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources, const backToRoutes = useCallback(() => onActiveRouteChange(null), [onActiveRouteChange]); useEscapeClose(route !== null && titleDraft === null && !deleteConfirm, backToRoutes); + /* ═════════ W54-T21 / D-673 — THE RUNGS THAT USED TO BE COVERED BY SILENCE ═══════════════ + * + * ⛔⛔ THE STAND-DOWNS ABOVE ONLY WORKED WHILE NOTHING ELSE CLAIMED ESCAPE. Standing down means + * "let the key fall through", and until this ticket it fell through to NOBODY, so React's own + * handlers on the rename input and the search box still saw it and the delete confirm simply + * ignored the press. D-673 puts a claim UNDERNEATH this whole panel - `CustomerGrid.tsx` closes + * the navigator - so a fall-through now closes the entire navigator instead. Every surface the + * open Route stands down for therefore has to claim the key itself, or the press it was meant + * to reach would take the panel down with it. + * + * ⛔ THE LINE ABOVE IS UNTOUCHED, DELIBERATELY. `verify_map.py` slices the FIRST + * `useEscapeClose` statement in this file and asserts each of its terms, so these three sit + * BELOW it; putting one above would hand that leg the wrong statement to read. + * + * ⚠ `renameEscaping` IS THE SAME ORDERING PROBLEM THE SHEET'S FORMULA EDITOR HAS. The arbiter + * blurs the focused element before it calls close, and the folder rename input's blur is what + * SAVES the new name, so a bare claim would have made Escape commit a rename it was pressed to + * cancel. The blur defers its decision by one microtask and this flag, raised by the close, + * wins that race by construction rather than by luck. + * + * ⚠ THE QUERY RUNG IS THE ONE BEHAVIOUR CHANGE, AND IT IS THE SMALL ONE. Escape with a typed + * route filter clears the filter and leaves the panel open, which is what the box's own + * handler always did; with the box empty there is nothing to clear and the press reaches the + * navigator's close. The box keeps its own handler because `verify_map.py` pins it. + */ + useEscapeClose(titleDraft !== null, () => setTitleDraft(null)); + useEscapeClose(deleteConfirm, () => setDeleteConfirm(false)); + useEscapeClose(renameId !== null, () => { + renameEscaping.current = true; + setRenameId(null); + }); + useEscapeClose(routeQuery !== "", () => setRouteQuery("")); + if (route) { // ⭐ W46-T25 / RULING R2's guard stood here: a Route projected from a legacy `route_order` // column was refused until an administrator migrated it, because unlocking an unmigrated one @@ -1736,9 +1771,16 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources, event.stopPropagation()} onBlur={(event) => { + // W54-T21 - deferred by ONE microtask so an Escape that blurred this input on + // its way to cancelling the rename gets to say so first. A click away, a Tab + // and the Enter path all still save, one microtask later, unchanged. const value = event.target.value.trim(); - if (value && value !== folder.name) finish(onFolderUpdate(folder, { name: value })); - setRenameId(null); + renameEscaping.current = false; + queueMicrotask(() => { + if (renameEscaping.current) return; + if (value && value !== folder.name) finish(onFolderUpdate(folder, { name: value })); + setRenameId(null); + }); }} onKeyDown={(event) => { if (event.key === "Enter") event.currentTarget.blur(); diff --git a/web/src/customer-grid/Toolbar.tsx b/web/src/customer-grid/Toolbar.tsx index ce5d22dec4b8ff62b7ee4679e242c9089d1ff2d1..c9a52fe16978299c0b99beaf3a78a55067e5d3d5 100644 --- a/web/src/customer-grid/Toolbar.tsx +++ b/web/src/customer-grid/Toolbar.tsx @@ -55,6 +55,17 @@ import { FilterBuilderPanel, FieldsHidePanel, Popover } from "../filter-kit"; import { MEASURE_OP_LIST, countConditions, newRuleId, opsForType } from "../filter-kit/ops"; import "./filters.css"; +/** + * ⭐⭐ W54-T49 · C4 — ONE connection, as the selector sees it: a stable id and the EDITABLE label + * its owner gave it. Two members and no third, because "which client's numbers are these" is + * answered by the id and read by the label; anything else a connection knows belongs to the + * Connectors panel, not to a picker above a grid. + */ +export interface ConnectionChoice { + id: string; + label: string; +} + interface ToolbarBaseProps { fields: Field[]; /** Identity used only to classify shared fields into ownership sections. */ @@ -257,6 +268,30 @@ interface ToolbarBaseProps { */ frozen?: boolean; + /** + * ⭐⭐ W54-T49 · RULING R7 / CONTRACT C4 — THE CONNECTION THIS TABLE IS READ THROUGH. + * + * R7, verbatim: *"Every Odoo-reading module gains a connection selector; picking one client + * shows only that client's numbers. ⛔ There is no 'All' option that blends two clients."* + * So the list carries real connections and nothing else: this control has no "All" row, and + * there is no value of `connectionId` that means "both". + * + * ⚠ OPTIONAL, AND A CALLER THAT PASSES NOTHING RENDERS NO CONTROL AT ALL — not an empty one, + * not an inert one. Same posture as `ViewSidebar`'s folder props (*"a caller that passes no + * `folders` and no handlers renders exactly the pre-wave-8 flat rail"*), and it is what keeps + * every existing mount of this toolbar byte-identical: a workspace with one connection has + * nothing to choose between and is shown nothing to choose with. + * + * ⛔ SUPPLIED, NEVER DERIVED. Which connections exist and which one is in force are SERVER + * answers (`perm_scope.connection_options` / `perm_scope.connection_scope`); a toolbar that + * guessed them would be wrong the moment an administrator added a client. + */ + connections?: ConnectionChoice[]; + /** The connection in force. It is always one id, because a read is always one connection. */ + connectionId?: string | null; + /** Read this table through that connection instead. One id, never a set. */ + onConnection?: (connectionId: string) => void; + /** * ⭐ W41-T42 · RULING R9 — what this table can pivot to: its LINK FIELDS. Empty means the table * has no link yet, and the control says exactly that rather than offering nothing silently. @@ -398,6 +433,26 @@ function IconRelational() { ); } +/** + * ⭐ W54-T49 — the connection selector's mark, and it is a REUSED glyph rather than a new one. + * + * The path is `icons.tsx::MENU_ICONS.swap` verbatim: the two opposed arrows this app already + * uses for "switch which of these is in force", which is exactly what choosing a connection + * does. It is drawn here at the toolbar's own 14px / 1.5 stroke rather than imported through + * `MenuIcon`, because that renders the menu's 16px / 1.3 and the controls in this row share a + * height and a baseline. `icons.tsx` and `iconShapes.ts` are untouched: the vocabulary has no + * plug or database mark, and inventing one belongs to whoever owns that file. + */ +function IconConnection() { + return ( + + + + ); +} function IconGroup() { return ( @@ -814,6 +869,9 @@ export default function Toolbar({ filterSeed = null, modeControl, frozen = false, + connections = [], + connectionId = null, + onConnection, relationalTargets = [], relational = null, onRelational, @@ -952,6 +1010,25 @@ export default function Toolbar({ // W41-T42 — the same idiom `colorLabel` and `groupLabel` already use: a control that HAS a // current answer names it on the trigger, so the reader does not have to open it to find out. const relationalLabel = relational ? `Related: ${relational.label}` : "Related"; + // ⭐⭐ W54-T49 (R7) — the same idiom again, and here it is load bearing rather than convenient: + // two connections show the same databases under the same column names, so the ONE thing on + // screen that says whose numbers these are is this trigger. It names the client, always. + const currentConnection = + connections.find((conn) => conn.id === connectionId) ?? connections[0]; + const connectionLabel = currentConnection + ? `Connection: ${currentConnection.label}` + : "Connection"; + /** + * ⛔ R7 — the control renders when there is a connection to name AND a host to take the choice. + * + * BOTH halves: a picker nothing listens to is a lie, and a picker with no connection behind it + * would name a client this workspace does not have. ⚠ ONE connection still renders it, unlike + * the nav rail's per-connection folders, and the asymmetry is deliberate: the rail is naming + * FOLDERS, which a single connection does not need, while this says whose numbers are on the + * screen, which is exactly as true at one client as at two. A caller that supplies neither + * prop renders nothing, which is every mount of this toolbar today. + */ + const canPickConnection = !!onConnection && connections.length > 0; /** * R11's greying, as one attribute. `inert` is not in React 18's JSX typings (it landed with @@ -976,6 +1053,41 @@ export default function Toolbar({ on. */} {modeControl} + {/* ⭐⭐ W54-T49 (R7 / C4) — WHICH CONNECTION THIS TABLE IS READ THROUGH. + FIRST in the strip, and first is the argument: every other control here operates on + rows, and this one decides which client's rows exist at all. It takes no `order:` of + its own, so it sits in the initial cluster with Fields, Filter, Sort and Color and + paints where the DOM puts it; the run W50-T07 froze (Color, Rows, Edit, Related, Notes, + Full screen) is untouched, in the markup and in the tab sequence alike. + + ⛔ NO "ALL" ROW, AND THERE IS NOWHERE TO PUT ONE. R7 is explicit that no option may + blend two clients, and the server agrees by construction: `perm_scope.connection_scope` + returns one connection or refuses. A radio group, never checkboxes, for the same + reason — the control's SHAPE has to say "exactly one" before anybody reads a label. */} + {canPickConnection && ( + } active={connections.length > 1}> + {(close) => ( +
+
Connection
+ {connections.map((conn) => ( + + ))} +
+ )} + + )} + {/* Fields — show / hide columns, searchable, Pre-set chips (item 7 remainder) */} {/* Owner item 23 — "Hide fields", the panel's actual job and Airtable's wording. */} } active={shownCount < fields.length}> diff --git a/web/src/customer-grid/ViewSidebar.tsx b/web/src/customer-grid/ViewSidebar.tsx index 44b34fce5dca6e438e547d2ab0359970546cca2f..6025c1cf68d4e6a0e70dd792afe1b485baf6fb6a 100644 --- a/web/src/customer-grid/ViewSidebar.tsx +++ b/web/src/customer-grid/ViewSidebar.tsx @@ -994,7 +994,25 @@ function DataDatabaseNavigator({ onClick={() => pushDataLevel({ kind: "origin", label: group.label })} > - {group.label} + {/* ⭐ W54-T48 (R4 / C4) — THE FULL NAME ON HOVER, BECAUSE THIS NAME IS NOW THE + USER'S. This row used to read the literal "Odoo" for every connected + database and could not truncate; it now reads the CONNECTION's keychain + label once a tenant has two connections to tell apart, and a label may run + to 80 characters against a rail measured to the pixel. `.cg-fold-name` + (index.css:5929) is `overflow:hidden; text-overflow:ellipsis; + white-space:nowrap`, so "Royal Production (Jakarta warehouse)" reads as + "Royal Production (Jakart…" with nothing to open it. + ⚠ ON THE SPAN, NOT ON THE BUTTON, and that is the accessibility half. The + button's accessible name is its `aria-label` ("Open folder "), which + already carries the whole label to a screen reader; a `title` on the button + would be a second name competing with it. On the text span it is a POINTER + affordance only and adds nothing to the accessibility tree. + ⚠ The same treatment `PathCrumbs` gives a truncatable path segment + (`title={segment.label}`, this file) and the shape `.cg-fold-name` already + takes in the view layer below. No CSS: a title needs none. */} + + {group.label} + {group.databases.length}
diff --git a/web/src/customer-grid/iconShapes.ts b/web/src/customer-grid/iconShapes.ts index d4908ebc634347d8092c980884f378bab7404582..2da82a632cfed11ed2e53e5a3a74caef5758393c 100644 --- a/web/src/customer-grid/iconShapes.ts +++ b/web/src/customer-grid/iconShapes.ts @@ -437,6 +437,37 @@ export const FOLDER_TONE_LABELS: Record = { * as two icon vocabularies, and a second source of colour would let the two marks drift apart. * ⛔ IT IS STILL NOT A `FolderShape`. A folder's mark is user-chosen and stored in nav prefs; this * one is what the row IS, so nothing offers it in the shape picker. + * + * ⭐⭐ W54-T41 (owner instruction 23) — THE OPTICAL NORMALISATION, AND WHY IT IS A TRANSFORM + * RATHER THAN NEW PATH DATA. + * + * Owner, verbatim: *"Under the view navigation rail, the height of the Database icon and the + * Folder icon is not the same, making the rail asymmetric and unpleasant when going back and + * forth along a path."* Both marks already shared the 16x16 box, the 16px render size and the + * 1.35 stroke, so nothing about the ATTRIBUTES said anything was wrong. The INK did: the cylinder + * draws from y 2.0 to y 14.0 and the default folder from y 3.6 to y 13.2, which is 12.0 units of + * geometry against 9.6 — about 19% taller, and a rail alternating between the two steps up and + * down as you walk a path. + * + * The fix is a UNIFORM scale of 0.8 about the group, offset by 1.6 across and 2.0 down, with the + * stroke pre-divided so it still RENDERS at 1.35: + * - vertical ink 0.8 x 12.0 + 1.35 = 10.95, the folder's 9.6 + 1.35 exactly; + * - top and bottom edges land on y 3.6 and y 13.2, the folder's own edges, so the two marks + * share a baseline as well as a height and the rail shows no step; + * - horizontal ink 0.8 x 9.0 = 7.2 wide, centred on x 8. Narrower than the folder, which is + * what the note above already documents as intended: the silhouettes must differ. + * + * ⛔ UNIFORM, never a y-only squash. The rim-depth note above is the reason: `ry` 1.9 against + * `rx` 4.5 is what stops the cylinder reading as a rectangle at 16px, and flattening only the + * vertical axis would push it straight back toward one. A uniform scale preserves the ratio. + * + * ⛔ AND THE `d` STRINGS ARE UNTOUCHED BY DESIGN. `shell/icons.tsx::DatabaseIcon` carries a + * deliberate byte-identical COPY of these three paths (importing the constant would drag the + * grid's 48 kB icon chunk into the eager shell entry), and `verify_icons.py::t35_database_faults` + * compares the two byte for byte. Editing the geometry here would red that leg from a file the + * shell copy cannot follow, so the normalisation lives in the RENDERER and the data stays data. + * `verify_icons.py::t41_ink_faults` measures the drawn ink of both marks — arcs sampled through + * the SVG centre parameterisation, so the rim's bulge counts — and holds the two extents equal. */ export function DatabaseMark({ size = 16 }: { size?: number }): ReactElement { const paint = folderTonePaint(DATABASE_MARK_TONE); @@ -449,16 +480,22 @@ export function DatabaseMark({ size = 16 }: { size?: number }): ReactElement { viewBox: "0 0 16 16", "aria-hidden": true, }, - DATABASE_SHAPE_PATHS.map((s) => - createElement("path", { - key: s.d, - d: s.d, - fill: "none", - stroke: paint.stroke, - strokeWidth: 1.35, - strokeLinecap: "round", - strokeLinejoin: "round", - }) + createElement( + "g", + { transform: "translate(1.6 2) scale(0.8)" }, + DATABASE_SHAPE_PATHS.map((s) => + createElement("path", { + key: s.d, + d: s.d, + fill: "none", + stroke: paint.stroke, + // Pre-divided by the group's scale, so what reaches the screen is still the 1.35 every + // sibling mark in this vocabulary strokes at. + strokeWidth: 1.35 / 0.8, + strokeLinecap: "round", + strokeLinejoin: "round", + }) + ) ) ); } diff --git a/web/src/customer-grid/types.ts b/web/src/customer-grid/types.ts index d7efcaf57951a56b5585618b0c9832b790d1e2d2..66b6ae415d98126fe18dbf504fb8aa4181e4889e 100644 --- a/web/src/customer-grid/types.ts +++ b/web/src/customer-grid/types.ts @@ -4234,17 +4234,40 @@ export interface RelatedEntry { */ export interface RelatedRefusal { code: string; + /** + * ⭐⭐ W54-T38 · INSTRUCTION 22 — **ONE SHORT SENTENCE**, and that is now a + * property of the wire rather than a hope about the server. The owner was shown this string + * four times on one screen at sixty words each, which DESIGN.md section 4 forbids in as many + * words ("never over-explain"). `relations.py` now authors two strings per refusal and this is + * the first one. + */ message: string; + /** + * ⭐⭐ THE DIAGNOSIS, for the disclosure. Word for word what `message` used to be: + * which hop went, which door is shut, what to do about it. + * + * ⛔⛔ OPTIONAL, AND THE ONE PLACE IT IS GENUINELY ABSENT IS MEASURED RATHER THAN + * GUESSED. The LISTING carries it (`routes_grid.related_refusals` returns `wall_refusals`' + * bags whole), so every refusal drawn from `/related` has one. A PIN-time refusal does not: + * `routes_grid._refusal_error` copies only `table`, `hop`, `path` and `candidates` into the X2 + * envelope, and that file is another ticket's fence. So an absent `detail` means "the server + * sent no diagnosis", which renders as the short sentence alone, never as an invented one. + * ⛔ THE CLIENT NEVER SPLITS `message` TO FILL THIS. Cutting a paragraph at its first full + * stop would make this file a second author of one wire contract, which is the rule + * `RecordDetail.tsx` already carries beside the refusal render. + */ + detail?: string; path: string[]; table?: string; hop?: string; } /** - * ⭐⭐ W53-T24 · RULING R13 · C3 — **THE THREE CODES, SPELLED EXACTLY ONCE IN THIS CLIENT.** + * ⭐⭐ W53-T24 · R13 · C3, EXTENDED BY W54-T38 · C5 — **THE FOUR CODES, + * SPELLED EXACTLY ONCE IN THIS CLIENT.** * - * ⛔ A CONSTANT RATHER THAN THREE STRING LITERALS SCATTERED THROUGH A RENDER, because R13's - * whole content is that these three are DIFFERENT ANSWERS: a typo in one literal at one call + * ⛔ A CONSTANT RATHER THAN FOUR STRING LITERALS SCATTERED THROUGH A RENDER, because R13's + * whole content is that these four are DIFFERENT ANSWERS: a typo in one literal at one call * site silently collapses that answer back into the default treatment, which is the empty-grid * failure wearing a new disguise, and no gate on either side of the wire would see it. Imported * where the states are chosen, so `tsc` binds the declaration to its consumer. @@ -4255,6 +4278,16 @@ export const RELATED_REFUSAL = { noRelatedRows: "no_related_rows", forbiddenTable: "forbidden_table", hopFiltered: "hop_filtered", + /** + * ⭐⭐ W54-T38 · CONTRACT C5's FOURTH ANSWER, and it is the one instruction 22 is + * about: the edge opens a database this deployment does not have any more. It is NOT a + * permission answer, it must never be treated as one, and the whole complaint was a reader + * being told to ask an administrator for access to a table nobody can grant. + * ⚠ `unknown_via` is a FIFTH code on the wire and is deliberately not spelled here: this + * client renders no branch of its own for it, and a constant nothing reads would be a + * declaration pretending to be a consumer. + */ + retiredTarget: "retired_target", } as const; /** @@ -4284,6 +4317,68 @@ export interface RelatedTab { * fourth prop would redden two gates for a mark that belongs to one row anyway. */ hops: 1 | 2; + /** + * ⭐⭐ W54-T39 — TRUE ONLY ON A PLACEHOLDER, AND IT TRAVELS HERE FOR THE SAME REASON `hops` + * DOES. While `/related` is in flight the rail knows about exactly one row, `Details`, and + * shows it alone with nothing to say more is coming — the owner's *"the left-side rail takes + * forever to load"*, photographed at `waves/wave54/shots/F-before-record.png`. The rail needs + * to be told it is waiting, and `verify_wiring.py` plus `verify_record_layout.py` both assert + * its mount as the exact string ``, so a fourth prop is not available to say it. The signal rides the tab. + * + * ⛔ A SKELETON TAB IS NEVER SELECTABLE AND NEVER RESOLVES TO AN EDGE. Its `entry.key` is + * `SKELETON_TAB_PREFIX + n`, a spelling no server edge can carry, so `RecordDetail`'s + * `activeTab` falls back to `"fields"` and `activeRelated` stays null exactly as it does before + * any listing arrives. `RecordRail` renders these rows as inert `
`s rather than buttons, + * so neither a click nor a Tab key can reach one. + * ⚠ OPTIONAL, and absent on every real tab: `relatedTabs` never sets it, so a tab built from + * the server's own answer cannot be mistaken for a placeholder. + */ + skeleton?: true; +} + +/** + * ⛔ THE ONE SPELLING A PLACEHOLDER ROW'S KEY MAY TAKE, and it is deliberately not a legal edge + * key: `relations.py` mints edge keys out of field, table and bridge names, none of which can + * begin with a space. So no listing can ever collide with one of these, and no stale selection + * can point at one. + */ +export const SKELETON_TAB_PREFIX = " skeleton:"; + +/** + * ⭐⭐ W54-T39 — THE RAIL'S IN-FLIGHT ROWS. Four, because the rail's real answer on tenant #0's + * `customer_data` is twenty-five and on its smallest database is two; four fills the fold without + * promising a count, which is what a skeleton is for. + * + * ⛔ DESIGN §4 — A SKELETON, NOT A SPINNER, and the same one the app already uses. `.lp-spin` + * belongs to a per-tab row load, where one small thing is fetching inside a settled page; this is + * the whole rail arriving, and the house answer to that is `shell/navExtras.css`'s + * `.shell-rail-skeleton`, which is flat-toned and does not animate at all. Following it means + * there is no shimmer for `prefers-reduced-motion` to have to undo. + * ⚠ NO COPY. The rows carry no words, so there is nothing here to get the dash rule or sentence + * case wrong; `RecordRail` marks the list `aria-busy` instead, which is what a screen reader + * wants and a sighted reader does not need told twice. + */ +export function skeletonTabs(count = 4): RelatedTab[] { + const out: RelatedTab[] = []; + for (let i = 0; i < count; i += 1) { + out.push({ + entry: { + key: `${SKELETON_TAB_PREFIX}${i}`, + label: "", + target: "", + served: false, + via: { direction: "forward", key: `${SKELETON_TAB_PREFIX}${i}` }, + path: [`${SKELETON_TAB_PREFIX}${i}`], + hops: 1, + }, + label: "", + subtitle: "", + hops: 1, + skeleton: true, + }); + } + return out; } /** @@ -4378,6 +4473,13 @@ export function relatedRefusals(body: unknown): RelatedRefusal[] { }; if (typeof raw?.table === "string" && raw.table) refusal.table = raw.table; if (typeof raw?.hop === "string" && raw.hop) refusal.hop = raw.hop; + /* ⭐⭐ W54-T38 — THE DIAGNOSIS, WHEN THE SERVER SENT ONE. Read exactly as `table` and `hop` + are: present and non-empty or absent entirely, never `""`, so the render can branch on + "is there a disclosure to draw" with a truth test and no second convention. + ⛔ AND IT IS NEVER SYNTHESISED FROM `message`. A client that cut the sentence at its first + full stop would be authoring copy out of a regular expression; the split is the server's, + and a refusal that arrives without one shows its sentence alone. */ + if (typeof raw?.detail === "string" && raw.detail) refusal.detail = raw.detail; out.push(refusal); } return out; diff --git a/web/src/filter-kit/FilterBuilderPanel.tsx b/web/src/filter-kit/FilterBuilderPanel.tsx index 2ae9086fd706cef4ed650a86d67ab10ce427ab79..be8b58d3ea2e12e86ef70b4e80fd1889cd44cb94 100644 --- a/web/src/filter-kit/FilterBuilderPanel.tsx +++ b/web/src/filter-kit/FilterBuilderPanel.tsx @@ -646,6 +646,19 @@ interface LevelContext { */ viewChoices: { id: string; name: string }[]; choicesFor: ChoicesFor; + /** + * ⭐⭐ W54-T31 (R8) — the HEADING the condition row's field list wears, or nothing. + * + * R8: the Fields list appears in exactly two places, and each one is labelled with what it is + * picking, so several `sales.. metrics` entries are distinguishable. This is the second place; + * the first is the Aggregate's column list in `sheet/BindingEditor.tsx`. + * + * ⛔ UNDEFINED IS THE DEFAULT AND IT MUST STAY PIXEL-IDENTICAL. The Data module's inline + * filter, the admin permission editor and the view builder all pass nothing, and + * `FieldSelectButton` renders no heading node at all when its `title` is undefined. A hardcoded + * string here would have put a Sheet sentence into three surfaces that did not ask for one. + */ + fieldPickerTitle?: string; } /** @@ -789,7 +802,8 @@ function LeafRow({ onRule: (r: FilterRule) => void; onRemove: () => void; }) { - const { fields, fieldByKey, measures, measureByKey, lists, viewChoices, choicesFor } = ctx; + const { fields, fieldByKey, measures, measureByKey, lists, viewChoices, choicesFor, + fieldPickerTitle } = ctx; const isMeasure = isMeasureRule(rule); const isCohort = rule.colId === COHORT_FIELD; const hasCohorts = lists.length > 0; @@ -966,10 +980,15 @@ function LeafRow({ you pick a thing to filter on, and a measure simply also asks for a period. Item 20 adds the type MARK to each row and takes NO grouping with it: the marks are what the optgroup was reaching for, and they say it per row instead of splitting the list. */} + {/* ⭐⭐ W54-T31 (R8) — THE HEADING GOES IN THE ELSE BRANCH, NEVER OVER THE WHOLE + EXPRESSION. `DELETED_FIELD_NOTE` explains a column that is gone; a heading merely says + what the list picks. A refusal outranks a label, so the note keeps winning on exactly + the rows it won on before, and a host that passes no heading gets `undefined` here, the + same value this expression has always produced. */} ( () => ({ fields: condFields, fieldByKey, measures, measureByKey, lists: cohorts, - viewChoices, choicesFor }), - [condFields, fieldByKey, measures, measureByKey, cohorts, viewChoices, choicesFor] + viewChoices, choicesFor, fieldPickerTitle }), + [condFields, fieldByKey, measures, measureByKey, cohorts, viewChoices, choicesFor, + fieldPickerTitle] ); return ( diff --git a/web/src/filter-kit/SheetFilterPopup.tsx b/web/src/filter-kit/SheetFilterPopup.tsx index 7883600c68ece40e8ba49bf970583e1d9d0d2d9c..6f25055c2768ec4c7bf0acd01aaa5c73e4e526c5 100644 --- a/web/src/filter-kit/SheetFilterPopup.tsx +++ b/web/src/filter-kit/SheetFilterPopup.tsx @@ -45,10 +45,17 @@ import { useId, useRef } from "react"; import { BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/OverlaySurface"; -import type { Field, FilterTree } from "../customer-grid/types"; -import { filterTreeNodes } from "../customer-grid/types"; +import type { + Conjunction, Field, FilterNode, FilterOp, FilterRule, FilterTree, +} from "../customer-grid/types"; +import { filterTreeConj, filterTreeNodes, isFilterGroup, isRuleActive } from "../customer-grid/types"; // Through the barrel, which is how every other consumer of this kit imports the panel. import { FilterBuilderPanel, countConditions } from "./index"; +// ⚠ DIRECT, NOT THROUGH THE BARREL, because `index.ts` re-exports four names from `ops.ts` and +// `opLabel` is not one of them. Widening the barrel would change what every other consumer of +// this kit can reach for a sentence only this file writes; a sibling import inside the same +// directory changes nothing outside it. +import { opLabel } from "./ops"; export interface SheetFilterPopupProps { /** The cell this filter belongs to, e.g. `B4`. Named in the title so the dialog says which @@ -71,9 +78,100 @@ export function conditionCountLabel(filters: FilterTree): string { return n === 1 ? "1 condition" : `${n} conditions`; } -/** The dialog itself. Split from the export ONLY so that `useOverlayLayer` runs BELOW the - * provider and therefore joins the same stack the value picker will join. */ -function SheetFilterDialog({ +/** + * ⭐⭐ W54-T35 (ruling R8, owner instruction 8) — WHAT THE FILTER SAYS, AS A SENTENCE. + * + * Owner, verbatim: *"the Filter module itself will show exactly what the filter is when we click + * 'View row' so its easy for user also to know what this filter is."* A count answers "how many + * rules are there"; it does not answer "what is this filter". So the drill needs the second + * thing, and `conditionCountLabel` directly above stays the answer to the first. + * + * ⛔ IT IS BUILT FROM `opLabel`, NOT FROM A SECOND OPERATOR VOCABULARY. `FilterBuilderPanel` + * paints each condition row's operator with `opLabel(op, fieldType)`, so the sentence and the + * builder behind the Edit door say the same words for the same rule. A local table would drift + * the first time the owner reworded one of them, and the reader would be told two things. + * + * ⛔ INACTIVE RULES ARE OMITTED, and that is the honest reading rather than a tidy one. A rule + * with a blank value is IGNORED by the engine (`isRuleActive`, whose Python mirror + * `filter_sql.is_rule_active` decides the same thing server-side), so the rows on screen were + * not narrowed by it. Naming it here would describe rows nobody is looking at. + * + * ⚠ THREE LEAVES AND THEN A COUNT. The band this feeds is one line across the foot of a modal + * whose job is the rows above it; a filter with nine rules cannot be read there whatever we do, and an ellipsis in the + * middle of a value is worse than a number. The dialog behind the Edit door is where a long + * filter is actually read, which is what makes the truncation safe rather than lossy. + */ +const MAX_SPOKEN_LEAVES = 3; + +/** One leaf, in the builder's own words. `fields` is a map so a nested walk stays linear. */ +function ruleSentence(rule: FilterRule, byKey: Map): string { + const field = byKey.get(rule.colId); + const name = field?.label || rule.colId; + // A column whose type is no longer known reads as text, which is what `opsForType` offers a + // missing column too: the op still has a label, so the rule still has a sentence. + const phrase = opLabel(rule.op as FilterOp, field?.type ?? "text"); + const listed = rule.values?.length ? rule.values.join(", ") : ""; + const single = typeof rule.value === "string" ? rule.value.trim() : ""; + const operand = listed || single; + // `value2` is the far end of a `between`, and the builder reads it as a pair. + const both = rule.value2 ? `${operand} and ${String(rule.value2).trim()}` : operand; + return both ? `${name} ${phrase} ${both}` : `${name} ${phrase}`; +} + +/** Does this node narrow anything? A group of blanks narrows nothing, same as a blank rule. */ +function nodeIsActive(node: FilterNode): boolean { + return isFilterGroup(node) + ? node.children.some(nodeIsActive) + : isRuleActive(node as FilterRule); +} + +function nodesSentence(nodes: FilterNode[], conj: Conjunction, byKey: Map): string { + const joiner = conj === "or" ? " or " : " and "; + const live = nodes.filter(nodeIsActive); + const spoken = live.slice(0, MAX_SPOKEN_LEAVES).map((node) => + isFilterGroup(node) + ? `(${nodesSentence(node.children, node.conj, byKey)})` + : ruleSentence(node as FilterRule, byKey)); + const rest = live.length - spoken.length; + if (rest > 0) spoken.push(rest === 1 ? "1 more condition" : `${rest} more conditions`); + return spoken.join(joiner); +} + +/** + * The filter, in readable terms. + * + * ⛔ EMPTY MEANS EMPTY: a filter that narrows nothing returns `""` rather than a sentence saying + * so. The caller is the one that knows what to say instead, and it already has + * `conditionCountLabel` for exactly that, so returning a phrase here would be a THIRD wording of + * "nothing yet" for the two surfaces to drift apart on. A caller that wants the count says + * `filterSentence(t, f) || conditionCountLabel(t)`, which is one line and reads as the rule. + */ +export function filterSentence( + filters: FilterTree | null | undefined, fields: Field[], +): string { + const byKey = new Map(fields.map((f) => [f.key, f])); + return nodesSentence(filterTreeNodes(filters), filterTreeConj(filters), byKey); +} + +/** + * The dialog itself. Split from `SheetFilterPopup` ONLY so that `useOverlayLayer` runs BELOW the + * provider and therefore joins the same stack the value picker will join. + * + * ⭐⭐ W54-T35 — AND THAT IS WHY IT IS NOW EXPORTED. `SheetFilterPopup` brings its OWN + * `OverlayProvider`, which is exactly right when the dialog is the only surface of its family on + * screen (the binding panel's case). It is exactly WRONG when the caller already has another + * body-level overlay open that the dialog must be ranked against: a private provider is a private + * stack, so the surface underneath would keep answering `isTop` true and would dismiss itself on + * the first pointerdown inside this dialog. `sheet/DrillModal.tsx` opens this over the linked + * record grid, and it supplies ONE provider for both, so both join one stack and the outside-click + * contract can order them. Callers with nothing else open should keep using `SheetFilterPopup`. + * + * ⚠ ESCAPE IS NOT WHAT THIS FIXES, and confusing the two is how the wrong shape gets shipped. + * Escape is arbitrated by the module-level stack in `ui/useEscapeClose` (topmost claimant wins, + * by push order) and has never needed a provider. `OverlayStackContext` orders OUTSIDE CLICKS and + * the Tab trap, and only for layers that can see each other. + */ +export function SheetFilterDialog({ addr, onClose, fields, filters, onChange, statusValues, }: SheetFilterPopupProps) { const panelRef = useRef(null); @@ -139,20 +237,45 @@ function SheetFilterDialog({ {/* `min-width: 0` so the builder's rows may shrink inside this flex column instead of pushing the dialog wider than the viewport on a small screen. */}
+ {/* ⭐⭐ W54-T31 (R8) — THE SECOND OF THE TWO LABELLED FIELDS LISTS. R8: "Each Fields + list is labelled with what it is picking, so several `sales.. metrics` entries are + distinguishable." The first is the Aggregate's column list in `BindingEditor`, + whose heading names the database and the fold; this one names the CELL, in the same + words this dialog's own title uses, because that is what tells a reader whose + filter they are choosing a field for. One line, sentence case: a heading says what + the list is for and then gets out of the way. + ⛔ Passed HERE and nowhere else. The prop is optional, so the Data module's inline + filter and the admin permission editor keep the picker they have. */}
- {/* ⛔ NOT "Save", AND DELIBERATELY QUIET. Nothing is held back, so a Save button would - imply a discard door that cannot exist without a draft copy of the tree, and the - filled `lp-dialog-btn-primary` (`--lp-primary`, a violet) would give a control that - merely closes the weight of a commit, in a palette the Sheet does not otherwise - wear. `lp-dialog-btn-quiet` is a hairline on the dialog's own surface. */} -
diff --git a/web/src/settings/PermsEditor.tsx b/web/src/settings/PermsEditor.tsx index e3b769f18d8169b8804e4a01b4e3e964a791e100..57fd1de58680f4f8ced93421cb265c4a6b8bb764 100644 --- a/web/src/settings/PermsEditor.tsx +++ b/web/src/settings/PermsEditor.tsx @@ -70,12 +70,14 @@ import { DatabasePermsPane } from "./DatabasePermsPane"; // C4: this lane's own stylesheet. `index.css` is B's and nothing here touches it. import "./perms.css"; import { + getConnectorGrants, getUserPerms, patchUser, + putConnectorGrants, putUserPerms, setPassword, } from "./settingsApi"; -import type { AdminUser } from "./settingsApi"; +import type { AdminUser, ConnectorKind } from "./settingsApi"; import type { PermsModule, PermsPayload, PermsRecord } from "./permsModel"; import { accessSummary, @@ -182,6 +184,28 @@ export function PermsEditor({ const [role, setRole] = useState(user.role ?? "user"); const [pw, setPw] = useState(""); + /** + * ⭐⭐ W54-T47 / R4 / contract C4 — THE THIRD AXIS. Owner, verbatim: *"Under Settings, an Admin + * should grant a user access to add connectors, so access becomes Database / Module / + * Connector."* + * + * ⛔ IT IS ITS OWN STATE RATHER THAN A THIRD GROUP OF `draft`, because it is not a registry key. + * `payload.modules` are databases and surfaces the perms record governs; a connector is a + * CREDENTIAL KIND out of `core/keychain.py::ENTRY_TYPES`, carried by its own route so the perms + * PUT body stays exactly the whole-record replace `permsModel.toPutBody` builds. Folding it in + * would have made every existing perms leg negotiate a key that is not a module. + * + * ⚠ `kinds` EMPTY IS ALSO THE FAILURE STATE, deliberately. A server that cannot answer, or one + * that predates this route, leaves the list empty and the section renders NO HEADING at all, + * which is the same rule the Database and Module groups already follow: a group with no members + * is not a labelled empty room. + */ + const [connKinds, setConnKinds] = useState([]); + /** The grants as the SERVER holds them, and the draft beside it. Same pairing, same reason, as + * `saved` / `draft` above: without the baseline there is nothing for "unsaved" to mean. */ + const [connSaved, setConnSaved] = useState([]); + const [connDraft, setConnDraft] = useState([]); + useEffect(() => { let dead = false; setLoad({ phase: "loading" }); @@ -211,6 +235,33 @@ export function PermsEditor({ }; }, [username]); + /** + * ⭐ W54-T47 — THE CONNECTOR AXIS IS READ ON ITS OWN WIRE, AND A FAILURE HERE IS SILENT. + * + * ⛔ IT MUST NOT BE ABLE TO BREAK THE PAGE. The perms GET above puts the whole editor into an + * error state when it cannot be read, and rightly: an admin must never be invited to save a + * record they were not shown. This one is the opposite case. The grants it fetches are the ONLY + * thing it can affect, absence of a grant is the ordinary state of every account in the product, + * and the wall is on the server either way. So a refusal leaves `connKinds` empty, the section + * renders nothing, and Database and Module keep working exactly as they did. + */ + useEffect(() => { + let dead = false; + setConnKinds([]); + setConnSaved([]); + setConnDraft([]); + void getConnectorGrants(username).then((r) => { + if (dead || !r.ok) return; + const granted = Array.isArray(r.data?.granted) ? r.data.granted.map(String) : []; + setConnKinds(Array.isArray(r.data?.kinds) ? r.data.kinds : []); + setConnSaved(granted); + setConnDraft(granted); + }); + return () => { + dead = true; + }; + }, [username]); + const payload = load.phase === "ready" ? load.payload : null; /** * ⭐ W40-T14 — the drill-in RESOLVED, which is the only form the render is allowed to trust. @@ -270,7 +321,14 @@ export function PermsEditor({ */ const accountDirty = name.trim() !== (user.name ?? "").trim() || role !== (user.role ?? "user"); - const anyDirty = dirty || accountDirty; + /** + * ⭐ W54-T47 — the Connector axis's own baseline comparison. Compared as SORTED text rather than + * by reference or length: the checkbox writes a new array on every click, so identity says + * nothing, and two lists of the same size can hold different kinds. + */ + const connKey = (list: string[]) => [...list].sort().join(""); + const connDirty = connKey(connDraft) !== connKey(connSaved); + const anyDirty = dirty || accountDirty || connDirty; /** * ⭐⭐ W47-T19 (owner instruction 11) — WHAT THE ONE SAVE SAYS IT SAVES. With the two buttons * merged there is a single control committing two different kinds of work, and a fixed label @@ -289,7 +347,9 @@ export function PermsEditor({ * `saves_show_they_are_working`'s own NC strips to prove leg 1 can still fire. Changing either * word means changing the gate that pins it, in the same commit, on purpose. */ - const saveLabel = dirty && !accountDirty ? "Save access" : "Save account"; + /** ⚠ W54-T47 — the Connector axis counts as ACCESS, which is what the owner called it. Widening + * the first operand rather than adding a third word keeps both pinned spellings intact. */ + const saveLabel = (dirty || connDirty) && !accountDirty ? "Save access" : "Save account"; const goBack = useCallback(() => { if (anyDirty) setAsk({ kind: "discard" }); @@ -400,6 +460,29 @@ export function PermsEditor({ return; } } + /** + * ⭐ W54-T47 — THE CONNECTOR AXIS COMMITS HERE, BETWEEN THE TWO, AND THAT POSITION IS THE + * ARGUMENT ABOVE APPLIED ONCE MORE. + * + * ⛔ AFTER THE ACCOUNT PATCH, because promoting the account to Admin makes every rule below + * inert and a refused PATCH must still write nothing at all. + * ⛔ BEFORE the `!payload` early return, because this grant does not live in the perms record + * and has its own route: a failing perms GET must not take the Connector axis down with it, + * for the same reason it does not take Deactivate down with it. + * ⛔ AND A FAILURE STOPS THE ACTION rather than being swallowed. This is a permission write; + * a half-save that reports success is how somebody comes to believe they revoked a connector + * they did not. + */ + if (connDirty) { + const g = await putConnectorGrants(username, connDraft); + if (!g.ok) { + setBusy(false); + setAsk(null); + setError(g.message); + return; + } + setConnSaved(connDraft); + } if (!payload) { setBusy(false); setAsk(null); @@ -429,7 +512,7 @@ export function PermsEditor({ } else { setError(r.message); } - }, [payload, draft, username, onSaved, accountDirty, name, role]); + }, [payload, draft, username, onSaved, accountDirty, name, role, connDirty, connDraft]); /** The account half's write. ⚠ THE PATCH STILL CARRIES NO `bus` (R1), and * that is load-bearing rather than tidy: with the picker gone this form @@ -860,6 +943,73 @@ export function PermsEditor({ )} + {/* ⭐⭐ W54-T47 / R4 / contract C4 — THE THIRD ROOM. Owner, verbatim: *"Under + Settings, an Admin should grant a user access to add connectors, so access becomes + Database / Module / Connector. This allows many connectors per tenant … depending + on the admin's configuration per user."* + + ⛔ IT SITS OUTSIDE THE `payload.modules.length` TERNARY ABOVE, and that is not a + layout choice. A connector is not a registry module, so a deployment that governs + no databases at all can still have an administrator deciding who may wire up + Shopify; nesting this inside that branch would have made the new axis disappear + for exactly the tenant with the least already set up. + + ⛔ A GROUP WITH NO MEMBERS RENDERS NO HEADING, the same rule the two groups above + follow and the same reason: an empty labelled room says the deployment lost + something rather than that it never had it. An older server, or one whose route + refused, leaves `connKinds` empty and nothing paints. + + ⚠ A CHECKBOX PER KIND AND NO `ModulePermsList`. That component's furniture is a + filter, a field list and a drill-in room; a connector has none of the three, and + borrowing the card would have promised three controls that cannot exist. The card + idiom is shared, the list component is not. */} + {connKinds.length ? ( + <> +
Connector
+ {/* ⚠ THE SECOND SENTENCE IS THE ONE A READER CANNOT GET BY LOOKING, and it is + what stops an admin reading an empty list as a lockout: no grant is the + ordinary state and it takes nothing away. */} +

+ Ticked connectors are the ones this account can add for the whole workspace. + Everyone can already add their own personal connections, so leaving these clear + takes nothing away. +

+ {connKinds.map((k) => { + const on = connDraft.includes(k.key); + return ( +
+
+ + {/* ⚠ Wrapped for the reason `ModulePermsList` wraps its own trailing + controls: `.set-perm-modhead` is `space-between` and lives in + `index.css`, which this lane does not own. One flex child in, one out. */} + + {k.tenantWide ? ( + + Every database in this workspace reads through it + + ) : null} + +
+
+ ); + })} + + ) : null} +
) : null} @@ -931,7 +1081,7 @@ export function PermsEditor({ that only asked about access would be understating what the click does. */}

Save these changes for {displayName}?

- {unsavedWords(dirty, accountDirty)} are written now, and a change to access takes + {unsavedWords(dirty || connDirty, accountDirty)} are written now, and a change to access takes effect the next time they load a page. {accessSummaryLine(payload, draft)}

@@ -942,7 +1092,7 @@ export function PermsEditor({ work now, and "your changes" over a form the reader cannot see behind the scrim is a question they cannot answer. */}

- {unsavedWords(dirty, accountDirty)} for {displayName} stay as they were. + {unsavedWords(dirty || connDirty, accountDirty)} for {displayName} stay as they were.

)} diff --git a/web/src/settings/settingsApi.ts b/web/src/settings/settingsApi.ts index 56fb08fda92161e4ef24fdfd12b59520f90406bc..4e0bc8ae5e00e7f07d8de4ef635d14f88d81e7f3 100644 --- a/web/src/settings/settingsApi.ts +++ b/web/src/settings/settingsApi.ts @@ -196,6 +196,61 @@ export function putUserPerms( }); } +// --- wave 54, W54-T47 / R4 / contract C4: the THIRD grant axis --------------- +// +// Owner, verbatim: *"Under Settings, an Admin should grant a user access to add +// connectors, so access becomes Database / Module / Connector."* Database and +// Module are two groupings of the `perms` record above; Connector is not a +// registry key at all, it is a CREDENTIAL KIND, so it has its own pair of calls +// rather than a third section of the perms body. +// +// ⛔ ADMIN-ONLY AND FAIL-CLOSED AT THE SERVER, exactly like the two above. And +// the grant these write is consulted by `POST /admin/keychain` itself +// (`core/perm_scope.may_add_connection`), so a client that never called them +// changes nothing: absence is the behaviour that shipped before this wave. + +/** One connectable kind, as the server declares it. */ +export interface ConnectorKind { + key: string; + label: string; + /** True when the whole workspace reads its databases through this source, so a + * connection of it is never personal. Granting it hands the member the + * workspace's own credential slot, which an admin should read before ticking. */ + tenantWide: boolean; +} + +export interface ConnectorGrants { + username: string; + /** The vocabulary, served rather than hard-coded here: it is + * `core/keychain.py::ENTRY_TYPES`, and a client copy is the drift a parity + * gate exists to stop. */ + kinds: ConnectorKind[]; + /** The kinds this account may create a business-wide connection of. Empty is + * the ordinary state and means "no grant", never "denied everything". */ + granted: string[]; +} + +export function getConnectorGrants( + username: string +): Promise> { + return call( + `/admin/users/${encodeURIComponent(username)}/connector-grants` + ); +} + +/** WHOLE-LIST REPLACE, for the reason `putUserPerms` is one: revoking has to be + * expressible, and a merge cannot express a deletion without a second + * vocabulary for it. An empty list is a legal body and it revokes. */ +export function putConnectorGrants( + username: string, + granted: string[] +): Promise> { + return call( + `/admin/users/${encodeURIComponent(username)}/connector-grants`, + { method: "PUT", body: JSON.stringify({ granted }) } + ); +} + /** Wave 14 C-AVATAR — own-profile photo. The server returns the refreshed `{user}` envelope; * the caller parses it with `session.parseUserEnvelope` so the shell chip updates live. */ export function setAvatar(dataUrl: string): Promise> { @@ -260,6 +315,12 @@ export function listKeychain(): Promise< /** Types that are always business-wide — the whole workspace reads its databases through * them, so "personal" would be a label rather than a boundary. */ tenantWideTypes?: string[]; + /** W54-T47 / R4 — the kinds THIS reader may create a business-wide connection of without + * being an admin, because an admin granted them the Connector axis. + * ⛔ COURTESY, NEVER THE WALL: `POST /admin/keychain` asks the server-side predicate + * regardless of what a client believes about this list. Absent reads as none, which is the + * behaviour every account had before this wave. */ + connectorGrants?: string[]; }> > { return call("/admin/keychain"); diff --git a/web/src/sheet/BindingEditor.tsx b/web/src/sheet/BindingEditor.tsx index abd1f87f350091c4cbdad3fa0725bda56b5668c0..c31f5b97faefa909a53ffe4dc3990d4bcabfdd8e 100644 --- a/web/src/sheet/BindingEditor.tsx +++ b/web/src/sheet/BindingEditor.tsx @@ -36,10 +36,11 @@ // ⚠ DESIGN CONTRACT: sentence case, quiet buttons, token-only colour and type, motion 150 ms // ease-out on opacity and transform, no emoji, and no em dash or en dash in any string on screen. -import { useCallback, useEffect, useMemo, useRef, useState } from "react"; +import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react"; import { fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge"; import type { SurfaceScope } from "../customer-grid/apiBridge"; import { FieldTypeIcon } from "../customer-grid/icons"; +import { BodyPortal, OverlayProvider, useOverlayLayer } from "../customer-grid/OverlaySurface"; import type { Field, FilterTree, Row } from "../customer-grid/types"; import { choiceVocabulary, topicForScope } from "../customer-grid/types"; // ⭐⭐ W53-T15 (ruling R8) — THE FILTER BUILDER IS NO LONGER MOUNTED IN THIS COLUMN. The SHARED @@ -59,6 +60,13 @@ const AGGREGATES = [ { fn: "max", label: "Maximum" }, ] as const; +/** The fold's name inside a sentence. `AGGREGATES` carries the capitalised option text a select + * needs; a heading reading "takes its Sum over" would be title case in the middle of a line, + * which the design contract's sentence-case rule forbids. Same five folds, said the other way. */ +const AGGREGATE_NOUN: Record = { + sum: "sum", count: "count", avg: "average", min: "minimum", max: "maximum", +}; + // ══ W53-T13: WHICH COLUMNS THE SERVER CAN ACTUALLY TOTAL (R7, standing rule 9) ═══════════════ // // ⭐⭐ THE PICKER MUST NOT OFFER A COLUMN THAT WILL REFUSE. `isNumericType` answers "does this @@ -333,6 +341,250 @@ function viewList(raw: unknown): { id: string; name: string }[] { return (raw as { id: string; name: string }[]).map((v) => ({ id: v.id, name: v.name })); } +// ══ ⭐⭐ W54-T31 (ruling R8; owner instructions 6 and 8) — THE AGGREGATE'S COLUMN LIST ═════════ +// +// ⭐⭐ R8, VERBATIM: "Aggregate is always visible. The Fields list appears in exactly two places: +// choosing the Aggregate's column, and choosing a field inside 'A filter I build here'. It is +// hidden everywhere else, including under 'A saved view', where the view already fixes the rows. +// Each Fields list is labelled with what it is picking, so several `sales.. metrics` entries are +// distinguishable." +// +// ⛔ WHAT CHANGED IS WHERE THE LIST LIVES, NOT WHETHER IT EXISTS. Before this ticket the list was +// a permanently expanded box inside a 380px column: it painted under "A saved view" as well, and +// it spent about 90px of the panel's height on a list nobody was currently choosing from +// (`shots/T31-fields-before.png`). Instruction 6 asks for the Data module's Fields presentation +// "but the popup in the middle, just like building a Filter under 'Rows to include'", so the list +// becomes a centred dialog opened from a control that shows the CHOSEN column. The panel keeps a +// single line for Column in every configuration, which is what instruction 8's "Fields should auto +// hide for everything that is not part of the Aggregate value Column or the Filter fields" buys. +// +// ⛔⛔ THE PROVIDER AROUND THE DIALOG IS THE SAME LOAD-BEARING ONE `SheetFilterPopup` DOCUMENTS, +// and it is why `SheetColumnPicker` is split from the dialog below it. The Sheet route mounts NO +// `OverlayProvider` of its own (`App.tsx` gives one to the hosted-grid branch only), so a +// body-level overlay opened here has a null `OverlayStackContext` and `useOverlayLayer` cannot +// tell whether a higher layer owns a pointerdown. Wrapping puts every layer opened underneath +// this dialog on one stack, so a click inside a nested picker is never read as an outside click +// that dismisses the surface below it. That failure is exactly the "clicking Fields just closes +// the window" report instruction 8 names. +// +// ⛔ AND IT IS MOUNTED LATE, CONDITIONALLY, for the reason the filter popup already records: +// `useOverlayLayer` claims Escape the moment it runs and `ui/useEscapeClose` hands the key to the +// LAST entry pushed. The editor's own claim was pushed at mount; this one is pushed when the +// dialog opens, so one Escape closes the column list and the next closes the panel. + +interface ColumnPickerProps { + /** The cell being bound, so the title says which cell this list is about. */ + addr: string; + /** The fold, said inside a sentence: "sum", "average", "minimum". */ + aggregateNoun: string; + /** The database's own label. Two databases can both offer a column called "Total". */ + databaseLabel: string; + /** The offer after the search box, which is what the list renders. */ + shown: Field[]; + /** The offer before the search box. The empty state must tell a search miss from an empty + * database, and those two ask different things of the reader. */ + offered: Field[]; + /** Every field the database has, for the third empty-state sentence. */ + all: Field[]; + chosen: string; + query: string; + onQuery: (next: string) => void; + onPick: (key: string) => void; + onClose: () => void; +} + +/** The dialog itself. Split from the export ONLY so `useOverlayLayer` runs BELOW the provider. */ +function ColumnPickerDialog({ + addr, aggregateNoun, databaseLabel, shown, offered, all, chosen, query, + onQuery, onPick, onClose, +}: ColumnPickerProps) { + const panelRef = useRef(null); + const titleId = useId(); + const listId = useId(); + useOverlayLayer({ + panelRef, + onDismiss: onClose, + dismissOnOutside: true, + initialFocus: "first", + restoreFocus: true, + trapFocus: true, + }); + + const offersMetric = offered.some(isMetricField); + + return ( + +
+
+
+

+ {`The column ${addr} takes its ${aggregateNoun} over`} +

+ +
+ + {/* ⭐ THE SHAPE IS `filter-kit/FieldsHidePanel.tsx`'s, which is what instruction 6 asks + for by name: a quiet heading, then a find box, then the rows. Nothing here is a new + control; `cg-fields-section-title`, `cg-type-search`, `cg-type-list`, `cg-type-row` + and `cg-fsel-hint` are all shipped, top-level classes in `index.css`. */} +
+ {/* ⭐⭐ THE HEADING R8 ASKS FOR, AND IT NAMES BOTH HALVES OF WHAT IS BEING PICKED: + which database the columns come from, and what they are going to be used for. The + owner's report was several entries reading "sales.. metrics" with nothing saying + which list they belonged to; a list that says what it is picking answers that + before a single row is read. */} +
+ {`Fields on ${databaseLabel} to take the ${aggregateNoun} over`} +
+ + {/* ⭐ THE SEARCH BOX HAS NO CONDITION AROUND IT (wave-50 R16). A control that appears + at eleven fields and not at ten is a control nobody learns is there. */} +
+ + + + + onQuery(e.currentTarget.value)} + /> +
+ + {/* ⛔ THE LIST IS NOT RENDERED WHEN IT HAS NO ROWS. `.sheet-pick-list` carries a + border and 3px of padding, so an empty one painted a thin bordered strip under + the search box with the explanation sitting outside it, which reads as a picker + that failed rather than a database with nothing to offer. */} + {shown.length > 0 && ( +
+ {shown.map((f) => ( + + ))} +
+ )} + + {/* ⛔ AN EMPTY LIST SAYS WHY (R16). The three causes need different acts from the + reader, and a database CAN carry number columns this database cannot total. */} + {shown.length === 0 && ( +

+ {offered.length > 0 + ? "No column matches that search." + : (all.some((f) => isNumericType(f.type)) + ? "The number columns on this database are worked out in the browser for " + + "each row, so there is nothing stored here to total." + : "This database has no number column to total.")} +

+ )} + + {/* ⭐ R7, said where the choice is made: a Metric is the one kind of column here that + answers over the period the panel sets. */} + {offersMetric && shown.length > 0 && ( +

+ A Metric column is measured over the period you choose in the panel. Every other + column holds one stored value per record. +

+ )} +
+
+
+
+ ); +} + +/** The centred column list, on its own overlay stack. See the block above for why the provider + * is not decoration. */ +export function SheetColumnPicker(props: ColumnPickerProps) { + return ( + + + + ); +} + +/** + * ⭐⭐ W54-T33 (owner instruction 24) — WHAT THE PANEL SHOWS WHILE ITS OPTIONS RESOLVE. + * + * ⛔ THE PRECEDENT IS `sheet/SheetRail.tsx::RailSkeleton` AND ITS DECISION IS NOT REOPENED HERE: + * one flat `--lp-surface-2` tone and no shimmer, because an animated sweep is a second thing moving + * on a surface whose whole job is to sit still, and `prefers-reduced-motion` would then need a + * third state. The bars are `aria-hidden` under ONE `role="status"`, so a screen reader hears + * "loading" once rather than six times. + * + * ⭐ THE SHAPE IS THE SETTLED PANEL'S. Three stacked label-plus-control lines (Database, + * Aggregate and Column, which W54-T30 gave a line each) and three blocks for the three fieldsets, + * at the scroller's own 12px gap, so the controls land where the bars were rather than shunting the + * column when they arrive. A skeleton shaped unlike the panel it stands in is worse than none. + */ +function BindingSkeleton({ addr }: { addr: string }) { + return ( +
+ {[0, 1, 2].map((i) => ( + + ))} +
+ ); +} + export interface BindingEditorProps { workbookId: string; addr: string; @@ -370,10 +622,34 @@ export default function BindingEditor({ // arrives the list is legitimately empty, and a notice keyed on emptiness would flash "that view // is gone" at every perfectly valid binding for as long as the fetch took. const [viewsLoaded, setViewsLoaded] = useState(false); + // ⭐⭐ W54-T33 (owner instruction 24) — WHETHER THE OPTIONS ON SCREEN ARE KNOWN TO BE THIS + // CELL'S. The cached read below is KEPT, and it is still not allowed to paint a configuration. + // `fetchWorkspace(scope, {allowCached: true})` is keyed per scope so it can never hand back + // another database's envelope, but it can be minutes old: a view deleted or renamed in another + // tab is still in it, the panel seated the saved view against that list, and `savedViewMissing` + // is held back until the fresh answer lands. So for the five to eight seconds this panel's three + // mount calls take warm, and up to seventy-eight on a cold compute, the reader was shown a + // plausible configuration nobody had saved. The scroller now paints a skeleton until the + // UNCACHED read for the CURRENT database has landed. + // + // ⛔ AND IT IS RAISED ON EVERY EXIT, INCLUDING THE FAILURES. A skeleton with no end is a worse + // answer than an empty list: offline, refused, or a database with no workspace door at all, the + // panel reveals what it has and the person can still read, cancel or close it. + // + // ⚠ IT IS NOT `viewsLoaded`, WHICH MEANS SOMETHING NARROWER AND HAS TO KEEP MEANING IT. That + // flag says the list of views is known to be current, which is what the "saved view is gone" + // notice needs before it may accuse anybody; a failed revalidate is no evidence a view was + // deleted, so it stays false there. This one only asks whether there is anything honest to show. + const [optionsResolved, setOptionsResolved] = useState(false); // ⭐⭐ W53-T15 (ruling R8) — WHETHER THE CENTRED FILTER DIALOG IS ON SCREEN, and the ONLY state // this ticket adds. The tree itself stays in `tree`/`setTree` below and the dialog writes // straight into that setter, so there is no draft to reconcile when it closes. const [filterPopupOpen, setFilterPopupOpen] = useState(false); + // ⭐⭐ W54-T31 (ruling R8) — WHETHER THE CENTRED COLUMN LIST IS ON SCREEN. It starts CLOSED on + // every configuration including an unbound cell: the panel's job on open is to show what the + // cell points at, and a list that opens itself would be back to spending the panel's height on + // a choice nobody has asked to make. + const [colPickerOpen, setColPickerOpen] = useState(false); // ⭐⭐ W52-T14 (instruction 11) — THE FILTER'S VALUE VOCABULARY NEEDS ROWS, NOT ONLY FIELDS. // A declared select/status carries its own list on `field.options`, which the filter kit // already falls back to with no `statusValues` at all. A SERVER-COMPUTED one (a `select` whose @@ -383,6 +659,22 @@ export default function BindingEditor({ // them the same way CustomerGrid does (`topicForScope` + `fetchTopicRows`, the exact pair the // grid's own load path uses), sharing that call's cache so a database already open elsewhere in // this session costs nothing extra here. + // + // ⭐⭐ W54-T36 (owner instruction 8: *"Adding a database cell takes forever to load now"*) — AND + // THAT READ IS NO LONGER PAID ON OPEN. MEASURED at tenant #0: the rows door answers 13.6 MB / + // 33,493 rows on `ut_odoo_orders`, 11.1 MB / 5,899 on `product_data` and 4.8 MB / 3,673 on + // `customer_data`, and the panel was awaiting all of it before it could show a Database select. + // Its ONLY consumer is `statusValues`, which is handed to `SheetFilterPopup` and to nothing + // else, and that dialog is behind a button that is itself behind the "A filter I build here" + // radio. So the pool is fetched when the filter is REACHED rather than when the panel opens. + // + // ⛔ "REACHED" MEANS THE RADIO, NOT THE BUTTON, and that is deliberate: the request starts the + // moment somebody chooses to build a filter, which is at least one click before the dialog can + // be on screen, and a cell SAVED with a filter asks for it at mount. A vocabulary that arrived + // after the dialog opened would be a picker offering nothing, which is worse than a slow panel. + // The rows land into `rawRows` and `statusValues` recomputes, so a dialog opened during the + // request fills itself in rather than staying empty. + const [rowsWanted, setRowsWanted] = useState(savedScope.kind === "filter"); const [rawRows, setRawRows] = useState([]); const [userOptions, setUserOptions] = useState([]); const [preview, setPreview] = useState(""); @@ -442,55 +734,103 @@ export default function BindingEditor({ // the server) is the one that knows what exists NOW, and the list is rebuilt from whichever // answer arrived last. // + // ⛔⛔ W54-T36 — THE UNCACHED READ GOES FIRST NOW AND IS USUALLY THE ONLY ONE, and the reason is + // W54-T33: the skeleton holds the whole scroller until `optionsResolved`, so the cached envelope + // PAINTS NOTHING. Reading it first therefore bought no earlier frame, while a cache MISS spent a + // second full server assembly ahead of the read that decides what is shown. MEASURED at tenant + // #0, warm: one workspace read is 2,646 ms on `customer` and 4,122 ms on `product`, and the two + // in parallel are 2,878 ms and 4,587 ms. Its remaining job is the failure fallback, which is + // where it is asked for now. + // // ⛔ A NULL REVALIDATE LEAVES THE CACHED LIST STANDING. `fetchWorkspace` answers null when the // call fails, and blanking a working dropdown because the network blinked would refuse a person - // their own saved views for a reason that has nothing to do with the views. + // their own saved views for a reason that has nothing to do with the views. That is why the + // cached read survives on that path: it is the panel's only offer when the server will not + // answer, and it costs nothing when the memo already holds this scope. useEffect(() => { let live = true; const scope = scopeOf(database); setViewsLoaded(false); + setOptionsResolved(false); + // ⭐ W54-T36 — THE POOL BELONGS TO THE DATABASE THAT WAS OPEN. Switching database drops it, and + // the rows effect below refetches only if the filter is still being used. + setRawRows([]); if (!scope) { setFields([]); setViews([]); - setRawRows([]); setUserOptions([]); + // ⛔ W54-T33 — RESOLVED, NOT LOADING. This database has no workspace door, so its empty + // lists are the true and final answer; leaving the flag down would leave a skeleton running + // forever over a panel that is never going to be given anything else. + setOptionsResolved(true); return () => { live = false; }; } (async () => { - // Run in parallel: the schema/views door and the rows door answer different questions and - // neither is gated on the other. `fetchTopicRows` shares `rowsCache` with the grid itself. - const [ws, rowsPayload] = await Promise.all([ - fetchWorkspace(scope, { allowCached: true }), - fetchTopicRows(topicForScope(scope)), - ]); - if (!live) return; - if (ws) { - setFields((ws.fields ?? []) as Field[]); - setViews(viewList(ws.views)); - } - setRawRows(rowsPayload?.rows ?? []); - setUserOptions(rowsPayload?.userOptions ?? ws?.userOptions ?? []); - + // ONE door, and it is the one that knows what exists now. const fresh = await fetchWorkspace(scope); if (!live) return; if (!fresh) { - // Offline or refused. Only claim the list is settled if the cached read produced one. - if (ws) setViewsLoaded(true); + // Offline or refused. The memo is the only offer left; only claim the list is settled if + // it produced one. + const ws = await fetchWorkspace(scope, { allowCached: true }); + if (!live) return; + if (ws) { + setFields((ws.fields ?? []) as Field[]); + setViews(viewList(ws.views)); + setUserOptions(ws.userOptions ?? []); + setViewsLoaded(true); + } + // ⛔ W54-T33 — BUT THE PANEL REVEALS EITHER WAY. Nothing better is coming for this + // database, and a skeleton that outlives the request it was waiting on tells the reader + // the panel is broken rather than that the server would not answer. + setOptionsResolved(true); return; } const list = viewList(fresh.views); setFields((fresh.fields ?? []) as Field[]); setViews(list); + // ⚠ THE `user` FIELDS' VOCABULARY COMES OFF THIS ENVELOPE, not off the rows. It was read + // from the rows payload with this as its fallback; the rows are no longer fetched here, so + // the fallback is the answer, and the rows effect below overwrites it when it does run. + setUserOptions(fresh.userOptions ?? []); setViewsLoaded(true); // ⛔ A SELECTED VIEW THAT NO LONGER EXISTS IS CLEARED, so Save cannot store a dead id — that // stored id is exactly the state this ticket was reported for. The notice in `Rows to // include` is what explains the empty control; clearing without saying so would read as the // panel losing the choice on its own. setViewId((cur) => (cur && !list.some((v) => v.id === cur) ? "" : cur)); + // ⛔ W54-T33 — LAST, AFTER THE DEAD ID IS CLEARED. React batches these into one paint, so + // the first frame the reader sees is the settled one: a view that no longer exists has + // already been dropped and its notice is already computed, rather than showing for a frame. + setOptionsResolved(true); })(); return () => { live = false; }; }, [database]); + // ⭐⭐ W54-T36 — THE FILTER'S VALUE POOL, ASKED FOR WHEN THE FILTER IS REACHED. See `rowsWanted` + // above for the measurement that moved it off the open path. Once wanted it stays wanted, so + // switching back to a saved view and returning does not re-ask. + useEffect(() => { + if (scopeKind === "filter" || filterPopupOpen) setRowsWanted(true); + }, [scopeKind, filterPopupOpen]); + + // ⛔ THE PANEL IS NEVER HELD ON THIS READ. It sets no loading flag and gates no control: the + // dialog opens with the declared vocabularies it already has and the computed ones fill in when + // the pool lands, which is what keeps a slow rows door out of the open path for good. + useEffect(() => { + if (!rowsWanted) return undefined; + const scope = scopeOf(database); + if (!scope) return undefined; + let live = true; + (async () => { + const payload = await fetchTopicRows(topicForScope(scope)); + if (!live) return; + setRawRows(payload?.rows ?? []); + if (payload?.userOptions) setUserOptions(payload.userOptions); + })(); + return () => { live = false; }; + }, [database, rowsWanted]); + /** The binding names a view the fresh list does not have. Said in the panel, not after a save. * * ⛔ IT STOPS BEING SAID THE MOMENT THE PERSON ANSWERS IT. The sentence asks for one of two acts, @@ -535,9 +875,9 @@ export default function BindingEditor({ [fields], ); - /** True when at least one Metric column is on offer, which is what the hint under the list is - * for: a Metric answers over the PERIOD chosen below, and no other column here does. */ - const offersMetric = useMemo(() => numericFields.some(isMetricField), [numericFields]); + // ⚠ W54-T31 - `offersMetric` MOVED, it was not dropped. The hint it gated belongs beside the + // rows it describes, and those rows now live in `ColumnPickerDialog`, which derives the same + // answer from the same list. A second copy here would have had no reader. /** The saved binding names a column this database will not total. Said in the panel, where the * choice is made, rather than as a refusal after a save. @@ -584,6 +924,15 @@ export default function BindingEditor({ || String(f.key).toLowerCase().includes(q)); }, [fieldQuery, numericFields]); + /** The chosen column, resolved over the FULL field list rather than over the offer, so a saved + * column this database cannot total still shows its own name beside the notice that says so. + * That is the same three-state rule `customer-grid/FieldSelect.tsx` documents at its head. */ + const chosenField = useMemo(() => fields.find((f) => f.key === field), [fields, field]); + + /** The database's own label, which the column list's heading names. Two databases can both + * carry a column called "Total", and the heading is where that ambiguity is answered. */ + const databaseLabel = databases.find((d) => d.key === database)?.label || database; + const binding = useMemo(() => { const agg: Record = fn === "count" ? { fn } : { fn, field }; const scope: Record = scopeKind === "view" @@ -626,7 +975,10 @@ export default function BindingEditor({ setPreview(got.value.display || String(got.value.value ?? "")); }; - const ready = Boolean(database) && (fn === "count" || Boolean(field)) + // ⭐ W54-T33 — `optionsResolved` FIRST, so Preview and Save are inert while the skeleton is up. + // A cell bound to a live view satisfies every other clause the moment the panel mounts, and a + // Save taken then would write back a binding assembled from a list nobody had seen yet. + const ready = optionsResolved && Boolean(database) && (fn === "count" || Boolean(field)) && (scopeKind === "filter" || Boolean(viewId)); const { y: startYear, m: startMonth } = splitYm(start); @@ -668,383 +1020,380 @@ export default function BindingEditor({ builder is taller than the page, and a panel that scrolls as a whole pushes Save below the fold with nothing on screen saying it is there. */}
- - -
- - {/* Count takes no column, and offering one would suggest count(column), which skips - blanks and answers a smaller number than the person meant. */} - {fn !== "count" && ( -
- Column - {/* ⭐ THE SEARCH BOX HAS NO CONDITION AROUND IT (R16). See the note on `shownFields`. */} -
- - - - - setFieldQuery(e.currentTarget.value)} - /> -
-
- {shownFields.map((f) => ( + {/* ⭐⭐ W54-T33 (owner instruction 24) — NOTHING BELOW PAINTS UNTIL THE OPTIONS ARE + THIS CELL'S. See `optionsResolved` above for what that means and why the cached + read is still made. The skeleton replaces the scroller's CONTENT rather than the + panel, which is what keeps the header, the close control and Cancel reachable, and + it must never be lifted to the panel itself: `migratePeriod`, `readOnDrag` and the + saved aggregate are seeded once at mount, so a remount here would re-read `initial` + and forget an edit somebody had already made. */} + {!optionsResolved && } + {optionsResolved && ( + <> + + +
+ + {/* Count takes no column, and offering one would suggest count(column), which skips + blanks and answers a smaller number than the person meant. */} + {fn !== "count" && ( +
+ Column + {/* ⭐⭐ W54-T31 (R8) — THE CONTROL SHOWS WHAT IS CHOSEN AND OPENS THE LIST; IT IS + NOT THE LIST. `cg-select cg-fsel` is the shipped footprint every replaced + ` setScopeKind("view")} /> + A saved view + + {scopeKind === "view" && ( + )} - {/* ⭐⭐ THE BIND TIME REFUSAL, SURFACED WHERE THE PERSON CAN ACT ON IT. The server - refuses this column by name (`field_not_aggregable`), but only once a number is - asked for; saying it here means the choice is corrected before a save. */} - {savedFieldUnavailable && ( + {/* ⭐ W53-T12 — SAID HERE, THE MOMENT THE LIST RESOLVES, rather than as a refusal after + a save or a refresh. `sheet-notice` with `role="alert"` is this panel's established + inline shape, so the sentence lands where the choice is made. */} + {savedViewMissing && (

- {`The saved column ${field} cannot be totalled on this database. ` - + "Pick a column from the list, or count the records instead."} + {`The saved view ${savedView.name || savedView.id} is not available any more. ` + + "Pick a view that still exists, or build a filter here."}

)} -
- )} -
- -
- Rows to include - - {scopeKind === "view" && ( - - )} - {/* ⭐ W53-T12 — SAID HERE, THE MOMENT THE LIST RESOLVES, rather than as a refusal after - a save or a refresh. `sheet-notice` with `role="alert"` is this panel's established - inline shape, so the sentence lands where the choice is made. */} - {savedViewMissing && ( -

- {`The saved view ${savedView.name || savedView.id} is not available any more. ` - + "Pick a view that still exists, or build a filter here."} -

- )} - - {/* ⭐⭐ W53-T15 (ruling R8) — A DOOR, NOT THE BUILDER. The same shared panel now opens - in a centred dialog: this column is `flex: 0 0 380px` and a condition row cannot fit - in it, so four conditions could only be reached by scrolling sideways. The button - says how many conditions the cell already carries, because the builder that used to - say so is now behind it. */} - {scopeKind === "filter" && ( - <> - - {/* ⛔⛔ MOUNTED ONLY WHILE OPEN, and that is what orders Escape correctly rather - than a flag inside the dialog. `useOverlayLayer` claims Escape as soon as it - runs and `ui/useEscapeClose` gives the key to the LAST entry pushed, so a - dialog mounted with the panel would have claimed Escape from the moment this - editor opened. Mounting it here, later in time, puts it ABOVE this panel's own - claim (pushed at mount, a few hundred lines up) and unmounting it hands Escape - straight back, so one press closes the filter and the next closes the panel. */} - {filterPopupOpen && ( - setFilterPopupOpen(false)} - /> - )} - - )} -
- - {/* ══ R9: THE PERIOD ══════════════════════════════════════════════════════════════════ */} -
- Period - - {/* ⭐⭐ W53-T16 / D-660 - WHETHER THIS CELL HAS A PERIOD AT ALL, said out loud. The - pickers below show a unit and a month whether or not the cell is using them, so - without this switch an all-time total read as "September 2026" on screen and the next - save made that true. It is also the only way back to all time once a period is set. */} -
- -

- {periodOn - ? "Only rows dated inside the period below are counted." - : "All time, so every row this cell's filter matches is counted whatever its date. " - + "Saving leaves it that way."} -

-
- - {periodOn && ( - <> -
- {/* THE QUICK PICKS. They normalize through the same function the pickers do, so This - never stamps today's month under a quarter or a year. */} -
- - -
+ {/* ══ R9: THE PERIOD ══════════════════════════════════════════════════════════════════ */} +
+ Period - {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the - sentence under it says what each one costs when the cell is copied. */} + {/* ⭐⭐ W53-T16 / D-660 - WHETHER THIS CELL HAS A PERIOD AT ALL, said out loud. The + pickers below show a unit and a month whether or not the cell is using them, so + without this switch an all-time total read as "September 2026" on screen and the next + save made that true. It is also the only way back to all time once a period is set. */}

- {locked - ? "Locked, so any copy of this cell keeps this period." - : `Not locked, so copying right or left moves the period by one ${UNIT_NOUN[unit]} ` - + "per column, and copying up or down keeps it."} + {periodOn + ? "Only rows dated inside the period below are counted." + : "All time, so every row this cell's filter matches is counted whatever its date. " + + "Saving leaves it that way."}

- {/* ⭐ "Use a cell" STAYS A LINK (R9). It reveals the A1 input rather than replacing the - picker, so the ordinary reader never meets a cell reference and the person who wants - one is one click away from it. */} - {!refOpen && ( - + {periodOn && ( + <> + + +
+ + {unit === "month" && ( + + )} + {unit === "quarter" && ( + + )} +
+ + {/* THE QUICK PICKS. They normalize through the same function the pickers do, so This + never stamps today's month under a quarter or a year. */} +
+ + +
+ + {/* ⭐ R9's LOCK. A switch rather than a checkbox: it has two states with names, and the + sentence under it says what each one costs when the cell is copied. */} +
+ +

+ {locked + ? "Locked, so any copy of this cell keeps this period." + : `Not locked, so copying right or left moves the period by one ${UNIT_NOUN[unit]} ` + + "per column, and copying up or down keeps it."} +

+
+ + {/* ⭐ "Use a cell" STAYS A LINK (R9). It reveals the A1 input rather than replacing the + picker, so the ordinary reader never meets a cell reference and the person who wants + one is one click away from it. */} + {!refOpen && ( + + )} + {refOpen && ( + + )} + )} - {refOpen && ( - +
+ + {/* ══ R10: THE DRAG RULES ═════════════════════════════════════════════════════════════ */} +
+ When dragged + + + + + + {dragDownFields.length === 0 && ( +

+ This database has no single select or link column to walk, so dragging down repeats + the same rows. +

)} - - )} -
- - {/* ══ R10: THE DRAG RULES ═════════════════════════════════════════════════════════════ */} -
- When dragged - - - - - - {dragDownFields.length === 0 && ( -

- This database has no single select or link column to walk, so dragging down repeats - the same rows. -

- )} -
- - {/* ⛔⛔ W53-T16 (owner instruction 13) - THE FOUR SENTENCE SUMMARY IS DELETED, NOT HIDDEN. - It restated the period, the lock and the two drag rules that the controls immediately - above already say, in a panel 380px wide where every line it took pushed Save further - off screen. The one line kept is R11's, because it is the only sentence here that names - something NO control shows: the filter in this cell was copied out of a view that has - since been deleted, and nothing else remembers that. */} - {adoptedFrom && ( -

- {`Filter adopted from the deleted view ${adoptedFrom}`} -

+ + + {/* ⛔⛔ W53-T16 (owner instruction 13) - THE FOUR SENTENCE SUMMARY IS DELETED, NOT HIDDEN. + It restated the period, the lock and the two drag rules that the controls immediately + above already say, in a panel 380px wide where every line it took pushed Save further + off screen. The one line kept is R11's, because it is the only sentence here that names + something NO control shows: the filter in this cell was copied out of a view that has + since been deleted, and nothing else remembers that. */} + {adoptedFrom && ( +

+ {`Filter adopted from the deleted view ${adoptedFrom}`} +

+ )} + + {preview &&

{`This cell would show ${preview}`}

} + {notice &&

{notice}

} + )} - - {preview &&

{`This cell would show ${preview}`}

} - {notice &&

{notice}

}
diff --git a/web/src/sheet/ChartDialog.tsx b/web/src/sheet/ChartDialog.tsx new file mode 100644 index 0000000000000000000000000000000000000000..2f961f2f261cb8fa839fd981b23f8dd408aa8c6b --- /dev/null +++ b/web/src/sheet/ChartDialog.tsx @@ -0,0 +1,593 @@ +// sheet/ChartDialog.tsx — the Insert tab's CHART dialog (wave 54, W54-T11, ruling R5). +// +// ⭐⭐ R5, VERBATIM: "A chart reads BOTH. A cell range, exactly like Excel, is the primary path; a +// database source is a second tab in the same dialog. Ship both." So this is ONE dialog with two +// source tabs, and the cell range tab is the one that opens. +// +// ⛔⛔ HOW THE DATABASE TAB SURVIVES `SheetChart.tsx`'s RULING R9, WHICH SAYS THE OPPOSITE THING +// AND IS STILL TRUE. That file's header reads: "A CHART IS A CAPABILITY, NOT A VIEW TYPE. It +// occupies a rectangle of cells and READS those cells; it has no binding, no database and no query +// of its own. If this file ever calls the sheet preview door it has become a second way to fetch a +// number, and the sheet would then have two answers for one cell." +// +// The two reconcile in exactly one way, and it is the design below: THE DATABASE TAB DOES NOT GIVE +// THE CHART A QUERY. It writes BOUND CELLS into the sheet and then anchors an ordinary cell range +// chart over them. The chart still reads cells. The numbers still come from the one existing +// binding path, evaluated server side for a bound cell exactly as a hand bound cell is. Nothing +// here fetches a value, and `SheetChartSpec` gains no field: it is the same three keys it has +// carried since W49-T08. +// +// ⭐ WHAT THE DATABASE TAB WRITES, in ONE call through the door, so it is ONE history step and ONE +// save: a header row of period labels as typed literals, and beneath it one bound cell per period, +// every one carrying the same database, aggregate and scope and its OWN period. Then the chart, +// then a refresh, because a stale cell holds no value until the workbook refreshes. +// +// ⛔ THE BINDING VOCABULARY IS COPIED, NOT INVENTED. `BindingEditor.tsx` is the declaration of it +// and the server fixture in `aios-web/api/verify_sheet.py` is the proof; this file reuses the same +// names (`database`, `aggregate.fn`, `aggregate.field`, `scope.filter`, `period.unit`, +// `period.start`, `period.locked`) and imports nothing from that panel, because W54-T11 may not +// reach into lane E's files. A second spelling of the vocabulary would be a second dialect. +// +// ⛔ ESCAPE COMES FROM THE KIT AND FROM NOWHERE ELSE. `useOverlayLayer` registers this surface on +// the shared stack and calls `ui/useEscapeClose.ts` itself, which is why there is no local keydown +// listener anywhere in this file. DESIGN.md section 4: a local keydown listener is the defect, not +// the shortcut. +// +// ⚠ MOUNTED CONDITIONALLY BY ITS CALLER, never rendered behind an `open` prop. `useOverlayLayer` +// has no active flag: it claims Escape the moment it runs, and the stack hands the key to the LAST +// entry pushed. Mounting late is what puts this dialog above anything already open, and popping it +// on close hands Escape straight back. +// +// ⚠ DESIGN CONTRACT (DESIGN.md 2 through 5): centred modal on the base kit's `.lp-dialog` surface, +// tokens only, sentence case, inline SVG in the house vocabulary and never an emoji, a skeleton +// rather than a spinner while the database list is in flight, press feedback that does not change +// layout, reduced motion honoured, and no em dash or en dash in any string that reaches a screen. + +import { useEffect, useId, useMemo, useRef, useState } from "react"; +import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface"; +// The document's own addresser, in SHEET coordinates. A second spelling of A1 in this file would +// be a second answer to a question the document already answers. +import { addressOf } from "./sheetState"; +import type { Cell, SheetChartSpec } from "./types"; + +export interface ChartRange { + col0: number; + row0: number; + col1: number; + row1: number; +} + +/** + * ⭐ THE EIGHT KINDS THE DOCUMENT CARRIES. `types.ts::SheetChartSpec` declares all eight and + * `platform/core/sheets.py::SHEET_CHART_KINDS` keeps all eight since W54-T09, so every one of them + * survives a save and a reload. Four are DRAWN today (`types.ts::SHEET_CHART_DRAWN_KINDS`) and the + * renderer widens next, so the stored kind is the person's real choice either way. + */ +export const CHART_KINDS: { kind: SheetChartSpec["kind"]; label: string }[] = [ + { kind: "bar", label: "Bar" }, + { kind: "column", label: "Column" }, + { kind: "line", label: "Line" }, + { kind: "area", label: "Area" }, + { kind: "pie", label: "Pie" }, + { kind: "donut", label: "Donut" }, + { kind: "scatter", label: "Scatter" }, + { kind: "combo", label: "Combo" }, +]; + +/** + * ⭐ THE AGGREGATE VOCABULARY, COPIED FROM `BindingEditor.tsx::AGGREGATES` NAME FOR NAME. The + * server normalizes `aggregate.fn` against this same set, so a name invented here would bind a + * cell the panel could never reopen. + */ +const AGGREGATES: { fn: string; label: string }[] = [ + { fn: "sum", label: "Sum" }, + { fn: "count", label: "Count" }, + { fn: "avg", label: "Average" }, + { fn: "min", label: "Minimum" }, + { fn: "max", label: "Maximum" }, +]; + +type PeriodUnit = "month" | "quarter" | "year"; + +const PERIOD_UNITS: { unit: PeriodUnit; label: string }[] = [ + { unit: "month", label: "Month" }, + { unit: "quarter", label: "Quarter" }, + { unit: "year", label: "Year" }, +]; + +/** How many months one step of a unit covers. Same arithmetic the binding panel states. */ +const MONTHS_PER_UNIT: Record = { month: 1, quarter: 3, year: 12 }; + +const MONTH_ABBR = [ + "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", +]; + +/** + * ⚠ THE FALLBACK RECTANGLE, AND WHY IT IS A FALLBACK RATHER THAN A REFUSAL. A chart OCCUPIES the + * rectangle it reads, so a one cell range is a chart nobody can see and an absent range is no + * chart at all. When the selection is a single cell the range grows from that cell to this size, + * and with no selection at all it starts at A1, which is the only anchor available. The dialog + * SAYS which rectangle it will cover, so the growth is visible before anything is inserted. + */ +const CHART_COLS = 4; +const CHART_ROWS = 6; + +/** How many periods the database tab writes, and the fence around what a person may ask for. */ +const DEFAULT_PERIODS = 6; +const MIN_PERIODS = 2; +const MAX_PERIODS = 24; + +const pad2 = (n: number) => String(n).padStart(2, "0"); + +const joinYm = (y: number, m: number) => `${y}-${pad2(m)}`; + +/** `{y, m}` out of a `"YYYY-MM"`; today when the string is absent or malformed. */ +function splitYm(ym: string): { y: number; m: number } { + const hit = /^(\d{4})-(\d{2})$/.exec(ym ?? ""); + if (!hit) { + const now = new Date(); + return { y: now.getFullYear(), m: now.getMonth() + 1 }; + } + const m = Number(hit[2]); + return { y: Number(hit[1]), m: m >= 1 && m <= 12 ? m : 1 }; +} + +/** + * ⭐ `start` IS THE PERIOD'S FIRST MONTH, which is what contract C2 means by it: `unit` and `start` + * have to jointly name exactly one window, so Q3 2026 is `2026-07` and the year 2026 is `2026-01`. + */ +export function periodStartOf(unit: PeriodUnit, ym: string): string { + const { y, m } = splitYm(ym); + if (unit === "year") return joinYm(y, 1); + if (unit === "quarter") return joinYm(y, 1 + 3 * Math.floor((m - 1) / 3)); + return joinYm(y, m); +} + +/** Move a start by whole periods. Negative steps go back. */ +export function shiftPeriod(unit: PeriodUnit, ym: string, steps: number): string { + const { y, m } = splitYm(periodStartOf(unit, ym)); + const total = y * 12 + (m - 1) + steps * MONTHS_PER_UNIT[unit]; + return joinYm(Math.floor(total / 12), (total % 12) + 1); +} + +/** What a header cell says for one period. Sentence case, and no dash anywhere near it. */ +export function periodLabel(unit: PeriodUnit, ym: string): string { + const { y, m } = splitYm(periodStartOf(unit, ym)); + if (unit === "year") return String(y); + if (unit === "quarter") return `Q${1 + Math.floor((m - 1) / 3)} ${y}`; + return `${MONTH_ABBR[m - 1]} ${y}`; +} + +const todayYm = (): string => { + const now = new Date(); + return joinYm(now.getFullYear(), now.getMonth() + 1); +}; + +/** The rectangle a cell range chart occupies, grown to something visible when it has to be. */ +export function chartRangeOf(sel: ChartRange | null): ChartRange { + const col0 = sel ? Math.min(sel.col0, sel.col1) : 0; + const row0 = sel ? Math.min(sel.row0, sel.row1) : 0; + const col1 = sel ? Math.max(sel.col0, sel.col1) : 0; + const row1 = sel ? Math.max(sel.row0, sel.row1) : 0; + if (col1 > col0 || row1 > row0) return { col0, row0, col1, row1 }; + return { col0, row0, col1: col0 + CHART_COLS - 1, row1: row0 + CHART_ROWS - 1 }; +} + +/** Where a database block lands: the selection's top left, or A1 when there is no selection. */ +export function landingOf(sel: ChartRange | null): { col: number; row: number } { + if (!sel) return { col: 0, row: 0 }; + return { col: Math.min(sel.col0, sel.col1), row: Math.min(sel.row0, sel.row1) }; +} + +export interface DatabaseBlockPlan { + cells: Record; + range: ChartRange; +} + +/** + * ⭐⭐ THE WHOLE OF THE DATABASE TAB'S WRITE, AS A PURE FUNCTION so a reader can see that it + * produces CELLS and a RECTANGLE and never a query. Two rows: period labels on top, one bound cell + * per period beneath. The chart is anchored over both rows, because the header row is the axis. + */ +export function planDatabaseBlock(opts: { + anchor: { col: number; row: number }; + database: string; + fn: string; + field: string; + unit: PeriodUnit; + periods: number; +}): DatabaseBlockPlan { + const { anchor, database, fn, field, unit } = opts; + const asked = Math.round(opts.periods); + const count = Math.max(MIN_PERIODS, Math.min(MAX_PERIODS, Number.isFinite(asked) ? asked : DEFAULT_PERIODS)); + const latest = periodStartOf(unit, todayYm()); + const cells: Record = {}; + for (let i = 0; i < count; i += 1) { + const start = shiftPeriod(unit, latest, i - (count - 1)); + const col = anchor.col + i; + cells[addressOf(col, anchor.row)] = { + kind: "literal", + state: "typed", + text: periodLabel(unit, start), + }; + cells[addressOf(col, anchor.row + 1)] = { + kind: "bound", + state: "stale", + binding: { + database, + // A count folds no column, exactly as the binding panel writes it. + aggregate: fn === "count" ? { fn } : { fn, field }, + scope: { filter: { conj: "and", nodes: [] } }, + // LOCKED, and that is not a default worth glossing: each cell names one fixed window, and + // an unlocked period would shift the moment somebody dragged the block sideways, moving a + // number with no edit behind it. + period: { unit, start, locked: true }, + }, + }; + } + return { + cells, + range: { col0: anchor.col, row0: anchor.row, col1: anchor.col + count - 1, row1: anchor.row + 1 }, + }; +} + +/** The eight glyphs, in the house vocabulary: 16 by 16, on `currentColor`, at most three paths. */ +function ChartKindIcon({ kind }: { kind: SheetChartSpec["kind"] }) { + const cls = "sheet-chart-kind-icon"; + if (kind === "bar") { + return ( + + ); + } + if (kind === "column") { + return ( + + ); + } + if (kind === "line") { + return ( + + ); + } + if (kind === "area") { + return ( + + ); + } + if (kind === "pie") { + return ( + + ); + } + if (kind === "donut") { + return ( + + ); + } + if (kind === "scatter") { + return ( + + ); + } + return ( + + ); +} + +type SourceTab = "range" | "database"; + +const SOURCE_TABS: { id: SourceTab; label: string }[] = [ + { id: "range", label: "A cell range" }, + { id: "database", label: "A database" }, +]; + +export interface ChartDialogProps { + /** The current selection, in SHEET coordinates, or null when there is none. */ + selection: ChartRange | null; + /** Escape, an outside pointerdown, the close mark, or Cancel. All the same event. */ + onClose: () => void; + /** + * The one door out. `cells` is present only on the database tab, and the caller commits it in a + * single call so the block, the chart and the refresh are one step. + */ + onCreate: ( + kind: SheetChartSpec["kind"], + range: ChartRange, + cells?: Record, + ) => void; +} + +export default function ChartDialog({ selection, onClose, onCreate }: ChartDialogProps) { + const panelRef = useRef(null); + const titleId = useId(); + + const [tab, setTab] = useState("range"); + const [kind, setKind] = useState("bar"); + const [databases, setDatabases] = useState<{ key: string; label: string }[]>([]); + const [loading, setLoading] = useState(true); + const [database, setDatabase] = useState(""); + const [fn, setFn] = useState("count"); + const [field, setField] = useState(""); + const [unit, setUnit] = useState("month"); + const [periods, setPeriods] = useState(String(DEFAULT_PERIODS)); + + // ⛔ RESTORE FOCUS IS OFF, AND THAT IS THE RIBBON'S RULE RATHER THAN AN OMISSION. Every ribbon + // button prevents default on mouse down so that pressing it never blurs the grid canvas, so the + // element this dialog would restore is the CANVAS. `Ribbon.tsx::closePop` already returns focus + // to the trigger on close, and it must win. + useOverlayLayer({ + panelRef, + onDismiss: onClose, + dismissOnOutside: true, + initialFocus: "first", + restoreFocus: false, + trapFocus: true, + }); + + /** + * ⭐ THE SAME DOOR THE RAIL AND THE BINDING PANEL READ, spelled the same way `SheetPage.tsx` + * spells it. FAILS SOFT ON PURPOSE: a refused or broken fetch leaves the picker with nothing to + * offer and the panel says so, which is a refusal a person can act on. A thrown error inside a + * dialog is not. + */ + useEffect(() => { + let live = true; + (async () => { + try { + const res = await fetch("/api/v1/nav", { credentials: "same-origin" }); + if (!res.ok) return; + const body = (await res.json()) as { pages?: { key: string; label: string }[] }; + if (!live) return; + const rows = (body.pages ?? []) + .filter((p) => p && typeof p.key === "string") + .map((p) => ({ key: p.key, label: p.label || p.key })); + setDatabases(rows); + setDatabase(rows[0]?.key ?? ""); + } catch { + /* the picker simply offers nothing, and the panel says so */ + } finally { + if (live) setLoading(false); + } + })(); + return () => { live = false; }; + }, []); + + const range = useMemo(() => chartRangeOf(selection), [selection]); + const rangeSentence = `The chart will cover ${addressOf(range.col0, range.row0)} to ` + + `${addressOf(range.col1, range.row1)}.`; + + const wantsField = fn !== "count"; + const ready = tab === "range" + ? true + : Boolean(database) && (!wantsField || field.trim().length > 0); + + const create = () => { + if (tab === "range") { + onCreate(kind, range); + return; + } + if (!ready) return; + const plan = planDatabaseBlock({ + anchor: landingOf(selection), + database, + fn, + field: field.trim(), + unit, + periods: Number(periods), + }); + onCreate(kind, plan.range, plan.cells); + }; + + const kindPicker = ( +
+ {CHART_KINDS.map((entry) => ( + + ))} +
+ ); + + return ( + +
+
+
+

Insert a chart

+ +
+ +
+ {SOURCE_TABS.map((entry) => ( + + ))} +
+ +
+ {tab === "range" ? ( + <> +

{rangeSentence}

+ {kindPicker} + + ) : ( + <> +
+ + {loading ? ( +
+ ) : databases.length === 0 ? ( +

No databases are available to read.

+ ) : ( + + )} + + + + + {wantsField && ( + <> + + setField(event.target.value)} + /> + + )} + + + + + + setPeriods(event.target.value)} + /> +
+ {/* The gallery is the same one the cell range tab shows, and the chosen kind is + shared between the two: the source is what the tabs choose, never the picture. */} +
+ Chart type + {kindPicker} +
+ {/* ⚠ SAID AT THE POINT OF CREATION, because a person who expected only a picture + must not be surprised to find a block of numbers. One sentence, not a + paragraph (DESIGN.md section 4: never over-explain). */} +

+ The periods are written into the sheet as cells, and the chart reads them. +

+ + )} +
+ +
+ + +
+
+
+ + ); +} diff --git a/web/src/sheet/DrillModal.tsx b/web/src/sheet/DrillModal.tsx index 93c94e4c508b8fa852b9475f4d796c1097084111..6c5b92f5c3c67f44b7503eb32271ee5e8b21b3ba 100644 --- a/web/src/sheet/DrillModal.tsx +++ b/web/src/sheet/DrillModal.tsx @@ -16,9 +16,59 @@ // chrome and NO comparison text: no "was 24,920", no badge, nothing. The staleness is a property of // the CELL and it is marked on the grid; repeating it here would be answering a question the person // did not ask, at the moment they asked a different one. +// +// ⭐⭐ W54-T34 (owner instruction 10) — NINE SECONDS OF NOTHING WAS THE DEFECT. +// Owner, verbatim: *"Clicking View rows still takes a long time; if it must, we need a loading +// button so the user knows their click worked."* This component used to render `null` for the whole +// of that wait, so a drill that was working and a click that never landed looked identical. Measured +// on tenant #0 (`.claude/wiki/waves/wave54/lanes/E/T36-baseline.md`): `drill_cell` costs 55 to 90 ms +// against a `ut_*` table but 9,248 to 9,448 ms against `customer_data`, which goes through the +// registry-module mirror rather than a DuckDB query. So the wait is real and it is long. +// +// ⛔ BOTH `null`S WERE THE DEFECT, NOT ONE. The request had no loading state and neither did the +// LAZY CHUNK behind it, so a warm answer could still be followed by a second blank window while +// 1,850 kB of `CustomerGrid` downloaded. The Suspense fallback's old note argued that "a skeleton +// behind a modal that is about to cover it would be a flash of furniture nobody asked for" - which +// was right when there was no skeleton at all and the two states were nothing and everything. Now +// the skeleton is ALREADY on screen when the answer lands, so keeping it up for the chunk is +// CONTINUITY rather than new furniture: the surface never blinks back to nothing. +// +// ⭐⭐ W54-T35 (owner instruction 8, ruling R8) — THE ROWS ARE HERE, SO THE REASON FOR THEM +// SHOULD BE TOO. Owner, verbatim: *"the Filter module itself will show exactly what the filter is +// when we click 'View row' so its easy for user also to know what this filter is. In fact, they +// should be able to change the filter there too. And if they make a mistake etc, they can just +// CTRL + Z to return the Cell to its original filter."* Three clauses, and each one is a decision +// recorded beside the code that answers it: the BAND (`DrillFilterBand`) states it, the shared +// `SheetFilterDialog` edits it, and one cell-scoped step of undo takes it back. +// +// ⛔⛔ THE BAND IS PORTALLED INTO `LinkGridModal`'s OWN CARD, WHICH LOOKS LIKE A LIBERTY AND IS +// THE CONSERVATIVE CHOICE. `LinkGridModal` has no slot for extra chrome and it is not this lane's +// file, so the two alternatives were a floating strip positioned over its header by copied +// geometry, or this. A floating strip fails three ways at once and every one of them is silent: +// it is OUTSIDE `panelRef`, so the shared dismissal contract reads a click on it as an outside +// pointerdown and closes the drill the instant you reach for Edit; it is outside the focus trap, +// so the control is mouse-only; and it re-derives a card size it does not own. A portal into the +// card is inside all three. The host is found by `data-overlay-kind="linked-record-grid"`, the +// attribute that component already publishes for exactly this kind of identification, and when +// it is absent the band simply does not render. +// +// ⛔ AND THE BAND MAY WEAR `.cg-link-grid-foot`, WHICH THE SKELETON ABOVE MAY NOT. The rule that +// stops `DrillSkeleton` borrowing `customer-grid/RecordDetail.css` is that the skeleton stands in +// for a chunk that has not arrived, so on a cold cache its class names would exist and its rules +// would not. This band renders ONLY as a child of a mounted `LinkGridModal`, i.e. only once that +// same chunk is in hand, so the stylesheet is guaranteed present. Same file, opposite verdict, +// for one reason: WHEN it paints. import { Suspense, lazy, useCallback, useEffect, useRef, useState } from "react"; +import { createPortal } from "react-dom"; +import { fetchTopicRows, fetchWorkspace } from "../customer-grid/apiBridge"; import type { SurfaceScope } from "../customer-grid/apiBridge"; +import { OverlayProvider } from "../customer-grid/OverlaySurface"; +import type { Field, FilterTree, Row } from "../customer-grid/types"; +import { choiceVocabulary, topicForScope } from "../customer-grid/types"; +import { + SheetFilterDialog, conditionCountLabel, filterSentence, +} from "../filter-kit/SheetFilterPopup"; import { useEscapeClose } from "../ui/useEscapeClose"; import { drillCell } from "./sheetApi"; import type { CellDrill } from "./sheetApi"; @@ -40,6 +90,23 @@ const LinkGridModal = lazy(() => import("../customer-grid/CustomerGrid").then((m) => ({ default: m.LinkGridModal })), ); +/** + * ⭐⭐ W54-T34 — THE CHUNK IS ASKED FOR WHEN THE READER ASKS FOR THE ROWS, NOT AFTER THEY ARRIVE. + * + * `React.lazy` starts its import on the first render that actually reaches ``, which + * on the success path is AFTER the drill has answered. On `customer_data` that is nine seconds, and + * the 1,850 kB download then begins from zero: two waits, back to back, for one click. Warming the + * module the moment this component mounts runs them together instead. Nothing is imported twice - + * the two dynamic imports name the same module, so the second one resolves off the registry. + * + * ⛔ AND THE BOOLEAN IT FEEDS IS NOT A CONVENIENCE, IT IS THE ESCAPE CLAIM. `LinkGridModal` joins + * the base kit's stack from inside itself, through `useOverlayLayer`, so it claims Escape only once + * it has MOUNTED. The window while its chunk is still in flight belongs to nobody. Knowing when the + * module is in hand is what lets the skeleton hold the claim for exactly that window and hand it + * over, rather than overlap it - the double-push the W51-T12 note below is careful to avoid. + */ +const warmLinkChunk = () => import("../customer-grid/CustomerGrid"); + /** * A Sheet binding names a DATABASE KEY; `LinkGridModal` wants a `SurfaceScope`. The two are not * the same vocabulary and the difference is only visible for the two compiled modules. @@ -54,17 +121,233 @@ const scopeOf = (database: string): SurfaceScope | null => { return database.startsWith("ut_") ? (database as SurfaceScope) : null; }; +/** + * ⭐⭐ W54-T34 — WHAT VIEW ROWS OPENS INTO WHILE ITS ROWS ARE FETCHED. + * + * ⛔ THE SKELETON LANGUAGE IS INHERITED, NOT INVENTED. `sheet/SheetRail.tsx::RailSkeleton` set it + * and `sheet/BindingEditor.tsx::BindingSkeleton` followed it one ticket ago: ONE flat + * `--lp-surface-2` tone, no shimmer (an animated sweep is a second thing moving on a surface whose + * whole job is to sit still, and `prefers-reduced-motion` would then need a third state), bars + * `aria-hidden` under ONE `role="status"` so a screen reader hears "loading" once, and 150 ms + * ease-out on opacity alone. A second skeleton dialect in the same stylesheet would be the cost. + * + * ⛔⛔ AND IT CANNOT BORROW `.cg-record-backdrop` / `.cg-link-grid-modal`, WHICH IS THE OBVIOUS + * SHORTCUT AND IS EXACTLY BACKWARDS. Those rules live in `customer-grid/RecordDetail.css`, imported + * by `RecordDetail.tsx` - inside the very chunk this skeleton is standing in for. On a cold cache + * the class names would be there and the rules would not, so the stand-in for a slow chunk would + * paint in native chrome, precisely when it is needed most. + * ([[portalling-drops-descendant-scoped-css]], same failure through a different door.) + * + * ⭐ THE GEOMETRY IS THE SETTLED MODAL'S, measured off `.cg-link-grid-modal`: the same + * `min(1320px, 100vw - 48px)` by `min(840px, 100vh - 48px)` card on the same centred scrim, a 54px + * head, then rows. That is what makes it a skeleton rather than a placeholder - the real grid lands + * where the bars were instead of resizing the surface under the reader's eyes. + */ +function DrillSkeleton( + { label, nodeRef }: { label: string; nodeRef: { current: HTMLDivElement | null } }, +) { + return ( +
+ +
+ ); +} + +/** + * ⭐⭐ W54-T35 / R8 — WHICH ROWS THE CELL ASKED FOR, IN THE TWO SHAPES A BINDING CAN SAY IT. + * + * ⛔ THE `view` ARM EXISTS SO THE EDITOR CAN BE WITHHELD, AND THAT IS R8 VERBATIM: *"The Fields + * list … is hidden everywhere else, including under 'A saved view', where the view already fixes + * the rows."* A saved view's rows are the VIEW's business; editing a filter here would either + * silently fork the cell off its view or edit the view for everybody who uses it. So a view-bound + * cell gets the sentence and no Edit door. + */ +export type DrillCellScope = + | { kind: "filter"; tree: FilterTree } + | { kind: "view"; name: string }; + +/** What the drill's own answer says about the scope, for a caller that passed none. */ +function scopeFromDrill(drill: CellDrill | null): DrillCellScope | null { + if (!drill) return null; + if (drill.view_id) return { kind: "view", name: "" }; + const tree = drill.filter as FilterTree | null | undefined; + return { kind: "filter", tree: tree ?? { conj: "and", nodes: [] } }; +} + +/** + * ⚠ TREE EQUALITY BY SERIALISATION, deliberately, and the shape is what makes it safe. A + * `FilterTree` is plain JSON with no cycles and no undefined-versus-absent subtleties that matter + * here: both sides of every comparison this file makes came out of the SAME builder, so their key + * order is the builder's own. A hand-written deep-equal over `FilterRule`'s eleven optional + * members is the thing that would quietly stop noticing a member somebody added later. + */ +const sameTree = (a: FilterTree | null, b: FilterTree | null): boolean => + JSON.stringify(a ?? null) === JSON.stringify(b ?? null); + +/** + * ⭐⭐ W54-T35 — THE BAND THAT STATES THE FILTER, at the foot of the rows it produced. + * + * ⛔ IT IS A STATEMENT FIRST AND A CONTROL SECOND. The sentence is the whole of the owner's first + * clause, so it takes the width and truncates with an ellipsis rather than being shortened into a + * count; the full text stays reachable as the element's `title`. `Edit the filter` is one quiet + * button in the card's own `cg-btn` chrome, which is what the editable footer of this same modal + * already uses, so nothing new is introduced into the surface's control vocabulary. + */ +function DrillFilterBand( + { text, onEdit, editing }: { text: string; onEdit: (() => void) | null; editing: boolean }, +) { + return ( +
+ + {text} + + {onEdit && ( + + )} +
+ ); +} + export interface DrillModalProps { workbookId: string; addr: string; /** The label the popup wears. The cell's own address is the honest one: it is what was clicked. */ label: string; onClose: () => void; + /** + * W54-T34: the drill has stopped waiting - it answered, or it was refused. The page uses this to + * take the busy state back off the control that was clicked. It is NOT "the rows are on screen": + * a refusal settles too, and a control left spinning over a refusal is the worse failure. + */ + onSettled?: () => void; + /** + * W54-T35: the cell's OWN rows-to-include, read off its binding by the page. + * + * ⚠ NOT THE SAME THING AS THE DRILL ANSWER'S `filter`, and the difference is worth a prop. The + * answer describes what the SERVER used for the rows on screen; this describes what the cell + * holds NOW, which is what an edit changes and what an undo restores. On a healthy save the two + * agree within one round trip. Absent, the answer is used instead, so a caller that passes + * nothing still gets a drill that states its filter. + */ + cellScope?: DrillCellScope | null; + /** + * W54-T35: persist a new filter for this cell and recompute it. Absent means no Edit door. + * + * ⛔ IT RESOLVES WHEN THE WRITE HAS SETTLED, which is what lets the rows be re-read afterwards + * rather than immediately: `GET …/drill` reads the STORED binding, so a re-read fired before + * the save landed would answer with the filter that is being replaced and paint the old rows + * over the new filter. + */ + onFilterChange?: (addr: string, tree: FilterTree) => void | Promise; } -export default function DrillModal({ workbookId, addr, label, onClose }: DrillModalProps) { +export default function DrillModal( + { workbookId, addr, label, onClose, onSettled, cellScope, onFilterChange }: DrillModalProps, +) { const [drill, setDrill] = useState(null); const [error, setError] = useState(""); + /** Is `LinkGridModal`'s module in hand? See `warmLinkChunk` for why this is a state and not a + * detail of Suspense. */ + const [linkReady, setLinkReady] = useState(false); + + /** ⚠ A REF, so a page that hands this an inline arrow does not re-run the fetch effect below on + * every one of its own renders. */ + const settledRef = useRef(onSettled); + settledRef.current = onSettled; + /** Same reason, one ticket later: the page hands this an inline arrow too. */ + const filterChangeRef = useRef(onFilterChange); + filterChangeRef.current = onFilterChange; + + // ── W54-T35 state ───────────────────────────────────────────────────────────────────────── + /** Is the centred filter dialog on screen? */ + const [filterOpen, setFilterOpen] = useState(false); + /** + * ⛔⛔ THE DRAFT IS THIS COMPONENT'S, NOT THE DIALOG'S, AND THE DIALOG'S OWN CONTRACT IS WHY. + * `SheetFilterPopup` holds no draft on purpose: `onChange` is the caller's setter and every + * keystroke commits. The binding panel can afford that because its setter is a `useState`. Here + * the setter would be a PUT plus a recompute, so a value typed into a condition box would be one + * save per character. So the keystrokes land here, and the dialog closing is the commit. + * ⚠ THAT IS ALSO WHY CLOSING IT IS NOT A CANCEL. Escape, an outside click and Done are the same + * event with three names in that dialog, and they stay the same event here: all three APPLY. + */ + const [draft, setDraft] = useState(null); + /** + * ⭐⭐ THE UNDO, AND IT IS ONE STEP SCOPED TO THIS CELL. Owner: *"if they make a mistake etc, + * they can just CTRL + Z to return the Cell to its original filter."* + * + * ⛔⛔ IT IS DELIBERATELY NOT `SheetPage`'s `historyRef`. That stack snapshots the WHOLE `sheets` + * array on every commit, so pushing a filter edit onto it would make one Ctrl+Z walk back + * whatever else the reader had typed since - an undo that reaches past the surface it was + * pressed on, into cells nobody was looking at. This holds ONE tree: the cell's filter as it + * stood when the dialog was opened. A second Ctrl+Z therefore has nothing to pop and does not + * go further back, which is the done-when clause spelled as a data structure rather than as a + * guard somebody has to remember to write. + */ + const [undoTree, setUndoTree] = useState(null); + /** The tree as it stood when the Edit door was last opened. See `openFilter`. */ + const preEditRef = useRef(null); + /** Bumped when a filter change has landed, so the rows are read again. */ + const [reloadSeq, setReloadSeq] = useState(0); + /** The filter kit's two vocabularies for this database. Fetched once the drill has answered. */ + const [fields, setFields] = useState([]); + const [statusValues, setStatusValues] = useState>({}); + + useEffect(() => { + let live = true; + // ⚠ BOTH OUTCOMES SET IT. A chunk that fails to load is React's own error path once + // `` renders, exactly as it was before this ticket; holding the skeleton up + // forever instead would turn a loud failure into a silent one that looks like a slow server. + void warmLinkChunk().then( + () => { if (live) setLinkReady(true); }, + () => { if (live) setLinkReady(true); }, + ); + return () => { live = false; }; + }, []); /** * ⭐⭐ W51-T12 - THE REFUSAL CARDS CLOSE ON ESCAPE TOO, AND THAT WAS THE HOLE. @@ -87,11 +370,39 @@ export default function DrillModal({ workbookId, addr, label, onClose }: DrillMo const escapeContainer = useCallback(() => cardRef.current as HTMLElement | null, []); useEscapeClose(showingCard, onEscape, { container: escapeContainer }); + /** + * ⭐⭐ W54-T34 — AND THE SKELETON IS A SURFACE OF OURS TOO, SO IT CLAIMS ESCAPE ON THE SAME TERMS. + * + * It renders OUTSIDE `LinkGridModal`, like the two refusal cards above it, so without a claim of + * its own Escape would do nothing for the whole nine seconds the reader is most likely to press + * it. ⛔ A LOCAL `keydown` LISTENER IS THE DEFECT, NOT THE SHORTCUT: the arbiter in + * `ui/useEscapeClose.ts` exists because per-overlay listeners resolve by registration order. + * + * ⛔ STILL EXACTLY ONE CLAIMANT AT A TIME, WHICH IS THE PROPERTY W51-T12 BOUGHT AND THIS MUST NOT + * SPEND. The predicate is the complement of every other state this component can be in: a refusal + * card is up (`showingCard`), or the popup itself is up (`drill && scope && linkReady`), or this + * is. A second `useEscapeClose` call is the right shape for that - the hook pushes only while its + * flag is true, so two calls that are never true together are never two entries. + */ + const skeletonRef = useRef(null); + const showingSkeleton = !showingCard && !(drill && scope && linkReady); + const skeletonContainer = useCallback(() => skeletonRef.current as HTMLElement | null, []); + useEscapeClose(showingSkeleton, onEscape, { container: skeletonContainer }); + + /** + * ⛔⛔ W54-T35 — `reloadSeq` IS A DEPENDENCY AND `setDrill(null)` IS STILL NOT CALLED. A filter + * that has just been changed has to be answered again, because the ids on screen were narrowed + * by the OLD one. But clearing the answer first would unmount `LinkGridModal`, put the skeleton + * back over a card the reader is already reading, and then remount the whole grid: a blink, in + * exactly the place W54-T34 spent a ticket removing one. The previous answer stays up and is + * REPLACED when the new one lands, so only the row list changes. + */ useEffect(() => { let live = true; (async () => { const got = await drillCell(workbookId, addr); if (!live) return; + settledRef.current?.(); if (!got.ok) { setError(got.message); return; @@ -101,7 +412,186 @@ export default function DrillModal({ workbookId, addr, label, onClose }: DrillMo return () => { live = false; }; - }, [workbookId, addr]); + }, [workbookId, addr, reloadSeq]); + + /** + * ⭐⭐ W54-T35 — WHAT THE BAND SAYS, AND WHAT THE DIALOG EDITS. + * + * The page's own reading of the cell wins, because it is the one that MOVES: it is rebuilt from + * the workbook after every commit, so the sentence changes the moment a filter is applied. The + * drill answer is the fallback for a caller that passed none, and it is a real one rather than a + * courtesy: the server sends the scope on every drill. + */ + const shown = cellScope ?? scopeFromDrill(drill); + const shownKind = shown?.kind ?? ""; + const shownTree = shown?.kind === "filter" ? shown.tree : null; + + /** + * ⭐ THE FIELD AND VALUE VOCABULARIES, FETCHED THE WAY `BindingEditor` FETCHES THEM, and warmed + * on the drill's answer rather than on the Edit click for the reason `warmLinkChunk` is warmed + * at mount: the two doors would otherwise run back to back for one gesture. + * + * ⛔ NEITHER CALL IS NEW TRAFFIC IN PRACTICE. `fetchWorkspace(scope, {allowCached: true})` is + * served from `wsCache` inside its freshness window, and `fetchTopicRows` shares `rowsCache` + * with the embedded grid that is loading the SAME topic one component away. ⚠ The cached read + * is enough here, unlike in the binding panel: nothing on this surface seats a saved view + * against the list, so a minutes-old field list cannot paint a configuration nobody saved. + */ + useEffect(() => { + if (!scope || shownKind !== "filter") return; + let live = true; + (async () => { + const [ws, rowsPayload] = await Promise.all([ + fetchWorkspace(scope, { allowCached: true }), + fetchTopicRows(topicForScope(scope)), + ]); + if (!live || !ws) return; + const list = (ws.fields ?? []) as Field[]; + const rows: Row[] = rowsPayload?.rows ?? []; + const options: string[] = rowsPayload?.userOptions ?? ws.userOptions ?? []; + const map: Record = {}; + // The same rule `Toolbar.tsx` and `BindingEditor.tsx` compute, through the same pure + // function, so a server-computed select has a value list here as well. + for (const f of list) { + if (f.type === "user") { + map[f.key] = options; + continue; + } + if (f.type === "select" || f.type === "multiselect" || f.type === "status") + map[f.key] = choiceVocabulary(f, rows); + } + setFields(list); + setStatusValues(map); + })(); + return () => { live = false; }; + // ⚠ `shownKind` RATHER THAN `shown`. The page rebuilds that object on every one of its own + // renders, so depending on it would re-run these two fetches for reasons that have nothing to + // do with this cell; only the KIND decides whether they run at all. + }, [scope, shownKind]); + + /** Persist a tree through the page's one binding writer, then read the rows again. */ + const applyTree = useCallback(async (tree: FilterTree) => { + await Promise.resolve(filterChangeRef.current?.(addr, tree)); + setReloadSeq((n) => n + 1); + }, [addr]); + + /** + * ⛔ CLOSING THE DIALOG IS THE COMMIT, and an unchanged tree commits nothing. Without that test + * every open-and-look would write the cell back to itself, which is a PUT, a recompute and a + * spurious undo step for a gesture that changed nothing. + */ + const closeFilter = useCallback(() => { + setFilterOpen(false); + const next = draft; + setDraft(null); + if (!next || sameTree(next, shownTree)) return; + // ⛔ THE UNDO STEP IS RECORDED HERE AND NOT AT THE OPEN, because a door that was opened and + // shut again changed nothing and must leave nothing to take back. Recording it on open would + // arm Ctrl+Z after a look, and the press would then write the cell back to itself: a PUT, a + // recompute and a stale mark, for a gesture that did nothing. + setUndoTree(preEditRef.current); + void applyTree(next); + }, [applyTree, draft, shownTree]); + + const openFilter = useCallback(() => { + if (!shownTree) return; + // "The filter it had before the edit" is the filter it has at the moment the door opens. It + // is held in a ref rather than in state because nothing renders it: it is read once, by the + // close above, and putting it in state would re-render the drill for no visible reason. + preEditRef.current = shownTree; + setDraft(shownTree); + setFilterOpen(true); + }, [shownTree]); + + /** + * ⭐⭐ WHERE THE KEYSTROKE ACTUALLY ARRIVES, WHICH IS NOT WHERE THE SHEET'S UNDO LIVES. + * + * Ctrl+Z on the Sheet belongs to `SheetGrid.tsx::onKeyDown` (through `shortcuts.ts`), a REACT + * handler on the grid's own wrapper. While this modal is open the grid canvas does not have + * focus - focus is trapped inside a body-level portal that is a SIBLING of the grid in the + * React tree, not a descendant - so that handler is not on the propagation path at all and + * cannot be reached from here. Nothing in lane D's file has to change, and nothing in it does. + * + * ⛔⛔ WHAT IS ON THE PATH IS `CustomerGrid.tsx`'s OWN Ctrl+Z, and it is the reason this is a + * capture-phase WINDOW listener rather than a React handler. That component installs + * `window.addEventListener("keydown", onKey, true)` for its per-database undo, and the drill + * mounts a CustomerGrid inside the linked-record popup. Capture listeners on one target run in + * registration order, and this component mounts BEFORE the lazy chunk that mounts that grid, so + * this one runs first and `stopImmediatePropagation` is what keeps a filter undo from also + * popping the data grid's stack. A React handler could not have got in front of it. + * + * ⛔ THE KEY IS CLAIMED FOR AS LONG AS THE DRILL IS OPEN, INCLUDING WHEN THERE IS NOTHING TO + * UNDO. That is the second half of the done-when: a second press must not go further back, and + * the only way to guarantee that is to consume it rather than to let it fall through to + * whichever stack is next in line. + * + * ⚠ AN INPUT KEEPS ITS OWN UNDO. The same guard `CustomerGrid` uses, for the same reason: a + * caret in a condition's value box is the browser's text undo, and stealing it would be worse + * than not having ours. Ctrl+Shift+Z and Ctrl+Y are not claimed; redo is not in this ticket. + */ + const undoRef = useRef<() => void>(() => {}); + undoRef.current = () => { + if (filterOpen || !undoTree) return; + setUndoTree(null); + void applyTree(undoTree); + }; + useEffect(() => { + const onKey = (event: KeyboardEvent) => { + if (!(event.ctrlKey || event.metaKey) || event.altKey || event.shiftKey) return; + if (event.key.toLowerCase() !== "z") return; + const el = document.activeElement as HTMLElement | null; + if (el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.isContentEditable)) + return; + event.preventDefault(); + event.stopImmediatePropagation(); + undoRef.current(); + }; + window.addEventListener("keydown", onKey, true); + return () => window.removeEventListener("keydown", onKey, true); + }, []); + + /** + * ⭐ THE CARD THE BAND IS PORTALLED INTO. `LinkGridModal` publishes + * `data-overlay-kind="linked-record-grid"` on its own `
`, so this identifies it by the + * attribute it already declares rather than by a class the stylesheet owns. + * + * ⚠ ONE RETRY ON THE NEXT FRAME, AND NO MORE. Effects run after commit, so the card is normally + * in the DOM by the time this runs; the frame is there for the commit in which Suspense reveals + * the chunk. A poll would be a component watching for a sibling forever. + */ + const showRows = Boolean(drill && scope && linkReady); + const [host, setHost] = useState(null); + useEffect(() => { + if (!showRows) { + setHost(null); + return; + } + const find = () => + document.querySelector('[data-overlay-kind="linked-record-grid"]'); + const found = find(); + if (found) { + setHost(found); + return; + } + const frame = window.requestAnimationFrame(() => setHost(find())); + return () => window.cancelAnimationFrame(frame); + }, [showRows]); + + /** + * The sentence. ⚠ NOT MEMOISED, and that is measured rather than lazy: `filterSentence` walks + * at most three live leaves and stops, so a memo keyed on a `shown` the page rebuilds every + * render would recompute exactly as often while costing an extra comparison. + */ + const said = shown?.kind === "filter" ? filterSentence(shown.tree, fields) : ""; + const bandText = !shown + ? "" + : shown.kind === "view" + ? (shown.name ? `Rows come from the saved view ${shown.name}` : "Rows come from a saved view") + // ⛔ THE FALLBACK IS THE COUNT, NOT A SECOND SENTENCE. `filterSentence` answers "" when the + // filter narrows nothing, which covers both an empty tree and one whose conditions are all + // still half typed; `conditionCountLabel` is the wording the dialog behind the Edit door + // already uses for that, so the two surfaces say the same thing about the same tree. + : said ? `Rows where ${said}` : conditionCountLabel(shown.tree); if (error) { // A refusal is a plain sentence naming the cause and the subject, per the design contract. @@ -116,7 +606,10 @@ export default function DrillModal({ workbookId, addr, label, onClose }: DrillMo ); } - if (!drill) return null; + // ⛔⛔ W54-T34 — THIS WAS `return null`, AND IT IS THE OWNER'S REPORT IN ONE LINE. For as long as + // the drill is in flight the reader got a blank screen, which is what a dead control also looks + // like. The surface opens immediately and fills in. + if (!drill) return ; if (!scope) { // Named rather than swallowed: a database the popup cannot address is a real gap, and a blank @@ -132,16 +625,63 @@ export default function DrillModal({ workbookId, addr, label, onClose }: DrillMo } return ( - // No fallback chrome: the popup either opens or it does not, and a skeleton behind a modal - // that is about to cover it would be a flash of furniture nobody asked for. - - - + // ⛔⛔ W54-T34 REVERSED THIS FALLBACK, DELIBERATELY. It read `fallback={null}` under the note + // "the popup either opens or it does not, and a skeleton behind a modal that is about to cover + // it would be a flash of furniture nobody asked for". That was a true statement about a tree + // with no skeleton in it: the choice then was between nothing and a brand new surface appearing + // for one frame. The same skeleton is now ALREADY on screen when the answer lands, so passing + // it here does not add a surface, it declines to REMOVE one - the chunk loads under the same + // card the reader has been looking at, and the popup replaces it in place. Handing `null` here + // now would blink the screen back to empty at the last moment, which is the defect this ticket + // exists to remove, arriving one step later. + /** + * ⭐⭐ W54-T35 — ONE `OverlayProvider` OVER BOTH SURFACES, AND WITHOUT IT THE EDIT DOOR CLOSES + * THE DRILL. `useOverlayLayer` defers to a higher layer only when it can SEE one: + * `if (!dismissOnOutside || (stack && !stack.isTop(id))) return;`, where `stack` is + * `useContext(OverlayStackContext)`. The Sheet route mounts no provider, so `LinkGridModal` + * ran with `stack === null` and treated a pointerdown ANYWHERE outside its own card as a + * dismissal - including one inside a filter dialog opened on top of it. Both layers register + * here instead, the dialog registers later, and the card stands down while it is up. This is + * the same trap `filter-kit/SheetFilterPopup.tsx` documents at the top of its own file, one + * layer further out, which is why the dialog is mounted through `SheetFilterDialog` (no + * provider of its own) rather than through `SheetFilterPopup` (which brings one). + * + * ⛔ ESCAPE IS UNAFFECTED AND STILL RESOLVES TO EXACTLY ONE SURFACE. That is the module-level + * stack in `ui/useEscapeClose`, not this one: the card claims when it mounts, the dialog + * claims when it opens and is therefore topmost, so one press closes the filter and the next + * closes the drill. The band claims nothing - it is a statement and a button inside the + * card, not an overlay - so the "exactly one claimant" property W51-T12 bought is unspent. + */ + + }> + + + {host && bandText && createPortal( + , + host, + )} + {filterOpen && draft && ( + + )} + ); } diff --git a/web/src/sheet/KeyTips.tsx b/web/src/sheet/KeyTips.tsx index 94a799ed04a5b3bd64acca4bae68c273dfcc4c6c..644a2dc170300ba89fe13b9aa664bd1163e6589c 100644 --- a/web/src/sheet/KeyTips.tsx +++ b/web/src/sheet/KeyTips.tsx @@ -71,6 +71,44 @@ function isTextChar(key: string): boolean { return /^[a-zA-Z0-9]$/.test(key); } +/** ⭐⭐ W54-T24 (instruction 11) — THE MEASURED CAUSE OF "shortcuts do not work when done fast". + * Typed slowly, a person presses Alt, RELEASES it, then types H: the keyup toggles the layer on + * and every later letter lands. Typed fast, the same person is still HOLDING Alt when H arrives, + * which is how the owner writes the sequence and how Excel itself accepts it. On that path the + * old code marked the press a chord, refused to activate, and the whole sequence died: measured + * 0 of 5 held runs against 5 of 5 sequential runs, headless Chromium, 2026-09-06. + * This predicate is what keeps the fix narrow. A held Alt plus a letter only becomes a key-tip + * activation when that letter names a live FIRST-LEVEL badge (today: H for Home), so every other + * Alt chord the browser owns (Alt+D, Alt+F, Alt+Left) is never touched. */ +function isFirstLevelCode(container: HTMLElement | null, ch: string): boolean { + return getTargets(container, "tabs").some((t) => t.code.startsWith(ch)); +} + +/** How long the pressed look stays on a control the key-tip layer fired. DESIGN's interaction + * layer: 100 to 200 ms, ease-out, transform and opacity ONLY. */ +const PRESS_MS = 120; + +/** ⭐ W54-T24, the second half of instruction 11. A key-tip activation calls `.click()` on a real + * button, so NO pointer event is ever dispatched and a `:active` or `pointerdown` rule on the + * ribbon can never fire for it. The key-tip path therefore needs its own brief press state, and + * this is it: a transform, which cannot move anything around it, degrading to a short opacity + * change when the reader asks for reduced motion. */ +function pressFeedback(el: HTMLElement): void { + const reduced = typeof window.matchMedia === "function" + && window.matchMedia("(prefers-reduced-motion: reduce)").matches; + const priorTransform = el.style.transform; + const priorOpacity = el.style.opacity; + const priorTransition = el.style.transition; + el.style.transition = reduced ? `opacity ${PRESS_MS}ms ease-out` : `transform ${PRESS_MS}ms ease-out`; + if (reduced) el.style.opacity = "0.72"; + else el.style.transform = "scale(0.97)"; + window.setTimeout(() => { + el.style.transform = priorTransform; + el.style.opacity = priorOpacity; + el.style.transition = priorTransition; + }, PRESS_MS); +} + /** Every `[data-kt]` element visible AT THIS DEPTH, with its badge code. */ function getTargets(container: HTMLElement | null, depth: Depth): Target[] { if (!container) return []; @@ -198,6 +236,7 @@ export default function KeyTips({ containerRef }: KeyTipsProps) { */ const activate = useCallback((el: HTMLButtonElement) => { const st = stateRef.current; + pressFeedback(el); // W54-T24: the pressed look lands on the same tick as the command if (st.depth === "tabs") { el.click(); setKt({ depth: "home", prefix: "", focusedIdx: 0 }); @@ -241,6 +280,27 @@ export default function KeyTips({ containerRef }: KeyTipsProps) { if (e.key === "Alt") { altDownAtRef.current = Date.now(); altChordRef.current = false; + // ⭐⭐ W54-T24 — TAKE THE BARE ALT AWAY FROM THE BROWSER, ON THE KEYDOWN. On Windows and + // Linux desktop Chrome an unconsumed Alt press-and-release moves focus into the browser's + // own menu bar, and everything typed next goes there instead of to this layer. The old code + // only prevented the default on the KEYUP, and only on the branch that toggled, so a press + // the layer rejected still armed the menu. Consuming it here costs nothing: a bare Alt has + // no other meaning on this page, and AltGr (which Windows delivers as Control plus Alt) is + // excluded so composed characters still work. + if (!e.ctrlKey && !e.metaKey && !e.shiftKey) e.preventDefault(); + return; + } + // ⭐⭐ W54-T24 — ALT HELD PLUS A FIRST LEVEL LETTER IS THE SAME COMMAND AS ALT THEN THE + // LETTER. This is the fast typist's path and the one that used to die: see + // `isFirstLevelCode` above for the measurement and for why the match is required, which is + // what keeps every browser owned Alt chord untouched. + if ((altDownAtRef.current !== null || e.altKey) && !e.ctrlKey && !e.metaKey + && !stateRef.current.active && isTextChar(e.key) + && isFirstLevelCode(containerRef.current, e.key.toUpperCase())) { + e.preventDefault(); e.stopPropagation(); + altChordRef.current = true; // the trailing Alt keyup must not toggle the layer a second time + activateFirstLevel(); + handleCharacter(e.key.toUpperCase()); return; } if (altDownAtRef.current !== null) altChordRef.current = true; // a real chord, not a bare press @@ -294,7 +354,7 @@ export default function KeyTips({ containerRef }: KeyTipsProps) { // no flash, since KT-17's soft signal is for an unmatched CHARACTER, not for every // non-actionable key a person might happen to touch. e.preventDefault(); e.stopPropagation(); - }, [activate, containerRef, flash, handleCharacter, stepBack, setKt]); + }, [activate, activateFirstLevel, containerRef, flash, handleCharacter, stepBack, setKt]); const onDocKeyUp = useCallback((e: KeyboardEvent) => { if (e.key !== "Alt") return; diff --git a/web/src/sheet/LinkDialog.tsx b/web/src/sheet/LinkDialog.tsx new file mode 100644 index 0000000000000000000000000000000000000000..94de12c9dbfbcfc8da2d6283bace929b79284142 --- /dev/null +++ b/web/src/sheet/LinkDialog.tsx @@ -0,0 +1,521 @@ +// sheet/LinkDialog.tsx — A CELL WEARING AN ATTACHMENT: its link, its note, and the four surfaces +// those two need (wave 54, W54-T14, owner instruction 5, ruling R3). +// +// ⭐⭐ WHY A LINK AND A NOTE SHARE ONE FILE, AND THE NAME ON THE FILE IS ONLY HALF OF IT. +// A link and a note are the two things a cell can carry that are NEITHER VALUE NOR STYLE. Neither +// changes what the cell says, neither is read by a formula, and neither is drawn by the value +// renderer: both are painted BESIDE the text, on the same canvas, out of the same mark vocabulary +// (`paintCellMarks` below is one function drawing both, in one save/restore pair each). Splitting +// them would put one line of canvas painting in a file of its own and leave a reader hunting for +// the second half of a rule that is stated once here: the top-right corner belongs to the cell's +// STATE mark, so an attachment never paints there. +// +// ⭐ WHAT THIS FILE EXPORTS, and which side of the seam each one lives on: +// `LinkDialog` the authoring surface, opened from the Insert tab's Links group. All three +// link kinds, validated at the door. +// `paintCellMarks` the canvas half, called from `SheetGrid.tsx::paintCell` in BOTH of its +// branches. No React, no CSS, no measurement of the cell's own text. +// `NoteBubble` what a note shows on hover. +// `followLink` resolve and follow, and say so in one sentence when the target is not there. +// +// ⛔ THE SERVER PARSES NEITHER HALF, AND THAT IS THE CONTRACT THIS FILE IS THE OTHER SIDE OF. +// `platform/core/sheets.py::_clean_link` clamps the href and keeps BOTH halves or neither, because +// the kind is what decides which door opens the target; it never asks whether a URL is reachable +// or whether `Sheet2!B7` exists. Its own note puts that decision "in the door that opens it, which +// can say so at the moment somebody clicks". `followLink` is that door. +// +// ⚠ THIS IS NOT `web_record_comments`. That gate governs the RECORD comment surface in the Data +// module, which is a thread of authored comments hanging off a record. A cell note is one string +// on one cell, with no author, no thread and no reply. Nothing here borrows its vocabulary. +// +// ⚠ DESIGN CONTRACT (DESIGN.md 2 through 5): tokens only and type on the scale, sentence case, no +// emoji, inline SVG in this app's own glyph style, popovers originate at their trigger, refusals +// are one sentence, and no em dash or en dash in any string that reaches a screen. + +import { useMemo, useState } from "react"; +import type { FormEvent } from "react"; +import type { Rectangle } from "@glideapps/glide-data-grid"; +import { AnchoredOverlay } from "../customer-grid/OverlaySurface"; +import type { AnchorRect } from "../customer-grid/OverlaySurface"; +// ⭐ THE DOCUMENT'S OWN A1 PARSER. A cell link's target is spelled exactly the way a formula +// reference is, so `Sheet2!B7` is split here by the same grammar that already reads one, rather +// than by a second regular expression that would disagree with it on the day a sheet name gains +// a space. `parseRef` returns the sheet name unquoted and the column as letters. +import { colToIndex, parseRef } from "./a1"; +// ⭐ THE PALETTE RESOLVER, IMPORTED AND NEVER REWRITTEN. `cellBorders.ts` owns the one memoised +// `--lp-*` reader in this folder; a mark drawn on the canvas cannot be reached by CSS, so this is +// how a canvas colour stays a token (DESIGN.md 2). +import { tokenColour } from "./cellBorders"; +import { MAX_LINK_HREF } from "./types"; +import type { Cell } from "./types"; +import "../styles/wave54/ribbon-insert.css"; + +/** The link a cell carries, with both halves present. `Cell["link"]` is the optional form. */ +export type CellLink = NonNullable; + +// ═══════════════════════════════════════════════════════════════════════════════════════════════ +// ⭐⭐ THE THREE KINDS, AND THE KIND IS WHAT DECIDES WHICH DOOR OPENS THE TARGET. +// +// `url` leaves the app entirely, in a new tab. +// `cell` is an A1 address inside THIS workbook: bare (`B7`) on the sheet the link sits on, or +// sheet qualified (`Summary!B7`) on any other tab of the same workbook. +// `sheet` is a tab, by name. +// +// ⛔ THE HREF IS ONE STRING FOR ALL THREE, because that is the shape the store already keeps +// (W54-T09 provisioned it and `verify_sheet.py` proves the round trip at 385/385). Widening it +// into a discriminated payload would be a second answer to a question the document has settled. +// ═══════════════════════════════════════════════════════════════════════════════════════════════ + +const KIND_LABEL: Record = { + url: "Web address", + cell: "Cell", + sheet: "Sheet", +}; + +/** Only a web address opens in a browser tab. Anything else is refused before `window.open`. */ +const WEB_SCHEME = /^https?:\/\//i; + +/** Does this look like it already carries a scheme of its own? */ +const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i; + +/** + * ⭐ THE TAB NAMES, READ OFF THE TAB BAR, AND THIS IS A REACH RATHER THAN A PROP FOR A REASON. + * `Ribbon.tsx::RibbonInsertDoor` carries a selection, the chart list and two cell doors, and it is + * a file this ticket may not widen. The workbook's own tab bar is in the document with a stable + * label, and `SheetGrid.tsx::switchTab` already reaches it exactly this way for Ctrl+PgUp, so this + * is the app's existing door rather than a new one. + * + * ⛔ `[aria-pressed]` IS WHAT TELLS A SHEET FROM "Add sheet". That bar's trailing button is an + * action rather than a tab and carries no pressed state, so filtering on the attribute is what + * keeps a sheet list from growing a phantom sheet at the end. An empty answer is honest: the + * dialog then asks for a typed name instead of pretending it knows the sheets. + */ +const sheetNamesOnScreen = (): string[] => { + if (typeof document === "undefined") return []; + return Array.from(document.querySelectorAll('[aria-label="Sheets"] button[aria-pressed]')) + .map((button) => (button.textContent ?? "").trim()) + .filter(Boolean); +}; + +/** Case-insensitive, because a person typing `summary` means the tab called `Summary`. */ +const matchSheet = (names: readonly string[], want: string): string | null => + names.find((name) => name.toLowerCase() === want.trim().toLowerCase()) ?? null; + +// ═══════════════════════════════════════════════════════════════════════════════════════════════ +// ⭐ THE AUTHORING SURFACE. +// ═══════════════════════════════════════════════════════════════════════════════════════════════ + +function IconLinkKind({ kind }: { kind: CellLink["kind"] }) { + return ( + + ); +} + +/** + * ⭐⭐ A POPOVER, NOT A MODAL, AND THE FILE NAME IS THE ONLY THING THAT SAYS OTHERWISE. DESIGN.md + * 4: "Menus and popovers originate at their trigger; modals remain centered." This surface asks + * for one short target and belongs beside the Link button that opened it, exactly as the Comment + * form does one group over; the chart dialog is centred because it is a chooser with two tabs and + * eight kinds. The overlay is mounted HERE rather than in `ribbonInsert.tsx` for the reason + * `ChartDialog` is: a tab module is a function the ribbon shell calls during its own render and + * cannot hold a hook, and a kind picker whose refusal survives a keystroke needs state. + * + * ⚠ NO LOCAL KEYDOWN LISTENER. Escape arrives through `AnchoredOverlay`, which registers with the + * one arbiter in `ui/useEscapeClose.ts`, and from nowhere else (DESIGN.md 5). + * + * ⚠ `restoreFocus={false}` IS LOAD BEARING FROM THE RIBBON. Every ribbon button cancels its own + * mouse-down so it never blurs the grid canvas, so the trigger never takes focus and the element + * this would restore is THE CANVAS. `Ribbon.tsx::closePop` already returns focus to the trigger + * and has to win. + */ +export default function LinkDialog({ + anchor, + held, + onClose, + onSubmit, +}: { + anchor: HTMLElement | null; + /** What the anchor cell already carries, so a second Insert > Link EDITS rather than replaces. */ + held?: CellLink; + onClose: () => void; + onSubmit: (link: CellLink) => void; +}) { + const sheets = useMemo(sheetNamesOnScreen, []); + const [kind, setKind] = useState(held?.kind ?? "url"); + const [href, setHref] = useState(() => (held?.kind === "url" ? held.href : "")); + const [addr, setAddr] = useState(() => (held?.kind === "cell" ? held.href : "")); + const [sheet, setSheet] = useState(() => ( + held?.kind === "sheet" ? held.href : (sheets[0] ?? "") + )); + const [why, setWhy] = useState(""); + + const pick = (next: CellLink["kind"]) => { + setKind(next); + setWhy(""); + }; + + /** + * ⛔ VALIDATED AT THE DOOR, IN ONE SENTENCE (DESIGN.md 5). The server clamps the length and + * stores whatever it is given, so this is the only place a person can be told that `B0` is not + * an address before the link is saved and clicked. A web address with no scheme is COMPLETED + * rather than refused, because `example.com` is what people type and `https` is what they mean. + */ + const submit = (event: FormEvent) => { + event.preventDefault(); + if (kind === "url") { + const typed = href.trim(); + if (!typed) { + setWhy("Type a web address first."); + return; + } + const full = HAS_SCHEME.test(typed) ? typed : `https://${typed}`; + if (!WEB_SCHEME.test(full)) { + setWhy("A web address has to start with http or https."); + return; + } + onSubmit({ href: full.slice(0, MAX_LINK_HREF), kind: "url" }); + return; + } + if (kind === "cell") { + const typed = addr.trim(); + const ref = parseRef(typed); + if (!ref) { + setWhy("That is not a cell address like B7 or Summary!B7."); + return; + } + if (ref.sheet && sheets.length && !matchSheet(sheets, ref.sheet)) { + setWhy(`This workbook has no sheet called ${ref.sheet}.`); + return; + } + onSubmit({ href: typed.slice(0, MAX_LINK_HREF), kind: "cell" }); + return; + } + const typed = sheet.trim(); + if (!typed) { + setWhy("Choose the sheet this cell should open."); + return; + } + if (sheets.length && !matchSheet(sheets, typed)) { + setWhy(`This workbook has no sheet called ${typed}.`); + return; + } + onSubmit({ href: typed.slice(0, MAX_LINK_HREF), kind: "sheet" }); + }; + + return ( + +
+

Link this cell to

+ + {/* ⭐ THREE BUTTONS RATHER THAN A SELECT, and they share one height and one baseline with + each other (DESIGN.md 4). The choice is small, closed and worth seeing at a glance; + `aria-pressed` is what a reader with a screen reader hears as the current kind. */} +
+ {(["url", "cell", "sheet"] as const).map((option) => ( + + ))} +
+ + {kind === "url" && ( + <> + + { setHref(event.target.value); setWhy(""); }} + /> + + )} + + {kind === "cell" && ( + <> + + { setAddr(event.target.value); setWhy(""); }} + /> +

+ A cell on this sheet, or Summary!B7 for a cell on another sheet of this workbook. +

+ + )} + + {kind === "sheet" && ( + <> + + {/* ⭐ THE TAB NAMES ARE OFFERED RATHER THAN TYPED wherever the tab bar is on screen. + Where it is not, the field falls back to a text box and the refusal below is the + only check left, which is the honest shape: this surface never claims to know a + list it could not read. */} + {sheets.length > 0 ? ( + + ) : ( + { setSheet(event.target.value); setWhy(""); }} + /> + )} + + )} + + {why &&

{why}

} + + +
+
+ ); +} + +// ═══════════════════════════════════════════════════════════════════════════════════════════════ +// ⭐⭐ THE CANVAS HALF. ONE FUNCTION, TWO MARKS, AND IT IS CALLED FROM BOTH OF `paintCell`'S +// BRANCHES. +// +// ⛔ IT PAINTS BESIDE THE TEXT AND NEVER RE-RENDERS IT. The unstyled branch has already handed the +// cell to glide's own renderer and the styled branch has already laid the value out itself, so +// measuring or re-drawing here would be a third answer to "what does this cell say" and a smear +// on top of the second. +// +// ⛔ THE TOP-RIGHT CORNER IS TAKEN, AND THAT IS WHY THE NOTE MARK IS NOT WHERE EXCEL PUTS IT. +// `SheetGrid.tsx::MARK_STYLE` owns that corner for the cell's STATE (R19's blue and yellow +// triangles, the typed dot, the refused bar) and the validation caret sits on the right edge below +// it. Two facts stacked in one corner is neither fact read, so the attachment mark takes the +// TOP LEFT corner, which nothing else in this grid paints. The convention Excel is actually +// setting is "a corner triangle means this cell carries something the value does not show", and +// that survives the move; the exact corner does not. +// +// ⛔ NO CSS REACHES EITHER MARK. Both colours come from `--lp-*` tokens through `tokenColour`. +// ═══════════════════════════════════════════════════════════════════════════════════════════════ + +/** How far in from a cell edge a mark sits, so the grid's own hairlines survive under it. */ +const MARK_INSET = 1; +/** The corner triangle's legs. Small enough to clear an ordinary value's first glyph. */ +const MARK_LEG = 6; + +export const paintCellMarks = ( + ctx: CanvasRenderingContext2D, + rect: Rectangle, + cell: Cell | null | undefined, +): void => { + if (!cell) return; + + // ⭐ A LINK IS AN UNDERLINE, because that is the affordance a person recognises without being + // told. It spans the cell's own text inset rather than the measured run: the run cannot be + // measured here without adopting the font the branch above already chose, and an underline that + // is a little wider than its word still reads as a link while a missing one reads as nothing. + if (cell.link?.href) { + ctx.save(); + ctx.fillStyle = tokenColour("--lp-blue-solid", "#5b8fd9"); + const y = Math.round(rect.y + rect.height / 2 + 7); + ctx.fillRect(rect.x + 8, y, Math.max(0, rect.width - 16), 1); + ctx.restore(); + } + + // ⭐ A NOTE IS A CORNER INDICATOR, in the note stratum's own ink (`index.css` declares + // `--lp-yellow-deep` as "note + Pre-set tag text", which is exactly this). + if (cell.note) { + ctx.save(); + ctx.fillStyle = tokenColour("--lp-yellow-deep", "#7e6428"); + ctx.beginPath(); + ctx.moveTo(rect.x + MARK_INSET, rect.y + MARK_INSET); + ctx.lineTo(rect.x + MARK_INSET + MARK_LEG, rect.y + MARK_INSET); + ctx.lineTo(rect.x + MARK_INSET, rect.y + MARK_INSET + MARK_LEG); + ctx.closePath(); + ctx.fill(); + ctx.restore(); + } +}; + +// ═══════════════════════════════════════════════════════════════════════════════════════════════ +// ⭐ WHAT A NOTE SHOWS ON HOVER. +// ═══════════════════════════════════════════════════════════════════════════════════════════════ + +/** + * ⭐⭐ IT ORIGINATES AT ITS CELL, IT IS NOT MODAL, AND IT DOES NOT TAKE THE KEYBOARD. + * + * ⛔ `initialFocus="none"` AND `restoreFocus={false}` ARE THE WHOLE OF "does not steal the + * keyboard from the grid". A hover surface that focused itself would move the caret off the canvas + * every time a pointer crossed a noted cell, and the arrow keys would stop moving the selection. + * With nothing inside focused, the kit's own restore has nothing to put back either. + * + * ⛔ IT IS POINTER TRANSPARENT (see the stylesheet). glide reports hover off the canvas UNDER + * this box, so a bubble that took a pointer would hide the cell it is describing from the very + * callback that opened it, and it would flicker. + * + * ⚠ Escape still reaches it, through `AnchoredOverlay` and the one arbiter, because an overlay + * that cannot be dismissed by the key every other overlay answers is the defect DESIGN.md 5 names. + */ +export function NoteBubble({ + anchor, + note, + onDismiss, +}: { + anchor: AnchorRect | null; + note: string; + onDismiss: () => void; +}) { + if (!note) return null; + return ( + +

{note}

+
+ ); +} + +// ═══════════════════════════════════════════════════════════════════════════════════════════════ +// ⭐⭐ THE DOOR THAT OPENS THE TARGET, AND THE ONE PLACE THAT CAN SAY IT IS NOT THERE. +// ═══════════════════════════════════════════════════════════════════════════════════════════════ + +/** What `followLink` needs from the grid, and nothing more. */ +export interface FollowContext { + /** Every tab of this workbook, in the tab bar's own order. */ + sheets: readonly { id: string; name: string }[]; + /** The tab the grid is showing right now. */ + tabId: string; + /** Show a tab, by id. */ + goToSheet: (sheetId: string) => void; + /** Put the selection on a zero-based SHEET cell of that tab, switching tabs first if it must. */ + goToCell: (sheetId: string, col: number, row: number) => void; + /** One sentence, and only ever one (DESIGN.md 5). */ + onNotice: (message: string) => void; +} + +/** + * Follow the link this cell carries. `false` means the cell carries none, which is what lets a + * click handler ask and fall through to its ordinary behaviour in one line. + * + * ⛔ EVERY REFUSAL IS ONE SENTENCE AND IS SAID AT THE MOMENT OF THE CLICK, which is where + * `platform/core/sheets.py` deliberately left it: the store keeps a target it never checked, so + * the check has to be here or it never happens at all. + */ +export const followLink = (cell: Cell | null | undefined, ctx: FollowContext): boolean => { + const link = cell?.link; + if (!link?.href) return false; + + if (link.kind === "url") { + if (!WEB_SCHEME.test(link.href)) { + ctx.onNotice("This link is not a web address, so it cannot be opened."); + return true; + } + // ⛔ `noopener,noreferrer` IS THE SECURITY HALF, not a preference: without `noopener` the page + // that opens keeps a handle on this one through `window.opener` and can navigate it. + // + // ⛔⛔ AND THE RETURN VALUE IS NOT AN ANSWER. `noopener` severs the handle BY DEFINITION, so + // the spec has `window.open` answer `null` on SUCCESS as well as on a blocked pop-up. Driven + // headless the day this was written: the tab really opened and the null check said the browser + // had blocked it, which is a refusal sentence in front of a person whose link worked. There is + // no way to tell the two apart while keeping the security half, so the security half wins and + // nothing is claimed about the result. + window.open(link.href, "_blank", "noopener,noreferrer"); + return true; + } + + if (link.kind === "sheet") { + const found = ctx.sheets.find( + (sheet) => sheet.name.toLowerCase() === link.href.trim().toLowerCase(), + ); + if (!found) { + ctx.onNotice(`This workbook has no sheet called ${link.href}.`); + return true; + } + ctx.goToSheet(found.id); + return true; + } + + const ref = parseRef(link.href); + if (!ref) { + ctx.onNotice(`${link.href} is not a cell address, so there is nothing to open.`); + return true; + } + // ⚠ A BARE ADDRESS MEANS THE SHEET THE LINK SITS ON, which is the tab the grid is showing: the + // link was authored there and it is stored on a cell of that tab. Only a qualified one is looked + // up by name, and only that one can fail to find a sheet. + const targetId = ref.sheet + ? (ctx.sheets.find((sheet) => sheet.name.toLowerCase() === ref.sheet.toLowerCase())?.id ?? null) + : ctx.tabId; + if (!targetId) { + ctx.onNotice(`This workbook has no sheet called ${ref.sheet}.`); + return true; + } + ctx.goToCell(targetId, colToIndex(ref.col) - 1, ref.row - 1); + return true; +}; diff --git a/web/src/sheet/Ribbon.tsx b/web/src/sheet/Ribbon.tsx index 4ef107eb559333421d59ca242a9d32f7ac7222b8..7ebd75be6786a63cea61fbeb47fcd784f964b93a 100644 --- a/web/src/sheet/Ribbon.tsx +++ b/web/src/sheet/Ribbon.tsx @@ -1,4 +1,12 @@ -// sheet/Ribbon.tsx — the Sheet's HOME ribbon (wave 50, W50-T19/A1; wave 51, W51-T15, ruling R8). +// sheet/Ribbon.tsx — the Sheet ribbon's SHELL (wave 50, W50-T19/A1; wave 51, W51-T15, ruling R8; +// split per tab by wave 54's base kit). +// +// ⭐⭐ W54 BASE KIT 2a — THIS FILE IS THE FRAME, AND THE TABS ARE MODULES. It carries the tab +// strip, the four action buttons, the roving-focus handler, the shared control vocabulary +// (`control`, `group`, `word`, `item`) and a REGISTRY. Every Home group lives in `ribbonHome.tsx`; +// a second tab is a second module registered in `TABS`, and neither module edits the other. The +// reason is mechanical rather than tidy: two wave-54 lanes both extend the ribbon, and two lanes +// cannot share one file. // // ⭐⭐ WHAT THIS COMPONENT IS AND IS NOT. It is a `role="toolbar"` of STATELESS controls: every // button reports one patch or one named act and holds nothing. The selection, the cells and the @@ -40,27 +48,26 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { KeyboardEvent, MouseEvent as ReactMouseEvent, ReactNode } from "react"; -import { CELL_FORMAT_KINDS } from "./types"; -import type { CellFormatKind, CellStyle, CellStylePatch } from "./types"; +import type { Cell, CellStyle, CellStylePatch, SheetChartSpec } from "./types"; // ⭐ W52-T15 — a component-owned side-effect import, exactly like `customer-grid/Toolbar.tsx`'s // own `import "./filters.css"`. See the stylesheet's own header for why this is not an // `index.css` `@import` line. import "../styles/wave52/ribbon.css"; -// ⭐ W52-T16 (instruction 18, ruling R4) — the new Clipboard/Editing/Cells/Styles icons live in -// their own file (`ribbonIcons.tsx`) rather than growing this one further; the icons already in -// THIS file (IconAlign, IconVAlign, ...) stay here — see that file's own header for why. -import { - IconAutoSum, IconCellFormat, IconClear, IconConditional, IconCopy, IconCut, IconDelete, - IconFillDown, IconFillRight, IconFormatPainter, IconInsert, IconPaste, -} from "./ribbonIcons"; +// ⭐⭐ W54 base kit 2a — THE REGISTERED TABS. Each module exports its own descriptor and its own +// control keys; this file imports them and nothing else from either. +import { HOME_TAB } from "./ribbonHome"; +// ⭐⭐ W54-T10 (lane B) — the second registered tab. Same three exports, same registry, and the +// shell learns nothing about it beyond its descriptor. +import { INSERT_TAB } from "./ribbonInsert"; // ⭐⭐ W52-T17 (instruction 20, ruling R7) — the KeyTips overlay is a SEPARATE keyboard-capture // layer, mounted once, that reads this file's DOM (`[data-kt]`, `[data-kt-opens]`) rather than // threading new props through 30+ `control()` call sites. See that file's own header for the // contract (C5) and the depth model (tabs -> Home controls -> one opened gallery). import KeyTips from "./KeyTips"; -import { AnchoredOverlay } from "../customer-grid/OverlaySurface"; // W53-T07 (instr 25): the portalled popover's own surface. A body-level node keeps no // ancestor rule, so its background, edge and shadow travel with it. See the file header. +// ⚠ SHELL, NOT HOME: `.sheet-ribbon-pop` is the surface EVERY tab's gallery paints on, so the +// import stays here where both tabs inherit it. import "../styles/wave53/ribbon-pop.css"; /** @@ -80,14 +87,28 @@ export type RibbonActionKind = | "format-accounting" | "format-custom" // Styles | "conditional-formatting" + // ⭐ W54-T05 — the two Styles acts that build a rule FROM THE SELECTION rather than opening the + // editor. They are separate members because each reads the selection's own numbers to work out + // the range it spreads across, which no `arg` on the existing act could carry. + | "colour-scale" | "data-bars" // Cells | "insert-row" | "insert-column" | "delete-row" | "delete-column" | "add-rows" | "add-columns" | "row-height" | "column-width" | "hide-rows" | "hide-columns" | "unhide" | "freeze" + // ⭐ W54-T07 — the two AUTOFITS, which are the same two questions the manual sizes ask, asked + // from the content instead. They are separate members rather than an `arg` on the existing acts + // because neither opens the number dialog at all: each measures the selection and writes. + | "autofit-rows" | "autofit-columns" // Editing | "autosum" | "fill-down" | "fill-right" | "clear-contents" | "clear-formats" | "clear-all" + // ⭐ W54-T07 — FIND AND SELECT'S THREE, and all three reach a surface that ALREADY EXISTS: + // `find` and `replace` open the one find box `SheetGrid.tsx` has carried since W51-T17 (the + // second one with its replace row showing), and `go-to` focuses the formula bar's cell address + // input, which is this app's Name Box and already jumps to whatever is typed into it. No act + // here opens a second search surface, and none may. + | "find" | "replace" | "go-to" // ⭐ W52-T15 (instruction 14) — the workbook's own acts. Their CONTROLS moved out of the // groups row and into the tab strip (`sheet-ribbon-tabs`), in the SAME horizontal space as // the Home tab; the act NAMES stay here because `SheetGrid.tsx`'s exhaustive switch still owns @@ -100,6 +121,35 @@ export interface RibbonAction { arg?: string | number; } +/** + * ⭐⭐ W54-T10 (lane B) — THE INSERT TAB'S DOOR, AND WHY IT IS NOT A NEW `RibbonActionKind`. + * + * ⛔ THE ACT UNION IS CLOSED BY AN EXHAUSTIVE SWITCH IN A FILE THIS LANE DOES NOT OWN. + * `SheetGrid.tsx::onRibbonAction` ends on `const _exhaustive: never = action.kind`, so a new + * member there is a compile error until that switch grows an arm, and growing it is another + * ticket's surface. That is the mechanical reason. The DESIGN reason is the better one: a chart, a + * sparkline, a link and a note are not NAMED ACTS at all. They are DOCUMENT WRITES, and the + * document already has doors for both shapes of them, one per level. A chart is a TAB level key, + * so it takes the tab's own replace-the-list door; a sparkline, a link and a note are CELL keys, + * so they take the same one commit door a style patch takes, which is what makes an inserted + * sparkline one history step and one save exactly like a paste. + * + * ⚠ OPTIONAL, for the reason `SheetGrid.tsx::onRules` states in full: a required prop would break + * every other lane's tree at the merge. Where it is absent the Insert tab renders every control + * DISABLED rather than wired to nothing, which is the fake affordance `canImport` refuses by name. + */ +export interface RibbonInsertDoor { + /** The selection as a SHEET-coordinate rectangle, or null when nothing is selected. */ + selection: { col0: number; row0: number; col1: number; row1: number } | null; + /** This tab's charts, and the one door that replaces the list. */ + charts: readonly SheetChartSpec[]; + onCharts: (next: SheetChartSpec[]) => void; + /** One or many cells, through the SAME commit door a style patch takes. */ + onCells: (edits: Record) => void; + /** Read a cell in SHEET coordinates, so a link or a note AMENDS rather than replaces. */ + cellAt: (col: number, row: number) => Cell | null; +} + export interface RibbonProps { /** * The style of the cell the selection is ANCHORED on, which is what the toggles report as @@ -115,45 +165,113 @@ export interface RibbonProps { canImport?: boolean; onApply: (patch: CellStylePatch) => void; onAction: (action: RibbonAction) => void; + /** ⭐ W54-T10 — the Insert tab's document doors. See {@link RibbonInsertDoor}. */ + insert?: RibbonInsertDoor; } // ═══════════════════════════════════════════════════════════════════════════════════════════════ -// THE ROVING ORDER, DERIVED FROM THE GROUPS RATHER THAN RESTATED BESIDE THEM. +// THE REGISTRY, AND THE ROVING ORDER DERIVED FROM IT RATHER THAN RESTATED BESIDE IT. // // ⛔ A HAND MAINTAINED PARALLEL ARRAY IS HOW ROVING FOCUS DIES SILENTLY: one `data-ribbon` typo and // `focusControl`'s query returns null, with every gate still green. `ControlKey` is derived from -// these arrays, so a control rendered under a name that is not in one of them is a TYPE ERROR. +// the registry below, so a control rendered under a name that is not in it is a TYPE ERROR. // ═══════════════════════════════════════════════════════════════════════════════════════════════ -// ⭐⭐ W52-T15 (instruction 14, contract C4) — IMPORT, REFRESH AND FULL SCREEN LIVE IN THE TAB -// STRIP NOW, NOT IN A RIBBON GROUP. They render in `sheet-ribbon-tabs`, which is on screen -// whether the groups row is collapsed or not, so they belong in `STRIP` (the set the roving -// handler reaches even when collapsed) rather than in a group array that vanishes with the rest. -const STRIP = ["tab-home", "import", "refresh", "fullscreen", "collapse"] as const; -const CLIPBOARD = ["paste", "cut", "copy", "painter"] as const; -const FONT = ["bold", "italic", "underline", "border", "fill", "color", "size"] as const; -// ⭐⭐ W53-T05 (instruction 16) — TWO VISUAL ROWS, ONE ROVING ORDER, AND THE ORDER IS THE READING -// ORDER. Excel lays Alignment out as two rows, so this array is re-sequenced to match what the eye -// walks: top row (vertical align, then Wrap text), then bottom row (horizontal align, then the two -// indents). ⛔ THE ARRAY IS THE ROVING SOURCE AND THE JSX IS NOT: a key listed here with no -// `control(...)` call rendering it makes ArrowRight land on nothing, with every gate still green, -// so the two are changed together or not at all. -const ALIGNMENT = [ - "top", "middle", "bottom", "wrap", "left", "center", "right", "outdent", "indent", -] as const; -const NUMBER = ["format", "currency", "percent", "comma", "decless", "decmore"] as const; -const STYLES = ["conditional"] as const; -const CELLS = ["insert", "delete", "cellformat"] as const; -const EDITING = ["autosum", "filldown", "fillright", "clear"] as const; +/** + * ⭐⭐ THE REGISTERED TABS, IN STRIP ORDER. A tab module owns its own groups, its own control keys + * and its own descriptor; this list is the whole of what the shell knows about any of them. + * + * ⭐⭐ INSERT IS REGISTERED AS OF W54-T10, AND IT WAS HELD BACK UNTIL IT HAD SOMETHING TO SHOW. + * The base kit shipped `ribbonInsert.tsx` exporting its descriptor with an EMPTY group list and + * deliberately left this array one entry long, because a registered empty tab paints a clickable + * tab that opens a blank toolbar row, and a visibly broken strip is worse than an unregistered + * module. W54-T10 gave the tab its four groups (Charts, Sparklines, Links, Comments) and added its + * descriptor here in the same change. Nothing else in this file moved to do it: `ControlKey`, + * `STRIP`, `reachable`, the tab-strip JSX and `Popover` are every one of them derived from this + * array, so a THIRD tab is the same one line. + */ +const TABS = [HOME_TAB, INSERT_TAB] as const; -const ORDER = [ - ...STRIP, ...CLIPBOARD, ...FONT, ...ALIGNMENT, ...NUMBER, ...STYLES, ...CELLS, ...EDITING, +/** + * ⭐⭐ W52-T15 (instruction 14, contract C4) — IMPORT, REFRESH AND FULL SCREEN LIVE IN THE TAB + * STRIP, NOT IN A RIBBON GROUP. They render in `sheet-ribbon-tabs`, which is on screen whether the + * groups row is collapsed or not, so they belong with the collapse chevron in the set the roving + * handler reaches even when collapsed rather than in a group array that vanishes with the rest. + * + * ⚠ THE KEY IS HERE AND THE BUTTON IS IN THE JSX, because the four differ in shape: one is gated + * on `canImport`, two carry an icon beside a word, one of those two also reports a pressed state, + * and the chevron is not a plain control button at all. `ControlKey` is derived from these keys, + * so the JSX still cannot render an action under a name this list does not carry. + * + * ⭐⭐ W54-T08 (owner instruction 7) — FULL SCREEN IS NO LONGER THE ODD ONE OUT. It used to paint + * its mark with the label living only in `aria-label` and `title`, and this note used to read as + * though that shape were settled. The owner has overruled it: the Sheet's control says + * "Full screen" on screen, the way the Data module's always has. + */ +const ACTIONS = [ + { key: "import" }, { key: "refresh" }, { key: "fullscreen" }, { key: "collapse" }, ] as const; -type ControlKey = (typeof ORDER)[number]; -type Popover = - | "" | "color" | "fill" | "format" | "border" | "size" | "insert" | "delete" | "cellformat" - | "clear"; +type TabId = (typeof TABS)[number]["id"]; +type ControlKey = + | (typeof TABS)[number]["key"] + | (typeof ACTIONS)[number]["key"] + | (typeof TABS)[number]["keys"][number]; + +/** + * ⭐ WHICH POPOVER IS OPEN, NAMED BY THE CONTROL THAT OWNS IT. Every popover hangs off a control, + * so the state is a `ControlKey` or nothing, and `closePop` reads it back to return focus to that + * exact button. Derived rather than hand-listed since W54, so a newly registered tab's gallery + * needs no edit here. + */ +export type Popover = "" | ControlKey; + +/** + * The strip: the tab buttons and the four actions. This is exactly what stays on screen when the + * groups row is collapsed, which is why it is also the collapsed roving order. + */ +const STRIP: readonly ControlKey[] = [ + ...TABS.map((tab) => tab.key), + ...ACTIONS.map((action) => action.key), +]; + +/** + * ⭐⭐ WHAT A TAB MODULE RENDERS AGAINST. Everything a group needs and nothing more: the shared + * control vocabulary, the state a control reads back, and the two emissions. A tab module is a + * pure function of this, which is what lets two lanes own two tabs without either one reaching + * into the shell's state or holding any of its own. + */ +export interface RibbonTabContext { + style: CellStyle | null; + frozen: boolean; + open: Popover; + anchorEl: HTMLElement | null; + /** The page's own door, unfiltered: an act that must NOT close an open gallery uses this. */ + onApply: (patch: CellStylePatch) => void; + apply: (patch: CellStylePatch) => void; + act: (kind: RibbonActionKind, arg?: string | number) => void; + openPop: (which: Popover) => (event: ReactMouseEvent) => void; + closePop: () => void; + control: ( + key: ControlKey, + label: string, + body: ReactNode, + onClick: (event: ReactMouseEvent) => void, + pressed?: boolean, + expanded?: boolean, + kt?: string, + ktOpens?: "gallery", + ) => ReactNode; + group: (name: string, body: ReactNode, extra?: string) => ReactNode; + word: (text: string) => ReactNode; + item: (label: string, onClick: () => void, on?: boolean, role?: string, kt?: string) => ReactNode; + /** + * ⭐ W54-T10 — the Insert tab's document doors, handed through unchanged. Undefined on a page + * that has not wired them, which is what the Insert tab reads to render itself disabled rather + * than offering a control with nothing behind it. See {@link RibbonInsertDoor}. + */ + insert?: RibbonInsertDoor; +} /** * ⭐ COLLAPSE IS REMEMBERED PER PERSON, and the key is namespaced so nothing else in the app can @@ -178,153 +296,6 @@ const writeCollapsed = (next: boolean) => { } }; -/** - * The ink a person may choose, as TOKEN NAMES. - * - * ⛔ A HEX HERE WOULD OUTLIVE THE PALETTE. What is stored in the workbook is this string, and - * `SheetGrid.tsx` resolves it against the document at paint time, so a palette change repaints - * every sheet ever written. The `*-deep` tones are the text safe end of each hue (DESIGN.md 3); - * the pale ones are fills and are never offered as ink. - */ -const INKS: { token: string; label: string }[] = [ - { token: "--lp-ink", label: "Default" }, - { token: "--lp-muted", label: "Muted" }, - { token: "--lp-blue-deep", label: "Blue" }, - { token: "--lp-green-deep", label: "Green" }, - { token: "--lp-yellow-deep", label: "Amber" }, - { token: "--lp-red-deep", label: "Red" }, - { token: "--lp-purple-deep", label: "Purple" }, -]; - -/** The fills, which are the tint end of the same hues, so ink stays readable on every one. */ -const FILLS: { token: string; label: string }[] = [ - { token: "--lp-surface-2", label: "Grey" }, - { token: "--lp-blue-tint", label: "Blue" }, - { token: "--lp-green-tint", label: "Green" }, - { token: "--lp-yellow-tint", label: "Amber" }, - { token: "--lp-red-tint", label: "Red" }, - { token: "--lp-purple-tint", label: "Purple" }, -]; - -/** - * ⛔ THE FIVE THE DOCUMENT MODEL CARRIES, AND ONLY THOSE. `CELL_FORMAT_KINDS` is mirrored in - * `platform/core/sheets.py` and a sixth spelling is REFUSED by name on the way in, so R8's - * Accounting and Custom code are offered as ACTS (`format-accounting`, `format-custom`) rather - * than smuggled in here as a kind the server would reject. - */ -const FORMAT_LABEL: Record = { - general: "General", - number: "Number", - currency: "Currency", - percent: "Percent", - date: "Date", -}; - -// ⭐ W52-T17 — each entry carries its own ONE-LETTER key-tip badge, painted fresh once `Alt, H, B` -// opens this gallery (KT-11). Non-colliding within the gallery's own scope, which is all KT-11 -// requires: a two-letter code from a DIFFERENT depth (Home's own "B" for this same control, or -// Styles' "L") means nothing here, because depth scopes the badge set entirely. -const BORDERS: { id: string; label: string; sides: Record; kt: string }[] = [ - { id: "all", label: "All sides", sides: { top: true, right: true, bottom: true, left: true }, kt: "A" }, - { id: "top", label: "Top", sides: { top: true }, kt: "T" }, - { id: "right", label: "Right", sides: { right: true }, kt: "R" }, - { id: "bottom", label: "Bottom", sides: { bottom: true }, kt: "B" }, - { id: "left", label: "Left", sides: { left: true }, kt: "L" }, -]; - -/** R8's four step size scale. Inter only, so a step is a SIZE and never a typeface. */ -const SIZE_STEPS: { id: string; label: string }[] = [ - { id: "small", label: "Small" }, - { id: "normal", label: "Normal" }, - { id: "large", label: "Large" }, - { id: "heading", label: "Heading" }, -]; - -function IconAlign({ to }: { to: "left" | "center" | "right" }) { - // Four rules; the short ones move, which is what says left, centre or right without a word. - const short = to === "left" ? "M2.5 8h6M2.5 12h7" - : to === "center" ? "M4.5 8h7M3.5 12h9" - : "M7.5 8h6M6.5 12h7"; - return ( - - ); -} - -/** The vertical three: a cell box, with the text rule sitting where the value would land. */ -function IconVAlign({ to }: { to: "top" | "middle" | "bottom" }) { - const y = to === "top" ? 5 : to === "middle" ? 8 : 11; - return ( - - ); -} - -function IconWrap() { - return ( - - ); -} - -function IconIndent({ out }: { out: boolean }) { - const arrow = out ? "M6.6 6.4L4.6 8l2 1.6" : "M4.6 6.4L6.6 8l-2 1.6"; - return ( - - ); -} - -function IconInk() { - return ( - - ); -} - -function IconFill() { - return ( - - ); -} - -function IconBorder() { - return ( - - ); -} - -/** Two decimal dots and the direction the count moves. Never a glyph, never a dash. */ -function IconDecimals({ more }: { more: boolean }) { - const arrow = more ? "M9.4 6.2L11.4 8l-2 1.8" : "M11.4 6.2L9.4 8l2 1.8"; - return ( - - ); -} - function IconRefresh() { return (
- {list.map((entry) => ( - - ))} -
- - - ); - - const format = style?.format; - const kind: CellFormatKind = format?.kind ?? "general"; - const decimals = format?.decimals ?? (kind === "currency" ? 2 : 0); - /** Stepping decimals on a date or on an unformatted cell means the cell becomes a number. */ - const numeric: CellFormatKind = - kind === "currency" || kind === "percent" ? kind : "number"; - - const stepDecimals = (delta: number) => onApply({ - format: { - ...format, - kind: numeric, - decimals: Math.min(10, Math.max(0, decimals + delta)), - }, - }); - /** Same idiom as the Data module's own `fullscreenLabel` (`customer-grid/Toolbar.tsx`). */ const fullscreenLabel = fullscreen ? "Exit full screen" : "Full screen"; + const tabContext: RibbonTabContext = { + style, frozen, open, anchorEl, onApply, apply, act, openPop, closePop, + control, group, word, item, insert, + }; + return (
- {/* ⭐ THE TAB STRIP. One tab today, and it is still a tab strip: it is where the collapse - chevron belongs and where a second tab would join without moving anything. + {/* ⭐ THE TAB STRIP, PAINTED FROM THE REGISTRY. One registered tab today, and it is still a + tab strip: it is where the collapse chevron belongs and where a second tab joins without + moving anything, because the button below is written once for whatever is registered. ⭐⭐ W52-T15 (instruction 14, contract C4) — IMPORT, REFRESH AND FULL SCREEN SIT HERE - NOW, in the SAME HORIZONTAL STRIP as the Home tab, rather than in a "Workbook" ribbon + NOW, in the SAME HORIZONTAL STRIP as the tabs, rather than in a "Workbook" ribbon group that Excel has no equivalent of. That group is gone from this file entirely. */}
- + {TABS.map((tab) => ( + + ))}
{canImport && control("import", "Import", word("Import"), () => act("import"))} {control("refresh", "Refresh", <>{word("Refresh")}, () => act("refresh"))} - {control("fullscreen", fullscreenLabel, , toggleFullscreen, - fullscreen)} + {/* ⭐⭐ W54-T08 (owner instruction 7) — THE WORD IS PAINTED, exactly like Refresh one + line above and exactly like the Data module's own control, which renders its + `fullscreenLabel` in a span beside the same mark. This used to be the mark alone. + The string already flipped with the state, so only the paint was missing. */} + {control("fullscreen", fullscreenLabel, + <>{word(fullscreenLabel)}, toggleFullscreen, fullscreen)}
- ))} - {/* ⚠ THE TWO R8 NAMES THE DOCUMENT MODEL DOES NOT CARRY YET. They are acts, - not kinds: `clean_cell` refuses an unknown `format.kind` BY NAME, so - writing `accounting` here would refuse the whole cell. */} - {item("Accounting", () => act("format-accounting"))} - {item("Custom code", () => act("format-custom"))} - {/* ⚠ THE TWO OPTIONS A1 NAMES BY NAME: decimals, and thousands. They are - shown only where they mean something; a date has neither and a percent - groups by locale. */} - {(kind === "number" || kind === "currency" || kind === "percent") && ( -
- Decimal places - - {decimals} - -
- )} - {kind === "number" && ( - - )} - - )} - - - {/* ⚠ CURRENCY HAS NO ROW IN THE TICKET'S OWN INLINE KeyTip LIST (named as one of - the examples with no row to copy). `CU` is invented, non-colliding. */} - {control("currency", "Currency", - $, - () => apply({ format: { kind: "currency", decimals: 2 } }), - kind === "currency", undefined, "CU")} - {control("percent", "Percent", - %, - () => apply({ format: { kind: "percent", decimals: 0 } }), - kind === "percent", undefined, "P")} - {control("comma", "Comma", - ,, - () => apply({ format: { kind: "number", decimals: 2, thousands: true } }), - kind === "number" && format?.thousands === true, undefined, "K")} - {/* ⭐ THE TICKET'S OWN MAPPING: Increase decimal is the DIGIT `0`, decrease is `9` - (spec KT-T1 — Corporate Finance Institute's "Alt+H+O" for Increase Decimal is - almost certainly the digit rendered as a letter, since Decrease Decimal is - `9`). `decless` is this file's DECREASE control, `decmore` is INCREASE. */} - {control("decless", "Decrease decimals", , - () => stepDecimals(-1), false, undefined, "9")} - {control("decmore", "Increase decimals", , - () => stepDecimals(1), false, undefined, "0")} - - ))} - - {/* ⭐⭐ W53-T05 (D-663) — STYLES, CELLS AND EDITING ARE ICON ONLY FROM HERE. Measured - at the contract viewport, the seven groups wanted about 1,680px of the 864px the - ribbon actually has, so Styles, Cells and Editing were off the right edge entirely - and the owner could not see that AutoSum, Insert, Delete and Clear already exist. - A caption beside a small same-size button is also the one thing Excel's Home ribbon - never does: only a wide combo box or a tall two-row-spanning button carries text. - ⛔ THE LABEL IS NOT DELETED, ONLY THE PAINTED WORD. `control()` passes its `label` - into BOTH `aria-label` and `title`, so a screen reader still announces "Conditional - formatting" and a hover still says it. `verify_api.py`'s `_RIBBON_GROUPS` pins each - of those label literals, and they are all still right there in the call. */} - {group("Styles", ( - <> - {control("conditional", "Conditional formatting", - , - () => act("conditional-formatting"), false, undefined, "L")} - - ))} - - {/* ⭐⭐ THE CELLS GROUP IS WHERE THE OLD "Rows and columns" STRIP WENT. Every act it - carried is still here and still reaches the same page callback; what is gone is a - second toolbar of its own. */} - {group("Cells", ( - <> - - {control("insert", "Insert", <>{}, - openPop("insert"), false, open === "insert", - "I", "gallery")} - {open === "insert" && ( - - {item("Insert row above", () => act("insert-row"))} - {item("Insert column left", () => act("insert-column"))} - {item("Add rows", () => act("add-rows"))} - {item("Add columns", () => act("add-columns"))} - - )} - - - {control("delete", "Delete", <>{}, - openPop("delete"), false, open === "delete", - "D", "gallery")} - {open === "delete" && ( - - {item("Delete row", () => act("delete-row"))} - {item("Delete column", () => act("delete-column"))} - - )} - - - {control("cellformat", "Format", - <>{}, - openPop("cellformat"), false, - open === "cellformat", "O", "gallery")} - {open === "cellformat" && ( - - {item("Row height", () => act("row-height"))} - {item("Column width", () => act("column-width"))} - {item("Hide rows", () => act("hide-rows"))} - {item("Hide columns", () => act("hide-columns"))} - {item("Unhide", () => act("unhide"))} - {/* ⭐ W51-T34 LANDED, so this OPENS a Freeze panes panel offering rows and - columns rather than toggling one column. The label had to move with the - behaviour: a control that says "Freeze first column" and opens a - two-axis panel is the kind of small lie an owner finds in the first - minute. `aria-checked` still reports whether ANYTHING is frozen, which - is the useful state for a person scanning the menu. - ⚠ THE LABEL IS BYTE-PINNED in `verify_api.py`'s `_RIBBON_GROUPS` Cells - tuple, so the two move in ONE commit or the rename reds a leg in a - ticket that never touched this file. */} - {item("Freeze panes", () => act("freeze"), frozen, - "menuitemcheckbox")} - - )} - - - ))} - - {group("Editing", ( - <> - {control("autosum", "AutoSum", , - () => act("autosum"), false, undefined, "U")} - {/* ⚠ FILL DOWN AND FILL RIGHT HAVE NO ROW IN THE TICKET'S OWN INLINE KeyTip LIST. - `FD`/`FR` are invented, non-colliding with `FP` (Format painter), `FS` (Font - size) or `FC` (Font colour). */} - {control("filldown", "Fill down", , - () => act("fill-down"), false, undefined, "FD")} - {control("fillright", "Fill right", , - () => act("fill-right"), false, undefined, "FR")} - - {control("clear", "Clear", <>{}, - openPop("clear"), false, open === "clear", - "E", "gallery")} - {open === "clear" && ( - - {item("Clear contents", () => act("clear-contents"))} - {item("Clear formats", () => act("clear-formats"))} - {item("Clear all", () => act("clear-all"))} - - )} - - - ))} + {/* ⭐⭐ THE ACTIVE TAB'S OWN GROUPS. `ribbonHome.tsx` holds every one of them, in R8's + order, and this is the whole of the shell's knowledge of what they are. */} + {activeTab.groups(tabContext)}
)} diff --git a/web/src/sheet/RulesDialog.tsx b/web/src/sheet/RulesDialog.tsx index a7bec0945717bffcfc65ac3bd5f031458705a87b..a31df2050d625918b7fc5763edd8d46a48934c5b 100644 --- a/web/src/sheet/RulesDialog.tsx +++ b/web/src/sheet/RulesDialog.tsx @@ -29,12 +29,14 @@ import { useCallback, useId, useState } from "react"; import { ConfirmDialog } from "../ui/ConfirmDialog"; import { - RULE_FILLS, RULE_INKS, RULE_OPS, RULE_OP_LABEL, - addRule, blankRule, moveRule, removeRule, ruleArity, rulesRefusal, updateRule, + DEFAULT_BAR_FILL, DEFAULT_RULE_SCALE, + RULE_FILLS, RULE_INKS, RULE_KIND_LABEL, RULE_OPS, RULE_OP_LABEL, RULE_SCALES, + addRule, blankRule, moveRule, rampBackground, rangeText, removeRule, ruleArity, ruleKind, + rulesRefusal, updateRule, } from "./rules"; import { listText, parseList } from "./validation"; -import { MAX_SHEET_RULES, MAX_VALIDATION_LIST } from "./types"; -import type { SheetRule, SheetRuleOp } from "./types"; +import { MAX_SHEET_RULES, MAX_VALIDATION_LIST, SHEET_RULE_KINDS } from "./types"; +import type { SheetRule, SheetRuleKind, SheetRuleOp } from "./types"; export interface RulesDialogProps { open: boolean; @@ -182,7 +184,37 @@ interface RuleCardProps { function RuleCard({ rule, index, count, onPatch, onMove, onRemove }: RuleCardProps) { const ids = useId(); + const kind = ruleKind(rule); const arity = ruleArity(rule.op); + + /** + * ⭐⭐ CHANGING THE KIND CHANGES WHAT THE RULE NEEDS TO BE COMPLETE, so it carries those needs + * with it rather than leaving a half-formed rule the save would refuse with a sentence about a + * control the card is no longer showing. A scale and a bar both ride `op: "between"`, which is + * what makes the server persist their two bounds with no new field; a scale gains the default + * ramp and a bar gains a fill. + * + * ⚠ `kind: undefined` IS HOW `cell` IS WRITTEN. It is the default and is stored as an absence + * (`types.ts::SHEET_RULE_KINDS`), so a rule switched to a scale and back is byte for byte the + * rule it started as. `JSON.stringify` drops an undefined value, which is what makes that true + * all the way to the document rather than only in this component. + */ + const setKind = (next: SheetRuleKind) => { + if (next === kind) return; + if (next === "cell") { + onPatch(rule.id, { kind: undefined }); + return; + } + onPatch(rule.id, { + kind: next, + op: "between", + scale: next === "scale" + ? (rule.scale ?? { low: DEFAULT_RULE_SCALE.low, high: DEFAULT_RULE_SCALE.high }) + : rule.scale, + style: next === "bar" ? { fill: rule.style?.fill || DEFAULT_BAR_FILL } : rule.style, + }); + }; + return (
  • @@ -192,7 +224,7 @@ function RuleCard({ rule, index, count, onPatch, onMove, onRemove }: RuleCardPro onPatch(rule.id, { range: e.target.value })} @@ -232,19 +264,38 @@ function RuleCard({ rule, index, count, onPatch, onMove, onRemove }: RuleCardPro
    + {/* ⭐⭐ W54-T05 — THE KIND IS ON THE CARD, NOT HIDDEN BEHIND THE MENU THAT MADE IT. A + colour scale and a data bar are created from the ribbon's Conditional formatting + gallery, and an editor that could not represent them would have listed a rule it + could not describe, or worse, quietly rewritten it into a condition nobody chose. */} + {kind === "cell" ? ( + + ) : null} {arity >= 1 ? (
  • ); } diff --git a/web/src/sheet/SheetChart.tsx b/web/src/sheet/SheetChart.tsx index f7dad45cf2d8c2c67919166a5a8f418315169242..18e0b39c4451ee4f312fb9249605e10c0ccc2023 100644 --- a/web/src/sheet/SheetChart.tsx +++ b/web/src/sheet/SheetChart.tsx @@ -1,4 +1,5 @@ -// sheet/SheetChart.tsx — a chart that OCCUPIES a rectangle of cells (wave 49, W49-T08, R9/R15). +// sheet/SheetChart.tsx — a chart that OCCUPIES a rectangle of cells (wave 49, W49-T08, R9/R15; +// widened to the eight kinds and given its move/resize gesture by wave 54, W54-T12, ruling R5). // // ⭐⭐ R9: A CHART IS A CAPABILITY, NOT A VIEW TYPE. It occupies a rectangle of cells and reads // those cells; it has no binding, no database and no query of its own. If this file ever calls @@ -21,23 +22,71 @@ // sized container and letting the viewBox scale, which is what an SVG viewBox is for. Adding size // props would have meant editing a file outside the fence, which is a ROOT question and not a // lane's to answer. +// +// ══════════════════════════════════════════════════════════════════════════════════════════════ +// ⭐⭐ W54-T12 — WHAT `viz/SeriesChart` ACTUALLY DRAWS, MEASURED RATHER THAN ASSUMED, BECAUSE THE +// WHOLE KIND MAPPING TURNS ON IT. +// +// ⛔⛔ `viz/SeriesChart` IS A BARS-ONLY RENDERER. Its only mark is `` +// growing UP from a baseline; it never reads `spec.kind` at all, so it draws GROUPED VERTICAL +// BARS for every one of the six names its own union carries. There is no polyline, no filled +// region and no arc anywhere in that file. (The Dashboard reaches for `viz/vega` when it wants +// those pictures; `SeriesChart` is the Y1 chart block's bar renderer and nothing else.) +// +// ⛔ SO DELEGATION IS NOT "THE APP'S EXISTING ANSWER" FOR SIX OF THOSE NAMES, IT IS A WRONG +// PICTURE. Handing `line` to it paints a bar chart under the word Line, which is the same defect +// as the `kind={isDrawnChartKind(chart.kind) ? chart.kind : "bar"}` narrowing this ticket removed +// from `SheetGrid.tsx`: a kind that is named on screen and not honoured in the drawing. +// +// ⛔ AND THE EXCEL NAMES DO NOT LINE UP WITH THE VIZ NAMES. Excel's naming is this ticket's +// contract: a COLUMN chart has vertical bars, a BAR chart has horizontal ones. Vertical bars is +// exactly the ONE picture `SeriesChart` draws correctly, and its name for it is `"bar"`. So: +// +// sheet `column` -> DELEGATED to `SeriesChart` as its `"bar"`: vertical bars, Excel's column +// chart, and the only kind the shared renderer genuinely draws. +// the other SEVEN (`bar` horizontal, `line`, `area`, `pie`, `donut`, `scatter`, `combo`) +// -> DRAWN HERE by {@link DrawnChart}, on the same 720x230 viewBox, from the +// same `fields` / `rows` / `series`, wearing the same `pg-*` palette. +// +// ⛔ `types.ts::isDrawnChartKind` IS STILL THE SWITCH, applied to the VIZ NAME rather than to the +// sheet's own. That is what makes the predicate honest again: before this ticket its branch could +// only ever go one way, and the narrowing at `SheetGrid.tsx`'s call site silently turned a pie +// into a bar chart. One kind is delegated, so both branches are live. +// +// ⛔ THE OWN-DRAWN MARKS BORROW `viz`'s PALETTE CLASSES (`pg-ser-0..3`, `pg-ax`, `pg-ax-lab`, +// `pg-legend*`), never a second set of colours. A palette declared twice is two answers to one +// question, and DESIGN.md 3 puts strokes on the DEEP companion while fills take the pastel, which +// is why the line and dot marks carry their own stroke rules in `styles/wave54/ribbon-insert.css` +// rather than reusing a fill class for a stroke. +// ══════════════════════════════════════════════════════════════════════════════════════════════ -import { useMemo } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { SeriesChart } from "../viz/SeriesChart"; import type { ChartSpec } from "../viz/chartData"; import type { WireField } from "../viz/seriesData"; import type { Row } from "../viz/types"; -import type { CellMap } from "./types"; +import type { CellMap, SheetChartDrawnKind, SheetChartSpec } from "./types"; +import { isDrawnChartKind } from "./types"; import { addressOf } from "./sheetState"; export interface SheetChartProps { /** Zero-based inclusive rectangle: the cells this chart occupies AND reads (R9, R15). */ range: { col0: number; row0: number; col1: number; row1: number }; cells: CellMap; - kind?: ChartSpec["kind"]; + kind?: SheetChartSpec["kind"]; /** Rendered size in px. The SVG scales to it; the renderer is not resized. */ width: number; height: number; + /** + * The gesture's PIXEL delta, handed up on release. A chart anchors to a cell RANGE, so this + * component cannot decide what a drag MEANS: only the grid knows how wide each column is and + * which rows are hidden. It reports pixels; `SheetGrid.tsx` turns them into a new `range`. + * + * ⚠ BOTH ARE OPTIONAL, so the component still renders wherever nothing has wired them, and the + * handles simply do not appear rather than moving something nobody will save. + */ + onMove?: (dx: number, dy: number) => void; + onResize?: (dx: number, dy: number) => void; } /** A cell's text, however it is stored. A chart reads what the sheet SHOWS. */ @@ -61,7 +110,547 @@ const columnType = (values: string[]): string => { return filled.every((v) => Number.isFinite(Number(v))) ? "int" : "text"; }; -export default function SheetChart({ range, cells, kind = "bar", width, height }: SheetChartProps) { +/** + * The sheet's kind said in the viz engine's vocabulary, or `null` for a picture the shared + * renderer does not have. See this file's header for why `column` and `bar` cross over. + */ +const VIZ_KIND: Record = { + column: "bar", + bar: null, + line: null, + area: null, + donut: null, + pie: null, + scatter: null, + combo: null, +}; + +// ── the own-drawn frame ──────────────────────────────────────────────────────────────────────── +// The same viewBox `SeriesChart` bakes in, deliberately: two charts of different kinds sitting on +// one sheet have to share a plot area, an axis inset and a label size, or the sheet reads as two +// products. The wrapper is still what sizes them (see the note above). +const W = 720; +const H = 230; +const PAD_L = 52; +const PAD_R = 10; +const PAD_T = 12; +const PAD_B = 34; + +const SERIES_SLOTS = 4; + +/** Axis furniture only, and short: an axis that needs six characters is a table. */ +const axisText = (v: number): string => { + if (!Number.isFinite(v)) return ""; + const abs = Math.abs(v); + if (abs >= 1e9) return `${(v / 1e9).toFixed(1)}B`; + if (abs >= 1e6) return `${(v / 1e6).toFixed(1)}M`; + if (abs >= 1e3) return `${(v / 1e3).toFixed(1)}k`; + return Number.isInteger(v) ? v.toLocaleString() : v.toFixed(2); +}; + +const readNumber = (row: Row, key: string): number => { + const v = (row as unknown as Record)[key]; + return typeof v === "number" && Number.isFinite(v) ? v : 0; +}; + +const readText = (row: Row, key: string): string => { + const v = (row as unknown as Record)[key]; + return v == null ? "" : String(v); +}; + +interface DrawnProps { + kind: SheetChartSpec["kind"]; + fields: WireField[]; + rows: Row[]; + series: { y: string; label: string }[]; +} + +/** The legend DESIGN.md 3 makes binding at two series or more. One shape for all seven drawings. */ +function Legend({ series }: { series: { y: string; label: string }[] }) { + if (series.length < 2) return null; + return ( +
    + {series.map((s, i) => ( + + + {s.label} + + ))} +
    + ); +} + +/** + * The point marks on a plotted series. ONE definition, shared by `line`, `area` and `combo`'s + * line half, because three copies of a circle is three places for a hover title to drift. + */ +function SeriesDots( + { slot, points, label, labels }: { + slot: number; + points: { x: number; y: number; v: number }[]; + label: string; + labels: string[]; + }, +) { + return ( + <> + {points.map((p, i) => ( + + {`${labels[i] || "(blank)"} and ${label}: ${axisText(p.v)}`} + + ))} + + ); +} + +/** + * ONE slice, for BOTH ring kinds. `inner` of 0 is a pie wedge and a positive radius is a donut + * segment, which is the whole of the difference between the two kinds: writing the arcs twice + * would have been two chances to get a sweep flag wrong and one picture to notice it in. + * + * ⚠ THE FULL CIRCLE IS ITS OWN CASE. An SVG arc of exactly 360 degrees has identical endpoints + * and draws NOTHING, so a single-category ring would vanish. It is stated as two half turns; the + * donut's inner circle is swept the other way so the default winding rule leaves the hole open. + */ +const slicePath = ( + cx: number, cy: number, r: number, inner: number, from: number, sweep: number, +): string => { + const to = from + sweep; + const big = sweep > Math.PI ? 1 : 0; + const full = sweep >= Math.PI * 2 - 1e-9; + const x0 = cx + r * Math.cos(from); + const y0 = cy + r * Math.sin(from); + const x1 = cx + r * Math.cos(to); + const y1 = cy + r * Math.sin(to); + if (inner <= 0) { + if (full) { + return `M ${cx} ${cy - r} A ${r} ${r} 0 1 1 ${cx} ${cy + r} ` + + `A ${r} ${r} 0 1 1 ${cx} ${cy - r} Z`; + } + return `M ${cx} ${cy} L ${x0} ${y0} A ${r} ${r} 0 ${big} 1 ${x1} ${y1} Z`; + } + if (full) { + return `M ${cx} ${cy - r} A ${r} ${r} 0 1 1 ${cx} ${cy + r} ` + + `A ${r} ${r} 0 1 1 ${cx} ${cy - r} Z ` + + `M ${cx} ${cy - inner} A ${inner} ${inner} 0 1 0 ${cx} ${cy + inner} ` + + `A ${inner} ${inner} 0 1 0 ${cx} ${cy - inner} Z`; + } + return `M ${x0} ${y0} A ${r} ${r} 0 ${big} 1 ${x1} ${y1} ` + + `L ${cx + inner * Math.cos(to)} ${cy + inner * Math.sin(to)} ` + + `A ${inner} ${inner} 0 ${big} 0 ` + + `${cx + inner * Math.cos(from)} ${cy + inner * Math.sin(from)} Z`; +}; + +/** + * The seven pictures the shared renderer does not have. Every one of them reads the SAME `fields` + * / `rows` / `series` the memo below already built, so no kind gets its own idea of what a row is, + * and every one draws into the same 720x230 viewBox, so two charts of different kinds sitting on + * one sheet share a plot area, an axis inset and a label size rather than reading as two products. + */ +function DrawnChart({ kind, fields, rows, series }: DrawnProps) { + const xKey = fields[0]?.key ?? "c0"; + const xIsNumeric = fields[0]?.type === "int"; + const labels = rows.map((row) => readText(row, xKey)); + const plotW = W - PAD_L - PAD_R; + const plotH = H - PAD_T - PAD_B; + const base = H - PAD_B; + // One label every nth slot: enough to read, never so many they collide. + const labelEvery = Math.max(1, Math.ceil(rows.length / 12)); + const footer = ( +

    + {`${rows.length} categor${rows.length === 1 ? "y" : "ies"} plotted`} +

    + ); + + if (kind === "pie" || kind === "donut") { + // A ring divided by the FIRST numeric series. Arc length encodes a share of a positive whole, + // so a negative value has no truthful geometry here and is left out of the total rather than + // drawn as a slice pointing the other way. + const key = series[0]?.y ?? ""; + const seriesLabel = series[0]?.label ?? "the first numeric column"; + const values = rows.map((row) => Math.max(0, readNumber(row, key))); + const total = values.reduce((a, b) => a + b, 0); + const cx = PAD_L + plotW / 2; + const cy = PAD_T + plotH / 2; + const r = Math.max(8, Math.min(plotW, plotH) / 2 - 4); + const inner = kind === "donut" ? r * 0.55 : 0; + const labelR = kind === "donut" ? (r + inner) / 2 : r * 0.62; + let angle = -Math.PI / 2; + return ( + <> + + {total <= 0 ? ( + + ) : ( + values.map((v, i) => { + const sweep = (v / total) * Math.PI * 2; + const from = angle; + angle += sweep; + const mid = from + sweep / 2; + const share = v / total; + return ( + + + {`${labels[i] || "(blank)"}: ${axisText(v)}`} + + {share >= 0.08 ? ( + + {`${Math.round(share * 100)}%`} + + ) : null} + + ); + }) + )} + +

    + {`${rows.length} slice${rows.length === 1 ? "" : "s"} of ${seriesLabel}`} +

    + + ); + } + + if (kind === "scatter") { + // x comes from the first column when it is numeric, and from the row index when it is not: + // a category axis with no order of its own is still a position, and pretending otherwise + // would drop every row of a chart whose first column is a name. + const xs = xIsNumeric + ? rows.map((row) => readNumber(row, xKey)) + : rows.map((_row, i) => i); + const xMin = Math.min(0, ...xs); + const xMax = Math.max(1, ...xs); + const xSpan = xMax - xMin || 1; + const yMax = Math.max( + 1, + ...series.flatMap((s) => rows.map((row) => readNumber(row, s.y))), + ); + return ( + <> + + + + + + {axisText(yMax)} + + + 0 + + {series.map((s, si) => ( + { + const v = readNumber(row, s.y); + return { + x: PAD_L + ((xs[i] - xMin) / xSpan) * plotW, + y: base - (v / yMax) * plotH, + v, + }; + })} + /> + ))} + {rows.map((_row, i) => + i % labelEvery === 0 ? ( + + {xIsNumeric ? axisText(xs[i]) : labels[i]} + + ) : null, + )} + +

    + {`${rows.length} point${rows.length === 1 ? "" : "s"} plotted`} +

    + + ); + } + + if (kind === "line" || kind === "area") { + // ⭐ ONE BRANCH FOR BOTH, because an area IS a line with the region under it filled. The + // stroke is drawn AFTER every fill so a series still reads as a series where two of them + // overlap, and the fills are transparent enough that the lower one is not erased. + const max = Math.max( + 1, + ...series.flatMap((s) => rows.map((row) => readNumber(row, s.y))), + ); + // Edge to edge rather than slot centres: nothing is occupying a slot here, so inset points + // would leave a margin at each end that reads as missing data. + const at = (i: number) => + (rows.length > 1 ? PAD_L + (i * plotW) / (rows.length - 1) : PAD_L + plotW / 2); + const yOf = (v: number) => base - (v / max) * plotH; + const plotted = series.map((s) => rows.map((row, i) => { + const v = readNumber(row, s.y); + return { x: at(i), y: yOf(v), v }; + })); + const lineOf = (points: { x: number; y: number }[]) => + points.map((p, i) => `${i === 0 ? "M" : "L"} ${p.x.toFixed(2)} ${p.y.toFixed(2)}`).join(" "); + return ( + <> + + + + + + {axisText(max)} + + + 0 + + {kind === "area" + ? plotted.map((points, si) => ( + points.length ? ( + + ) : null + )) + : null} + {plotted.map((points, si) => ( + points.length ? ( + + ) : null + ))} + {plotted.map((points, si) => ( + + ))} + {rows.map((_row, i) => + i % labelEvery === 0 ? ( + + {labels[i]} + + ) : null, + )} + + {footer} + + ); + } + + if (kind === "combo") { + // The first numeric series as bars, the second as a line over them. With only one numeric + // series it draws that one as bars and says nothing extra: a line with no second measure + // would be the same values drawn twice, which reads as agreement between two sources. + const barKey = series[0]?.y ?? ""; + const lineDef = series[1]; + const barVals = rows.map((row) => readNumber(row, barKey)); + const lineVals = lineDef ? rows.map((row) => readNumber(row, lineDef.y)) : []; + const max = Math.max(1, ...barVals, ...lineVals); + const slotW = plotW / Math.max(1, rows.length); + const barW = Math.max(2, slotW * 0.6); + const at = (i: number) => PAD_L + i * slotW + slotW / 2; + const yOf = (v: number) => base - (v / max) * plotH; + const points = lineVals.map((v, i) => ({ x: at(i), y: yOf(v), v })); + const path = points + .map((p, i) => `${i === 0 ? "M" : "L"} ${p.x.toFixed(2)} ${p.y.toFixed(2)}`) + .join(" "); + return ( + <> + + + + + + {axisText(max)} + + + 0 + + {barVals.map((v, i) => ( + 0 ? 1 : 0, base - yOf(v))} + > + {`${labels[i] || "(blank)"}: ${axisText(v)}`} + + ))} + {lineDef && path ? ( + + ) : null} + {lineDef ? ( + + ) : null} + {rows.map((_row, i) => + i % labelEvery === 0 ? ( + + {labels[i]} + + ) : null, + )} + + {footer} + + ); + } + + // `bar`: Excel's HORIZONTAL orientation, which is the one the shared renderer does not have. + const groupH = plotH / Math.max(1, rows.length); + const barH = Math.max(2, (groupH * 0.72) / Math.max(1, series.length)); + const max = Math.max( + 1, + ...series.flatMap((s) => rows.map((row) => readNumber(row, s.y))), + ); + return ( + <> + + + + + + 0 + + + {axisText(max)} + + {rows.map((row, i) => { + const top = PAD_T + i * groupH + (groupH - barH * series.length) / 2; + return ( + + {series.map((s, si) => { + const v = readNumber(row, s.y); + return ( + 0 ? 1 : 0, (v / max) * plotW)} + height={Math.max(1, barH - 1.5)} + > + {`${labels[i] || "(blank)"} and ${s.label}: ${axisText(v)}`} + + ); + })} + {i % labelEvery === 0 ? ( + + {labels[i]} + + ) : null} + + ); + })} + + {footer} + + ); +} + +// ── the gesture ─────────────────────────────────────────────────────────────────────────────── +// +// ⭐ DESIGN.md, quoted, because it is this ticket's own rule: "track pointer movement 1:1 with +// pointer capture, preserve the grab offset, allow reversal, and use a critically damped spring +// from the presentation value on release". Bounce is only for a momentum-bearing gesture and this +// is not one, so the spring is critically damped: it returns without ever crossing zero. +// +// ⛔ WHY THE PRESENTATION VALUE SETTLES AT ALL. The document is the truth and the grid re-anchors +// the chart the instant the new `range` lands, so the transform this component held during the +// drag has to come off. Snapping it off is a jump; releasing it through the spring is the same +// arrival, taken in 150 to 250 ms, from wherever the finger actually let go. + +type Nudge = { dx: number; dy: number; dw: number; dh: number }; +const ZERO: Nudge = { dx: 0, dy: 0, dw: 0, dh: 0 }; +const NUDGE_KEYS: (keyof Nudge)[] = ["dx", "dy", "dw", "dh"]; +/** rad/s. Higher is a shorter settle; at zeta = 1 there is no overshoot at any speed. */ +const OMEGA = 22; +/** Below half a pixel and half a pixel per second, the spring has arrived. */ +const AT_REST = 0.5; + +const prefersReducedMotion = (): boolean => + typeof window !== "undefined" + && typeof window.matchMedia === "function" + && window.matchMedia("(prefers-reduced-motion: reduce)").matches; + +export default function SheetChart({ + range, + cells, + kind = "bar", + width, + height, + onMove, + onResize, +}: SheetChartProps) { const { fields, rows, series } = useMemo(() => { const { col0, row0, col1, row1 } = range; const loCol = Math.min(col0, col1); @@ -107,24 +696,189 @@ export default function SheetChart({ range, cells, kind = "bar", width, height } }; }, [range, cells]); + const delegated = useMemo(() => { + const viz = VIZ_KIND[kind]; + return viz !== null && isDrawnChartKind(viz) ? viz : null; + }, [kind]); + const spec: ChartSpec = useMemo( () => ({ id: "sheet-chart", - kind, + kind: delegated ?? "bar", x: fields[0]?.key, y: series[0]?.y, agg: "sum", }), - [kind, fields, series], + [delegated, fields, series], ); + const [nudge, setNudge] = useState(ZERO); + const [flash, setFlash] = useState(false); + const grab = useRef<{ x: number; y: number; mode: "move" | "resize" } | null>(null); + const frame = useRef(null); + + const stopSettle = useCallback(() => { + if (frame.current !== null && typeof cancelAnimationFrame === "function") { + cancelAnimationFrame(frame.current); + } + frame.current = null; + }, []); + + useEffect(() => stopSettle, [stopSettle]); + + /** The critically damped return, integrated from the value the finger let go at. */ + const settle = useCallback((from: Nudge) => { + if (prefersReducedMotion() || typeof requestAnimationFrame !== "function") { + // ⛔ Reduced motion replaces the spring with a short opacity change, never with a slide + // taken faster: the whole point is that nothing travels across the screen. + setNudge(ZERO); + setFlash(true); + window.setTimeout(() => setFlash(false), 140); + return; + } + let value: Nudge = { ...from }; + let velocity: Nudge = { ...ZERO }; + let last = performance.now(); + const step = (now: number) => { + const dt = Math.min(0.032, Math.max(0.001, (now - last) / 1000)); + last = now; + let moving = false; + const nextValue: Nudge = { ...ZERO }; + const nextVelocity: Nudge = { ...ZERO }; + for (const key of NUDGE_KEYS) { + const accel = -2 * OMEGA * velocity[key] - OMEGA * OMEGA * value[key]; + nextVelocity[key] = velocity[key] + accel * dt; + nextValue[key] = value[key] + nextVelocity[key] * dt; + if (Math.abs(nextValue[key]) > AT_REST || Math.abs(nextVelocity[key]) > AT_REST) { + moving = true; + } + } + value = nextValue; + velocity = nextVelocity; + if (!moving) { + setNudge(ZERO); + frame.current = null; + return; + } + setNudge(value); + frame.current = requestAnimationFrame(step); + }; + frame.current = requestAnimationFrame(step); + }, []); + + const beginDrag = useCallback((mode: "move" | "resize") => + (event: React.PointerEvent) => { + if (event.button !== 0) return; + event.preventDefault(); + event.stopPropagation(); + stopSettle(); + grab.current = { x: event.clientX, y: event.clientY, mode }; + event.currentTarget.setPointerCapture(event.pointerId); + setNudge(ZERO); + }, [stopSettle]); + + const duringDrag = useCallback((event: React.PointerEvent) => { + const held = grab.current; + if (!held) return; + // 1:1 with the pointer, from the offset it was grabbed at, so pushing back the way it came + // undoes the drag exactly rather than starting a new one. + const dx = event.clientX - held.x; + const dy = event.clientY - held.y; + setNudge(held.mode === "move" + ? { dx, dy, dw: 0, dh: 0 } + : { dx: 0, dy: 0, dw: dx, dh: dy }); + }, []); + + const endDrag = useCallback((event: React.PointerEvent) => { + const held = grab.current; + if (!held) return; + grab.current = null; + if (event.currentTarget.hasPointerCapture(event.pointerId)) { + event.currentTarget.releasePointerCapture(event.pointerId); + } + const dx = event.clientX - held.x; + const dy = event.clientY - held.y; + if (held.mode === "move") onMove?.(dx, dy); + else onResize?.(dx, dy); + settle(held.mode === "move" + ? { dx, dy, dw: 0, dh: 0 } + : { dx: 0, dy: 0, dw: dx, dh: dy }); + }, [onMove, onResize, settle]); + + // ⭐ THE DRAG IS NOT THE ONLY WAY, which DESIGN.md requires: the arrow keys walk the anchor one + // cell at a time from the same two controls, and the Insert tab's own dialog sets a range + // outright. A step is this chart's own width over the columns it spans, which IS one column on + // the grid it is sitting on. + const stepX = Math.max(8, width / Math.max(1, Math.abs(range.col1 - range.col0) + 1)); + const stepY = Math.max(8, height / Math.max(1, Math.abs(range.row1 - range.row0) + 1)); + + const arrowKeys = useCallback((mode: "move" | "resize") => + (event: React.KeyboardEvent) => { + const send = mode === "move" ? onMove : onResize; + if (!send) return; + if (event.key === "ArrowLeft") send(-stepX, 0); + else if (event.key === "ArrowRight") send(stepX, 0); + else if (event.key === "ArrowUp") send(0, -stepY); + else if (event.key === "ArrowDown") send(0, stepY); + else return; + event.preventDefault(); + }, [onMove, onResize, stepX, stepY]); + + const tools = (onMove || onResize) ? ( +
    + {onMove ? ( + + ) : null} + {onResize ? ( + + ) : null} +
    + ) : null; + + const shell: React.CSSProperties = { + width: Math.max(24, width + nudge.dw), + height: Math.max(24, height + nudge.dh), + transform: nudge.dx || nudge.dy ? `translate(${nudge.dx}px, ${nudge.dy}px)` : undefined, + opacity: flash ? 0.72 : undefined, + }; + if (!series.length) { // Named rather than drawn empty: a chart frame with no series reads as "the data is zero", // which is a different and wrong statement. return ( -

    This range has no numeric column to chart.

    + {tools}
    ); } @@ -132,9 +886,17 @@ export default function SheetChart({ range, cells, kind = "bar", width, height } return ( // ⭐ THE WRAPPER IS THE SIZING MECHANISM. `SeriesChart` draws into a fixed 720x230 viewBox, so // scaling it to an arbitrary cell rectangle is the wrapper's job and the renderer stays - // untouched. `viz/**` belongs to no lane in this wave. -
    - + // untouched. `viz/**` belongs to no lane in this wave, and the own-drawn kinds use the same + // viewBox for the same reason. +
    + {delegated + ? + : ( +
    + +
    + )} + {tools}
    ); } diff --git a/web/src/sheet/SheetGrid.tsx b/web/src/sheet/SheetGrid.tsx index 6f55d5e66d5a94eeb7f4923982daf814d862ba82..b933a2a2fb31111726c1fc3fa12412c4bf2e8227 100644 --- a/web/src/sheet/SheetGrid.tsx +++ b/web/src/sheet/SheetGrid.tsx @@ -97,7 +97,7 @@ import type { ChangeEvent as ReactChangeEvent, KeyboardEvent as ReactKeyboardEve import { createPortal } from "react-dom"; import type { DataEditorRef, DrawCellCallback, DrawHeaderCallback, EditableGridCell, GridColumn, - GridSelection, Item, GridCell, Rectangle, + GridMouseEventArgs, GridSelection, Item, GridCell, Rectangle, } from "@glideapps/glide-data-grid"; import { CompactSelection, DataEditor, GridCellKind } from "@glideapps/glide-data-grid"; // ⛔⛔ THIS IMPORT IS THE GRID. Without it glide's STRUCTURAL stylesheet is not in this chunk and @@ -106,6 +106,7 @@ import { CompactSelection, DataEditor, GridCellKind } from "@glideapps/glide-dat import "@glideapps/glide-data-grid/dist/index.css"; import { lightTheme } from "../customer-grid/theme"; import { AnchoredOverlay } from "../customer-grid/OverlaySurface"; +import type { AnchorRect } from "../customer-grid/OverlaySurface"; // ⭐ INSTRUCTION 15 — clicking a sheet cell folds the nav rail exactly as a Data-module cell // click already does (`customer-grid/CustomerGrid.tsx::selectView`). One shared signal, one // shared listener (`shell/Shell.tsx::onNavMinimize`); this file never dispatched it before. @@ -119,6 +120,11 @@ import { acceptedText, acceptsSuggestion, refsIn, suggest, } from "./formulaAssist"; import type { SuggestItem } from "./formulaAssist"; +// ⭐⭐ W54-T25 / RULING R9(i) — FORMULA ENTRY'S TWO PURE RULES, FROM THE PURE ENGINE. Closing an +// unfinished formula and walking one reference through Excel's four anchor states are both string +// arithmetic, so they live in `formulaEval.ts` where `verify_formula_engine.py` compiles them and +// EXECUTES the claim under node. This file owns only the keystroke and the commit that call them. +import { autoCloseFormula, cycleAnchorAtCaret } from "./formulaEval"; import { colorForSlot } from "./refColors"; import "../styles/wave52/sheet-grid.css"; // ⛔⛔ CONTRACT C8: ONE ESCAPE ARBITER FOR THE WHOLE APP, topmost wins. Nothing in this tree adds @@ -127,7 +133,9 @@ import "../styles/wave52/sheet-grid.css"; import { useEscapeClose } from "../ui/useEscapeClose"; import CellActionBar from "./CellActionBar"; import Ribbon from "./Ribbon"; -import type { RibbonAction } from "./Ribbon"; +// ⭐ W54-T10 (lane B) — `RibbonInsertDoor` is the Insert tab's document door, declared beside the +// act union it deliberately is not part of. See its own doc comment in `Ribbon.tsx`. +import type { RibbonAction, RibbonInsertDoor } from "./Ribbon"; import { RulesDialog, ValidationDialog } from "./RulesDialog"; import SheetChart from "./SheetChart"; import ShortcutsPanel from "./ShortcutsPanel"; @@ -135,17 +143,35 @@ import { colToIndex, indexToCol } from "./a1"; // ⛔⛔ W51-T18 — THE RULE ENGINE AND THE VALIDATION CHECKER ARE PURE AND SHEET LOCAL, and that is // what lets `verify_api.py` compile them beside `sheetState.js` and EXECUTE the ten operators // rather than grep for their names. This component is the only place their answers meet a canvas. -import { overlayRuleStyle, ruleStyleAt, ruleSubject } from "./rules"; +// ⭐ W54-T05 adds `ruleBarAt` and the two rule FACTORIES beside them, for the reason that +// module's own head note gives: a proportional width cannot be said as a style, so a data +// bar has a second door, and both doors walk one shared first-match list. +import { + addRule, barRule, numericBounds, overlayRuleStyle, ruleBarAt, ruleStyleAt, ruleSubject, + scaleRule, +} from "./rules"; +// ⭐ WAVE 54 BASE KIT — three seams split out of this hub file so four lanes can work at once. +// `cellBorders.ts` owns the per-cell border paint AND the palette-token resolver that its stroke +// setup needs; `clipboardOps.ts` owns what a copy is made of; `sparkline.ts` is an empty seam that +// answers `false` today. All three were moved or wired without changing a pixel. +import { paintCellBorders, tokenColour } from "./cellBorders"; +import { buildCopyPayload, runCopySelection } from "./clipboardOps"; +import { drawSparkline } from "./sparkline"; +// ⭐ W54-T14 / LANE B — A CELL'S ATTACHMENTS: the canvas marks, the hover bubble and the door that +// follows a link. `LinkDialog.tsx` owns all three beside the surface that authors them; this file +// owns only the wiring, which is one call in the paint and one in each grid's click and hover. +import { NoteBubble, followLink, paintCellMarks } from "./LinkDialog"; +import type { FollowContext } from "./LinkDialog"; import { canonicalEntry, checkEntry, filterList, refusalLabel, screenEdits, validationEdits, validationOf, } from "./validation"; import { - formatCellText, stylePaints, sheetExtent, + fontPx, fontStack, formatCellText, stylePaints, sheetExtent, DEFAULT_COL_WIDTH, DEFAULT_SHEET_COLS, DEFAULT_SHEET_ROWS, MAX_CELL_INDENT, MAX_COL_WIDTH, MIN_COL_WIDTH, } from "./types"; import type { - Cell, CellStyle, CellStylePatch, CellValign, SheetRule, SheetTab, Workbook, + Cell, CellStyle, CellStylePatch, CellValign, SheetChartSpec, SheetRule, SheetTab, Workbook, } from "./types"; import { addressOf, appendLineBreak, autoSumFormula, boundDragLabel, cellAt, @@ -154,7 +180,8 @@ import { editableText, fillCells, fillDown, fillRight, findMatches, isFilled, markOf, noMatchLabel, nothingHiddenLabel, paintPatch, pasteCells, frozenBandSize, lockstepScrollX, - setFormula, shiftCells, splitAddress, styleCells, styleOf, usedExtent, viewIndexOf, + rememberCut, setFormula, shiftCells, splitAddress, styleCells, styleOf, usedExtent, + viewIndexOf, visibleIndices, withHidden, } from "./sheetState"; import type { @@ -163,9 +190,10 @@ import type { // ⛔⛔ W51-T17 — ONE TABLE, TWO CONSUMERS. `shortcuts.ts` is the key map AND the panel's rows, and // it imports NOTHING: see its head note on tsc's emitted root. This file matches against it and // `ShortcutsPanel.tsx` renders it, so the two cannot advertise different keys. -import { arrowStep, columnBand, edgeIndex, matchShortcut, rowBand, shortcutOwner, structureAxis } - from "./shortcuts"; -import type { ShortcutId } from "./shortcuts"; +import { arrowStep, columnBand, commitDirection, commitTarget, edgeIndex, edgeStart, + extendEdgeRect, isArrowKey, matchShortcut, rowBand, shortcutOwner, structureAxis, + tabRunOrigin } from "./shortcuts"; +import type { SelectionAxis, SelectionRect, ShortcutId } from "./shortcuts"; /** * ⭐⭐ W50-T20 — THE EXTENT IS THE SHEET'S NOW, AND THESE ARE ONLY ITS DEFAULTS. @@ -197,6 +225,64 @@ const HEADER_HEIGHT = 36; const MIN_ROW_HEIGHT = 18; const MAX_ROW_HEIGHT = 200; +/** + * ⭐⭐ W54-T06 — ONE OFFSCREEN 2D CONTEXT, BECAUSE A ROW'S HEIGHT IS ASKED OUTSIDE PAINT TIME. + * + * glide asks how tall a row is BEFORE it paints anything, and a wrapped value's line count is a + * measurement in a font, not a guess from a character count: `measureText` is the only honest + * answer and it needs a canvas context. The one glide paints into is not ours to borrow between + * frames, so this is a canvas of our own, created once, never mounted, never drawn. + * + * ⚠ IT ANSWERS `null` WHERE THERE IS NO DOCUMENT (a node proof, a test runner), and every caller + * treats that as "no wrapped row is taller than the base", which is exactly what the grid did + * before this ticket. A measurement that cannot be taken must not become a guess. + */ +let measureCtx: CanvasRenderingContext2D | null | undefined; +const measureContext = (): CanvasRenderingContext2D | null => { + if (measureCtx === undefined) { + measureCtx = typeof document === "undefined" + ? null + : document.createElement("canvas").getContext("2d"); + } + return measureCtx; +}; + +/** + * ⭐ THE WRAP ITSELF, SHARED BY THE MEASUREMENT AND THE PAINT so the two cannot disagree. Words + * are added to a line until the next one would cross the cell's inner width, in whatever font + * `ctx` is ALREADY set to; a single word wider than the column stays on its own line and is + * clipped, because breaking inside a word would hyphenate an account code. + */ +const wrapIntoLines = ( + ctx: CanvasRenderingContext2D, + text: string, + inner: number, +): string[] => { + const out: string[] = []; + let line = ""; + for (const word of text.split(/\s+/)) { + const next = line ? `${line} ${word}` : word; + if (line && ctx.measureText(next).width > inner) { + out.push(line); + line = word; + } else { + line = next; + } + } + if (line) out.push(line); + return out; +}; + +/** + * ⭐⭐ W54-T19 (instruction 13) — THE ONE SURFACE THE KEYBOARD RESCUE STANDS DOWN FOR. + * + * A modal owns the keyboard for as long as it is open, so a focus that goes nowhere INSIDE one is + * the modal's own business to answer, not the sheet's. Pulling the keyboard back to the grid + * underneath it would be the sheet reaching through a dialog, which is worse than the scroll the + * rescue exists to prevent. + */ +const MODAL_SELECTOR = '[role="dialog"], [role="alertdialog"]'; + /** * ⭐ W51-T16 — R8's FOUR SIZE STEPS, IN THE ONE UNIT A CANVAS UNDERSTANDS. * @@ -206,6 +292,11 @@ const MAX_ROW_HEIGHT = 200; * other three step around it rather than inventing a second scale. */ const SIZE_PX: Record = { s: 11, m: 13, l: 16, xl: 20 }; +// ⭐ W54-T03 / R11 — THIS TABLE IS NOW THE NAMED HALF OF A TWO SHAPE SLOT, and it is unchanged +// on purpose. `types.ts::SIZE_STEP_PT` maps the same four names to 8, 10, 12 and 15 POINTS, and +// `types.ts::fontPx` rounds a point size to four thirds of itself, which reproduces these four +// numbers exactly. So a document written before the size box existed paints identically, and the +// only cells that take the other branch are the ones somebody set a point size on. /** R8's size menu emits a step NAME; C2 stores a letter. One table, so the two cannot drift. */ const SIZE_OF_STEP: Record = { @@ -314,6 +405,19 @@ export interface SheetGridProps { * dialog's own notice says rather than leaving it to be discovered. */ onRules?: (rules: SheetRule[]) => void; + + // ── W54-T10, LANE B'S WIRING (one contiguous addition, so a merge can see it whole) ───────── + /** + * ⭐⭐ THE PERSISTENCE DOOR FOR THIS TAB'S CHARTS, and it is the SAME optional-persistence-door + * pattern `onHideBands` and `onRules` above are, for the same reason stated there: `commitSheets` + * lives in `SheetPage.tsx`, and a REQUIRED prop would break another lane's tree at the merge. + * So an inserted chart appears the moment it is inserted (the list is local state below), and it + * is WRITTEN to the document only where the page has wired this. + * ⛔ AND THE TWO-WRITERS RULE APPLIES UNCHANGED: with this wired the DOCUMENT is the single + * answer, or a local copy outlives the state it mirrored and an undo repaints from a stale list. + */ + onCharts?: (charts: SheetChartSpec[]) => void; + /** A dragged column width, once the drag has ENDED. See the note on `dragWidth` below. */ onColumnWidth: (colIndex: number, width: number) => void; @@ -357,26 +461,11 @@ const MARK_STYLE: Record(); -const tokenColour = (token: string, fallback: string): string => { - if (!token) return fallback; - if (token.startsWith("#")) return token; - const cached = TOKEN_CACHE.get(token); - if (cached !== undefined) return cached || fallback; - const value = getComputedStyle(document.documentElement).getPropertyValue(token).trim(); - TOKEN_CACHE.set(token, value); - return value || fallback; -}; /** glide hands back a union; every kind this grid offers carries its value in `data`. */ const typedText = (value: EditableGridCell): string => { @@ -448,6 +537,20 @@ interface SheetMenu { interface FindState { query: string; at: number; + /** + * ⭐ W54-T07 — WHAT REPLACE WOULD WRITE IN PLACE OF THE MATCH, and an empty string is a real + * answer rather than a missing one: replacing a word with nothing is how a person deletes it + * everywhere at once. + */ + replace?: string; + /** + * ⭐ W54-T07 — WHETHER THE PANEL WAS OPENED BY REPLACE RATHER THAN BY FIND. One box, two + * shapes: Ctrl+F and the ribbon's Find item leave this absent and the panel shows what it + * always showed, and the ribbon's Replace item sets it and the same panel grows a second + * input plus its two buttons. A person who asked to FIND is never shown a field they did not + * ask for, which is the whole reason this flag exists rather than the row always being there. + */ + replacing?: boolean; } /** What the row height or column width dialog is asking for, and what it opened with. */ @@ -495,10 +598,31 @@ export default function SheetGrid({ workbook, tab, busy = false, onEdit, onViewRows, formulaBar, onRefresh, onSaveNow, onOpenImport, onCommit, onUndo, onRedo, onNotice, - onSelect, onStructure, onGrow, onFreeze, onColumnWidth, onHideBands, onRules, onSelectTab, + onSelect, onStructure, onGrow, onFreeze, onColumnWidth, onHideBands, onRules, onCharts, + onSelectTab, options, }: SheetGridProps) { const [selection, setSelection] = useState(undefined); + /** + * ⭐⭐ W54-T28 / R9(iv) — THE TAB RUN'S MEMORY, AND THE ONE BIT THAT SAYS WHO MOVED. + * + * `tabRunAt` holds the column a run of Tabs STARTED at, so the Enter that ends the run can + * return to it; `shortcuts.ts::tabRunOrigin` owns the rule for what it becomes on each press. + * `commitNav` is raised for exactly one selection change, by the commit-navigation arm in + * `onKeyDown`, and read back in `onSelectionChange` below. + * + * ⛔ THE FLAG IS WHY THE RESET CAN LIVE IN `onSelectionChange` AT ALL. The done-when asks the + * run to reset when the selection moves by anything other than Tab, and that handler is the ONE + * door every move goes through - an arrow, a click, the name box, Ctrl+End, a header pick. But + * a Tab goes through it too, so without a way to tell the run's own move apart from everybody + * else's, the very press that opened the run would immediately close it. + * + * ⛔ REFS, NOT STATE, AND THAT IS DELIBERATE. Neither one is drawn, and a state update here + * would re-render the whole grid on every Tab; worse, `onSelectionChange` would then read the + * flag from a stale closure in the same batch that set it. + */ + const tabRunAt = useRef(null); + const commitNav = useRef(false); /** * ⭐ W51-T17 — THE TWO SURFACES THE KEYBOARD OPENS, and both live INSIDE this component's own * box rather than in a portal: portalling drops every descendant-scoped rule with no error at @@ -534,12 +658,25 @@ export default function SheetGrid({ */ const [painter, setPainter] = useState(null); const [ask, setAsk] = useState(null); + /** + * ⛔ W54-T21 — THE ROW HEIGHT / COLUMN WIDTH DIALOG CLOSES THROUGH THE ARBITER. It used to read + * Escape off its own number input, which is the local-handler shape DESIGN.md section 4 names + * as the defect: a `role="dialog"` deciding for itself whether it may act. Declared beside the + * state it closes, and unconditionally, so the hook order never changes between renders. + */ + useEscapeClose(ask !== null, () => setAsk(null)); /** * ⭐⭐ W51-T34 / R17 — WHAT THE FREEZE PANES PANEL IS ASKING FOR. Two counts, held together * rather than as two states, because `setFreeze` merges a patch into the record it already has * and answering one of them alone would silently keep whatever the other one was. */ const [freezeAsk, setFreezeAsk] = useState<{ rows: number; cols: number } | null>(null); + /** + * ⛔ W54-T21 — AND THE FREEZE PANES PANEL, for the same reason and through the same door. It + * carried the Escape branch TWICE, once on each of its two number inputs, which is precisely + * the drift a single arbiter entry removes: two copies of one rule can disagree. + */ + useEscapeClose(freezeAsk !== null, () => setFreezeAsk(null)); /** * ⚠ THE ROW HEIGHT IS SHEET WIDE AND SESSION LOCAL, AND BOTH HALVES ARE DELIBERATE. C2 carries * `hiddenRows` and `hiddenCols` but no per-row height, so there is nowhere in the document to @@ -576,6 +713,13 @@ export default function SheetGrid({ */ const [rulesLocal, setRulesLocal] = useState<{ tabId: string; rules: SheetRule[] } | null>(null); + /** + * ⭐ W54-T10 / LANE B — the chart list's local fallback, the same shape as `rulesLocal` above and + * kept for exactly the reason that one is: it exists only while the page has not wired + * `onCharts`, and it yields to the document the moment the page has. + */ + const [chartsLocal, setChartsLocal] = + useState<{ tabId: string; charts: SheetChartSpec[] } | null>(null); /** The validation list editor: which addresses it will write, and what the anchor holds now. */ const [listAsk, setListAsk] = useState<{ addrs: string[]; list: string[] } | null>(null); @@ -585,6 +729,27 @@ export default function SheetGrid({ /** W52-T06 — the floating formula editor. `null` means no formula is being authored right now. */ const [formulaEdit, setFormulaEdit] = useState(null); const formulaInputRef = useRef(null); + /** + * ⭐⭐ W54-T21 / INSTRUCTION 18 — THE ONE FLAG THAT STOPS ESCAPE COMMITTING WHAT IT CANCELLED. + * + * ⛔⛔ THE ARBITER BLURS BEFORE IT CLOSES, AND THIS EDITOR'S BLUR IS ITS COMMIT DOOR. Read + * `ui/useEscapeClose.ts`: the one capture-phase handler takes the focused element, calls blur + * on it, and only THEN calls the topmost entry's close. The floating input's blur is what + * commits a formula on a click away, so a naive registration would make Escape write the very + * draft it was pressed to throw away - the exact opposite of instruction 18. + * + * ⛔ SO THE BLUR DOOR DEFERS ITS DECISION BY ONE MICROTASK, WHICH IS DETERMINISTIC AND NOT A + * RACE. `blur` then `close` are two statements of ONE synchronous handler, and a microtask + * queued inside the first cannot run until that whole handler has returned. The close therefore + * always gets to raise this flag first. A frame or a timeout would be a guess; a microtask is + * an ordering guarantee. + * + * ⚠ IT IS RAISED BY BOTH ESCAPE OUTCOMES, not only by the abandon. The first Escape over an + * open suggestion list dismisses the LIST and keeps the edit alive (FA-23 #1), and that press + * blurs the input just the same, so it has to suppress the commit too or the two-stage ladder + * would commit on its first rung. + */ + const formulaEscaping = useRef(false); /** * ⭐⭐ W53-T02 / INSTRUCTION 11 — EVERY EXIT PATH RETURNS TO READY, AND THE KEYBOARD HAS TO * COME WITH IT. Excel's four cell modes (Ready/Enter/Edit/Point) all fall back to Ready on any @@ -663,6 +828,12 @@ export default function SheetGrid({ const localRules = rulesLocal?.tabId === tab.id ? rulesLocal.rules : tab.rules; const rules = (onRules ? tab.rules : localRules) ?? []; + // ⭐ W54-T10 / lane B: THE SAME TWO-WRITERS RULE AGAIN, for the charts the Insert tab appends. + // Read as one expression here so the anchor loop below has exactly one list to draw, whichever + // writer produced it. + const localCharts = chartsLocal?.tabId === tab.id ? chartsLocal.charts : tab.charts; + const charts = (onCharts ? tab.charts : localCharts) ?? []; + // ⚠ MEMOISED ON A STRING KEY, not on the array. A hidden band is rebuilt on every render (it is // read through two `??`s), so an array in the dependency list would be a new object every time // and the memo would rebuild a 100,000 entry table per keystroke on a grown sheet. @@ -906,6 +1077,11 @@ export default function SheetGrid({ const onSelectionChange = useCallback((next: GridSelection) => { setSelection(next); + // ⭐⭐ W54-T28 / R9(iv): "the run resets when the selection is moved by anything other than + // Tab", said in the one place every move arrives at. The commit arm raises the flag for its + // own move and this consumes it, so a Tab keeps the run and everything else ends it. + if (commitNav.current) commitNav.current = false; + else tabRunAt.current = null; // R11: the bar is anchored to the selection and unmounts when the selection changes. Clearing // the anchor here is what makes "disappears when the selection changes" true rather than // approximately true. @@ -1093,7 +1269,28 @@ export default function SheetGrid({ }); }, []); - const abandonFormulaEditor = useCallback(() => setFormulaEdit(null), []); + /** + * ⭐⭐ W54-T21 / INSTRUCTION 18 — ESCAPE CANCELS THE EDIT AND THE CELL GOES BACK TO WHAT IT HELD. + * + * ⛔ THE RESTORE IS A REPAINT, NOT A WRITE, AND THAT IS THE WHOLE POINT. Nothing in this + * editor's life touches the document: the draft lives in `formulaEdit` and only a COMMIT ever + * reaches `commitWithRecalc`. So the prior value was never lost and re-writing it here would be + * a save round trip that could itself fail. What the canvas needs is to be TOLD the cell + * changed, because glide repaints damaged cells only and the cell under the editor has been + * wearing a reference border and an editor overlay. Damaging it makes the next paint read the + * stored cell again, which IS the prior value. + * + * ⚠ THE FLAG IS RAISED BEFORE THE STATE DROPS, so the blur this abandon is about to be + * followed by (see `formulaEscaping` above) cannot commit the draft on its way out. + */ + const abandonFormulaEditor = useCallback(() => { + formulaEscaping.current = true; + if (formulaEdit) { + const target = [{ cell: [formulaEdit.viewCell[0], formulaEdit.viewCell[1]] as Item }]; + (formulaEdit.inBand ? bandGridRef : gridRef).current?.updateCells(target); + } + setFormulaEdit(null); + }, [formulaEdit]); /** Enter/Tab outside point mode, and the second half of PM-12 inside it. */ const commitFormulaEditor = useCallback(() => { @@ -1106,7 +1303,15 @@ export default function SheetGrid({ // beside `formulaEdit`) instead of stranded in Enter or Point mode. Both updates land in the // same React batch, so nothing renders in between and the draft is already destructured. setFormulaEdit(null); - commitWithRecalc({ [addr]: commitTyped(cellAt(tab, addr), draft, cellValueGetter) }); + // ⭐⭐ W54-T25 / R9(i) — THE AUTO-CLOSE HAPPENS HERE, BEFORE STORAGE, AND ONLY HERE. What + // `commitTyped` is handed is what the cell stores, what the formula bar reads back and what + // the evaluator computes, so all three see one identical closed text. Closing the DISPLAY + // instead would leave a cell that looks balanced and is stored broken. + // ⛔ AND THE ABANDON DOOR NEVER PASSES THROUGH HERE. Escape drops the draft without a write + // (see `abandonFormulaEditor` above), so an unfinished formula that was cancelled is still + // cancelled rather than tidied up and saved. + const closed = autoCloseFormula(draft); + commitWithRecalc({ [addr]: commitTyped(cellAt(tab, addr), closed, cellValueGetter) }); // Mirrors glide's own default Enter-commit: the selection moves down one row, so the custom // editor does not feel like a different control from editing any other cell. // ⚠ NOT `applySelection` -- that helper is declared FURTHER DOWN this component (it is the @@ -1123,6 +1328,22 @@ export default function SheetGrid({ } }, [cellValueGetter, commitWithRecalc, formulaEdit, onSelectionChange, tab]); + /** + * ⭐⭐ W54-T21 — THE BLUR DOOR, AND THE ONE REASON IT IS NO LONGER THE COMMIT ITSELF. + * + * A click away still commits, exactly as it always has. What changed is that the decision is + * taken one microtask later, so an Escape that blurred this input on its way to closing the + * editor gets to say "not this one" first. See `formulaEscaping` beside the state above for + * why the ordering is a guarantee rather than a hope. + */ + const onFormulaBlur = useCallback(() => { + formulaEscaping.current = false; + queueMicrotask(() => { + if (formulaEscaping.current) return; + commitFormulaEditor(); + }); + }, [commitFormulaEditor]); + /** * PM-4/PM-5/PM-7/PM-8: every point-mode proposal, arrived at from either the anchor (a fresh * arrow press) or the previous proposal (a continued one), goes through this ONE splice so @@ -1202,6 +1423,34 @@ export default function SheetGrid({ ); const formulaDropdownOpen = !!formulaEdit && !formulaEdit.dismissed && formulaSuggestions.length > 0; + /** + * ⭐⭐ W54-T21 / DESIGN.md SECTION 4 — THE FORMULA EDITOR'S ESCAPE, THROUGH THE ONE ARBITER. + * + * ⛔ IT USED TO BE THREE BRANCHES OF `onFormulaKeyDown`, which is the shape section 4 exists to + * end: a surface deciding for itself whether it is allowed to answer a key. The stack decides + * now. A menu or a dialog opened over this editor registers LATER, so it is topmost and takes + * the press; nothing below hears the key at all. + * + * ⭐ THE TWO-STAGE LADDER FA-23 #1 SHIPPED IS PRESERVED, AND IT LIVES HERE RATHER THAN IN THE + * ARBITER'S `cancelEditFirst`. That option cancels an edit by BLURRING the focused input and + * stopping, which for this editor would mean the suggestion list survived and the draft was + * committed by the blur - the opposite of both rungs. One entry, one close, and the close reads + * the state to decide which rung it is on. + * + * ⚠ THE DISMISS RUNG RAISES `formulaEscaping` TOO. Its press blurred the input on the way in, + * and without the flag that blur would commit the very draft the person is still typing. Focus + * comes straight back through W54-T19's keyboard rescue, which sees a focus that went nowhere + * while an editor is open and hands it to this input. + */ + useEscapeClose(formulaEdit !== null, () => { + if (formulaDropdownOpen) { + formulaEscaping.current = true; + setFormulaEdit((prev) => (prev ? { ...prev, dismissed: true } : prev)); + return; + } + abandonFormulaEditor(); + }); + const onFormulaKeyDown = useCallback((e: ReactKeyboardEvent) => { if (!formulaEdit) return; const { draft, caret, mode } = formulaEdit; @@ -1233,12 +1482,29 @@ export default function SheetGrid({ ); return; } - // FA-23 #1 / PM-13's precedence note: the FIRST Escape closes the list only. - if (e.key === "Escape") { - e.preventDefault(); - setFormulaEdit({ ...formulaEdit, dismissed: true }); - return; - } + // ⛔ W54-T21: FA-23 #1's first rung, the one that dismisses the list, is NOT read here any + // more. It is the first rung of the arbiter registration above, and a copy of it in this + // handler would be a second owner of one key press. + } + + // ⭐⭐ W54-T25 / R9(i) — F4 CYCLES THE ANCHORS OF THE REFERENCE UNDER THE CARET. + // + // ⛔ ABOVE THE POINT-MODE BLOCK ON PURPOSE, so one key means one thing wherever the editor is + // open. A proposal being pointed at lives in this same draft text, so cycling it is the same + // edit on the same string; the mode, the anchor and the insert start are all left alone. + // + // ⛔⛔ AND IT STOPS THE KEY EVEN WHEN NOTHING CHANGES. `cycleAnchorAtCaret` answers null when + // the caret is not on a reference, which is a decided answer rather than an oversight (see its + // own note): while this editor is open F4 belongs to it, and letting the press fall through + // would hand the same key to the grid's whole-formula cycle on a cell that is being edited. + if (e.key === "F4") { + e.preventDefault(); + const cycled = cycleAnchorAtCaret(draft, caret); + if (!cycled) return; + setFormulaEdit((prev) => (prev + ? { ...prev, draft: cycled.text, caret: cycled.caret, dropdownIndex: 0 } + : prev)); + return; } if (mode === "point") { @@ -1259,8 +1525,9 @@ export default function SheetGrid({ commitFormulaEditor(); return; } - // PM-13: Esc in point mode abandons the WHOLE edit, not merely the proposal. - if (e.key === "Escape") { e.preventDefault(); abandonFormulaEditor(); return; } + // ⛔ W54-T21: PM-13 - Esc in point mode abandons the WHOLE edit rather than the proposal - + // is unchanged behaviour, and it is now the arbiter's second rung above. Point mode reaches + // the same abandon the enter mode does, which is what PM-13 always asked for. if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) { // PM-14: any other typed character leaves point mode and is inserted literally. No // `preventDefault` -- the browser's own keystroke does the inserting. @@ -1291,9 +1558,11 @@ export default function SheetGrid({ if (e.key === "Enter") { e.preventDefault(); commitFormulaEditor(); return; } // D-1: Tab is captured ONLY while the dropdown is open (handled above); otherwise it traverses // focus like any other control, so nothing here intercepts it. - if (e.key === "Escape") { e.preventDefault(); abandonFormulaEditor(); } + // ⛔ W54-T21: and NOTHING in this handler reads Escape, in any branch. The arbiter's listener + // is capture phase on the document and stops propagation, so a branch here could never fire + // anyway - it would be dead code that a later reader would trust. }, [ - abandonFormulaEditor, acceptFormulaSuggestion, clampCol, clampRow, commitFormulaEditor, + acceptFormulaSuggestion, clampCol, clampRow, commitFormulaEditor, commitPointReference, formulaDropdownOpen, formulaEdit, formulaSuggestions, proposeCell, ]); @@ -1403,12 +1672,38 @@ export default function SheetGrid({ * cells, solid instead of dashed) still counts as a change worth a repaint. Same shape as the * shimmer's `pendingBoundKey` above, and a negative view row is the frozen band's own grid for * the same reason. + * + * ⭐⭐ W54-T23 / INSTRUCTION 17 — IT NOW WALKS **BOTH** OUTLINE SOURCES, AND THAT IS THE WHOLE + * OF THIS TICKET'S CHANGE. There are exactly two above: `formulaRefCells`, which falls back to + * the SELECTED cell's stored formula when no editor is open, and `formulaPointCells`, the live + * dashed proposal. This key used to be built from the first alone, on the reasoning that the + * proposal is always written into the draft and so is always a subset of it. That reasoning is + * true today and it is not a guarantee: `refsIn` deliberately refuses a token followed by an + * opening bracket, reading it as a function name, so a proposal inserted immediately before one + * is a point cell with no reference entry at all. Damaging only the first source would then + * leave the second's cells outside the one repaint path that can ever take an outline OFF the + * canvas. Walking both makes "no outline can outlive its reference" a property of the code + * rather than of an argument about it. + * + * ⚠ A POINT-ONLY CELL CARRIES NO COLOUR, so it is keyed as such and paints nothing: the border + * still comes from `formulaRefCells` alone, and this addition changes only WHICH cells are + * asked to repaint. Widening a damage set can cost a repaint; it cannot invent a border. + * + * ⛔ MEASURED FIRST, ON THE OWNER'S OWN SEQUENCE, AND IT WAS ALREADY CLEAN. Thirty two states + * were read off the real canvas at this tip by counting pixels in the six REF_COLORS: point + * mode, commit, Escape, re-selection, a mouse drag, the blur commit, Delete, undo, a wheel + * scroll, a focus that fell to the body, and a reopened editor whose reference was shrunk. Not + * one of them left a pixel behind. So this is a HARDENING of a guarantee that already held, not + * a repair of a residue that was seen. The frames and counts are in the wave 54 handoff. */ const refPaintKey = useMemo(() => { const parts: string[] = []; for (const [key, color] of formulaRefCells) { parts.push(`${key}:${color}:${formulaPointCells.has(key) ? "dash" : "solid"}`); } + for (const key of formulaPointCells) { + if (!formulaRefCells.has(key)) parts.push(`${key}:none:dash`); + } return parts.join("|"); }, [formulaPointCells, formulaRefCells]); const paintedRefCells = useRef([]); @@ -1507,31 +1802,16 @@ export default function SheetGrid({ * a currency cell arrives in Excel as the currency somebody chose. That is the same string * `displayData` carries, which is what makes glide's own Ctrl+C agree with the ribbon's button * — and it is why the two copy doors can share one builder at all. + * + * ⭐ WAVE 54 BASE KIT: the BODY moved to `clipboardOps.ts::buildCopyPayload` unchanged, with its + * four closed-over values handed over as arguments instead. The `useCallback` stays HERE, with + * the same dependency array, because two consumers depend on its identity — the native-copy + * `useEffect` below and `copySelection` both name `heldFor` in their own arrays. */ - const heldFor = useCallback((range: CellRange) => { - const lines: string[] = []; - // ⭐ W51-T19: the CELLS are kept beside the text, so a bound cell pasted back into the sheet - // can take its drag rules. See `copiedRef` for why the text alone cannot carry a binding. - const block: (Cell | null)[][] = []; - for (let r = Math.min(range.row0, range.row1); r <= Math.max(range.row0, range.row1); r += 1) { - const line: string[] = []; - const row: (Cell | null)[] = []; - for (let c = Math.min(range.col0, range.col1); c <= Math.max(range.col0, range.col1); - c += 1) { - const cell = cells[addrAt(c, r)] ?? null; - line.push(formatCellText(cell, displayText(cell))); - row.push(cell); - } - lines.push(line.join("\t")); - block.push(row); - } - return { - text: lines.join("\n"), - col: realCol(Math.min(range.col0, range.col1)), - row: realRow(Math.min(range.row0, range.row1)), - cells: block, - }; - }, [addrAt, cells, realCol, realRow]); + const heldFor = useCallback( + (range: CellRange) => buildCopyPayload(range, cells, addrAt, realCol, realRow), + [addrAt, cells, realCol, realRow], + ); /** * ⭐⭐ W53-T03 / INSTRUCTION 24 — THE NATIVE Ctrl+C IS A COPY THIS COMPONENT KNOWS ABOUT NOW. @@ -1568,6 +1848,7 @@ export default function SheetGrid({ if (!range) return; const held = heldFor(range); copiedRef.current = held; + if (event.type === "cut") rememberCut(held); setCopyMarquee({ col: held.col, row: held.row, cols: held.cells[0]?.length ?? 0, rows: held.cells.length }); }; @@ -1756,7 +2037,8 @@ export default function SheetGrid({ * Borders painted nothing: creating a cell would have meant `kind: "literal"`, and * `handTypedCount` counts every literal, so the header would have claimed three hand typed * values nobody typed. Contract C2's `empty` kind removes that trade, and the decision moved - * into `sheetState.ts::styleCells` where a node proof can execute it rather than grep it. + * into `cellStyleOps.ts::styleCells` where a node proof can execute it rather than grep it. + * (Wave 54 moved that function one file further, out of `sheetState.ts`, which re-exports it.) * * ⚠ R19 / R20, DECIDED AND STATED: styling a BOUND cell is allowed and is NOT a conversion. * A colour changes nothing about where the value comes from, the binding survives, the mark @@ -1872,6 +2154,120 @@ export default function SheetGrid({ else onNotice("The sheet tabs are not on screen, so the keyboard cannot reach them."); }, [onNotice, onSelectTab, tab.id, workbook.sheets]); + // ═══════════════════════════════════════════════════════════════════════════════════════════ + // ⭐⭐ W54-T14 / LANE B — A CELL'S ATTACHMENTS, WIRED IN ONE PLACE. + // + // A link and a note are the two things a cell can carry that are neither value nor style, and + // `LinkDialog.tsx` owns every part of them that can be owned away from this file: the authoring + // surface, the two canvas marks, the hover bubble and the resolve-and-follow door. What CANNOT + // leave is the wiring, because only this component knows where a cell is on screen, which of + // the two grids reported the pointer, and how a sheet coordinate becomes a view one. That is + // this block, plus one call in the paint and one line in each grid's click and hover. + // + // ⛔ NO NEW `RibbonActionKind`. Following a link is a click on the canvas, not a named act, so + // `onRibbonAction`'s exhaustive switch is untouched and every other lane still compiles. + // ═══════════════════════════════════════════════════════════════════════════════════════════ + + /** + * ⭐ A LINK TO A CELL ON ANOTHER TAB IS TWO STEPS, AND THE SECOND ONE CANNOT RUN YET. Switching + * tabs re-renders this component with a different `tab`, and the view coordinates the selection + * is written in belong to THAT sheet's visible rows and columns, which do not exist until the + * render happens. So the destination is parked here and applied by the effect below, on the + * render where it is finally addressable. A ref rather than state: parking it must not itself + * cause a render. + */ + const pendingJump = useRef<{ sheetId: string; col: number; row: number } | null>(null); + + /** The note under the pointer, or null. `addr` is what keeps a hover from re-rendering per pixel. */ + const [noteHover, setNoteHover] = + useState<{ addr: string; note: string; anchor: AnchorRect } | null>(null); + + /** Show a tab by id, through the SAME wrap-around door Ctrl+PgUp uses. */ + const goToSheet = useCallback((sheetId: string) => { + const sheets = workbook.sheets ?? []; + const from = sheets.findIndex((sheet) => sheet.id === tab.id); + const to = sheets.findIndex((sheet) => sheet.id === sheetId); + if (from < 0 || to < 0) { + onNotice("That sheet is not in this workbook any more."); + return; + } + if (to !== from) switchTab(to - from); + }, [onNotice, switchTab, tab.id, workbook.sheets]); + + /** + * ⛔ THE REFUSAL IS THE `realCol` / `realRow` ROUND TRIP, and that is why it is one test rather + * than three. `viewIndexOf` does not fail on a miss, it answers the nearest visible index at or + * below, so a hidden column and a column past the end of the sheet both come back as a + * PLAUSIBLE view index pointing at the wrong cell. Asking the inverse pair whether that index + * really is the cell we asked for catches hidden, out of extent and off the end in one line. + */ + const goToCell = useCallback((sheetId: string, col: number, row: number) => { + if (sheetId !== tab.id) { + pendingJump.current = { sheetId, col, row }; + goToSheet(sheetId); + return; + } + pendingJump.current = null; + const viewCol = viewIndexOf(visCols, col); + const viewRow = viewRowOf(row); + if (realCol(viewCol) !== col || realRow(viewRow) !== row) { + onNotice("That cell is hidden or past the end of this sheet, so there is nothing to open."); + return; + } + applySelection( + { col0: viewCol, row0: viewRow, col1: viewCol, row1: viewRow }, + [viewCol, viewRow], + ); + }, [applySelection, goToSheet, onNotice, realCol, realRow, tab.id, viewRowOf, visCols]); + + useEffect(() => { + const jump = pendingJump.current; + if (!jump || jump.sheetId !== tab.id) return; + goToCell(jump.sheetId, jump.col, jump.row); + }, [goToCell, tab.id]); + + /** Everything `followLink` needs, and nothing this component would not hand any other reader. */ + const followContext = useMemo(() => ({ + sheets: (workbook.sheets ?? []).map((sheet) => ({ id: sheet.id, name: sheet.name })), + tabId: tab.id, + goToSheet, + goToCell, + onNotice, + }), [goToCell, goToSheet, onNotice, tab.id, workbook.sheets]); + + /** + * Follow the link on this address, if it carries one. `false` means it does not, which is what + * lets both grids' click handlers ask in one line and fall through to what they already did. + */ + const followCellLink = useCallback( + (addr: string): boolean => followLink(cellAt(tab, addr), followContext), + [followContext, tab], + ); + + /** + * ⭐ ONE HOVER READER FOR BOTH GRIDS, told which one is asking. Every callback the frozen band + * grid is given is the main grid's wrapped in `fromBand`, and a hover is no different: a note on + * a frozen row has to show its bubble at the row a person is actually pointing at. + * + * ⛔ IT RETURNS THE CURRENT STATE UNCHANGED WHENEVER NOTHING MOVED. glide fires this on every + * pointer move over the canvas, so setting state per event would re-render the whole grid at + * mouse frequency, and the bubble's own overlay would remount under the pointer. + */ + const onNoteHover = useCallback((args: GridMouseEventArgs, band: boolean) => { + if (args.kind !== "cell") { + setNoteHover((current) => (current ? null : current)); + return; + } + const location = band ? fromBand(args.location) : args.location; + const addr = addrAt(location[0], location[1]); + const note = cells[addr]?.note ?? ""; + setNoteHover((current) => { + if (!note) return current ? null : current; + if (current && current.addr === addr) return current; + return { addr, note, anchor: rectAnchor(args.bounds) }; + }); + }, [addrAt, cells, fromBand]); + /** * ⭐⭐ Ctrl+1 — CONTRACT C1's "THE SAME IMPLEMENTATION, NOT TWO COPIES OF IT", TAKEN LITERALLY. * @@ -1960,9 +2356,91 @@ export default function SheetGrid({ row: viewRowOf(place.row - 1), }; applySelection({ col0: view.col, row0: view.row, col1: view.col, row1: view.row }); - setFind({ query, at }); + // ⚠ W54-T07 MADE THIS A FUNCTIONAL UPDATE, AND THE REASON IS ONE LINE: the record now carries + // the panel's SHAPE (`replacing`) as well as its query, so writing a fresh literal here would + // fold the replace row away the moment somebody pressed Next. + setFind((was) => ({ ...(was ?? {}), query, at })); }, [applySelection, onNotice, tab, viewRowOf, visCols]); + // ═══════════════════════════════════════════════════════════════════════════════════════════ + // ⭐⭐ W54-T07 — REPLACE, THROUGH THE SAME LIST FIND WALKS AND THE SAME DOOR EVERY BULK EDIT + // TAKES. + // + // ⛔ THERE IS NO SECOND SEARCH HERE. The addresses come from `findMatches`, exactly as the walk + // above gets them, so what Replace all changes is precisely the set Next would have visited; + // two matchers would eventually disagree about a formula cell and nobody would know which was + // right. + // + // ⛔ AND NO SECOND WRITE PATH. The edits go out through `commitWithRecalc`, which is what Clear + // all and the paste already use: one history step, one PUT carrying the `rev` that was read, and + // the dependents recomputed in the same commit rather than at the next Refresh. + // + // ⚠ IT REPLACES IN THE TEXT A PERSON TYPED, NOT IN THE VALUE THEY SEE. `editableText` is + // `=SUM(B4:B8)` where `displayText` is `31`, and only the first of those is something a write + // can put back. `findMatches` searches BOTH, so a cell can legitimately match on its displayed + // number and hold nothing to change; it is left exactly as it was and the count says so. + // ═══════════════════════════════════════════════════════════════════════════════════════════ + const replaceMatches = useCallback((query: string, into: string, all: boolean) => { + const needle = String(query ?? "").trim(); + if (!needle) { + onNotice("Type what to look for first, then replace it."); + return; + } + const hits = findMatches(tab, needle); + if (hits.length === 0) { + onNotice(noMatchLabel(needle)); + return; + } + /** A case-insensitive replace of every occurrence, done by index rather than by a regular + * expression: a query is free text, and a person searching for a currency amount would + * otherwise have their own dots and brackets read as syntax. */ + const swap = (text: string): string => { + const hay = text.toLowerCase(); + const look = needle.toLowerCase(); + let out = ""; + let from = 0; + for (;;) { + const hit = hay.indexOf(look, from); + if (hit < 0) break; + out += text.slice(from, hit) + into; + from = hit + look.length; + } + return out + text.slice(from); + }; + // ⛔ A SINGLE REPLACE ACTS ON THE MATCH THE PERSON IS STANDING ON, which is the one the walk + // last selected. Before any walk there is no such match, so the first press takes the first + // one, exactly as Enter in the query box would have. + // + // ⚠ A MATCH IS A CELL HERE, NOT A CHARACTER OFFSET, and that is a documented deviation from + // Excel rather than an oversight. `findMatches` answers with ADDRESSES, so a cell saying the + // word twice is one entry in its list and one press of Replace changes both occurrences in + // it. Offering finer granularity would mean a second matcher that tracked offsets, and two + // matchers eventually disagree about what a match is with nothing to report the difference. + const index = all ? -1 : Math.min(Math.max(find?.at ?? -1, 0), hits.length - 1); + const targets = all ? hits : [hits[index]]; + const edits: Record = {}; + for (const addr of targets) { + const cell = cellAt(tab, addr); + const before = editableText(cell); + const after = swap(before); + if (after === before) continue; + edits[addr] = commitTyped(cell, after); + } + const changed = Object.keys(edits).length; + if (changed === 0) { + onNotice(`Nothing writable on this sheet says ${JSON.stringify(needle)}. A cell can match ` + + "on the value it shows while holding a formula that does not say it."); + return; + } + commitWithRecalc(edits); + // ⚠ THE WALK'S PLACE MOVES BACK ONE, and that is arithmetic rather than caution: the cell just + // written no longer matches, so the next render's list is one shorter and everything after the + // replaced entry has slid down into its index. Standing one before it means the next press of + // Next lands on what really is the next match. + if (!all) setFind((was) => ({ ...(was ?? { query: needle }), at: Math.max(-1, index - 1) })); + onNotice(changed === 1 ? "Replaced one cell." : `Replaced ${changed} cells.`); + }, [commitWithRecalc, find, onNotice, tab]); + // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐ W50-T20 — THE STRUCTURE CONTROLS. They RAISE an intent and decide nothing. // @@ -2005,39 +2483,22 @@ export default function SheetGrid({ /** * COPY, and CUT, which is a copy that then clears. * - * ⛔ THE CLEAR ONLY HAPPENS IF THE COPY SUCCEEDED. A browser that refuses clipboard access on a - * cut would otherwise delete a person's cells with nothing on the clipboard to paste back. + * ⭐ WAVE 54 BASE KIT: the BODY moved to `clipboardOps.ts::runCopySelection` unchanged, with its + * six closed-over values handed over as arguments instead. The `useCallback` stays HERE, with + * the same dependency array, because the ribbon's Copy and Cut items and the shortcut router + * all name `copySelection` in theirs. `copiedRef` and `setCopyMarquee` are absent from that + * array for the reason they always were: a ref and a `useState` setter are stable for the life + * of the component, so naming them would say something untrue about what this callback watches. + * + * ⛔ THE CLEAR ONLY HAPPENS IF THE COPY SUCCEEDED, and that rule now lives beside the promise + * chain that implements it. A browser that refuses clipboard access on a cut would otherwise + * delete a person's cells with nothing on the clipboard to paste back. * * ⭐ WHAT IT PUTS ON THE CLIPBOARD IS {@link heldFor}'s, which glide's own Ctrl+C now records * through the same builder. */ const copySelection = useCallback((cut: boolean) => { - const range = viewRange(); - if (!range) { - onNotice(cut ? "Select a cell first, then cut it." : "Select a cell first, then copy it."); - return; - } - // ⭐ W53-T03: the block and its text are built by `heldFor`, the ONE builder both copy doors - // share, so a native Ctrl+C and this button can never record different things about the same - // selection. - const held = heldFor(range); - const block = held.cells; - const text = held.text; - // ⛔ RECORDED ONLY ON A SUCCESSFUL WRITE, so the sheet never believes it holds a block the - // clipboard does not. It is a SEPARATE `then` so that the clear stays the one line a - // W51-T17 gate leg pins: a cut clears the source only after the copy landed, and folding - // the two together would have moved that leg's anchor for no reason at all. - navigator.clipboard.writeText(text) - .then(() => { - copiedRef.current = held; - // ⭐ W52-T07: a NEW copy/cut is the closest thing to "the clipboard changed" this app can - // observe, so it replaces the marquee rather than requiring an Escape first. - setCopyMarquee({ col: held.col, row: held.row, cols: block[0]?.length ?? 0, - rows: block.length }); - }) - .then(() => { if (cut) clearSelection(); }) - .catch(() => onNotice("This browser did not let the sheet write to the clipboard. " - + "Press Ctrl+C instead.")); + runCopySelection(cut, viewRange, heldFor, copiedRef, setCopyMarquee, clearSelection, onNotice); }, [clearSelection, heldFor, onNotice, viewRange]); /** @@ -2236,6 +2697,123 @@ export default function SheetGrid({ setAsk(null); }, [ask, onColumnWidth, onNotice, realCol, viewRange]); + // ═══════════════════════════════════════════════════════════════════════════════════════════ + // ⭐⭐ W54-T07 — AUTOFIT, AND THE TWO AXES ARE NOT SYMMETRICAL. SAY IT OUT LOUD. + // + // ⛔⛔ A COLUMN FITS ITSELF; A ROW MOVES THE SHARED BASE. That is a consequence of the document + // model and not a shortcut taken quietly. `SheetTab` carries `colWidths`, a real per-column map + // the server already persists, so AutoFit column width writes one width per selected column + // through the SAME `onColumnWidth` door the width dialog and the drag handle use, and it + // survives a reload for free. There is no `rowHeights` key anywhere in the contract, and + // inventing one here would be a contract change only the root may make (see `rowHeight`'s own + // declaration above, which says the same thing about the manual dialog). So AutoFit row height + // sets the sheet-wide BASE to fit the tallest content among the SELECTED rows. A reader who + // does not find this written down will read the difference as a bug. + // + // ⭐ THE MEASUREMENT IS THE PAINT'S OWN, TWICE OVER. It uses the module-level offscreen context + // and `wrapIntoLines` W54-T06 added for the row heights, and it builds the font string from the + // same `fontPx` / `fontStack` / `SIZE_PX` that `paintCell` builds it from, with the same + // padding. A column sized in Inter cannot then be painted in Georgia. + // + // ⚠ AND IT ANSWERS WITH A SENTENCE WHERE IT CANNOT MEASURE. `measureContext` is null where + // there is no document at all, and a selection of empty cells has no widest text; neither is + // allowed to become a guess that silently resizes somebody's sheet. + // ═══════════════════════════════════════════════════════════════════════════════════════════ + + /** + * The font string one cell's text is measured in, which is the string `paintCell` sets on the + * canvas before it draws that cell, plus the size in pixels the caller needs for a line height. + */ + const cellFontOf = useCallback((style: CellStyle | undefined) => { + // ⚠ READ ONCE INTO A LOCAL. `SIZE_PX` is keyed by the four step NAMES and `fontPx` takes the + // point number, so the branch has to narrow a slot that carries either; narrowing an optional + // chain rather than a plain value is the shape that silently stops narrowing. + const asked = style?.size; + const size = typeof asked === "number" + ? fontPx(asked) + : SIZE_PX[asked ?? "m"] ?? SIZE_PX.m; + const weight = style?.bold ? "600 " : ""; + const slant = style?.italic ? "italic " : ""; + return { + size, + font: `${slant}${weight}${size}px ${fontStack(style?.font, lightTheme.fontFamily)}`, + /** `paintCell`'s own left inset, indent included, mirrored so the two cannot disagree. */ + pad: 8 + Math.max(0, Math.min(MAX_CELL_INDENT, style?.indent ?? 0)) * 8, + }; + }, []); + + /** Widen or narrow every selected column to its own widest value. */ + const autoFitColumns = useCallback(() => { + const range = viewRange(); + const ctx = measureContext(); + if (!range || !ctx) { + onNotice("Select a cell in the columns to fit first, then fit them to their contents."); + return; + } + let fitted = 0; + for (let c = Math.min(range.col0, range.col1); c <= Math.max(range.col0, range.col1); + c += 1) { + const real = realCol(c); + let widest = 0; + for (const [addr, cell] of Object.entries(cells)) { + const at = splitAddress(addr); + if (!at || at.col - 1 !== real) continue; + const text = formatCellText(cell, displayText(cell)); + if (!text) continue; + const face = cellFontOf(cell?.style); + ctx.font = face.font; + // The right inset is the paint's own 8, the left one is `pad`, which carries the indent. + widest = Math.max(widest, ctx.measureText(text).width + face.pad + 8); + } + if (widest <= 0) continue; + onColumnWidth(real, Math.max(MIN_COL_WIDTH, + Math.min(MAX_COL_WIDTH, Math.ceil(widest)))); + fitted += 1; + } + if (fitted === 0) { + onNotice("These columns hold nothing to measure, so their width is left as it is."); + } + }, [cellFontOf, cells, onColumnWidth, onNotice, realCol, viewRange]); + + /** Raise or lower the sheet's row height to fit the tallest value in the selected rows. */ + const autoFitRows = useCallback(() => { + const range = viewRange(); + const ctx = measureContext(); + if (!range || !ctx) { + onNotice("Select a cell in the rows to fit first, then fit them to their contents."); + return; + } + const widthOf = new Map(); + for (const column of columns) widthOf.set(Number(column.id), column.width); + let tallest = 0; + for (let r = Math.min(range.row0, range.row1); r <= Math.max(range.row0, range.row1); + r += 1) { + const real = realRow(r); + for (const [addr, cell] of Object.entries(cells)) { + const at = splitAddress(addr); + if (!at || at.row - 1 !== real) continue; + const text = formatCellText(cell, displayText(cell)); + if (!text) continue; + const face = cellFontOf(cell?.style); + ctx.font = face.font; + // ⚠ ONLY A WRAPPED CELL RUNS TO MORE THAN ONE LINE. An unwrapped value is clipped by its + // own column rather than folded, so measuring it against the column's width would ask for + // room the paint will never use. + const width = widthOf.get(at.col - 1); + const lines = cell?.style?.wrap && width !== undefined + ? wrapIntoLines(ctx, text, width - face.pad - 8).length + : 1; + // The 8 is the paint's own top and bottom inset (4 each), exactly as `wrapHeights` uses. + tallest = Math.max(tallest, lines * Math.round(face.size * 1.35) + 8); + } + } + if (tallest <= 0) { + onNotice("These rows hold nothing to measure, so the row height is left as it is."); + return; + } + setRowHeight(Math.max(MIN_ROW_HEIGHT, Math.min(MAX_ROW_HEIGHT, Math.ceil(tallest)))); + }, [cellFontOf, cells, columns, onNotice, realRow, viewRange]); + /** * ⭐⭐ W51-T34 / R17 — THE ONE DOOR BOTH FREEZE AXES GO THROUGH, and it is the page's own * `onFreeze`, which is `setFreeze` behind `commitSheets`: one history step, one PUT, and the @@ -2389,6 +2967,39 @@ export default function SheetGrid({ // -- Styles. R8: this group is conditional formatting's ONLY door. ----------------------- case "conditional-formatting": setRulesOpen(true); return; + // ⭐⭐ W54-T05 — A COLOUR SCALE AND A DATA BAR ARE BUILT FROM THE SELECTION AND GO OUT + // THROUGH `saveRules`, WHICH IS THE DOOR THE DIALOG ALREADY USES. There is no second + // writer of `tab.rules` in this file and there must not be: the local list, the cap + // refusal and the "these last as long as the sheet stays open" notice all live behind + // that one function, and a second path would have to restate all three. + // + // ⚠ THE BOUNDS ARE MEASURED NOW AND STORED, WHICH IS A REAL LIMITATION RATHER THAN A + // SHORTCUT TAKEN QUIETLY. They ride `op: "between"` in `value` and `value2`, which the + // server already persists, so the rule survives a save with no new field; the price is + // that the scale does not re-normalise when the numbers later change. Make the rule + // again over the selection to re-measure it. `rules.ts::scaleRule` says the same thing + // where the decision lives. + case "colour-scale": case "data-bars": { + const addrs = selectedAddrs(); + const bounds = numericBounds(addrs.map((addr) => ruleSubject(cellAt(tab, addr)))); + if (!bounds) { + onNotice("Select a block of numbers first. A colour scale and a data bar both read " + + "the values in the selection to work out the range they spread across."); + return; + } + const range = selectionRange(); + const built = action.kind === "colour-scale" + ? scaleRule(range, bounds.low, bounds.high) + : barRule(range, bounds.low, bounds.high); + const out = addRule(rules, built); + if (out.refusal) { + onNotice(out.refusal); + return; + } + saveRules(out.rules); + return; + } + // -- Cells ------------------------------------------------------------------------------ case "insert-row": structure("row", 1); return; case "delete-row": structure("row", -1); return; @@ -2401,6 +3012,10 @@ export default function SheetGrid({ case "hide-rows": hideBand("row"); return; case "hide-columns": hideBand("col"); return; case "unhide": unhideAll(); return; + // ⭐ W54-T07 — the two AUTOFITS. Their asymmetry is stated where they are implemented, + // beside `applyAsk`, which is the writer they share with the manual dialog. + case "autofit-rows": autoFitRows(); return; + case "autofit-columns": autoFitColumns(); return; // ⭐⭐ W51-T34 / R17 — THE FREEZE ACT OPENS THE PANES PANEL NOW, because R17 asks for // ROWS AND COLUMNS and a single toggle can only ever answer one of them. Every // act the toggle had is still inside it, freezing the first column included, and @@ -2416,14 +3031,119 @@ export default function SheetGrid({ case "clear-formats": clearSelectionWith("formats"); return; case "clear-all": clearSelectionWith("all"); return; + // ⭐⭐ W54-T07 — FIND AND SELECT'S THREE, AND NOT ONE OF THEM BUILDS A SURFACE. + // + // ⛔ `find` DOES EXACTLY WHAT Ctrl+F DOES, to the byte, because it is the same box: opening + // it fresh over an open one would throw away a query somebody is halfway through typing, + // which is why both doors take the `was ?? ...` shape rather than assigning. + // ⛔ `replace` OPENS THAT SAME BOX with its second row showing. There is no second find box + // in this app and there must not be: a second matcher would eventually disagree with + // `findMatches` about what a formula cell says, and nothing would report the difference. + // ⭐ `go-to` FOCUSES THE FORMULA BAR'S CELL ADDRESS INPUT, which is Excel's Name Box and + // already jumps to whatever address is typed into it. Reaching it by its accessible name + // is the idiom `Ribbon.tsx`'s own roving focus uses to reach a control it does not hold a + // ref to, and the bar is rendered INSIDE this component's wrapper, so the query is + // scoped to this grid rather than to the document. + case "find": + setFind((was) => was ?? { query: "", at: -1 }); + return; + case "replace": + setFind((was) => ({ + query: was?.query ?? "", at: was?.at ?? -1, + replace: was?.replace ?? "", replacing: true, + })); + return; + case "go-to": { + const box = wrapRef.current?.querySelector( + 'input[aria-label="Cell address"]', + ); + if (!box) { + onNotice("The cell address box is not on screen, so there is nowhere to type an " + + "address to go to."); + return; + } + box.focus(); + box.select(); + return; + } + default: { const _exhaustive: never = action.kind; return _exhaustive; } } - }, [anchorStyle, applyStyle, autoSum, clearSelection, clearSelectionWith, copySelection, + }, [anchorStyle, applyStyle, autoFitColumns, autoFitRows, autoSum, clearSelection, + clearSelectionWith, copySelection, fillSelection, frozenCols, frozenRows, hideBand, onGrow, onNotice, onOpenImport, onRefresh, - pasteFromClipboard, rowHeight, stepIndent, structure, toggleFormatPainter, unhideAll]); + pasteFromClipboard, rowHeight, rules, saveRules, selectedAddrs, selectionRange, stepIndent, + structure, tab, toggleFormatPainter, unhideAll]); + + // ═══════════════════════════════════════════════════════════════════════════════════════════ + // ⭐⭐ W54-T19 (INSTRUCTION 13) — THE HALF OF THE DEFECT THAT NEVER REACHES glide AT ALL. + // + // ⛔⛔ MEASURED, NOT REASONED. At 1440x900 against a real authenticated sheet: with the canvas + // focused, twelve ArrowDown and eight ArrowRight move the selection and every scroll offset on + // the page stays at zero. Blur the canvas so `document.body` holds the keyboard, and fifteen + // ArrowDown drag `.dvn-scroller` from 0 to 600 while the selection does not move one cell. + // `.dvn-scroller` is glide's own scroller (6836 tall inside a 653 tall box), so the page LOOKS + // like the sheet scrolled itself and the selected cell sits frozen where it was. That is the + // owner's report exactly, and no edit to the handler above can reach it: glide's `onKeyDown` + // fires only while its canvas holds the keyboard. + // + // ⛔⛔ SO THE FIX IS THE FOCUS, NOT THE KEY. The scroll is the browser's answer to an arrow that + // nothing owns, so the sheet stops letting the keyboard fall on the floor in the first place: + // whenever focus goes NOWHERE while the sheet is up, the grid takes it straight back, and the + // next arrow reaches glide and moves the selection exactly as it does in the healthy path. + // Every one of the ticket's states resolves to the same one cause. A fast click on a chrome + // region that takes no focus, and an overlay that closes while its own focused node unmounts, + // both leave `document.activeElement` on ``; a menu, a text box or a button that DOES + // hold focus is never touched here, because focus did not go nowhere. + // + // ⛔ AND IT IS THE ONLY SHAPE AVAILABLE, WHICH IS WORTH RECORDING RATHER THAN REDISCOVERING. + // `verify_grid_ux.py`'s W52-T07 contract C8 leg asserts that this file contains NO raw keydown + // listener at all, so that Escape can never be answered anywhere but the one arbiter. A + // document level key guard for the arrows would red that leg. Reaching for the focus instead + // satisfies both rules honestly rather than dodging one of them. + // + // ⚠ DEFERRED BY ONE FRAME, AND RE-TESTED. A click that lands somewhere focusable blurs first + // and focuses second, so claiming the keyboard synchronously inside `focusout` would fight the + // very gesture that is about to place it correctly. One frame later the browser has settled, + // and the claim happens only if the keyboard is still nowhere. + // + // ⚠ TWO GRIDS AND ONE EDITOR. A selection inside the frozen band lives on the band's own + // `DataEditor` (`frozenSelection`), and while a formula is being authored the arrows belong to + // that input's point mode, so the claim goes to whichever of the three currently owns them. + // + // ⛔ NOTHING HERE READS Escape, in any branch. Escape belongs to the sheet's own arbiter and to + // DESIGN.md section 4. + // ═══════════════════════════════════════════════════════════════════════════════════════════ + useEffect(() => { + let frame = 0; + const claim = () => { + const at = document.activeElement; + // Somebody took the keyboard in the meantime, which is the outcome this wants anyway. + if (at !== null && at !== document.body && at !== document.documentElement) return; + if (document.querySelector(MODAL_SELECTOR)) return; + if (formulaEdit) { + formulaInputRef.current?.focus(); + return; + } + (inBand ? bandGridRef : gridRef).current?.focus(); + }; + const rescue = (event: FocusEvent) => { + // A related target means another control took the keyboard on purpose. Only a focus that + // went NOWHERE is the state an arrow scrolls in. + if (event.relatedTarget !== null) return; + if (!document.hasFocus()) return; + frame = window.requestAnimationFrame(claim); + }; + document.addEventListener("focusout", rescue, true); + claim(); + return () => { + window.cancelAnimationFrame(frame); + document.removeEventListener("focusout", rescue, true); + }; + }, [formulaEdit, inBand]); // ═══════════════════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W51-T17 — RULING R7's EXCEL WORKING SET, THROUGH THE ONE TABLE IN `shortcuts.ts`. @@ -2445,14 +3165,101 @@ export default function SheetGrid({ // ⚠ AND Ctrl+F IS NOT SWALLOWED WHERE THE SHEET IS NOT LOOKING. This handler is glide's own // `onKeyDown`, which fires only while the grid canvas holds the keyboard, so the browser's find // still opens everywhere else on the page. That is why there is no document listener here. + // ⚠ W54-T19 KEPT IT THAT WAY. The arrow that never reaches this handler is answered by taking + // the FOCUS back (the effect above), not by reading keys off the document, so contract C8's + // "no raw keydown listener in this file" still holds and Escape still has exactly one arbiter. // ═══════════════════════════════════════════════════════════════════════════════════════════ const onKeyDown = useCallback( (event: { key: string; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean; altKey: boolean; cancel: () => void; preventDefault: () => void; }) => { + // ═════════════════════════════════════════════════════════════════════════════════════ + // ⭐⭐ W54-T28 (INSTRUCTION 19, R9(iv)) — ENTER DOWN, TAB RIGHT, AND THE RETURN. + // + // R9(iv), verbatim: "Commit navigation: Enter down, Tab right, Shift+Enter up, Shift+Tab + // left, and Enter returns to the column the Tab run started at." + // + // ⛔⛔ THE DEFECT, MEASURED IN A REAL BROWSER AT 1440x900 READING BOTH THE ADDRESS BOX AND + // `document.activeElement`. On an empty sheet at B3, Enter left the address at B3 and put + // the focus in a `gdg-input` textarea; Shift+Enter did the same. Three Tabs reached E3 + // correctly, and the Enter after them opened an editor on E3 rather than landing on B4. An + // arrow pressed next then read as inert, because the editor was sitting open swallowing it. + // + // ⛔⛔ THE CAUSE IS ONE STRING, AND IT IS DELIBERATELY NOT CHANGED. `KEYBINDINGS` above + // binds `activateCell` to space, Enter, shift+Enter and F2, so the grid library ACTIVATED + // the cell instead of committing and moving. That library calls THIS handler first and + // skips its own table entirely once the press has been cancelled, so answering the four + // keys here leaves the string exactly as it was - which matters twice over: W54-T25's F2 + // clause depends on `activateCell` still carrying F2, and space still starts an edit. + // + // ⛔ TAB AND SHIFT+TAB WERE ALREADY RIGHT, AND THEY ARE STILL BROUGHT THROUGH HERE. The + // library binds neither, so they were moving the selection by the browser's own focus + // traversal through the accessibility table - which is why the measurement found the focus + // on a `TD` afterwards, one press away from leaving the grid altogether. Answering all four + // in one arm is what makes the run's origin knowable, and stopping the browser is what + // keeps the keyboard on the canvas so the next arrow key works straight away. + // + // ⛔ IT SITS ABOVE THE SHORTCUT LOOKUP, NOT INSIDE EITHER BRANCH BELOW. `commitDirection` + // refuses any press carrying Ctrl, Meta or Alt, so Ctrl+Enter still fills the selection and + // Alt+Enter still inserts a line break; nothing else in the table claims a bare Enter or + // Tab. Arrows are untouched, because that same function answers null for all four of them. + // + // ⚠ THE ARITHMETIC IS NOT HERE. `commitDirection`, `commitTarget` and `tabRunOrigin` live + // in the import-free `shortcuts.ts`, so a gate RUNS R9(iv) rather than reading it. + // + // ⚠ THE BOUNDS ARE ASKED FOR, NEVER WRITTEN DOWN. `visCols` and `visRows` come from the + // open sheet's own extent (W54-T29 moved it to 200 by 10,000), and the row floor is the + // frozen band's negative range, so Shift+Enter can still walk up into a frozen row. + // ═════════════════════════════════════════════════════════════════════════════════════ + const commit = commitDirection(event); + const commitFrom = selection?.current?.cell; + if (commit !== null && commitFrom) { + event.cancel(); + event.preventDefault(); + const origin = tabRunAt.current; + const land = commitTarget( + { col: commitFrom[0], row: commitFrom[1] }, commit, origin, + { + minCol: 0, + maxCol: Math.max(0, visCols.length - 1), + minRow: -bandRows, + maxRow: Math.max(0, visRows.length - 1), + }, + ); + tabRunAt.current = tabRunOrigin(origin, commit, commitFrom[0]); + commitNav.current = true; + applySelection({ col0: land.col, row0: land.row, col1: land.col, row1: land.row }); + return; + } + const hit: ShortcutId | null = matchShortcut(event); + // ═════════════════════════════════════════════════════════════════════════════════════ + // ⭐⭐ W54-T19 (INSTRUCTION 13) — AN ARROW STOPS THE BROWSER FIRST, BEFORE ANY BRANCHING. + // + // ⛔⛔ THE DEFECT, AND IT IS INSIDE glide RATHER THAN IN THIS FILE. glide 6.0.3 matches an + // arrow through its own keybindings and then sets `cancelOnlyOnMove`, so it stops the + // browser ONLY when the selection actually moved. On the last row, the last column, or + // with no current cell, the match happens, the move does not, nothing stops the browser, + // and the native arrow scroll runs on `.dvn-scroller` instead. That is the owner's exact + // report, word for word: the cell freezes in place and the page scrolls. + // + // ⛔ SO IT SITS ABOVE ALL THREE EXITS. The `hit === null` fall through returns early for a + // plain arrow, and `shortcutOwner(hit) === "canvas"` returns early for Shift+Arrow, so a + // guard placed after either one would miss the two commonest presses in the sheet. + // + // ⛔ IT STOPS THE BROWSER AND NOTHING ELSE. This is deliberately not the `cancel` half of + // the pair used below: cancelling would tell glide to keep its hands off, and glide is + // precisely the thing that MOVES the selection for a plain arrow and extends it for + // Shift+Arrow. Stopping only the native scroll leaves both of those exactly as they were. + // + // ⚠ AND IT IS THE FOUR ARROWS ONLY. A blanket stop on every key here would swallow the + // printable character that opens the formula editor a few lines below, and typing in a + // sheet would stop working. + // ═════════════════════════════════════════════════════════════════════════════════════ + if (isArrowKey(event.key)) event.preventDefault(); + if (hit === null) { // ⭐⭐ R5 (W52-T09): TYPING OVER A BOUND CELL NO LONGER ASKS FIRST. A bound cell is still // `readonly` (glide's own type-to-edit never opens for it), so the keystroke still has to @@ -2474,6 +3281,39 @@ export default function SheetGrid({ const inBand = current.cell[1] < 0; const viewCell: readonly [number, number] = inBand ? [current.cell[0], current.cell[1] + bandRows] : current.cell; + // ═══════════════════════════════════════════════════════════════════════════════════ + // ⭐⭐ W54-T22 (INSTRUCTION 16) — ONE `=` PRODUCES ONE `=`, NEVER TWO. + // + // ⛔⛔ THE DEFECT, MEASURED IN A REAL BROWSER AT 1440x900, THREE TIMES. Click a cell, + // press `=` once, and the floating editor holds `==`. Press `=` then `1` and it holds + // `==1`. Type `=1+1` and it holds `==1+1`. ONLY THE FIRST CHARACTER DOUBLES, and that + // is most of the diagnosis: a handler running twice would double every key, and a + // concatenating draft would grow without bound. It is ONE extra insertion, arriving + // exactly at the moment this component's editor mounts and takes the keyboard. + // + // ⛔⛔ THE CAUSE IS THE MISSING SECOND DOOR, AND THE TWO DOORS ARE INDEPENDENT. glide's + // `cancel` is glide-only - it raises glide's own cancelled flag and stops glide - while + // `preventDefault` is the real DOM one that stops the BROWSER. The two branches below + // took only the first, so the browser's own default action for that same keydown still + // ran; by the time it did, the effect beside `formulaEdit` had focused + // `formulaInputRef`, so the browser typed the character a SECOND time into an input + // whose draft `openFormulaEditor` had already set to exactly that character. Every + // later keystroke arrives once because by then the input is the only thing focused and + // `onFormulaChange` reads its value raw. + // + // ⛔ SO THE STOP IS SCOPED TO THE BRANCHES THAT OPEN THIS COMPONENT'S OWN EDITOR, and + // the predicate is hoisted so ONE decision covers both of them. Every other printable + // character falls through to glide's OWN type-to-edit overlay, which mounts an empty + // textarea and RELIES on that same default action to deliver its first character. A + // blanket stop here would make typing a letter open an empty editor and swallow the + // keystroke, so this must never widen past the two branches below. + // + // ⚠ IT HOLDS IN THE FROZEN BAND FOR FREE: both `DataEditor` mounts are wired to this + // one handler, so there is no second copy of this decision to keep in step. + // ═══════════════════════════════════════════════════════════════════════════════════ + const opensOwnEditor = !!(cell && cell.kind === "bound") + || (!validationOf(cell) && (cell?.kind === "formula" || event.key === "=")); + if (opensOwnEditor) event.preventDefault(); if (cell && cell.kind === "bound") { event.cancel(); openFormulaEditor(addr, event.key, 1, viewCell, inBand); @@ -2508,8 +3348,26 @@ export default function SheetGrid({ case "jump-edge": case "extend-edge": { const step = arrowStep(event.key); if (!step || !cur) return; - const col = realCol(cur.cell[0]); - const row = realRow(cur.cell[1]); + // ⭐⭐ W54-T20 — TWO PERPENDICULAR PRESSES LEAVE A BLOCK, NOT A LINE. + // + // ⛔ THE EXTENSION TRAVELS FROM THE CURRENT RECTANGLE'S ACTIVE END, and it moves ONE + // axis. Handing the anchor in on both axes, which is what this arm used to do, made + // every press recompute a fresh jump from the anchor and collapse the axis it was not + // moving, so Ctrl+Shift+Down followed by Ctrl+Shift+Left replaced a column with a row. + // The anchor still never moves: it is passed to `applySelection` unchanged, and it is + // one corner of the rectangle {@link extendEdgeRect} returns. + const anchor = { col: cur.cell[0], row: cur.cell[1] }; + const axis: SelectionAxis = step.dRow !== 0 ? "row" : "col"; + const held: SelectionRect = { + col0: cur.range.x, row0: cur.range.y, + col1: cur.range.x + cur.range.width - 1, + row1: cur.range.y + cur.range.height - 1, + }; + const startAt = hit === "extend-edge" + ? edgeStart(held, anchor, axis) + : (axis === "row" ? anchor.row : anchor.col); + const col = realCol(axis === "row" ? anchor.col : startAt); + const row = realRow(axis === "row" ? startAt : anchor.row); // ⛔ THE EDGE IS COMPUTED IN THE SHEET'S OWN COORDINATES AND MAPPED BACK. A run of // values is a run of ADDRESSES; walking glide's visible rows would stop at a hidden // band and call it the end of the data. @@ -2521,7 +3379,7 @@ export default function SheetGrid({ applySelection({ col0: to.col, row0: to.row, col1: to.col, row1: to.row }); } else { applySelection( - { col0: cur.cell[0], row0: cur.cell[1], col1: to.col, row1: to.row }, + extendEdgeRect(held, anchor, axis === "row" ? to.row : to.col, axis), cur.cell, ); } @@ -2801,6 +3659,30 @@ export default function SheetGrid({ const { ctx, rect, col, row } = args; const cell = cells[addrAt(col, row)] ?? null; + // ═══════════════════════════════════════════════════════════════════════════════ + // ⭐ WAVE 54 BASE KIT — THE SPARKLINE SEAM, ASKED AS EARLY AS THE SIGNATURE ALLOWS. + // + // `drawSparkline` is handed the cell, so this is the first statement that can possibly call + // it: `cell` has to be read first. It answers `false` today and NOTHING changes; when lane B + // fills it in, a `true` means that cell's whole paint belonged to the sparkline. + // + // ⛔ THE TRUE BRANCH IS A BARE `return;`, AND THAT IS DELIBERATE TWICE OVER. glide 6.0.3 + // ignores a `DrawCellCallback`'s return (see D-642 above), so `return;` is the only way to + // say "done"; and the gates COUNT the other calls rather than merely looking for them -- + // `verify_api.py` pins the default renderer at EXACTLY two call sites and `verify_grid_ux.py` + // pins the marquee closure at exactly three, on the RAW file, so adding either call here + // would red a leg belonging to a different ticket for a line that changed no pixel. ⚠ That + // also means naming those calls in prose HERE, with their parentheses and semicolon, moves a + // count: this note says them in words on purpose. + // + // ⚠ LANE B: THIS RETURNS BEFORE `ruleStyleAt` AND BEFORE ALL FOUR OVERLAY CLOSURES + // (`paintRefBorder`, `paintMarquee`, `paintShimmer`, `paintMark`). A sparkline cell therefore + // wears NO conditional-format rule, NO copy marquee, NO reference border and NO corner mark + // unless you decide it should and call them. That decision is yours; the seam does not make + // it for you. + // ═══════════════════════════════════════════════════════════════════════════════ + if (cell && drawSparkline(ctx, rect, cell, cells)) return; + // ═══════════════════════════════════════════════════════════════════════════════ // ⭐⭐ W51-T18 — THE RULE IS ASKED BEFORE THE EARLY RETURN, AND THAT IS THE HALF // THAT GETS MISSED. `is empty` is one of C2's ten operators, so a rule over @@ -2818,6 +3700,12 @@ export default function SheetGrid({ // written to the document, which is what keeps a rule editable and reversible. // ═══════════════════════════════════════════════════════════════════════════════ const ruleStyle = ruleStyleAt(rules, realCol(col), realRow(row), ruleSubject(cell)); + // ⭐⭐ W54-T05 — THE DATA BAR IS ASKED SEPARATELY BECAUSE A PROPORTION IS NOT A STYLE. + // `RuleStyle` can say a fill, an ink and a weight; it cannot say "three fifths of the way + // across this cell". Both questions walk the SAME first-match list inside `rules.ts`, so the + // bar and the fill can never come from two different rules, and a bar rule answers the style + // door with an empty style: it claims the cell against the rules below it without filling it. + const ruleBar = ruleBarAt(rules, realCol(col), realRow(row), ruleSubject(cell)); // ⭐⭐ W52-T06 / CR-1, CR-5, CR-10, PM-6 — THE COLOURED REFERENCE BORDER. Read BEFORE the // `!cell` early return, for the same reason `ruleStyle` is (W51-T18's own note two lines up): @@ -2962,6 +3850,10 @@ export default function SheetGrid({ // ⭐ `drawContent()` IS the default renderer, and it must run BEFORE the mark so // the mark sits on top of the value rather than under it. drawContent(); + // ⭐ W54-T14 / LANE B — the link underline and the note corner, in BOTH branches for the + // same reason R19's own mark is in both: an attachment on a bold cell would otherwise + // vanish, and a cell that shows nothing of what it carries carries it invisibly. + paintCellMarks(ctx, rect, cell); paintShimmer(); paintMark(); paintRefBorder(); @@ -2978,6 +3870,19 @@ export default function SheetGrid({ ctx.fillRect(rect.x + 1, rect.y + 1, rect.width - 1, rect.height - 1); } + // 1b. THE DATA BAR, AFTER THE BACKGROUND AND BEFORE THE TEXT CLIP, which is the whole of the + // ordering decision: painted later it would cover the number it measures, and painted + // inside the clip it would be cut by the text box rather than by the cell. The fraction + // is already clamped to 0..1 by the engine; the extra guard here is against a width of + // zero, which some canvas implementations still stroke as a hairline. + if (ruleBar && ruleBar.fraction > 0) { + const barWidth = Math.max(1, Math.round((rect.width - 2) * ruleBar.fraction)); + ctx.save(); + ctx.fillStyle = tokenColour(ruleBar.fill, "#dbeafe"); + ctx.fillRect(rect.x + 1, rect.y + 2, barWidth, rect.height - 3); + ctx.restore(); + } + // 2. THE TEXT, clipped to its own cell. A long bold value must stop at the column // edge exactly as glide's does, or it paints over its neighbour's value. ctx.beginPath(); @@ -2988,10 +3893,20 @@ export default function SheetGrid({ // are settled BEFORE anything is measured. A canvas measures text in the font that is // set at the time, so choosing the size after `measureText` would centre a heading // using the body size's width. - const size = SIZE_PX[style.size ?? "m"] ?? SIZE_PX.m; + // ⭐⭐ W54-T03 / R11 — TWO SHAPES, ONE SLOT, AND THE PIXELS DO NOT MOVE. A `size` that is one + // of C2's four step NAMES is still read out of the table above, byte for byte as it was; a + // size that is a NUMBER is a POINT size and goes through `fontPx`. The two agree by + // construction: 8, 10, 12 and 15 points round to 11, 13, 16 and 20 px, which is exactly what + // that table holds, so every cell styled before this ticket paints at the size it always did. + // ⭐ W54-T03 / R10 — AND THE FACE IS THE CELL'S OWN. `fontStack` resolves the stored NAME to + // a stack ending in a generic family, falling back to the grid's own Inter when the cell + // names none. The app's chrome is unaffected: this is one canvas string, on cell text only. + const size = typeof style.size === "number" + ? fontPx(style.size) + : SIZE_PX[style.size ?? "m"] ?? SIZE_PX.m; const weight = style.bold ? "600 " : ""; const slant = style.italic ? "italic " : ""; - ctx.font = `${slant}${weight}${size}px ${lightTheme.fontFamily}`; + ctx.font = `${slant}${weight}${size}px ${fontStack(style.font, lightTheme.fontFamily)}`; ctx.fillStyle = tokenColour(style.color ?? "", lightTheme.textDark ?? "#202433"); ctx.textBaseline = "middle"; @@ -3008,17 +3923,11 @@ export default function SheetGrid({ const inner = rect.width - pad - 8; const lines: string[] = []; if (style.wrap && text) { - let line = ""; - for (const word of text.split(/\s+/)) { - const next = line ? `${line} ${word}` : word; - if (line && ctx.measureText(next).width > inner) { - lines.push(line); - line = word; - } else { - line = next; - } - } - if (line) lines.push(line); + // ⭐ W54-T06 MOVED THE LOOP ITSELF to `wrapIntoLines` at the top of this file, unchanged, + // and called it from BOTH here and `wrapHeights` below. The row's height and the row's + // paint are now one measurement asked twice rather than two measurements that agree by + // inspection: a wrapped value that needs three lines is given three lines of room. + lines.push(...wrapIntoLines(ctx, text, inner)); } else { lines.push(text); } @@ -3031,11 +3940,42 @@ export default function SheetGrid({ if (valign === "top") top = rect.y + 4 + lineHeight / 2; else if (valign === "bottom") top = rect.y + rect.height - 4 - block + lineHeight / 2; + // ═══════════════════════════════════════════════════════════════════════════════ + // ⭐⭐ W54-T06 — THE TURN, AND THE SIGN IS THE WHOLE OF IT. + // + // `CellStyle.textRotation` is Excel's own signed degree: POSITIVE is counterclockwise, the + // way a protractor reads and the way `core/sheets.py::_clean_style` clamps it. A canvas y + // grows DOWNWARD, so the same visual turn is a NEGATIVE `rotate`, and the negation happens + // once, here, rather than in the gallery that writes the number: what the document stores + // stays the number a person asked for. + // + // ⛔ THE CONTEXT IS TURNED ABOUT THE CELL'S OWN CENTRE, INSIDE THE TEXT CLIP that was set a + // few lines above, so a turned value still stops at its own cell edge instead of writing + // over its neighbour. It is also inside the one `ctx.save()` this branch already opened, so + // the transform is undone by the `ctx.restore()` that was always there and the borders, + // marks and marquees below are painted in untouched device space. + // + // ⚠ A TURNED RUN IS CENTRED IN BOTH AXES, whatever the cell's align and valign say. Those + // two describe where a HORIZONTAL run sits against the cell's corners, and a run leaving its + // corner at an angle simply leaves the box: left-aligned at 90 degrees the whole value would + // be clipped away and the control would read as broken. Excel makes the same trade. + // ═══════════════════════════════════════════════════════════════════════════════ + const turn = typeof style.textRotation === "number" ? style.textRotation : 0; + if (turn !== 0) { + const cx = rect.x + rect.width / 2; + const cy = rect.y + rect.height / 2; + ctx.translate(cx, cy); + ctx.rotate((-turn * Math.PI) / 180); + ctx.translate(-cx, -cy); + top = cy - block / 2 + lineHeight / 2; + } + lines.forEach((line, index) => { const width = ctx.measureText(line).width; let x = rect.x + pad; if (style.align === "center") x = rect.x + (rect.width - width) / 2; else if (style.align === "right") x = rect.x + rect.width - 8 - width; + if (turn !== 0) x = rect.x + (rect.width - width) / 2; const y = top + index * lineHeight; ctx.fillText(line, x, y); // 3. THE UNDERLINE is drawn, not requested: a canvas has no text decoration, so the @@ -3048,24 +3988,14 @@ export default function SheetGrid({ ctx.restore(); // 4. THE BORDERS, outside the text clip so a side lands ON the cell edge. - const border = style.border; - if (border) { - ctx.save(); - ctx.strokeStyle = tokenColour("--lp-line-strong", "#c9ced8"); - ctx.lineWidth = 1; - ctx.beginPath(); - const left = rect.x + 0.5; - const top = rect.y + 0.5; - const right = rect.x + rect.width - 0.5; - const bottom = rect.y + rect.height - 0.5; - if (border.top) { ctx.moveTo(left, top); ctx.lineTo(right, top); } - if (border.bottom) { ctx.moveTo(left, bottom); ctx.lineTo(right, bottom); } - if (border.left) { ctx.moveTo(left, top); ctx.lineTo(left, bottom); } - if (border.right) { ctx.moveTo(right, top); ctx.lineTo(right, bottom); } - ctx.stroke(); - ctx.restore(); - } - + // ⭐ WAVE 54 BASE KIT: the paint itself moved to `cellBorders.ts` unchanged, so the border + // work and the rest of this hub file can be edited by two lanes at once. The `if (border)` + // guard moved with it, which is why an absent `style.border` is handed over rather than + // tested here. + paintCellBorders(ctx, rect, style.border); + + // ⭐ W54-T14 / LANE B — the attachment marks, this branch's half of the pair above. + paintCellMarks(ctx, rect, cell); paintShimmer(); paintMark(); paintRefBorder(); @@ -3089,6 +4019,188 @@ export default function SheetGrid({ [bandRows, paintCell], ); + // ═══════════════════════════════════════════════════════════════════════════════════════════ + // ⭐⭐ W54-T06 — A WRAPPED ROW GETS TALLER, AND ITS HEIGHT IS DERIVED RATHER THAN STORED. + // + // ⛔⛔ NOTHING NEW IS WRITTEN TO THE DOCUMENT, AND THAT IS THE DESIGN RATHER THAN A SHORTCUT. + // A row's needed height is a pure function of facts the tab ALREADY persists: which cells wrap, + // what they say, the face and size they say it in, and how wide their column is. So there is no + // `rowHeights` key to invent, no second writer of geometry to keep in step with `colWidths`, + // and the done-when's "survives a reload" holds for free: `_clean_style` round-trips the `wrap` + // flag, and the height falls out of it on the next render. + // + // ⭐ THE MEASUREMENT IS THE PAINT'S OWN. Same `wrapIntoLines`, same font string built from the + // same `fontPx` / `fontStack` / `SIZE_PX` the styled branch uses, same padding, same 1.35 line + // height. A row sized in Inter cannot then be painted in Georgia. + // + // ⚠ KEYED BY THE SHEET'S ROW, NOT THE VIEW'S, so hiding a row or a column moves nothing: the + // lookup below translates through `realRow`, exactly as `addrAt` does. + // ═══════════════════════════════════════════════════════════════════════════════════════════ + const wrapHeights = useMemo(() => { + const out = new Map(); + const ctx = measureContext(); + if (!ctx) return out; + // ⛔ A HIDDEN COLUMN CONTRIBUTES NOTHING. `columns` is the VISIBLE table, so a wrapped cell + // in a column nobody can see has no width to wrap against and no say in the row's height. + const widthOf = new Map(); + for (const column of columns) widthOf.set(Number(column.id), column.width); + for (const [addr, cell] of Object.entries(cells)) { + const style = cell?.style; + if (!style?.wrap) continue; + const at = splitAddress(addr); + if (!at) continue; + const width = widthOf.get(at.col - 1); + if (width === undefined) continue; + const text = formatCellText(cell, displayText(cell)); + if (!text) continue; + const size = typeof style.size === "number" + ? fontPx(style.size) + : SIZE_PX[style.size ?? "m"] ?? SIZE_PX.m; + const weight = style.bold ? "600 " : ""; + const slant = style.italic ? "italic " : ""; + ctx.font = `${slant}${weight}${size}px ${fontStack(style.font, lightTheme.fontFamily)}`; + const pad = 8 + Math.max(0, Math.min(MAX_CELL_INDENT, style.indent ?? 0)) * 8; + const count = wrapIntoLines(ctx, text, width - pad - 8).length; + // The 8 is the paint's own top and bottom inset (4 each), which is what `valign` top and + // bottom measure from, so a row is exactly as tall as the block plus the room it sits in. + const needed = Math.min(MAX_ROW_HEIGHT, count * Math.round(size * 1.35) + 8); + const row = at.row - 1; + out.set(row, Math.max(out.get(row) ?? 0, needed)); + } + return out; + }, [cells, columns]); + + /** + * ⭐⭐ THE HEIGHT GLIDE IS HANDED, AS A FUNCTION OF THE ROW. `DataEditor` takes + * `number | ((index: number) => number)`, so this is a supported shape rather than a trick. + * + * ⛔⛔ AND `rowHeight` STAYS A NUMBER IN SCOPE UNDER THAT EXACT NAME. The Row height dialog + * writes it, the chart anchors read it, and the frozen band's box is + * `HEADER_HEIGHT + bandRows * rowHeight` -- a uniform assumption `verify_api.py` byte-pins. So + * the manual ask still sets the BASE and this only ever raises it: a derived height can never + * go below the height a person asked for. + */ + const rowHeightAt = useCallback( + (index: number) => Math.max(rowHeight, wrapHeights.get(realRow(index)) ?? 0), + [realRow, rowHeight, wrapHeights], + ); + /** + * ⭐ W54-T12 / LANE B — THE ONE CHART WRITER, LIFTED OUT OF `insertDoor` SO THE DRAG CAN SHARE + * IT. Two writers of one list is the defect this file already carries a rule about: the local + * fallback and its notice have to read the same whichever gesture produced the new list, or a + * chart dragged on an unwired page would save while a chart inserted on it would not. + */ + const writeCharts = useCallback((next: SheetChartSpec[]) => { + if (!onCharts) { + setChartsLocal({ tabId: tab.id, charts: next }); + onNotice("This chart sits on the sheet for as long as it stays open. Saving it with the " + + "workbook arrives with the page's own door."); + return; + } + onCharts(next); + }, [onCharts, onNotice, tab.id]); + + /** + * ⭐⭐ W54-T12 / LANE B — A PIXEL DELTA BECOMES A CELL RANGE, AND ONLY THIS FILE CAN DO IT. + * + * ⛔ A CHART ANCHORS TO A RECTANGLE OF CELLS, so "move" and "resize" both mean editing `range` + * and neither means storing a pixel. `SheetChart.tsx` owns the GESTURE and reports what the + * pointer travelled; the geometry that turns that into columns and rows is here, because only + * this component knows each column's own width, which rows are hidden, and where the visible + * table starts. + * + * ⚠ THE COLUMN STEP IS A NEAREST-BOUNDARY WALK RATHER THAN A DIVISION. Column widths differ + * since W50-T20, so dividing by an average drifts by a whole column as soon as somebody has + * dragged one, and it drifts more the further right the chart sits. + * + * ⛔ IT CLAMPS AT BOTH ENDS AND NEVER INVERTS. A resize moves the FAR corner only and is held + * at or past the near one, so a range cannot turn inside out and cannot leave the sheet. + */ + const nudgeChart = useCallback( + (chart: SheetChartSpec, dx: number, dy: number, mode: "move" | "resize") => { + const lo = Math.min(chart.range.col0, chart.range.col1); + const hi = Math.max(chart.range.col0, chart.range.col1); + const top = Math.min(chart.range.row0, chart.range.row1); + const bottom = Math.max(chart.range.row0, chart.range.row1); + const viewLo = visCols.indexOf(lo); + const viewHi = visCols.indexOf(hi); + const viewTop = visRows.indexOf(top); + const viewBottom = visRows.indexOf(bottom); + if (viewLo < 0 || viewHi < 0 || viewTop < 0 || viewBottom < 0) return; + + const nearestView = (x: number) => { + let best = 0; + let bestGap = Infinity; + for (let i = 0; i < visCols.length; i += 1) { + const gap = Math.abs(columnX(i) - x); + if (gap < bestGap) { bestGap = gap; best = i; } + } + return best; + }; + const clamp = (v: number, low: number, high: number) => Math.min(high, Math.max(low, v)); + const lastCol = visCols.length - 1; + const lastRow = visRows.length - 1; + + let nextLo = viewLo; + let nextHi = viewHi; + let nextTop = viewTop; + let nextBottom = viewBottom; + if (mode === "move") { + const stepCols = clamp( + nearestView(columnX(viewLo) + dx) - viewLo, -viewLo, lastCol - viewHi, + ); + const stepRows = clamp( + Math.round(dy / rowHeight), -viewTop, lastRow - viewBottom, + ); + nextLo = viewLo + stepCols; + nextHi = viewHi + stepCols; + nextTop = viewTop + stepRows; + nextBottom = viewBottom + stepRows; + } else { + nextHi = clamp(nearestView(columnX(viewHi + 1) + dx) - 1, viewLo, lastCol); + nextBottom = clamp(viewBottom + Math.round(dy / rowHeight), viewTop, lastRow); + } + const range = { + col0: visCols[nextLo], col1: visCols[nextHi], + row0: visRows[nextTop], row1: visRows[nextBottom], + }; + if (range.col0 === chart.range.col0 && range.col1 === chart.range.col1 + && range.row0 === chart.range.row0 && range.row1 === chart.range.row1) return; + writeCharts(charts.map((c) => (c.id === chart.id ? { ...c, range } : c))); + }, + [charts, columnX, rowHeight, visCols, visRows, writeCharts], + ); + + /** + * ⭐⭐ W54-T10 / LANE B — THE INSERT TAB'S DOOR, BUILT WHERE THE DOCUMENT ACTUALLY IS. + * + * ⛔ IT IS NOT A NEW `RibbonActionKind`, and that is deliberate rather than a shortcut: the act + * union is closed by the exhaustive switch at the bottom of `onRibbonAction`, and a chart, a + * sparkline, a link and a note are DOCUMENT WRITES rather than named acts. They take the + * document's own doors, one per level. `onCells` IS `onCommit`, so a sparkline, a link and a + * note are one history step and one save exactly like a paste; `onCharts` is the tab-level door + * above, with its local fallback while the page has not wired one. + * + * ⛔ AND THE SELECTION CROSSES IN SHEET COORDINATES, TRANSLATED HERE. glide's indices count + * VISIBLE rows and columns, so `realCol` / `realRow` run before the rectangle leaves this file. + * A ribbon tab must never see a view index: it has no way to know one from a real one. + */ + const insertDoor = useMemo(() => { + const range = viewRange(); + return { + selection: range ? { + col0: realCol(Math.min(range.col0, range.col1)), + row0: realRow(Math.min(range.row0, range.row1)), + col1: realCol(Math.max(range.col0, range.col1)), + row1: realRow(Math.max(range.row0, range.row1)), + } : null, + charts, + onCharts: writeCharts, + onCells: onCommit, + cellAt: (col: number, row: number) => cellAt(tab, addressOf(col, row)), + }; + }, [charts, onCommit, realCol, realRow, tab, viewRange, writeCharts]); + return (
    {/* ⭐ THE HOME RIBBON, THEN THE FORMULA BAR, THEN THE CELLS. That order is instruction 10 @@ -3104,6 +4216,7 @@ export default function SheetGrid({ canImport={onOpenImport !== undefined} onApply={applyStyle} onAction={onRibbonAction} + insert={insertDoor} /> {/* ⛔ NOTHING WHEN THERE IS NOTHING. An empty wrapper here would take padding and a border @@ -3208,8 +4321,12 @@ export default function SheetGrid({ setDropdown({ addr: clicked, anchor: rectAnchor(args.bounds), query: "" }); return; } + // ⭐ W54-T14 / LANE B — a linked cell is FOLLOWED on click, in the band exactly + // as in the body: the address is already the main grid's, through `fromBand`. + if (followCellLink(clicked)) return; setAnchor(args.bounds); }} + onItemHovered={(args: GridMouseEventArgs) => onNoteHover(args, true)} onCellContextMenu={(item: Item, args) => { args.preventDefault(); setAnchor(null); @@ -3267,7 +4384,11 @@ export default function SheetGrid({ // constant the single source of that geometry rather than a guess about a library. // ⭐ W51-T16: the Row height dialog writes this, and the chart anchors below read the // SAME state, so a taller row moves a chart with its cells instead of leaving it behind. - rowHeight={rowHeight} + // ⭐⭐ W54-T06: IT IS A FUNCTION OF THE ROW NOW, and `rowHeight` is still its floor. A + // row carrying a wrapped value is as tall as that value needs; every other row is + // exactly the height it was. The FROZEN BAND above deliberately keeps the plain number + // -- see `rowHeightAt`'s own note and the band's `height` expression. + rowHeight={rowHeightAt} rowMarkers="number" // ⚠ ALSO PASSED FOR THE SAME REASON, AND IT WAS WRONG BEFORE. glide derives the row // marker width from the row COUNT (36 px at 200 rows), while `ROW_MARKER_WIDTH` here is @@ -3300,6 +4421,7 @@ export default function SheetGrid({ fillHandle onCellEdited={onCellEdited} onCellsEdited={onCellsEdited} + onDelete={() => false} onPaste={onPaste} onFillPattern={onFillPattern} onKeyDown={onKeyDown} @@ -3360,8 +4482,18 @@ export default function SheetGrid({ setDropdown({ addr: clicked, anchor: rectAnchor(args.bounds), query: "" }); return; } + // ⭐⭐ W54-T14 / LANE B — A LINKED CELL IS FOLLOWED ON CLICK, and the action bar + // yields to it for the reason the dropdown two lines up already does: two surfaces + // over one cell is one too many, and the underline is what advertised the gesture. + // A target that does not resolve says so here, in one sentence, which is exactly + // where `platform/core/sheets.py` left that decision. + if (followCellLink(clicked)) return; setAnchor(args.bounds); }} + // ⭐ W54-T14 / LANE B — the note bubble's own gesture. Hover is read off the SAME + // callback for both grids, told which one is asking, so a note on a frozen row opens + // its bubble at the row a person is actually pointing at. + onItemHovered={(args: GridMouseEventArgs) => onNoteHover(args, false)} // ⭐ AND THE COLUMN HEADER'S OWN CLICK, which the library offers directly. glide has // already written a `columns` selection by the time this runs, for the same reason and // with the same problem; this replaces it with the rectangle the acts read. @@ -3416,7 +4548,9 @@ export default function SheetGrid({ right if the positioning parent WAS the canvas box; sitting in `.sheet-grid-wrap` they were already the height of `.sheet-grid-head` too low, and the ribbon above would have added its own height to the same error. */} - {(tab.charts ?? []).map((chart) => { + {/* ⭐ W54-T10 / lane B — `charts` rather than `tab.charts` directly: the same + document-or-local expression the rules list already uses, resolved once above. */} + {charts.map((chart) => { const lo = Math.min(chart.range.col0, chart.range.col1); const hi = Math.max(chart.range.col0, chart.range.col1); const top = Math.min(chart.range.row0, chart.range.row1); @@ -3438,19 +4572,34 @@ export default function SheetGrid({
    + {/* ⭐ W54-T12 / lane B — THE KIND GOES THROUGH RAW. It used to be narrowed to the + four the shared viz renderer draws, which meant a person who chose Pie got a bar + chart with nothing on screen saying so; `SheetChart.tsx` now owns that switch and + draws the rest itself. The two callbacks below carry a PIXEL delta, because a + chart anchors to CELLS and only this file can turn pixels into a range. */} nudgeChart(chart, dx, dy, "move")} + onResize={(dx, dy) => nudgeChart(chart, dx, dy, "resize")} />
    ); @@ -3609,10 +4758,7 @@ export default function SheetGrid({ max={ask.kind === "row-height" ? MAX_ROW_HEIGHT : MAX_COL_WIDTH} value={ask.value} onChange={(e) => setAsk({ ...ask, value: Number(e.target.value) })} - onKeyDown={(e) => { - if (e.key === "Enter") applyAsk(ask.value); - else if (e.key === "Escape") setAsk(null); - }} + onKeyDown={(e) => { if (e.key === "Enter") applyAsk(ask.value); }} />
    + + {/* ⭐⭐ W54-T07 — REPLACE LIVES IN THE FIND BOX, AND THAT IS THE WHOLE POINT. Excel + shows Find and Replace as two tabs of one dialog; this app already had the find + half, so the ticket grew it a second row rather than building a second search + surface that would have to agree with this one about what a match is. + ⛔ IT IS SHOWN ONLY WHERE IT WAS ASKED FOR. Ctrl+F and the ribbon's Find item leave + `replacing` absent and this panel is byte for byte the panel it has always been; the + ribbon's Replace item sets it. A person who asked to find is not handed a field that + can overwrite their sheet. + ⚠ SAME CONTROL VOCABULARY, NO NEW SHAPE: the input is `.sheet-find-input` and the + two buttons are `.sheet-find-btn`, which already reset their own native chrome and + already carry the focus ring this row uses (DESIGN.md sections 2 and 4). */} + {find.replacing && ( + <> + + setFind({ ...find, replace: e.target.value })} + onKeyDown={(e) => { + if (e.key === "Enter") { + e.preventDefault(); + replaceMatches(find.query, find.replace ?? "", false); + } + }} + /> + + + + )} + + ))} +
    + + + ); + + // ── W54-T03 (instruction 4, R10 + R11): what the Font group READS off the anchor cell ────── + // + // ⭐⭐ NO NEW ACT AND NO SHELL EDIT. `apply()` already takes a `CellStylePatch` and `style` is + // already the anchor cell's own style, so the family picker is a patch, the size box is a patch + // and each stepper is a patch computed from the size that is there. `RibbonActionKind` gains no + // member and `SheetGrid.tsx::onRibbonAction` gains no case, which is what keeps this ticket + // inside one lane's files. + // + // ⚠ THE GRID'S `case "font-size":` ARM SURVIVES AND IS SIMPLY NO LONGER SPOKEN TO. It maps the + // retired Small/Normal/Large/Heading menu onto the four step names; nothing in this file emits + // that act any more, and the arm is in a file this lane does not own. + const points = fontPt(style?.size); + const family = style?.font ?? DEFAULT_CELL_FONT; + + /** + * Read the size box and write what it asked for, NORMALIZING the box either way. + * + * ⚠ IT CLAMPS RATHER THAN REFUSES, exactly as the rotation and the indent do: 400 is somebody + * asking for the largest there is, not an entry that has to be rejected. Text that is not a + * number at all snaps back to the size the cell already had, so the box can never be left + * showing something the document does not say. + */ + const commitPoints = (input: HTMLInputElement) => { + const asked = Number.parseInt(input.value.trim(), 10); + const next = Number.isFinite(asked) ? clampFontPt(asked) : points; + input.value = String(next); + if (next !== points) apply({ size: next }); + }; + + // ── W54-T06 (instruction 5, R2): what the Alignment group READS off the anchor cell ────── + // + // ⚠ UPRIGHT IS AN ABSENCE, so the readback normalizes it to zero rather than to `undefined`: + // the gallery's Horizontal entry has to be able to show as the one that is ON, and a cell that + // was never turned is exactly as horizontal as one that was turned back. + const rotation = typeof style?.textRotation === "number" ? style.textRotation : 0; + const turned = rotation !== 0; + + const format = style?.format; + const kind: CellFormatKind = format?.kind ?? "general"; + const decimals = format?.decimals ?? (kind === "currency" ? 2 : 0); + /** Stepping decimals on a date or on an unformatted cell means the cell becomes a number. */ + const numeric: CellFormatKind = + kind === "currency" || kind === "percent" ? kind : "number"; + + const stepDecimals = (delta: number) => onApply({ + format: { + ...format, + kind: numeric, + decimals: Math.min(10, Math.max(0, decimals + delta)), + }, + }); + + return ( + <> + {/* ⭐⭐ W52-T16 (instruction 18, ruling R4) — THE ARRANGEMENT INSTRUCTION 18 NAMES + EXPLICITLY: a large split Paste on the left (icon above, caption below) with Cut, + Copy and Format painter stacked as three small icon+label rows to its right, + exactly like Excel's own Clipboard group. + ⚠ DOCUMENTED DEVIATION (contract C4) — real Excel's Paste is a SPLIT button: a + direct click pastes, and a separate caret opens Paste Special and friends. This + app's `RibbonActionKind` union (`SheetGrid.tsx`'s exhaustive switch, OUTSIDE this + ticket's file fence) has no act for those sub-options, and adding one is lane B's + surface, not this ticket's. So Paste stays a SINGLE button here — same tall + left-slot layout Excel uses, still firing `act("paste")` directly on click, with + `data-kt="V"` and no `data-kt-opens` (it does not actually open a menu in this + codebase). The LAYOUT is what instruction 18 and R4 ask for; the backend act stays + exactly what W51-T16 already built. */} + {group("Clipboard", ( +
    + + {control("paste", "Paste", <>{}{word("Paste")}, + () => act("paste"), false, undefined, "V")} + + {/* ⭐⭐ W53-T06 (owner instruction 17) — CUT, COPY AND FORMAT PAINTER ARE ICONS, + WITH NO WORD BESIDE THEM. Excel's Clipboard group is one large captioned Paste + and three small icon-only controls; a caption beside a 26px button is the one + thing its Home ribbon never does. Paste KEEPS its caption, and that is the + faithful reading rather than an inconsistency: the researched convention is + that only a wide combo box or a TALL two-row-spanning button carries text, and + the large Paste is exactly that. + ⛔ THE LABEL IS NOT DELETED, ONLY THE PAINTED WORD. `control()` writes its + `label` argument into BOTH `aria-label` and `title`, so a screen reader still + announces "Format painter" and a hover still says it. That matters twice over: + `verify_api.py`'s `_RIBBON_GROUPS` pins the literals `"Cut"`, `"Copy"` and + `"Format painter"` as the proof this group still offers what R8 names, and an + icon-only control with no accessible name is a regression no gate in this repo + would catch. */} +
    + {control("cut", "Cut", , () => act("cut"), + false, undefined, "X")} + {control("copy", "Copy", , () => act("copy"), + false, undefined, "C")} + {control("painter", "Format painter", , + () => act("format-painter"), false, undefined, "FP")} +
    +
    + ))} + + {/* ⭐⭐ W54-T03 (owner instruction 4, rulings R10 + R11) — THE FONT GROUP IS EXCEL'S OWN + TWO ROWS. Top row: the font FAMILY combo, then the editable font SIZE box with its own + gallery caret, then Increase and Decrease font size. Bottom row: bold, italic, underline, + then borders, fill colour and text colour, which is exactly what this group carried + before. The mechanism is the one Clipboard and Alignment already established: a COLUMN + wrapper inside `.sheet-ribbon-group-controls`, each row a plain row flex of the SAME + `.sheet-ribbon-btn` buttons, no new control shape and no new button size. + + ⛔⛔ TWO ROWS IS NOT MERELY FAITHFUL, IT IS THE CONSTRAINT (D-663). The strip already + overflows: measured on this tree at 1440x900, Cells and Editing are past the right edge + already, and a family combo added to a single-line Font group would have pushed Number off + too. Two 26px rows fill `--sheet-ribbon-band` exactly, so the ribbon does not grow by a + pixel in either direction; the group is in fact NARROWER than the one line it replaces. + + ⭐ R10 IN ONE SENTENCE: the family control styles CELL CONTENT and nothing else. The + shell, this ribbon and every label stay Inter; what a person sets a cell in is that cell's + data, exactly as its fill colour is, and `types.ts`'s note on `CELL_SIZES` was rewritten + in this same change to say so rather than to say the opposite. + ⭐ R11 IN ONE SENTENCE: the size box widens the EXISTING `size` slot to a point size on + both halves of the document. There is no second `fontSize` field to disagree with it. */} + {group("Font", ( +
    +
    + {/* ⚠ THE COMBO SHOWS THE FACE THE ANCHOR CELL IS IN, and it names the default rather + than going blank when the cell carries none: a blank combo reads as "no answer" + where the truth is "the default one". */} + + {control("font", "Font", <>{word(family)}, + openPop("font"), !!style?.font, open === "font", + "FF", "gallery")} + {open === "font" && ( + + {/* ⛔ EACH NAME IS PREVIEWED IN ITS OWN FACE, which is why these are written out + rather than passed through `item()`. The inline `fontFamily` is the SAME + carve-out the colour swatches above take for their inline `background`: what + is being shown is the DATA a person is choosing, not app chrome, so the token + scale has nothing to say about it. No size is set here, and none may be. */} + {CELL_FONTS.map((name) => ( + + ))} + + )} + + + {/* ⛔⛔ THE BOX COMES BEFORE THE CARET INSIDE THE SLOT, AND THAT ORDER IS LOAD BEARING + TWICE OVER. It is Excel's own arrangement, and `verify_ui.py::_RIBBON_KEYTIPS` pins + `control("size", ...)` to the sequence "FS" by scanning forward from that call, so + nothing may sit between the call and its own key-tip argument. + ⚠ THE INPUT IS THE ONE RIBBON CONTROL THAT MUST TAKE FOCUS. Every button here + cancels its own mousedown so the canvas keeps the keyboard; a box a person types a + number into cannot do that. The selection is React state in `SheetGrid.tsx` and is + not glide's to drop, so the patch still lands on the cells that were selected. */} + + { + // The toolbar's arrows belong to the toolbar only outside a text box. Inside one + // they belong to the caret, so this handler keeps them. + e.stopPropagation(); + if (e.key === "Enter") e.currentTarget.blur(); + if (e.key === "Escape") { + e.currentTarget.value = String(points); + e.currentTarget.blur(); + } + }} + onBlur={(e) => commitPoints(e.currentTarget)} + /> + {control("size", "Font size", , + openPop("size"), false, open === "size", + "FS", "gallery")} + {open === "size" && ( + + {FONT_SIZE_STEPS.map((step) => item( + String(step), () => apply({ size: step }), step === points, "menuitemradio", + ))} + + )} + + + {/* ⭐ THE TWO STEPPERS WALK THE GALLERY'S OWN LIST AND STOP AT ITS ENDS. `stepFontPt` + returns the size it was given when there is no next entry, so the largest and the + smallest are quiet no-ops rather than an error or a wrap around. From a size that is + not on the list at all, it walks to the nearest entry in the direction asked for. */} + {control("grow", "Increase font size", , + () => apply({ size: stepFontPt(points, 1) }), false, undefined, "FG")} + {control("shrink", "Decrease font size", , + () => apply({ size: stepFontPt(points, -1) }), false, undefined, "FK")} +
    + +
    + {control("bold", "Bold", B, + () => apply({ bold: !style?.bold }), style?.bold === true, undefined, "1")} + {control("italic", "Italic", + I, + () => apply({ italic: !style?.italic }), style?.italic === true, undefined, "2")} + {control("underline", "Underline", + U, + () => apply({ underline: !style?.underline }), style?.underline === true, + undefined, "3")} + + + {control("border", "Borders", <>, + openPop("border"), + Object.values(style?.border ?? {}).some(Boolean), open === "border", + "B", "gallery")} + {open === "border" && ( + + {BORDERS.map((entry) => item( + entry.label, () => apply({ border: entry.sides }), false, "menuitem", entry.kt, + ))} + {item("No border", () => apply({ border: null }), false, "menuitem", "N")} + + )} + + + {/* ⚠ FILL COLOUR AND TEXT COLOUR BOTH OPEN A SWATCH POPOVER IN THIS CODEBASE + (`open === "fill"` / `open === "color"`), so both carry `data-kt-opens` + per the general C4 rule even though the ticket's own inline example list did + not annotate Fill colour with "/opens" — a judgment call, documented here and + in the HANDOFF, resolved in favour of matching the code's real behaviour. */} + + {control("fill", "Fill colour", + <>, + openPop("fill"), !!style?.fill, open === "fill", + "H", "gallery")} + {open === "fill" && swatches("fill", FILLS)} + + + {control("color", "Text colour", + <>, + openPop("color"), !!style?.color, + open === "color", "FC", "gallery")} + {open === "color" && swatches("color", INKS)} + +
    +
    + ))} + + {/* ⭐⭐ W53-T05 (instruction 16) — ALIGNMENT IS TWO ROWS, NOT ONE LINE. Excel stacks + the vertical three over the horizontal three and hangs the rest to their right; + one long line was this group's only real departure from it. The mechanism is the + one `.sheet-ribbon-clip-stack` already established for Clipboard: a COLUMN wrapper + inside `.sheet-ribbon-group-controls`, which is itself a row flex, with each row a + plain row flex of the SAME `control()` buttons. No new control shape, no new + button size, and the two rows total 52px, which is exactly the height Clipboard's + large Paste already sets, so the ribbon does not grow by a pixel. + ⚠ THE SIX ALIGNMENT BUTTONS STAY ICON ONLY, and so does Wrap text: the researched + Excel convention is that only a WIDE combo box or a TALL two-row-spanning button + carries a caption, and none of these is either. `control()` writes the label into + both `aria-label` and `title`, so every one of them keeps its accessible name. + ⭐⭐ W54-T06 LANDED ORIENTATION, and the reason W53-T05 could not is worth keeping: + it assumed a new control meant a new `RibbonActionKind`, and the shell's switch + closes on `const _exhaustive: never = action.kind`, which no single lane could + extend. The base kit changed that answer by declaring `CellStyle.textRotation`, so + the turn is a STYLE PATCH through the `apply()` door every colour already uses and + no act was needed at all. + ⛔ MERGE AND CENTER IS STILL NOT HERE, and its reason has not changed: it needs a + merged-cell model `sheet/types.ts` does not have, so a control rendered anyway + would be the fake affordance `RibbonProps` refuses by name. Raised in the HANDOFF + as a PRD amendment instead. */} + {group("Alignment", ( +
    +
    + {/* ⚠ TOP/MIDDLE/BOTTOM VERTICAL ALIGN HAS NO ROW IN THE TICKET'S OWN INLINE + KeyTip LIST (it names align top/middle/bottom as one of the examples with no + row to copy). `AT`/`AM`/`AB` follows the same two-letter shape the spec's + real Excel sequences use for the horizontal three (`AL`/`AC`/`AR`). */} + {control("top", "Align top", , () => act("align-top"), + false, undefined, "AT")} + {control("middle", "Align middle", , + () => act("align-middle"), false, undefined, "AM")} + {control("bottom", "Align bottom", , + () => act("align-bottom"), false, undefined, "AB")} + {control("wrap", "Wrap text", , () => act("wrap-text"), + false, undefined, "W")} + + {/* ⭐⭐ W54-T06 (instruction 5, ruling R2) — TEXT ORIENTATION, AND IT NEEDED NO NEW + ACT. The base kit had already declared `CellStyle.textRotation` and + `core/sheets.py::_clean_style` already clamped and kept it, so `CellStylePatch` + carries the key and `apply({ textRotation: n })` writes it directly. That is why + this control could land inside one lane's files: `RibbonActionKind` gains no + member, so the shell's exhaustive switch in `SheetGrid.tsx` gains no arm and + `Ribbon.tsx` is untouched. The lane's OTHER three obligations were paid in the same + change - `stylePaints` counts the key, `paintCell` turns the canvas, and + `cellStyleOps.ts::STYLE_KEYS` names it so the Format painter clears it. + ⚠ FIVE ENTRIES, WHICH IS EXCEL'S OWN LIST MINUS THE ONE THIS SLOT CANNOT SAY. + Vertical stacked text is not a rotation at all (it is a per character layout), and + the slot is a signed degree between -90 and 90, so offering it would be a control + that writes nothing. + ⛔ HORIZONTAL WRITES `null`, NOT ZERO. `applyStylePatch` removes a null key, so a + cell turned and set back upright is byte for byte the cell it was; a stored zero + would leave an undo comparing unequal to the thing it undid. */} + + {control("orientation", "Orientation", <>, + openPop("orientation"), turned, open === "orientation", + "FQ", "gallery")} + {open === "orientation" && ( + + {ORIENTATIONS.map((entry) => item( + entry.label, + () => apply({ textRotation: entry.degrees === 0 ? null : entry.degrees }), + rotation === entry.degrees, + "menuitemradio", + ))} + + )} + +
    +
    + {/* ⛔ THIS `.map` STAYS A MAP. Unrolling it into three literal `control("left", + ...)` calls would delete the `to === "left" ? "AL" : ...` ternary that + `verify_ui.py::_RIBBON_ALIGN_H_TERNARY` pins byte for byte — the horizontal + three are the one trio whose key is a variable, which is why their key-tips + are checked as that one expression rather than per call. */} + {(["left", "center", "right"] as const).map((to) => control( + to, + to === "left" ? "Align left" : to === "center" ? "Align centre" : "Align right", + , + () => apply({ align: style?.align === to ? null : to }), + style?.align === to, + undefined, + to === "left" ? "AL" : to === "center" ? "AC" : "AR", + ))} + {control("outdent", "Decrease indent", , + () => act("indent-decrease"), false, undefined, "5")} + {control("indent", "Increase indent", , + () => act("indent-increase"), false, undefined, "6")} +
    +
    + ))} + + {group("Number", ( + <> + + {control("format", "Number format", + <>{FORMAT_LABEL[kind]}, + openPop("format"), kind !== "general", + open === "format", "N", "gallery")} + {open === "format" && ( + + {/* ⚠ FILTERED, AND D-671 IS WHY. Wave 54's base kit widened `CELL_FORMAT_KINDS` + to the server's six so the parity leg stops reading a drift, and `code` is the + sixth. `CellFormatKind` still EXCLUDES it, `types.ts` says in terms that the + ribbon's code item stays an ACT until W51-T20 lands the painter, and + `isCellFormatKind` is the predicate that file names for exactly this call. So + the menu offers the same five kinds it offered before, and the map is type + correct again rather than indexing a label table with a name that has no row. */} + {CELL_FORMAT_KINDS.filter(isCellFormatKind).map((entry) => ( + + ))} + {/* ⚠ THE TWO R8 NAMES THE DOCUMENT MODEL DOES NOT CARRY YET. They are acts, + not kinds: `clean_cell` refuses an unknown `format.kind` BY NAME, so + writing `accounting` here would refuse the whole cell. */} + {item("Accounting", () => act("format-accounting"))} + {item("Custom code", () => act("format-custom"))} + {/* ⚠ THE TWO OPTIONS A1 NAMES BY NAME: decimals, and thousands. They are + shown only where they mean something; a date has neither and a percent + groups by locale. */} + {(kind === "number" || kind === "currency" || kind === "percent") && ( +
    + Decimal places + + {decimals} + +
    + )} + {kind === "number" && ( + + )} +
    + )} +
    + + {/* ⚠ CURRENCY HAS NO ROW IN THE TICKET'S OWN INLINE KeyTip LIST (named as one of + the examples with no row to copy). `CU` is invented, non-colliding. */} + {control("currency", "Currency", + $, + () => apply({ format: { kind: "currency", decimals: 2 } }), + kind === "currency", undefined, "CU")} + {control("percent", "Percent", + %, + () => apply({ format: { kind: "percent", decimals: 0 } }), + kind === "percent", undefined, "P")} + {control("comma", "Comma", + ,, + () => apply({ format: { kind: "number", decimals: 2, thousands: true } }), + kind === "number" && format?.thousands === true, undefined, "K")} + {/* ⭐ THE TICKET'S OWN MAPPING: Increase decimal is the DIGIT `0`, decrease is `9` + (spec KT-T1 — Corporate Finance Institute's "Alt+H+O" for Increase Decimal is + almost certainly the digit rendered as a letter, since Decrease Decimal is + `9`). `decless` is this file's DECREASE control, `decmore` is INCREASE. */} + {control("decless", "Decrease decimals", , + () => stepDecimals(-1), false, undefined, "9")} + {control("decmore", "Increase decimals", , + () => stepDecimals(1), false, undefined, "0")} + + ))} + + {/* ⭐⭐ W53-T05 (D-663) — STYLES, CELLS AND EDITING ARE ICON ONLY FROM HERE. Measured + at the contract viewport, the seven groups wanted about 1,680px of the 864px the + ribbon actually has, so Styles, Cells and Editing were off the right edge entirely + and the owner could not see that AutoSum, Insert, Delete and Clear already exist. + A caption beside a small same-size button is also the one thing Excel's Home ribbon + never does: only a wide combo box or a tall two-row-spanning button carries text. + ⛔ THE LABEL IS NOT DELETED, ONLY THE PAINTED WORD. `control()` passes its `label` + into BOTH `aria-label` and `title`, so a screen reader still announces "Conditional + formatting" and a hover still says it. `verify_api.py`'s `_RIBBON_GROUPS` pins each + of those label literals, and they are all still right there in the call. */} + {/* ⭐⭐ W54-T05 (owner instruction 5, ruling R2) — STYLES IS TWO STACKED ROWS NOW. + + Conditional formatting became a GALLERY: highlight-cells rules still open the editor + W51-T18 built, and the two new items build a rule FROM THE SELECTION and route it through + the same `saveRules` door rather than opening a second one. Cell styles is a gallery of + named presets that write real `CellStyle` values. + + ⛔ FORMAT AS TABLE AND SORT AND FILTER ARE OUT, BY RULING R2, and that is a decision rather + than an omission. Owner, verbatim: the table function IS basically the data module itself, + so we do not need it. + + ⭐ THE TWO ROWS ARE A WIDTH DECISION, NOT A TIDY (D-663). The strip already overflows at + 1440x900, and a second control laid beside the first would have pushed Editing further + past the right edge. Stacked, the group is 26px wide plus its carets instead of twice + that, and two 26px rows come to exactly `--sheet-ribbon-band`, so the ribbon does not grow + by a pixel in either direction. Same mechanism Clipboard, Alignment and Font already use. + + ⛔ THE LABEL "Conditional formatting" IS BYTE-PINNED in `verify_api.py`'s `_RIBBON_GROUPS` + Styles tuple and its key-tip "L" in `verify_ui.py::_RIBBON_KEYTIPS`, so both stay exactly + where they were even though the control now opens a menu instead of firing an act. */} + {group("Styles", ( +
    + + {control("conditional", "Conditional formatting", + <>, + openPop("conditional"), false, open === "conditional", "L", "gallery")} + {open === "conditional" && ( + + {item("Highlight cells rules", () => act("conditional-formatting"))} + {item("Colour scales", () => act("colour-scale"))} + {item("Data bars", () => act("data-bars"))} + {item("Manage rules", () => act("conditional-formatting"))} + + )} + + + {control("cellstyles", "Cell styles", + <>, + openPop("cellstyles"), false, open === "cellstyles", "J", "gallery")} + {open === "cellstyles" && ( + + {/* ⛔ WRITTEN OUT RATHER THAN PASSED THROUGH `item()` FOR ONE REASON: each row + previews itself in the style it applies, which `item()` has no slot for. It is + the same carve-out the font family gallery above takes, and the click still + goes through the SAME `apply(...)` door every other control in this file uses, + with no act and no new plumbing at all. */} + {CELL_STYLES.map((preset) => ( + + ))} + + )} + +
    + ))} + + {/* ⭐⭐ THE CELLS GROUP IS WHERE THE OLD "Rows and columns" STRIP WENT. Every act it + carried is still here and still reaches the same page callback; what is gone is a + second toolbar of its own. */} + {group("Cells", ( + <> + + {control("insert", "Insert", <>{}, + openPop("insert"), false, open === "insert", + "I", "gallery")} + {open === "insert" && ( + + {item("Insert row above", () => act("insert-row"))} + {item("Insert column left", () => act("insert-column"))} + {item("Add rows", () => act("add-rows"))} + {item("Add columns", () => act("add-columns"))} + + )} + + + {control("delete", "Delete", <>{}, + openPop("delete"), false, open === "delete", + "D", "gallery")} + {open === "delete" && ( + + {item("Delete row", () => act("delete-row"))} + {item("Delete column", () => act("delete-column"))} + + )} + + + {control("cellformat", "Format", + <>{}, + openPop("cellformat"), false, + open === "cellformat", "O", "gallery")} + {open === "cellformat" && ( + + {item("Row height", () => act("row-height"))} + {item("Column width", () => act("column-width"))} + {/* ⭐⭐ W54-T07 — THE TWO AUTOFITS SIT BESIDE THE TWO MANUAL SIZES, which is + Excel's own arrangement and also the honest one: each pair is the same + question asked once by hand and once from the content. Both act on the + SELECTION, and the asymmetry between them is real rather than a shortcut, + so `SheetGrid.tsx` states it where it is implemented: the document stores a + width PER COLUMN and one shared row height, so a column fits itself and a + row moves the base. */} + {item("AutoFit row height", () => act("autofit-rows"))} + {item("AutoFit column width", () => act("autofit-columns"))} + {item("Hide rows", () => act("hide-rows"))} + {item("Hide columns", () => act("hide-columns"))} + {item("Unhide", () => act("unhide"))} + {/* ⭐ W51-T34 LANDED, so this OPENS a Freeze panes panel offering rows and + columns rather than toggling one column. The label had to move with the + behaviour: a control that says "Freeze first column" and opens a + two-axis panel is the kind of small lie an owner finds in the first + minute. `aria-checked` still reports whether ANYTHING is frozen, which + is the useful state for a person scanning the menu. + ⚠ THE LABEL IS BYTE-PINNED in `verify_api.py`'s `_RIBBON_GROUPS` Cells + tuple, so the two move in ONE commit or the rename reds a leg in a + ticket that never touched this file. */} + {item("Freeze panes", () => act("freeze"), frozen, + "menuitemcheckbox")} + + )} + + + ))} + + {/* ⭐⭐ W54-T07 (owner instruction 5, ruling R2) — EDITING IS TWO ROWS AND FINISHES THE GROUP. + Excel's Editing group is AutoSum, Fill, Clear, Sort & Filter and Find & Select; R2 removes + Sort & Filter outright (owner, verbatim: the table function IS basically the data module + itself), so what completes the group is Find and select and nothing else. + + ⛔ THE STACK IS A WIDTH DECISION (D-663), and this is the group where it bites hardest: + Editing is the LAST of the seven, so everything the six before it spend comes out of its + own right edge. Two 26px rows come to exactly `--sheet-ribbon-band`, so the ribbon does not + grow by a pixel in height, and three controls wide instead of five is a group NARROWER than + the one it replaces. Same mechanism Clipboard, Alignment, Font and Styles already use. + + ⭐ FIND AND SELECT OPENS THE FIND BOX THAT ALREADY EXISTS. `SheetGrid.tsx` has carried a + `role="search"` panel since W51-T17 and Ctrl+F already reaches it; all three items here + speak to that one surface, so there is no second find box in this app and no second place + for the two to disagree about what a match is. + ⛔ ITS KEY-TIP IS `SL`, NOT EXCEL'S `FD`. Excel's own Find & Select sequence collides here + with Fill down, whose `FD` is byte-pinned in `verify_ui.py::_RIBBON_KEYTIPS`; a duplicate + badge would make one of the two unreachable from the keyboard, so the newcomer takes the + free sequence rather than the incumbent giving up a pinned one. */} + {group("Editing", ( +
    +
    + {control("autosum", "AutoSum", , + () => act("autosum"), false, undefined, "U")} + {/* ⚠ FILL DOWN AND FILL RIGHT HAVE NO ROW IN THE TICKET'S OWN INLINE KeyTip LIST. + `FD`/`FR` are invented, non-colliding with `FP` (Format painter), `FS` (Font + size) or `FC` (Font colour). */} + {control("filldown", "Fill down", , + () => act("fill-down"), false, undefined, "FD")} + {control("fillright", "Fill right", , + () => act("fill-right"), false, undefined, "FR")} +
    +
    + + {control("clear", "Clear", <>{}, + openPop("clear"), false, open === "clear", + "E", "gallery")} + {open === "clear" && ( + + {item("Clear contents", () => act("clear-contents"))} + {item("Clear formats", () => act("clear-formats"))} + {item("Clear all", () => act("clear-all"))} + + )} + + + {control("findselect", "Find and select", <>, + openPop("findselect"), false, open === "findselect", + "SL", "gallery")} + {open === "findselect" && ( + + {item("Find", () => act("find"))} + {item("Replace", () => act("replace"))} + {/* ⭐ GO TO ADDS NO SURFACE OF ITS OWN. Excel's Name Box is already in this app, + as the formula bar's cell address input, and it already jumps to whatever + address is typed into it; what a Go to item owes a person is therefore the + focus, not a second dialog asking the same question. */} + {item("Go to", () => act("go-to"))} + + )} + +
    +
    + ))} + + ); +}; + +/** + * ⭐ THE DESCRIPTOR THE SHELL REGISTERS. `bodyClass` and `toolbarLabel` are here rather than in + * the shell because a tab-agnostic frame cannot know that the Home row is the Formatting toolbar; + * a second tab paints its own row under its own name through the same two fields. + */ +export const HOME_TAB = { + id: "home", + /** The tab button's own `data-ribbon` key, and its first-level key-tip badge (KT-4/KT-8). */ + key: "tab-home", + kt: "H", + label: "Home", + bodyClass: "sheet-ribbon-home", + toolbarLabel: "Formatting", + keys: HOME_KEYS, + groups: homeGroups, +} as const; diff --git a/web/src/sheet/ribbonInsert.tsx b/web/src/sheet/ribbonInsert.tsx new file mode 100644 index 0000000000000000000000000000000000000000..a6d6c4c751081f04031d5b55ef375cc2f9c50929 --- /dev/null +++ b/web/src/sheet/ribbonInsert.tsx @@ -0,0 +1,649 @@ +// sheet/ribbonInsert.tsx — the INSERT TAB of the Sheet's ribbon (wave 54, base kit part 2a; +// filled and REGISTERED by W54-T10, owner instruction 5, ruling R3). +// +// ⭐⭐ REGISTERED NOW, AND IT WAS NOT BEFORE ON PURPOSE. The base kit shipped this module exporting +// its descriptor with an EMPTY group list, and `Ribbon.tsx`'s `TABS` carried Home alone, because a +// registered empty tab paints a clickable tab that opens a blank toolbar row. W54-T10 gives the tab +// its four groups and adds its descriptor to that array in the same change, which is the whole of +// the wiring this module owes: the shell reads `keys` for the roving order, `groups` for the row, +// and the rest of the descriptor for the tab button. +// +// ⭐ WHAT A TAB MODULE OWES THE SHELL is set out in `ribbonHome.tsx`'s header, and this file is the +// same three exports: +// `INSERT_KEYS` the control keys this tab renders, IN ROVING ORDER. Every key here joins the +// shell's `ControlKey` union automatically, which is what makes a control rendered +// under an unlisted name a TYPE ERROR. +// `insertGroups` the groups, as a function of the shell's `RibbonTabContext`. +// `INSERT_TAB` the descriptor. +// +// ⛔⛔ RULING R3 — FOUR GROUPS, AND THE ABSENCES ARE THE RULING. Excel's own Insert tab in +// `reference/EXCEL 2.png` also carries Tables, PivotTable, Recommended PivotTables, Illustrations, +// Slicer, Timeline, Text and Symbols. NONE of them is here and none of them is coming: the DATA +// module exists exactly for tables and pivots, and R3 names the rest out. Ours is Charts, +// Sparklines, Links and Comments. +// +// ⛔⛔ THESE CONTROLS DO NOT ADD A NAMED ACT, AND THAT IS DELIBERATE. `RibbonActionKind` is closed +// by an exhaustive switch in `SheetGrid.tsx`, a file this lane does not own, so a new member would +// be a compile error in every lane at once. A chart, a sparkline, a link and a note are DOCUMENT +// WRITES rather than named acts, and they take the document's own doors instead, handed over as +// `ctx.insert` (`Ribbon.tsx::RibbonInsertDoor`): a chart is a TAB level key and takes the +// replace-the-list door, and the other three are CELL keys and take the same one commit door a +// style patch takes. +// ⚠ W54-T11 ADDS ONE CALL TO `act`, AND IT NAMES AN ACT THAT ALREADY EXISTED. The chart dialog's +// database tab writes bound cells, and a bound cell is `stale` until the workbook refreshes, so +// the block would sit empty without `refresh`. The union is untouched. +// +// ⛔ NO FAKE AFFORDANCE. `RibbonProps.canImport`'s own comment is the precedent: a control is +// offered only where a door for it exists. When `ctx.insert` is undefined every control below +// renders DISABLED, through a native `
    ` rather than a per-button flag, because +// the shell's shared `control(...)` helper takes no disabled argument and this lane may not widen +// it. In the app after `SheetGrid.tsx` wires the door it is never undefined; the fence is what +// keeps this module honest if the prop is ever dropped. +// +// ⚠ A TAB MODULE IS A FUNCTION, NOT A COMPONENT. `Ribbon.tsx` CALLS `activeTab.groups(ctx)` during +// its own render, so a hook here would attach to the shell and its order would change the moment +// somebody switched tabs. That is why the two small forms below are UNCONTROLLED: they read their +// value out of the submitted form rather than out of a `useState` this file cannot have. +// +// ⚠ DESIGN CONTRACT (DESIGN.md 2 through 5): inline SVG on `currentColor` and never emoji, token +// only colour and type, sentence case labels, no em dash or en dash in a string that reaches a +// screen, and the two overlay shapes kept apart: POPOVERS originate at their trigger through +// `AnchoredOverlay` (the link and comment forms) while MODALS REMAIN CENTRED (the chart dialog, +// through `useOverlayLayer` and `BodyPortal`). Never a local keydown listener in either case. + +import { useState } from "react"; +import type { FormEvent } from "react"; +import type { RibbonTabContext } from "./Ribbon"; +// ⭐⭐ W54-T11 (ruling R5) — THE CHART GALLERY IS GONE AND A DIALOG STANDS WHERE IT STOOD. R5 reads +// "A chart reads BOTH. A cell range, exactly like Excel, is the primary path; a database source is +// a second tab in the same dialog. Ship both." A gallery of eight kinds cannot carry a second +// source, so the eight kinds moved INTO the dialog and this tab keeps ONE Charts control that +// opens ONE surface. DESIGN.md 4: modals remain centred, which is what makes this a dialog rather +// than a wider popover. +// ⚠ THE HOOKS LIVE IN THE DIALOG, WHICH IS A REAL COMPONENT. `insertGroups` is a function the +// shell calls during its own render, so it still may not hold state of its own; `ChartDialog` may +// hold all it likes, and the shell's popover state is what mounts it. +import ChartDialog from "./ChartDialog"; +import type { ChartRange } from "./ChartDialog"; +// ⭐⭐ W54-T14 — THE LINK FORM MOVED OUT AND GREW THE OTHER TWO KINDS. W54-T10 shipped an +// uncontrolled one-field form here that could only write `kind: "url"`; a kind picker whose +// refusal has to survive a keystroke needs state, and `insertGroups` is a function the ribbon +// shell calls during its own render and may not hold one. So the Links group mounts a real +// component, exactly as the Charts group mounts `ChartDialog`, and that component owns its own +// anchored overlay. The Comments group's form stays uncontrolled: it has one field and no refusal. +import LinkDialog from "./LinkDialog"; +import type { CellLink } from "./LinkDialog"; +import { MAX_CELL_NOTE } from "./types"; +import type { Cell, SheetChartSpec, SparklineKind } from "./types"; +// ⭐ THE DOCUMENT'S OWN ADDRESSER, in SHEET coordinates. The door hands over a sheet-coordinate +// rectangle and a sheet-coordinate reader, so the address a cell edit is keyed by is built with +// the same function `SheetGrid.tsx` builds every other one with. A second spelling of A1 in this +// file would be a second answer to a question the document already answers. +import { addressOf } from "./sheetState"; +// ⭐ THE DOCUMENT'S OWN A1 PARSER, and the reason this ticket does not write a second one. A rule's +// range, a chart's range and a sparkline's range are all the same rectangle spelled the same way, +// so `D40:B2` normalises here exactly as it does in the conditional-format dialog. +import { parseRange } from "./rules"; +import type { RuleRect } from "./rules"; +import { AnchoredOverlay } from "../customer-grid/OverlaySurface"; +// ⭐ This tab's own stylesheet, a component-owned side-effect import, exactly as `ribbonHome.tsx` +// imports its own. See the stylesheet's header for what it restates and why. +import "../styles/wave54/ribbon-insert.css"; + +const CHARTS = ["chart"] as const; +const SPARKLINES = ["sparkline-line", "sparkline-column", "sparkline-winloss"] as const; +const LINKS = ["link"] as const; +const COMMENTS = ["comment"] as const; + +/** + * ⭐⭐ THE INSERT TAB'S ROVING ORDER, WHICH IS ALSO ITS TYPE. The shell spreads this into the union + * every `control(...)` key is checked against, so the arrays above are the single source of both + * the reading order and the vocabulary. + * ⛔ THE ARRAY IS THE ROVING SOURCE AND THE JSX IS NOT: a key listed here with no `control(...)` + * call rendering it makes ArrowRight land on nothing, with every gate still green, so the two are + * changed together or not at all. + */ +export const INSERT_KEYS = [...CHARTS, ...SPARKLINES, ...LINKS, ...COMMENTS] as const; + +/** + * ⭐ THE EIGHT KINDS AND THE FALLBACK RECTANGLE BOTH MOVED TO `ChartDialog.tsx` (W54-T11), which + * is where they are now chosen and computed. The dialog also SAYS which rectangle it will cover, + * which is what the retired gallery could not do: the range was grown silently, because + * `RibbonTabContext` carries no notice path and there was nowhere honest to say so. + */ + +/** A short unique id. No uuid library, and none is needed: this is a key within one document. */ +const chartId = (): string => + `ch-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 7)}`; + +function IconChart() { + return ( + + ); +} + +function IconSparkLine() { + return ( + + ); +} + +function IconSparkColumn() { + return ( + + ); +} + +function IconSparkWinLoss() { + return ( + + ); +} + +function IconLink() { + return ( + + ); +} + +function IconComment() { + return ( + + ); +} + +/** + * ⚠ `IconCaret` IS GONE WITH THE GALLERY (W54-T11). A caret says "a menu opens under this button", + * and the Charts control now opens a centred modal instead; wearing the caret would have promised + * the wrong surface. The two form popovers below never wore one. + */ + +// ═════════════════════════════════════════════════════════════════════════════════════════════ +// ⭐⭐ W54-T13 — THE TWO RANGES EXCEL ASKS FOR, AND WHY THE SECOND ONE IS NOT A FIELD ON THE SPEC. +// +// Excel's "Create Sparklines" asks for a DATA range and a LOCATION range, and W54-T10 shipped +// neither: it wrote one sparkline onto the cell the selection started on. That was the honest +// minimum for a tab that had to exist; a location range is what makes the group useful, because +// the ordinary case is one sparkline PER ROW of a block, not one sparkline for a block. +// +// ⛔ THE LOCATION IS THE CELL THE SPEC IS STORED ON. `CellSparkline` carries a DATA range and +// nothing else, deliberately: a location range of six cells is six cells each carrying their own +// spec over their own slice, which is what makes one of them movable, deletable and undoable on +// its own. Adding a `location` field would have given the document two answers to "where is this +// drawn" and let them disagree. +// +// ⛔ THE MAPPING IS STATED ON SCREEN, in one sentence, because it is the one thing a person cannot +// guess: N location cells split the data range into N slices ALONG THE OTHER AXIS. When the counts +// do not divide the form REFUSES rather than truncating, because a silently shortened range is a +// picture of data nobody chose. +// ═════════════════════════════════════════════════════════════════════════════════════════════ + +/** Where one sparkline goes, and the slice of the data range it draws. */ +interface SparkPlacement { + col: number; + row: number; + range: RuleRect; +} + +/** `B2` for one cell, `B2:E7` for a rectangle. The corners are normalised on the way in. */ +const rangeText = (r: RuleRect): string => { + const a = addressOf(Math.min(r.col0, r.col1), Math.min(r.row0, r.row1)); + const b = addressOf(Math.max(r.col0, r.col1), Math.max(r.row0, r.row1)); + return a === b ? a : `${a}:${b}`; +}; + +const many = (n: number, word: string): string => `${n} ${word}${n === 1 ? "" : "s"}`; + +const KIND_LABEL: Record = { + line: "Line sparkline", + column: "Column sparkline", + winloss: "Win loss sparkline", +}; + +/** + * ⭐ A SENSIBLE NEIGHBOUR, RATHER THAN AN EMPTY BOX. Excel leaves the location blank and makes the + * person work it out; the two shapes people actually select have an obvious answer, so it is + * offered and stays editable: + * • a single COLUMN of readings gets ONE cell directly under it, because slicing a column of + * numbers into one sparkline per number would draw a picture of one value; + * • anything else gets a COLUMN of cells directly to the right, one per row, which is the + * one sparkline per row that the group exists for. A single row is that same rule with one + * row in it, so it lands on the single cell to the right. + */ +const defaultLocation = (r: RuleRect): RuleRect => { + const c0 = Math.min(r.col0, r.col1); + const c1 = Math.max(r.col0, r.col1); + const r0 = Math.min(r.row0, r.row1); + const r1 = Math.max(r.row0, r.row1); + if (c0 === c1 && r1 > r0) return { col0: c0, row0: r1 + 1, col1: c0, row1: r1 + 1 }; + return { col0: c1 + 1, row0: r0, col1: c1 + 1, row1: r1 }; +}; + +/** + * THE MAPPING RULE, IN CODE. One cell takes the whole data range; a location COLUMN of N cells + * takes the rows of the data range in N equal slices; a location ROW of N cells takes its columns + * the same way. Anything that does not divide comes back as a refusal in one sentence. + */ +const planSparklines = ( + data: RuleRect, + loc: RuleRect, +): { items: SparkPlacement[] } | { why: string } => { + const dc0 = Math.min(data.col0, data.col1); + const dc1 = Math.max(data.col0, data.col1); + const dr0 = Math.min(data.row0, data.row1); + const dr1 = Math.max(data.row0, data.row1); + const lc0 = Math.min(loc.col0, loc.col1); + const lc1 = Math.max(loc.col0, loc.col1); + const lr0 = Math.min(loc.row0, loc.row1); + const lr1 = Math.max(loc.row0, loc.row1); + const lCols = lc1 - lc0 + 1; + const lRows = lr1 - lr0 + 1; + const n = lCols * lRows; + + if (n === 1) { + return { items: [{ col: lc0, row: lr0, range: { col0: dc0, row0: dr0, col1: dc1, row1: dr1 } }] }; + } + if (lCols > 1 && lRows > 1) { + return { why: "A location range of more than one cell has to be a single row or a single column." }; + } + + const items: SparkPlacement[] = []; + if (lCols === 1) { + const rows = dr1 - dr0 + 1; + if (rows % n !== 0) { + return { why: `Those counts do not divide: ${many(rows, "row")} into ${many(n, "cell")}.` }; + } + const step = rows / n; + for (let i = 0; i < n; i += 1) { + items.push({ + col: lc0, + row: lr0 + i, + range: { col0: dc0, col1: dc1, row0: dr0 + i * step, row1: dr0 + i * step + step - 1 }, + }); + } + return { items }; + } + + const cols = dc1 - dc0 + 1; + if (cols % n !== 0) { + return { why: `Those counts do not divide: ${many(cols, "column")} into ${many(n, "cell")}.` }; + } + const step = cols / n; + for (let i = 0; i < n; i += 1) { + items.push({ + col: lc0 + i, + row: lr0, + range: { row0: dr0, row1: dr1, col0: dc0 + i * step, col1: dc0 + i * step + step - 1 }, + }); + } + return { items }; +}; + +/** + * ⭐⭐ A REAL COMPONENT, AND THAT IS WHAT BUYS THE STATE. `insertGroups` is a FUNCTION the shell + * calls during its own render, so a `useState` written there would attach to the shell and its + * hook order would change the moment somebody switched tabs. The two older forms in this file + * dodged that by staying uncontrolled; a refusal has to survive a keystroke, so this one is + * mounted as a component instead. The shell's popover state is what mounts and unmounts it, which + * is also what re-seeds the two fields from the current selection each time it opens. + * + * ⚠ NO LOCAL KEYDOWN LISTENER. Escape comes from `AnchoredOverlay` and from nowhere else. + */ +function SparklineForm({ + kind, + selection, + onCreate, +}: { + kind: SparklineKind; + selection: RuleRect | null; + onCreate: (kind: SparklineKind, items: SparkPlacement[]) => void; +}) { + const seed: RuleRect = selection ?? { col0: 0, row0: 0, col1: 0, row1: 0 }; + const [data, setData] = useState(() => rangeText(seed)); + const [location, setLocation] = useState(() => rangeText(defaultLocation(seed))); + const [why, setWhy] = useState(""); + + const submit = (event: FormEvent) => { + event.preventDefault(); + const d = parseRange(data); + if (!d) { + setWhy("That data range is not an address like B2:E2."); + return; + } + const l = parseRange(location); + if (!l) { + setWhy("That location range is not an address like F2."); + return; + } + const plan = planSparklines(d, l); + if ("why" in plan) { + setWhy(plan.why); + return; + } + onCreate(kind, plan.items); + }; + + return ( +
    +

    {KIND_LABEL[kind]}

    + + + { setData(event.target.value); setWhy(""); }} + /> + + + { setLocation(event.target.value); setWhy(""); }} + /> + +

    + A location column of N cells takes N rows of the data range, a location row of N cells + takes N columns, and one cell takes the whole range. +

    + + {why &&

    {why}

    } + + +
    + ); +} + +export const insertGroups = (ctx: RibbonTabContext) => { + // ⚠ `item` IS NO LONGER TAKEN OFF THE CONTEXT, and that is W54-T11's doing rather than an + // oversight: the only menu this tab ever painted was the chart gallery, and the eight kinds are + // buttons inside `ChartDialog` now. The shell still offers the helper to every tab. + const { open, anchorEl, openPop, closePop, control, group, word, insert, act } = ctx; + + /** + * ⭐ THE ANCHOR CELL, IN SHEET COORDINATES. The door hands the selection over already translated + * (`SheetGrid.tsx` maps every view index through `realCol` / `realRow` before it gets here), so + * nothing in this file has to know that a hidden row moves what glide calls row 3. + */ + const anchorAt = (): { col: number; row: number } => { + const sel = insert?.selection; + if (!sel) return { col: 0, row: 0 }; + return { col: Math.min(sel.col0, sel.col1), row: Math.min(sel.row0, sel.row1) }; + }; + + /** + * ⭐⭐ THE ONE DOOR OUT OF THE DIALOG, AND BOTH TABS COME THROUGH IT (W54-T11, R5). + * + * The cell-range tab hands over a kind and a rectangle and nothing else, which is exactly what + * the retired gallery did. The database tab ALSO hands over the cells it wants written, and this + * is where the ordering matters: + * 1. the cells go in ONE call, so the block is ONE history step and ONE save; + * 2. the chart is anchored over the rectangle those cells occupy; + * 3. a refresh runs, because a `stale` cell holds no value until the workbook refreshes. + * + * ⛔ RULING R9 SURVIVES THIS INTACT. The chart still READS CELLS: it is handed a rectangle and + * never a database, a binding or a query, so there is still exactly one way to fetch a number in + * this document and it is the binding path a bound cell already uses. + * + * ⛔ `refresh` IS AN EXISTING `RibbonActionKind`. Nothing new joins that union here: adding a + * member would be a compile error in `SheetGrid.tsx`'s exhaustive switch, in every lane at once. + */ + const createChart = ( + kind: SheetChartSpec["kind"], + range: ChartRange, + cells?: Record, + ) => { + if (!insert) return; + if (cells) insert.onCells(cells); + insert.onCharts([...insert.charts, { id: chartId(), range, kind }]); + closePop(); + if (cells) act("refresh"); + }; + + /** + * ⭐⭐ EVERY LOCATION CELL IN ONE CALL, WHICH IS ONE HISTORY STEP AND ONE SAVE. `insert.onCells` + * takes many cells at a time for exactly this: six sparklines written one call each would be six + * undos to take back and six writes to the store for one gesture. + * + * ⚠ A CELL WITH NO RECORD BECOMES `empty` / `typed` CARRYING ONLY THE SPARKLINE. That is the + * shape W54-T09 provisioned server side (`platform/core/sheets.py::_clean_sparkline` keeps the + * slot on an empty cell), and it is the ordinary case: a sparkline cell usually holds no text. + * A cell that DOES have a record is amended rather than replaced, so a sparkline never eats a + * formula, a style or a binding, and the renderer draws it as an underlay under that cell's own + * value (`sheet/sparkline.ts`). + */ + const addSparklines = (kind: SparklineKind, items: SparkPlacement[]) => { + if (!insert) return; + const edits: Record = {}; + for (const item of items) { + const held = insert.cellAt(item.col, item.row); + const sparkline = { kind, range: item.range }; + edits[addressOf(item.col, item.row)] = held + ? { ...held, sparkline } + : { kind: "empty", state: "typed", sparkline }; + } + insert.onCells(edits); + closePop(); + }; + + /** + * Which of the three sparkline triggers is showing its form, or `null` when none is. + * ⛔ THE KIND IS THE TRIGGER, NOT A CONTROL INSIDE THE FORM. Three buttons stay three + * affordances (the group is Excel's own three, and a menu over three items costs a press without + * buying anything); putting a fourth kind picker in the popover would also let `aria-expanded` on + * the Line button describe a Column form. + */ + const openKind: SparklineKind | null = + open === "sparkline-line" ? "line" + : open === "sparkline-column" ? "column" + : open === "sparkline-winloss" ? "winloss" + : null; + + /** + * ⭐ W54-T14 — ALL THREE KINDS THROUGH ONE WRITER. The dialog has already decided which kind it + * is and validated the target for that kind; this only amends the anchor cell, so a link never + * eats a value, a formula, a style or a binding. + */ + const addLink = (link: CellLink) => { + if (!insert) return; + const { col, row } = anchorAt(); + const held = insert.cellAt(col, row); + const next: Cell = held ? { ...held, link } : { kind: "empty", state: "typed", link }; + insert.onCells({ [addressOf(col, row)]: next }); + }; + + const addNote = (note: string) => { + if (!insert) return; + const { col, row } = anchorAt(); + const held = insert.cellAt(col, row); + const next: Cell = held + ? { ...held, note } + : { kind: "empty", state: "typed", note }; + insert.onCells({ [addressOf(col, row)]: next }); + }; + + /** What the anchor cell already carries, so the two forms open on it rather than on blank. */ + const heldAt = (): Cell | null => { + if (!insert) return null; + const { col, row } = anchorAt(); + return insert.cellAt(col, row); + }; + + return ( + /* ⛔ THE FENCE IS THE DISABLED STATE, AND IT IS NATIVE RATHER THAN PER BUTTON. A + `
    ` disables every descendant form control the browser knows about, so one + attribute covers the six controls and both forms without the shell's `control(...)` helper + growing a ninth argument this lane may not give it. The rules that strip its own box live in + `styles/wave54/ribbon-insert.css`. */ +
    + {group("Charts", ( + + {control("chart", "Chart", <>{word("Chart")}, + openPop("chart"), false, open === "chart", "C", "gallery")} + {/* ⚠ MOUNTED CONDITIONALLY, never rendered behind an `open` prop: `useOverlayLayer` + claims Escape the moment it runs, so a hidden dialog would hold the key. The + `insert` guard is belt and braces, and it is not the fieldset's job here: the + dialog portals to the body and is therefore OUTSIDE the disabled fence. */} + {open === "chart" && insert && ( + + )} + + ))} + + {/* ⭐ THREE CONTROLS RATHER THAN ONE WITH A GALLERY. Excel's Sparklines group is exactly + three buttons, the choice is small and closed, and a menu over three items costs a press + without buying anything. Each one opens the SAME authoring form, already knowing its kind. + ⚠ `data-kt-opens="gallery"` IS WHAT MAKES THE ALT LAYER OPEN THEM. `KeyTips.tsx` fires a + badge with no such attribute as a plain command and never descends; these three now open + a popover, so they have to say so or the key tip would flash and land nowhere. */} + {group("Sparklines", ( + + {control("sparkline-line", "Line sparkline", , + openPop("sparkline-line"), false, open === "sparkline-line", "SL", "gallery")} + {control("sparkline-column", "Column sparkline", , + openPop("sparkline-column"), false, open === "sparkline-column", "SC", "gallery")} + {control("sparkline-winloss", "Win loss sparkline", , + openPop("sparkline-winloss"), false, open === "sparkline-winloss", "SW", "gallery")} + {openKind && insert && ( + /* ⚠ `role="dialog"` RATHER THAN `role="menu"`, for the reason the Link form states + one group down: a form is not a list of commands. + ⭐ `key` FORCES A REMOUNT PER KIND, which is what re-seeds the two fields from the + current selection when the person moves from Line to Column without closing. */ + + + + )} + + ))} + + {group("Links", ( + + {control("link", "Link", <>{word("Link")}, + openPop("link"), false, open === "link", "I", "gallery")} + {/* ⚠ MOUNTED CONDITIONALLY AND OUTSIDE THE FIELDSET, for the two reasons the Charts + group states: an overlay claims Escape the moment it runs, so a hidden one would + hold the key; and it portals to the body, which puts it outside the disabled fence, + so the `insert` guard is written here rather than inherited. + ⚠ `role="dialog"` RATHER THAN `role="menu"` (the component says so): a form is not a + list of commands, and a menu role would promise arrow-key item navigation that is + not there. The shell's `control(...)` still writes `aria-haspopup="menu"` on the + trigger, which it hardcodes for every expandable control; widening that helper is + outside this lane's fence, so the mismatch is recorded here rather than papered + over. */} + {open === "link" && insert && ( + { addLink(link); closePop(); }} + /> + )} + + ))} + + {group("Comments", ( + + {control("comment", "Comment", <>{word("Comment")}, + openPop("comment"), false, open === "comment", "M", "gallery")} + {open === "comment" && ( + +
    { + event.preventDefault(); + const field = event.currentTarget.elements.namedItem("note"); + const note = field instanceof HTMLTextAreaElement ? field.value.trim() : ""; + if (note) addNote(note.slice(0, MAX_CELL_NOTE)); + closePop(); + }} + > + +