diff --git a/RELEASES.json b/RELEASES.json
index 83144b8d18b63e2ed8f92801ef7aa52af52b9671..a29aeb84c2fb4b8ea3ff469c7c6692eede88c7d1 100644
--- a/RELEASES.json
+++ b/RELEASES.json
@@ -1,5 +1,5 @@
{
- "current": "463db38",
+ "current": "fb85b60",
"releases": [
{
"version": "v71",
diff --git a/VERSION b/VERSION
index b57bdfc698a39515e6cd7413fca65efac104e183..bf828be3d91d7e7f8e1fb36ba29faf84e5e49021 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-463db38
+fb85b60
diff --git a/api/application_registry.py b/api/application_registry.py
index ee2cc6dc423a87f734bdc64d7e6413e32cad54a7..e62d6e5e1e48b962a929733b33e232535ec76793 100644
--- a/api/application_registry.py
+++ b/api/application_registry.py
@@ -7,14 +7,57 @@ import uuid
APPLICATION_TYPES = ("chart", "route", "map", "timeseries")
+APPLICATION_TEMPLATE_KINDS = ("route", "catalog")
_KEY = "applications_v1"
_MAX = 500
+# Routing and Catalog are the first authored App templates. These are wire contracts, not
+# executable module declarations: the client renders a trusted platform surface from the stored
+# definition. ``required`` is consumed by the creation flow and enforced again below, so a
+# future client cannot weaken a template by skipping a wizard step.
+_TEMPLATE_CONTRACTS = {
+ "route": {
+ "kind": "route",
+ "label": "Routing",
+ "applicationType": "route",
+ "displayMode": "map",
+ "fieldRoles": [
+ {"key": "title", "label": "Record title", "required": True, "types": []},
+ {"key": "latitude", "label": "Latitude", "required": False,
+ "types": ["text", "int", "currency", "pct", "rating", "number", "float", "decimal"]},
+ {"key": "longitude", "label": "Longitude", "required": False,
+ "types": ["text", "int", "currency", "pct", "rating", "number", "float", "decimal"]},
+ ],
+ "defaultPlacement": {"section": "app", "order": 0},
+ },
+ "catalog": {
+ "kind": "catalog",
+ "label": "Catalog",
+ # Catalog is a template discriminator over an existing trusted renderer contract. The
+ # governed Application type vocabulary stays four-way; the client launches the Catalog
+ # surface from ``templateKind`` rather than teaching every shared type mirror a fifth word.
+ "applicationType": "map",
+ "displayMode": "map",
+ "fieldRoles": [
+ {"key": "key", "label": "Record key", "required": True, "types": []},
+ {"key": "title", "label": "Record title", "required": True, "types": []},
+ {"key": "image", "label": "Image", "required": False,
+ "types": ["image", "attachment", "url", "text"]},
+ ],
+ "defaultPlacement": {"section": "app", "order": 0},
+ },
+}
+
class ApplicationError(ValueError):
pass
+def template_contracts():
+ """The trusted renderer contracts offered by the Application creation flow."""
+ return [copy.deepcopy(_TEMPLATE_CONTRACTS[kind]) for kind in APPLICATION_TEMPLATE_KINDS]
+
+
def blank_doc():
return {"schema": 1, "applications": {}, "defaults": {}}
@@ -125,6 +168,125 @@ def _allowed(compatible, allowed_databases):
else set(compatible or ()) & set(allowed_databases))
+def _contract_fields(database, semantic_records=None, field_contracts=None):
+ """Return ``{field key: type}`` from a caller's already permission-scoped contract.
+
+ The nav creation door supplies its served schema fields. The older Application door supplies
+ governed semantic records. Supporting both here keeps one validator while never making this
+ registry reach around either caller's database/field wall.
+ """
+ fields = {}
+ raw = ((field_contracts or {}).get(database)
+ if isinstance(field_contracts, dict) else None)
+ if isinstance(raw, dict):
+ raw = list(raw.values())
+ for row in raw if isinstance(raw, (list, tuple)) else ():
+ if not isinstance(row, dict):
+ continue
+ key = str(row.get("key") or row.get("field") or "").strip()
+ if key:
+ fields[key] = str(row.get("type") or row.get("dataType") or "").strip().lower()
+ records = ((semantic_records or {}).get(database)
+ if isinstance(semantic_records, dict) else None)
+ for row in (records or {}).values() if isinstance(records, dict) else ():
+ if not isinstance(row, dict):
+ continue
+ key = str(row.get("field") or row.get("key") or "").strip()
+ if key and key not in fields:
+ fields[key] = str(row.get("dataType") or row.get("type") or "").strip().lower()
+ return fields
+
+
+def _template_definition(kind, payload, *, semantic_records=None, field_contracts=None,
+ allowed_databases=None):
+ contract = _TEMPLATE_CONTRACTS[kind]
+ template_kind = str(payload.get("templateKind") or "").strip().lower()
+ if template_kind != kind:
+ raise ApplicationError(f"{kind} applications require templateKind {kind!r}")
+ source = str(payload.get("sourceDatabase") or "").strip()[:120]
+ if not source:
+ raise ApplicationError("sourceDatabase is required")
+ if source not in set(allowed_databases or ()):
+ raise PermissionError("an Application cannot bind a database you cannot open")
+ if "compatibleDatabases" in payload:
+ compatible = _compat(payload.get("compatibleDatabases"))
+ if compatible != [source]:
+ raise ApplicationError("a template Application has exactly one sourceDatabase")
+
+ raw_map = payload.get("fieldMap")
+ if not isinstance(raw_map, dict):
+ raise ApplicationError("fieldMap must be an object")
+ roles = {row["key"]: row for row in contract["fieldRoles"]}
+ extras = sorted(set(raw_map) - set(roles))
+ if extras:
+ raise ApplicationError("fieldMap contains roles outside the template contract: "
+ + ", ".join(extras))
+ missing = sorted(key for key, role in roles.items()
+ if role["required"] and not str(raw_map.get(key) or "").strip())
+ if missing:
+ raise ApplicationError("fieldMap is missing required roles: " + ", ".join(missing))
+ available = _contract_fields(source, semantic_records, field_contracts)
+ if not available:
+ raise ApplicationError("the source database has no readable field contract")
+ field_map = {}
+ for role, raw_field in raw_map.items():
+ field = str(raw_field or "").strip()
+ if not field:
+ continue
+ if len(field) > 160 or field not in available:
+ raise ApplicationError(f"fieldMap role {role!r} does not name a source field")
+ allowed_types = set(roles[role].get("types") or ())
+ if allowed_types and available[field] not in allowed_types:
+ raise ApplicationError(
+ f"fieldMap role {role!r} cannot use field type {available[field]!r}")
+ field_map[role] = field
+ latitude, longitude = field_map.get("latitude"), field_map.get("longitude")
+ if bool(latitude) != bool(longitude):
+ raise ApplicationError("Routing needs both coordinate fields or neither")
+ if latitude and latitude == longitude:
+ raise ApplicationError("Routing latitude and longitude must use different fields")
+
+ raw_placement = payload.get("navPlacement")
+ if not isinstance(raw_placement, dict) or set(raw_placement) != {"section", "order"}:
+ raise ApplicationError("navPlacement must contain section and order")
+ section = str(raw_placement.get("section") or "").strip().lower()
+ order = raw_placement.get("order")
+ if section != "app":
+ raise ApplicationError("template Applications must be placed in App")
+ if isinstance(order, bool) or not isinstance(order, int) or not 0 <= order <= 999:
+ raise ApplicationError("navPlacement order must be an integer from 0 to 999")
+ return {"templateKind": kind, "sourceDatabase": source, "fieldMap": field_map,
+ "navPlacement": {"section": "app", "order": order}}
+
+
+def validate_application(payload, tenant, *, semantic_records=None, field_contracts=None,
+ allowed_databases=None):
+ """Validate the server-authored identity/tenant envelope and any template definition."""
+ payload = payload if isinstance(payload, dict) else {}
+ if payload.get("id") not in (None, ""):
+ raise ApplicationError("application id is server assigned")
+ if "tenant" in payload and str(payload.get("tenant") or "") != str(tenant):
+ raise PermissionError("an Application cannot be created for another tenant")
+ template_kind = str(payload.get("templateKind") or "").strip().lower()
+ if template_kind and template_kind not in APPLICATION_TEMPLATE_KINDS:
+ raise ApplicationError("application template kind is not recognized")
+ expected_type = (_TEMPLATE_CONTRACTS[template_kind]["applicationType"]
+ if template_kind else "")
+ kind = str(payload.get("type") or expected_type).strip().lower()
+ if kind not in APPLICATION_TYPES:
+ raise ApplicationError("application type is not recognized")
+ if template_kind:
+ if kind != expected_type:
+ raise ApplicationError(
+ f"{template_kind} template Applications require type {expected_type!r}")
+ return _template_definition(
+ template_kind, payload, semantic_records=semantic_records,
+ field_contracts=field_contracts, allowed_databases=allowed_databases)
+ if any(key in payload for key in ("sourceDatabase", "fieldMap", "navPlacement")):
+ raise ApplicationError("only a template Application may carry template fields")
+ return {}
+
+
def _public(app, user, is_admin=False, *, allowed_databases=None, target_database=None,
is_default=False):
row=copy.deepcopy(app)
@@ -160,23 +322,34 @@ def list_apps(runtime, user, is_admin=False, *, database=None, kind=None, starre
return sorted(rows,key=lambda x:(str(x.get("updatedAt") or ""),str(x.get("id"))),reverse=True)
-def create(runtime, tenant, user, payload, *, semantic_records=None, allowed_databases=None):
+def create(runtime, tenant, user, payload, *, semantic_records=None, field_contracts=None,
+ allowed_databases=None):
payload=payload if isinstance(payload,dict) else {}
- kind=str(payload.get("type") or "").lower()
- if kind not in APPLICATION_TYPES: raise ApplicationError("application type is not recognized")
+ template_kind=str(payload.get("templateKind") or "").strip().lower()
+ expected_type = (_TEMPLATE_CONTRACTS.get(template_kind) or {}).get("applicationType")
+ kind=str(payload.get("type") or expected_type or "").strip().lower()
+ definition = validate_application(
+ payload, tenant, semantic_records=semantic_records, field_contracts=field_contracts,
+ allowed_databases=allowed_databases)
name=" ".join(str(payload.get("name") or "").split())[:120]
if not name: raise ApplicationError("application name is required")
app_id=f"app_{uuid.uuid4().hex[:16]}"; now=dt.datetime.now(dt.timezone.utc).isoformat()
- compatible = _compat(payload.get("compatibleDatabases"))
+ compatible = ([definition["sourceDatabase"]] if definition
+ else _compat(payload.get("compatibleDatabases")))
if _allowed(compatible, allowed_databases) != set(compatible):
raise PermissionError("an Application cannot bind a database you cannot open")
+ raw_config = payload.get("config")
+ if definition and raw_config is None:
+ raw_config = {"schemaVersion": 1,
+ "display": {"mode": _TEMPLATE_CONTRACTS[template_kind]["displayMode"]}}
app={"id":app_id,"tenant":str(tenant),"type":kind,"name":name,
"compatibleDatabases":compatible,
"semanticRoleBindings":_governed_bindings(
payload.get("semanticRoleBindings"), compatible, semantic_records or {}),
- "config":_typed_config(kind, payload.get("config")),
+ "config":_typed_config(kind, raw_config),
"share":{"mode":"private","users":[]},"starredBy":[],"createdBy":user,
"createdAt":now,"updatedAt":now,"revision":1}
+ app.update(definition)
def apply(raw):
doc=_clean_doc(raw)
if len(doc["applications"])>=_MAX: raise ApplicationError("application limit reached")
@@ -188,11 +361,19 @@ def create(runtime, tenant, user, payload, *, semantic_records=None, allowed_dat
def mutate(runtime, app_id, user, is_admin, patch, *, semantic_records=None,
allowed_databases=None, target_database=None):
patch=patch if isinstance(patch,dict) else {}; landed={}
+ immutable = sorted(set(patch) & {
+ "id", "tenant", "type", "templateKind", "sourceDatabase", "fieldMap", "navPlacement"
+ })
+ if immutable:
+ raise ApplicationError("Application identity and template definition are immutable: "
+ + ", ".join(immutable))
def apply(raw):
doc=_clean_doc(raw); app=doc["applications"].get(app_id)
if not app: raise ApplicationError("application does not exist")
if not _allowed(app.get("compatibleDatabases"), allowed_databases):
raise ApplicationError("application does not exist")
+ if app.get("templateKind") in APPLICATION_TEMPLATE_KINDS and "compatibleDatabases" in patch:
+ raise ApplicationError("a template Application's sourceDatabase is immutable")
star_only = set(patch) <= {"starred"}
if star_only:
if not may_read(app,user,is_admin): raise PermissionError("application is not available")
@@ -230,15 +411,19 @@ def mutate(runtime, app_id, user, is_admin, patch, *, semantic_records=None,
def duplicate(runtime, app_id, tenant, user, is_admin=False, *, semantic_records=None,
- allowed_databases=None):
+ field_contracts=None, allowed_databases=None):
app=load(runtime)["applications"].get(app_id)
if not may_read(app,user,is_admin): raise ApplicationError("application does not exist")
if not _allowed(app.get("compatibleDatabases"), allowed_databases):
raise ApplicationError("application does not exist")
- return create(runtime,tenant,user,{"type":app["type"],"name":f"{app['name']} copy",
+ payload={"type":app["type"],"name":f"{app['name']} copy",
"compatibleDatabases":app.get("compatibleDatabases"),
- "semanticRoleBindings":app.get("semanticRoleBindings"),"config":app.get("config")},
- semantic_records=semantic_records, allowed_databases=allowed_databases)
+ "semanticRoleBindings":app.get("semanticRoleBindings"),"config":app.get("config")}
+ for key in ("templateKind", "sourceDatabase", "fieldMap", "navPlacement"):
+ if key in app: payload[key]=copy.deepcopy(app[key])
+ return create(runtime,tenant,user,payload,
+ semantic_records=semantic_records, field_contracts=field_contracts,
+ allowed_databases=allowed_databases)
def delete(runtime, app_id, user, is_admin=False, *, allowed_databases=None):
diff --git a/api/connectors_amazon.py b/api/connectors_amazon.py
index e5170fc066cca078ad46e5a9ce6fe56040228f68..aa610b83d89a415036ceab9e3ca4d24f37084abf 100644
--- a/api/connectors_amazon.py
+++ b/api/connectors_amazon.py
@@ -41,6 +41,100 @@ from harness.amazon_client import ( # noqa: F
#: comments in `keychain.py` warn about it in as many words.
ENTRY_TYPE = "amazon_sp"
+#: W55-T19 / R7 / C10 — AMAZON'S OWN ENABLEMENT DOCUMENT. This is deliberately not Odoo's
+#: model catalogue or connector config: Amazon publishes report schemas, not ``fields_get``, and
+#: its seven databases are enabled at the provider boundary rather than masquerading as Odoo
+#: models. The document lives on the request's tenant runtime, so two tenants can make opposite
+#: choices without a process-global map ever seeing either answer.
+ENABLEMENT_KEY = "amazon_connector_enablement"
+ENABLEMENT_ROUTE = "/connectors/amazon_sp/databases/{databaseKey}/enablement"
+
+
+class EnablementConfigError(ValueError):
+ """The tenant's stored Amazon enablement document is malformed."""
+
+
+def database_keys():
+ """The authored Amazon database keys, derived from the connector's one report roster."""
+ return tuple("ut_amzn_" + str(name) for name in REPORT_TYPES)
+
+
+def read_database_enablement(rt):
+ """Return this tenant's fail-closed Amazon database enablement state.
+
+ An absent document preserves the connector's shipped behaviour: all seven databases are on.
+ Once a document exists, every value must be a real boolean and every key must belong to the
+ authored Amazon roster. A malformed or unreadable document disables every row in the detail
+ response and marks the capability unavailable; it never guesses through corrupt tenant state.
+ """
+ keys = database_keys()
+ try:
+ current = rt.get(ENABLEMENT_KEY) if rt is not None else None
+ except Exception: # noqa: BLE001
+ return {"available": False, "databases": {key: False for key in keys}}
+ # Runtime/store readers use ``{}`` for a genuinely absent document, so both empty forms are
+ # the migration default rather than malformed state.
+ if current is None or current == {}:
+ return {"available": True, "databases": {key: True for key in keys}}
+ if not isinstance(current, dict):
+ return {"available": False, "databases": {key: False for key in keys}}
+ stored = current.get("databases")
+ if not isinstance(stored, dict):
+ return {"available": False, "databases": {key: False for key in keys}}
+ if (set(stored) - set(keys)
+ or any(type(value) is not bool for value in stored.values())):
+ return {"available": False, "databases": {key: False for key in keys}}
+ return {"available": True,
+ # Absent keys stay on so a later report addition does not silently disappear for
+ # every tenant that saved an older version of this document.
+ "databases": {key: stored.get(key, True) for key in keys}}
+
+
+def set_database_enabled(rt, database_key, enabled):
+ """Persist one tenant's Amazon database choice without touching its materialised rows."""
+ key = str(database_key or "").strip()
+ known = set(database_keys())
+ if key not in known:
+ raise KeyError(key)
+ if type(enabled) is not bool:
+ raise ValueError("enabled must be true or false")
+
+ def _set(current):
+ if current is None:
+ current = {}
+ if not isinstance(current, dict):
+ raise EnablementConfigError("the stored Amazon enablement document is malformed")
+ stored = current.get("databases", {})
+ if not isinstance(stored, dict):
+ raise EnablementConfigError("the stored Amazon database choices are malformed")
+ if (set(stored) - known
+ or any(type(value) is not bool for value in stored.values())):
+ raise EnablementConfigError("the stored Amazon database choices are malformed")
+ # A fresh document contains the whole current roster. That makes the stored answer
+ # inspectable while retaining the migration rule above for future database additions.
+ choices = {name: stored.get(name, True) for name in database_keys()}
+ choices[key] = enabled
+ return {**current, "databases": choices}
+
+ rt.update(ENABLEMENT_KEY, _set, flush="sync")
+ return read_database_enablement(rt)
+
+
+def enablement_capability(rt, is_admin):
+ """The provider-aware capability served by Amazon's connector detail response."""
+ state = read_database_enablement(rt)
+ can_manage = bool(is_admin) and state["available"]
+ return {"provider": ENTRY_TYPE,
+ "mode": "database",
+ "canManage": can_manage,
+ # A member receives no write URL. The route still enforces administrator status; this
+ # is the matching affordance wall, not the permission boundary.
+ "updatePath": ENABLEMENT_ROUTE if can_manage else "",
+ # Disabling changes only this config document. No mirror or ``ut_amzn_*`` row is
+ # removed, so re-enabling resumes against the same materialised database.
+ "preservesData": True,
+ "available": state["available"]}
+
def probe_credential(fields, timeout=8):
"""`{ok, message}` for a stored `amazon_sp` credential: the keychain's liveness probe.
diff --git a/api/deps.py b/api/deps.py
index 72fc24821c6bbf83881ac09cfc2beea102b5ff06..545f91e0c0b73d152631aeb7dec17a256001e7f5 100644
--- a/api/deps.py
+++ b/api/deps.py
@@ -103,10 +103,40 @@ class Session:
# the Customer/Product pool builders, connector routes, provider routes, Odoo, or an environment
# lookup from this boundary. A cache miss is a named refusal, never permission to refresh from the
# source of truth. That is what "data the app already stores or serves" means in executable form.
-_ASSISTANT_BUILT_INS = {
+# These two keys name registry modules backed by runtime pools. They are DATABASES the product
+# may open, but they are not materialised `ut_*` documents and they are not DuckDB read-through
+# mirrors. Keeping that distinction in the request boundary prevents a route resolver from
+# treating `product_data` as though `_sources()` could bind it to a mirror table.
+MODULE_CACHE_DATABASES = {
"customer_data": {"label": "Odoo customers", "cache_prefix": "pool"},
"product_data": {"label": "Odoo products", "cache_prefix": "product_pool"},
}
+# The Assistant predates the public taxonomy above. Its private name remains an alias so its
+# snapshot-only contract and every existing caller stay byte-for-byte unchanged.
+_ASSISTANT_BUILT_INS = MODULE_CACHE_DATABASES
+
+
+def module_cache_source(database: str):
+ """Metadata for a runtime-cache database, or None for every materialised/mirror key."""
+ meta = MODULE_CACHE_DATABASES.get(str(database or ""))
+ return dict(meta) if meta else None
+
+
+def module_cache_rows(session: Session, database: str):
+ """The current viewer's scoped rows for one known runtime-cache database.
+
+ This is deliberately the interactive grid boundary, not the Assistant snapshot reader:
+ `scoped_table` applies the same team/agent and row grants as the module page, while
+ `Session.require` keeps the account and tenant-catalogue checks in their one chokepoint.
+ Unknown keys fail before either check, so an absent relation target cannot be mislabeled as
+ a permission denial.
+ """
+ key = str(database or "")
+ if module_cache_source(key) is None:
+ raise KeyError(key)
+ session.require(key)
+ import core.perm_scope as perm_scope
+ return list(perm_scope.scoped_table(session.user, key, st=session.runtime) or [])
def _assistant_refuse(status, code, message):
diff --git a/api/odoo_relational.py b/api/odoo_relational.py
index 5c334def5acf106a8fd148c2c48029ab4072307e..611086cff46e784c919b8a1d849a8ec2ca8be8e6 100644
--- a/api/odoo_relational.py
+++ b/api/odoo_relational.py
@@ -48,6 +48,7 @@ wider link would count 31,418 documents and call them open invoices, so those tw
the oracle's predicate as an explicit `payment_state` condition pair.
"""
import datetime as _dt
+import json as _json
#: ⛔ ROUTE ENTITLEMENT, NOT THE SPAWN GATE — `refresh()` stopped reading this at W53-T39 / R3,
#: which admits on CONFIGURED CREDENTIALS (`available()`) so a second Odoo tenant needs no edit.
@@ -1869,6 +1870,137 @@ def authoritative_schema_snapshot():
return models, errors
+# The compiled TABLES tuple remains the curated mirror contract. This is the separate, per-tenant
+# discovery cache for every other Odoo model the active API account may read (W55-T17 / C9).
+MODEL_CATALOG_KEY = "odoo_readable_model_catalog"
+MODEL_CATALOG_VERSION = 1
+MODEL_READ_PAGE = 2000
+MODEL_CATALOG_TTL = _dt.timedelta(hours=6)
+_MODEL_FIELD_TYPES = {
+ "boolean": "checkbox", "integer": "int", "float": "number", "monetary": "currency",
+ "date": "date", "datetime": "datetime",
+}
+
+
+def discover_readable_models(client):
+ """Read-only introspection over an injected Odoo client.
+
+ ``ir.model`` supplies candidates, ``check_access_rights('read')`` narrows them to this API
+ account, and ``fields_get`` supplies only fields that account may inspect. No method in this
+ path can mutate Odoo; the production client independently blocks write-shaped method names.
+ """
+ errors = []
+ try:
+ candidates = client.search_read(
+ "ir.model", [], ["model", "name", "transient"], order="name,model")
+ except Exception as exc: # noqa: BLE001
+ return [], [f"ir.model: {type(exc).__name__}: {exc}"]
+ rows = []
+ for item in candidates or ():
+ model = str((item or {}).get("model") or "").strip().lower()
+ if not model:
+ continue
+ try:
+ readable = client.execute_kw(
+ model, "check_access_rights", ["read"], {"raise_exception": False})
+ except Exception as exc: # noqa: BLE001
+ errors.append(f"{model}: access: {type(exc).__name__}: {exc}")
+ continue
+ if not bool(readable):
+ continue
+ try:
+ fields = client.fields_get(
+ model, attributes=("string", "type", "required", "readonly", "relation"))
+ except Exception as exc: # noqa: BLE001
+ fields = {}
+ errors.append(f"{model}: fields: {type(exc).__name__}: {exc}")
+ clean_fields = {}
+ for name, meta in (fields or {}).items():
+ if not str(name).strip() or not isinstance(meta, dict):
+ continue
+ clean_fields[str(name)] = {k: meta.get(k) for k in
+ ("string", "type", "required", "readonly", "relation")
+ if k in meta}
+ rows.append({"model": model,
+ "name": " ".join(str((item or {}).get("name") or model).split()),
+ "fields": clean_fields})
+ rows.sort(key=lambda row: (str(row.get("name") or "").casefold(), row["model"]))
+ return rows, errors
+
+
+def _catalog_slot(connection_id):
+ return str(connection_id or DEFAULT_CONNECTION)
+
+
+def readable_model_catalog(rt, connection_id=None):
+ """The last complete tenant-local catalogue; reading it never contacts Odoo."""
+ try:
+ cached = rt.get(MODEL_CATALOG_KEY) if rt is not None else None
+ except Exception: # noqa: BLE001
+ cached = None
+ if not isinstance(cached, dict) or cached.get("version") != MODEL_CATALOG_VERSION:
+ return {"version": MODEL_CATALOG_VERSION, "complete": False, "capturedAt": "",
+ "models": [], "errors": []}
+ cached = (cached.get("connections") or {}).get(_catalog_slot(connection_id)) or {}
+ return {"version": MODEL_CATALOG_VERSION,
+ "complete": cached.get("complete") is True,
+ "capturedAt": str(cached.get("capturedAt") or ""),
+ "models": [dict(row) for row in (cached.get("models") or ())
+ if isinstance(row, dict) and row.get("model")],
+ "errors": [str(value) for value in (cached.get("errors") or ())][:50]}
+
+
+def refresh_readable_model_catalog(rt, connection_id=None, client=None, force=False):
+ """Populate one tenant's catalogue once, or explicitly refresh it; never widen on failure."""
+ current = readable_model_catalog(rt, connection_id)
+ if current["capturedAt"] and not force:
+ try:
+ captured = _dt.datetime.fromisoformat(current["capturedAt"])
+ if _dt.datetime.now(_dt.timezone.utc) - captured < MODEL_CATALOG_TTL:
+ return current
+ except (TypeError, ValueError):
+ pass
+ source = None
+ if client is None:
+ try:
+ source = (rt.odoo_source() if connection_id is None
+ else rt.odoo_source(connection_id))
+ except Exception: # noqa: BLE001
+ source = None
+ if source is None:
+ return current
+ try:
+ if client is None:
+ from core.odoo import get_odoo
+ with source._bound(): # tenant credential + scope
+ rows, errors = discover_readable_models(get_odoo())
+ else:
+ rows, errors = discover_readable_models(client)
+ except Exception as exc: # noqa: BLE001
+ rows, errors = [], [f"catalogue: {type(exc).__name__}: {exc}"]
+ # A partial retry is not evidence that a previously readable model disappeared. Preserve a
+ # complete, stamped catalogue in full whenever the new pass reports any error; otherwise one
+ # refused model could silently shrink the enablement roster. A first-ever partial pass may be
+ # retained for diagnostics, but an entirely failed pass still has no catalogue to publish.
+ if errors and current["complete"] and current["capturedAt"]:
+ return current
+ if not rows and errors:
+ return current
+ captured = _dt.datetime.now(_dt.timezone.utc).isoformat()
+ result = {"version": MODEL_CATALOG_VERSION, "complete": not errors,
+ "capturedAt": captured, "models": rows, "errors": errors[:50]}
+ slot = _catalog_slot(connection_id)
+
+ def _cache(current_cache):
+ current_cache = dict(current_cache) if isinstance(current_cache, dict) else {}
+ connections = dict(current_cache.get("connections") or {})
+ connections[slot] = result
+ return {"version": MODEL_CATALOG_VERSION, "connections": connections}
+
+ rt.update(MODEL_CATALOG_KEY, _cache, flush="sync")
+ return result
+
+
#: ⭐⭐ W53-T38 / C2 — THE CONNECTOR SCHEMA SPEC ODOO HAS NEVER HAD.
#:
#: Amazon and Meta each got a `ConnectorTableSpec` row per table in `platform/core/connector_spec.py`
@@ -2463,11 +2595,16 @@ def split_table_key(table_key):
keeps its legacy key.
"""
raw = str(table_key or "").strip()
- if raw in BASE_TABLE_KEYS:
- return raw, None
+ try:
+ from core import connector_spec
+ dynamic_prefix = connector_spec.ODOO_MODEL_TABLE_PREFIX
+ except Exception: # noqa: BLE001
+ dynamic_prefix = "ut_odoo_model_"
base, sep, cid = raw.rpartition(CONNECTION_SEP)
- if sep and cid and base in BASE_TABLE_KEYS:
+ if sep and cid and (base in BASE_TABLE_KEYS or base.startswith(dynamic_prefix)):
return base, cid
+ if raw in BASE_TABLE_KEYS or raw.startswith(dynamic_prefix):
+ return raw, None
return None, None
@@ -2550,7 +2687,10 @@ def table_subject_for(table_key):
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 ""))
+ raw_base = base if base is not None else str(table_key or "")
+ subject = TABLE_SUBJECTS.get(raw_base)
+ if subject is None and raw_base.startswith("ut_odoo_model_"):
+ subject = f"odoo.model.{raw_base}"
if not subject or not cid:
return subject
return f"{subject}@{cid}"
@@ -2737,17 +2877,49 @@ def read_config(rt):
"frozenAt": str(cur.get("frozenAt") or "")}
-def grid_choices(rt):
- """`[{key, label, enabled}]` for every grid this connector can materialise — DERIVED from
- `TABLES`, never a second hand-typed list (contract C2's parity leg asserts exactly that).
+def grid_choices(rt, connection_id=None):
+ """Every API-readable model, with the curated TABLES roster retained as its stable front.
⚠ ABSENT MEANS ENABLED. A tenant that has never opened the panel has every grid, which is
what they have today; only an explicit untick turns one off. The alternative — an empty
config meaning "nothing enabled" — would silently unspawn ten live databases on deploy.
+
+ W55-T17 keeps two facts separate: ``TABLES`` is what the mirror materialiser knows, while the
+ tenant-local catalogue is what this API account may read. A readable model already represented
+ by a curated table is covered there; every remaining readable model receives a stable raw-model
+ key and defaults off. Stored choices survive catalogue refreshes because config is keyed by the
+ stable database key, never by its position.
"""
chosen = read_config(rt)["grids"]
- return [{"key": key, "label": label, "enabled": bool(chosen.get(key, True))}
- for _bucket, key, label, _fields in TABLES]
+ catalogue = readable_model_catalog(rt, connection_id)
+ fixed = [{"key": key, "label": label, "model": ODOO_TABLE_MODELS.get(key, ""),
+ "relevant": True, "defaultEnabled": True,
+ "enabled": bool(chosen.get(key, True))}
+ for _bucket, key, label, _fields in TABLES]
+ # Before discovery, keep the established curated defaults. A complete stamped catalogue is
+ # authoritative for this API account, so a curated database whose model is absent must not be
+ # offered: relevance never widens access.
+ if catalogue["complete"] and catalogue["capturedAt"]:
+ readable = {str(row.get("model") or "") for row in catalogue["models"]}
+ fixed = [row for row in fixed if not row["model"] or row["model"] in readable]
+ covered = {row["model"] for row in fixed if row["model"]}
+ dynamic = []
+ try:
+ from core import connector_spec
+ for item in catalogue["models"]:
+ model = str(item.get("model") or "")
+ if not model or model in covered:
+ continue
+ key = connector_spec.odoo_model_table_key(model)
+ dynamic.append({"key": key,
+ "label": connector_spec.odoo_model_label(model, item.get("name")),
+ "model": model, "relevant": False, "defaultEnabled": False,
+ "enabled": chosen.get(key) is True})
+ except Exception: # noqa: BLE001
+ dynamic = []
+ return sorted(fixed + dynamic,
+ key=lambda row: (not row["enabled"], not row["relevant"],
+ str(row["label"]).casefold(), row["key"]))
def enabled_buckets(rt):
@@ -2756,6 +2928,14 @@ def enabled_buckets(rt):
return {bucket for bucket, key, _l, _f in TABLES if chosen.get(key, True)}
+def enabled_discovered_models(rt, connection_id=None):
+ """The explicitly enabled long-tail model rows; curated TABLES never enter this set."""
+ fixed = {str(model) for model in ODOO_TABLE_MODELS.values() if model}
+ return [row for row in grid_choices(rt, connection_id)
+ if row.get("enabled") is True and row.get("model") not in fixed
+ and str(row.get("key") or "").startswith("ut_odoo_model_")]
+
+
def sync_seconds(rt):
"""How often this tenant's Odoo mirror should resync, or None for `manual` (R11).
@@ -3157,6 +3337,119 @@ def _ensure_table_inplace(cur, key, label, fields, rows, username, stamp):
return counts
+def _model_field_specs(catalogue_row):
+ """Safe grid fields for one discovered model; binary payloads are never copied into cells."""
+ fields = catalogue_row.get("fields") if isinstance(catalogue_row, dict) else {}
+ fields = fields if isinstance(fields, dict) else {}
+ ordered = sorted(fields.items(), key=lambda item: (item[0] != "id", item[0]))
+ out = []
+ for raw_name, meta in ordered:
+ meta = meta if isinstance(meta, dict) else {}
+ raw_type = str(meta.get("type") or "char")
+ if raw_type == "binary":
+ continue
+ out.append({"key": str(raw_name),
+ "label": str(meta.get("string") or raw_name),
+ "type": _MODEL_FIELD_TYPES.get(raw_type, "text"),
+ "source": "odoo",
+ "automation": {"preset": True}})
+ if not any(field["key"] == "id" for field in out):
+ out.insert(0, {"key": "id", "label": "ID", "type": "int", "source": "odoo",
+ "automation": {"preset": True}})
+ for preferred in ("display_name", "name", "id"):
+ match = next((field for field in out if field["key"] == preferred), None)
+ if match is not None:
+ match["pinned"] = True
+ break
+ return out
+
+
+def _model_cell(value):
+ """Make XML-RPC relation/list values durable without inventing a relation to another table."""
+ if isinstance(value, (list, tuple, dict)):
+ return _json.dumps(value, ensure_ascii=False, sort_keys=isinstance(value, dict))
+ return value
+
+
+def _read_model_rows(client, catalogue_row):
+ """Read one explicitly enabled model in stable pages; every call is a read method."""
+ model = str(catalogue_row.get("model") or "")
+ fields = [field["key"] for field in _model_field_specs(catalogue_row)]
+ rows, offset = [], 0
+ while True:
+ page = client.search_read(model, [], fields, limit=MODEL_READ_PAGE,
+ offset=offset, order="id")
+ for item in page or ():
+ rid = (item or {}).get("id")
+ if rid in (None, ""):
+ continue
+ rows.append({"_id": str(rid),
+ **{name: _model_cell((item or {}).get(name)) for name in fields}})
+ if len(page or ()) < MODEL_READ_PAGE:
+ break
+ offset += len(page)
+ return rows
+
+
+def sync_discovered_models(rt, source_connection_id=None, namespace=None,
+ username="automation", today=None):
+ """Materialise only explicitly enabled long-tail models, atomically and tenant-bound.
+
+ Disabled models are absent from this pass rather than represented by an empty row set. That
+ distinction is the preservation guarantee: no updater touches their definition, rows, fields,
+ grants, ownership, or tenant rename, and re-enabling resumes against the same stable key.
+ """
+ catalogue = refresh_readable_model_catalog(rt, connection_id=source_connection_id)
+ by_model = {str(row.get("model") or ""): row for row in catalogue.get("models") or ()}
+ selected = [choice for choice in enabled_discovered_models(rt, source_connection_id)
+ if str(choice.get("model") or "") in by_model]
+ if not selected:
+ return {}
+ ut = _ut()
+ existing = dict(rt.get(ut.STORE_KEY) or {})
+ keys = [table_key_for(str(choice["key"]), namespace) for choice in selected]
+ missing = [key for key in keys if key not in existing]
+ if missing and len(existing) + len(missing) > ut.MAX_TABLES:
+ raise Refused(f"tenant holds {len(existing)} of MAX_TABLES={ut.MAX_TABLES} databases and "
+ f"needs {len(missing)} more enabled Odoo models; nothing was created")
+ source = (rt.odoo_source() if source_connection_id is None
+ else rt.odoo_source(source_connection_id))
+ if source is None:
+ raise Refused("the selected Odoo connection is unavailable, so no discovered model was read")
+ prepared, errors = [], []
+ from core.odoo import get_odoo
+ with source._bound(): # tenant credential + scope
+ client = get_odoo()
+ for choice, key in zip(selected, keys):
+ model = str(choice["model"])
+ row = by_model[model]
+ try:
+ values = _read_model_rows(client, row)
+ except Exception as exc: # noqa: BLE001
+ errors.append(f"{model}: {type(exc).__name__}: {exc}")
+ continue
+ stored_n = len(((existing.get(key) or {}).get("rows")) or {})
+ if stored_n and len(values) < stored_n * MAX_SHRINK:
+ errors.append(f"{model}: read returned {len(values)} rows against {stored_n} "
+ "stored; preserved the prior database instead")
+ continue
+ prepared.append((key, str(choice["label"]), _model_field_specs(row), values, model))
+ written = {}
+ stamp = today or _iso_today()
+ ut.register_connected(*(key for key, _label, _fields, _rows, _model in prepared))
+
+ def _apply(cur):
+ cur = cur if isinstance(cur, dict) else {}
+ for key, label, fields, rows, model in prepared:
+ written[key] = _ensure_table_inplace(cur, key, label, fields, rows, username, stamp)
+ cur[key]["connector"] = {"key": "odoo", "model": model, "readOnly": True}
+ return cur
+
+ if prepared:
+ rt.update(ut.STORE_KEY, _apply, flush="sync")
+ return {"tables": written, "errors": errors}
+
+
def is_royal(tenant):
"""ENTITLEMENT by slug, kept verbatim for the five callers outside this module.
@@ -3341,6 +3634,12 @@ def refresh(rt, tenant, username="automation", cur=None, today=None, connection_
plan_report = {}
written = apply_plan(rt, built, username=username, today=today, report=plan_report,
connection_id=ns)
+ # The fixed mirror roster above and the discovered long tail deliberately use separate
+ # materialisers. Only an explicit long-tail enablement reaches this read-only path; disabled
+ # databases are not passed an empty set and therefore cannot be erased by reconciliation.
+ discovered_report = (sync_discovered_models(
+ rt, source_connection_id=connection_id, namespace=ns, username=username, today=today)
+ if rt is not None else {})
# ⭐⭐ 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
@@ -3349,6 +3648,9 @@ def refresh(rt, tenant, username="automation", cur=None, today=None, connection_
declared_report = _refresh_declared_schema(rt)
out = {"tables": written,
**({"schemaDeclared": declared_report} if declared_report else {}),
+ **({"discovered": discovered_report}
+ if discovered_report and (discovered_report.get("tables")
+ or discovered_report.get("errors")) 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 {}),
diff --git a/api/routes_connectors.py b/api/routes_connectors.py
index e48fae1bb772207693755fb83c15f249316eca25..8060022ff5bfa231be2f729296db9a187e944ee6 100644
--- a/api/routes_connectors.py
+++ b/api/routes_connectors.py
@@ -1107,6 +1107,26 @@ def _schema_catalog(session):
return _schema_catalog_rt(session.runtime)
+def _odoo_raw_models(rt, snapshot=None):
+ """Raw fields from stamped discovery, or the legacy snapshot before discovery exists."""
+ if snapshot is None:
+ import core.user_tables as user_tables
+ snapshot = user_tables.odoo_schema_snapshot(rt)
+ legacy = dict((snapshot or {}).get("models") or {})
+ try:
+ import odoo_relational
+ discovered = odoo_relational.readable_model_catalog(rt)
+ except Exception: # noqa: BLE001
+ discovered = {}
+ if not discovered.get("capturedAt"):
+ return legacy
+ # A stamp means this tenant-bound account has spoken. Even a partial stamped set is safer
+ # than adding snapshot-only models that the current account never proved it may read.
+ return {str(item.get("model") or ""): dict(item.get("fields") or {})
+ for item in (discovered.get("models") or ())
+ if str(item.get("model") or "")}
+
+
def _schema_catalog_rt(rt):
"""The same catalogue, over a RUNTIME rather than a session.
@@ -1119,7 +1139,7 @@ def _schema_catalog_rt(rt):
import core.user_tables as user_tables
enabled = rt.get(_ODOO_SCHEMA_ENABLEMENTS) or {}
snapshot = user_tables.odoo_schema_snapshot(rt)
- raw_models = snapshot.get("models") or {}
+ raw_models = _odoo_raw_models(rt, snapshot)
if raw_models:
rows = []
for model, raw_fields in raw_models.items():
@@ -1156,10 +1176,21 @@ def odoo_schema(session: Session = Depends(require_session)):
fields = _schema_catalog(session)
import core.user_tables as user_tables
snapshot = user_tables.odoo_schema_snapshot(session.runtime)
+ try:
+ import odoo_relational
+ discovered = odoo_relational.readable_model_catalog(session.runtime)
+ except Exception: # noqa: BLE001
+ discovered = {}
+ has_discovery = bool(discovered.get("capturedAt"))
+ complete = (discovered.get("complete") is True if has_discovery
+ else snapshot.get("complete") is True)
return {"fields": fields, "default": "off", "adminOnly": True,
- "complete": snapshot.get("complete") is True,
- "capturedAt": snapshot.get("capturedAt"),
- "errors": list(snapshot.get("errors") or ()), "source": "Odoo"}
+ "complete": complete,
+ "capturedAt": (discovered.get("capturedAt") if has_discovery
+ else snapshot.get("capturedAt")),
+ "errors": list((discovered.get("errors") if has_discovery
+ else snapshot.get("errors")) or ()),
+ "source": "Odoo"}
@router.patch("/connectors/odoo/schema/{field_key}")
@@ -1168,7 +1199,13 @@ def odoo_schema_enable(field_key: str, body: dict = Body(default=None),
_odoo_admin(session)
import core.user_tables as user_tables
_snapshot = user_tables.odoo_schema_snapshot(session.runtime)
- if _snapshot.get("complete") is not True:
+ try:
+ import odoo_relational
+ _discovered_complete = odoo_relational.readable_model_catalog(
+ session.runtime).get("complete") is True
+ except Exception: # noqa: BLE001
+ _discovered_complete = False
+ if _snapshot.get("complete") is not True and not _discovered_complete:
raise err(409, "odoo_schema_unavailable",
"run a successful schema sync before changing raw-field enablement")
known = {field["key"] for field in _schema_catalog(session)}
@@ -1294,6 +1331,18 @@ def _detail_connect(entry_type, is_admin):
"tenantWide": tenant_wide}
+def _replacement_field_specs(entry_type):
+ """The write-only fields that may change on an existing credential.
+
+ This is deliberately a projection of the Connect descriptor rather than another provider
+ vocabulary. URL, database, account and every future non-secret field stay server-held during
+ replacement; only fields the existing descriptor marks secret cross this door.
+ """
+ spec = _detail_connect(entry_type, True) or {}
+ return [dict(field) for field in (spec.get("fields") or [])
+ if field.get("secret") is True and str(field.get("key") or "").strip()]
+
+
def _oauth_slot_entries(rt, uname, row):
"""A per-user OAuth connection, rendered as C4's `keychain` entry shape.
@@ -1332,7 +1381,8 @@ def _oauth_slot_entries(rt, uname, row):
# A per-user slot is personal by construction, in the vocabulary `routes_keychain`
# already declares. Never a third word for the same idea.
"scope": "personal",
- "testable": False}]
+ "testable": False,
+ "replaceable": False}]
def _detail_keychain(rt, uname, is_admin, row):
@@ -1353,6 +1403,7 @@ def _detail_keychain(rt, uname, is_admin, row):
# already decided admin vs member vs nothing, and deciding again here is how two answers to
# one question get born ([[one-question-two-normalizers]]).
can_connect = manage in ("keychain", "keychain_personal")
+ can_replace = bool(is_admin and can_connect and _replacement_field_specs(entry_type))
entries = []
if entry_type:
try:
@@ -1370,6 +1421,11 @@ def _detail_keychain(rt, uname, is_admin, row):
# xmlrpc check otherwise. The flag says whether a Test control would have
# something to call, and it always does.
"testable": True,
+ # W55-T18 / C10: credential replacement is an administrator action. The
+ # client reads this wall instead of inferring it from scope or from whether
+ # a masked preview happened to be visible. The replacement endpoint changes
+ # this row's encrypted payload in place; no secret is added to this DTO.
+ "replaceable": can_replace,
})
except Exception: # noqa: BLE001
entries = []
@@ -1398,9 +1454,7 @@ def _odoo_catalog_by_model(rt):
not offer. Today that diff is empty, which is the honest answer, and it fills itself the moment
the catalogue starts filtering instead of needing somebody to remember.
"""
- import core.user_tables as user_tables
- snapshot = user_tables.odoo_schema_snapshot(rt)
- raw_models = snapshot.get("models") or {}
+ raw_models = _odoo_raw_models(rt)
offered = {}
for row in _schema_catalog_rt(rt):
offered.setdefault(str(row.get("model") or ""), []).append(row)
@@ -1675,13 +1729,13 @@ def _detail_databases(rt, is_admin, connector_key, uname=""):
shared = {}
for choice in choices:
key = str(choice.get("key") or "")
- model = str(models.get(key) or "")
+ model = str(choice.get("model") or models.get(key) or "")
if model:
shared.setdefault(model, []).append(key)
out = []
for choice in choices:
key = str(choice.get("key") or "")
- model = str(models.get(key) or "")
+ model = str(choice.get("model") or models.get(key) or "")
fields, excluded = catalog.get(model, ([], []))
# ⚠ THE SPEC WINS WHERE IT SPEAKS, AND THE MIRROR STILL GROUPS. `native` is a DISPLAY fact
# (what Odoo calls this table); `shared` above is keyed by the model the ENABLEMENT flag
@@ -1721,13 +1775,16 @@ def _amazon_databases(rt, is_admin, spec=None):
⚠ NO FIELD TOGGLES. `canToggleFields` is False for Amazon in `_detail_introspection`; there is
no `PATCH /connectors/amazon_sp/schema/{field}` route and this wave does not build one. Fields
- are disclosed, not switched, and a control that could only ever 409 is R7's banned shape.
+ are disclosed, not switched. Database enablement is a separate provider capability and route,
+ never the generic Odoo-table flag consumed by `DatabasesTab`.
"""
try:
from harness import amazon_schema
import connectors_amazon as cx
except Exception: # noqa: BLE001
return []
+ enablement = cx.read_database_enablement(rt)
+ enabled = enablement.get("databases") or {}
cat = amazon_schema.catalogue()
tables = cat.get("tables") or {}
@@ -1771,7 +1828,10 @@ def _amazon_databases(rt, is_admin, spec=None):
"defaultLabel": str(declared.get("label")
or LABELS_AMAZON.get(key) or key),
"native": str(declared.get("native") or rep),
- "enabled": True,
+ # W55-T19 / R7 — AMAZON'S OWN tenant-local answer. This is deliberately not
+ # read from Odoo's grid config, and disabling it leaves every stored row and
+ # definition untouched: only this provider config document changes.
+ "enabled": enabled.get(key) is True,
"fields": fields,
"excluded": excluded,
"sharesFieldsWith": [k for k in by_report.get(rep, ()) if k != key]})
@@ -1849,10 +1909,10 @@ def _detail_introspection(rt, is_admin, row):
"catalogueComplete": False, "capturedAt": "", "excludedBasis": ""}
if key == "amazon_sp":
# ⭐⭐ W52 · R6. Introspectable under the AMENDED test (a real schema artifact, not a
- # `fields_get`), and deliberately with NO toggles: there is no Amazon field-toggle route
- # and no Amazon table-config route, so both flags are False. A control that could only
- # ever 409 is R7's banned shape, and naming the connector introspectable buys the
- # DISCLOSURE only.
+ # `fields_get`), and deliberately with NO generic toggles: there is no Amazon field-toggle
+ # route, and `canToggleTables` belongs to Odoo's config surface. W55-T19 serves Amazon's
+ # database switches through the separate `enablement` capability instead, so this flag
+ # stays False and can never send Amazon through an Odoo endpoint.
#
# ⛔ `catalogueComplete` IS FALSE AND SAYING SO IS THE HONEST ANSWER. Only two of the seven
# tables have a published artifact; the other five measure their columns from the report's
@@ -1882,8 +1942,13 @@ def _detail_introspection(rt, is_admin, row):
try:
import core.user_tables as user_tables
snapshot = user_tables.odoo_schema_snapshot(rt)
- complete = snapshot.get("complete") is True
- captured = str(snapshot.get("capturedAt") or "")
+ import odoo_relational
+ discovered = odoo_relational.readable_model_catalog(rt)
+ has_discovery = bool(discovered.get("capturedAt"))
+ complete = (discovered.get("complete") is True if has_discovery
+ else snapshot.get("complete") is True)
+ captured = str((discovered.get("capturedAt") if has_discovery
+ else snapshot.get("capturedAt")) or "")
except Exception: # noqa: BLE001
complete, captured = False, ""
return {"introspectable": True,
@@ -1903,13 +1968,13 @@ def _detail_introspection(rt, is_admin, row):
def _detail_overview(row, databases, graph):
"""C4's `overview` half: what the modal's first tab reads, top to bottom.
- `creates` is the table LABELS this connector stands behind: the declared grids when the
+ `creates` is the ENABLED table LABELS this connector stands behind: the declared grids when the
connector declares any, and otherwise the tables its own permitted graph actually found. Both
are real readings of THIS workspace; neither is a provider template.
"""
creates = [str(entry.get("label") or "") for entry in (databases or [])
- if str(entry.get("label") or "")]
- if not creates and isinstance(graph, dict) and graph.get("status") == "ready":
+ if entry.get("enabled") is True and str(entry.get("label") or "")]
+ if not databases and isinstance(graph, dict) and graph.get("status") == "ready":
creates = [str(table.get("label") or "") for table in (graph.get("tables") or ())
if str(table.get("label") or "")]
return {"key": str(row.get("key") or ""),
@@ -1925,6 +1990,24 @@ def _detail_overview(row, databases, graph):
"creates": creates}
+def _detail_enablement(rt, is_admin, row):
+ """A provider-owned enablement capability, or ``None`` when this connector has no door.
+
+ Amazon is intentionally the first entry and is named here rather than inferred from whether a
+ database list happened to be non-empty. Odoo keeps its model-catalogue and config routes;
+ every other connector keeps no enablement affordance until its provider declares one.
+ """
+ if str(row.get("key") or "") != "amazon_sp":
+ return None
+ try:
+ import connectors_amazon as cx
+ return cx.enablement_capability(rt, bool(is_admin))
+ except Exception: # noqa: BLE001
+ # Fail closed. An unreadable provider capability is no write door.
+ return {"provider": "amazon_sp", "mode": "database", "canManage": False,
+ "updatePath": "", "preservesData": True, "available": False}
+
+
def connector_detail(rt, user, uname, is_admin, connector_key):
"""The whole C4 detail DTO for one connector, or `None` when this reader has no such card.
@@ -1946,6 +2029,9 @@ def connector_detail(rt, user, uname, is_admin, connector_key):
return {"overview": _detail_overview(row, databases, graph),
"keychain": _detail_keychain(rt, uname, bool(is_admin), row),
"databases": databases,
+ # W55-T19 / R7 / C10 — a provider-specific capability. The client neither infers it
+ # from ``introspectable`` nor sends Amazon through Odoo's schema/config endpoints.
+ "enablement": _detail_enablement(rt, bool(is_admin), row),
# ⭐ W49-T14 / R24 — WHETHER THE DATABASES TAB MAY DISCLOSE ANYTHING AT ALL, and what
# THIS reader may do there. An addition to C4, declared on `_detail_introspection`:
# without it an empty `databases` list is "this connector has no schema" and "this
@@ -1957,6 +2043,52 @@ def connector_detail(rt, user, uname, is_admin, connector_key):
"relationships": graph}
+def _set_amazon_database_enablement(database_key, body, session):
+ """The testable core of Amazon's tenant-scoped administrator enablement door."""
+ if not session.admin:
+ raise err(403, "not_admin",
+ "only an administrator can change Amazon database enablement")
+ if not session.runtime.available():
+ raise err(503, "store_unavailable", "the tenant store is unavailable")
+ request = body if isinstance(body, dict) else {}
+ if set(request) != {"enabled"} or type(request.get("enabled")) is not bool:
+ raise err(400, "bad_enabled", "enabled must be true or false")
+
+ import connectors_amazon as cx # noqa: PLC0415 - provider owns state
+ key = str(database_key or "").strip()
+ try:
+ state = cx.set_database_enabled(session.runtime, key, request["enabled"])
+ except KeyError:
+ # One refusal for blank, malformed and cross-provider keys. The response does not expose
+ # the rest of the tenant's Amazon roster.
+ raise err(404, "unknown_amazon_database",
+ "Amazon does not declare a database with that key")
+ except cx.EnablementConfigError:
+ raise err(409, "amazon_enablement_unavailable",
+ "the stored Amazon enablement settings are invalid. Nothing was changed.")
+ except ValueError:
+ raise err(400, "bad_enabled", "enabled must be true or false")
+ except Exception: # noqa: BLE001
+ raise err(503, "enablement_unconfirmed",
+ "the server could not confirm the Amazon database setting. Reload before "
+ "trying again.")
+ return {"provider": cx.ENTRY_TYPE,
+ "key": key,
+ "enabled": state["databases"].get(key) is True,
+ # This route changes only the provider config document. It never deletes a mirror or
+ # a materialised table, and the wire states that invariant explicitly.
+ "preservesData": True}
+
+
+# Literal and provider-owned. It appears before the generic connector detail route so future
+# dynamic route additions cannot turn Amazon enablement into an Odoo-model dispatch by accident.
+@router.patch("/connectors/amazon_sp/databases/{database_key}/enablement")
+def amazon_database_enablement(database_key: str, body: dict = Body(default=None),
+ session: Session = Depends(require_session)):
+ """Enable or disable one declared Amazon database for this tenant, without deleting data."""
+ return _set_amazon_database_enablement(database_key, body, session)
+
+
# ⚠ DECLARED AFTER THE LITERAL `/connectors/odoo/*` ROUTES. FastAPI matches in declaration order,
# and while none of those ends in `/detail` — so no shadowing is possible today — the ordering is
# the habit that keeps it impossible tomorrow. `/connectors/directory` is two segments and cannot
@@ -1977,6 +2109,155 @@ def connectors_detail(connector_key: str, session: Session = Depends(require_ses
return detail
+class _ReplacementConflict(Exception):
+ """The addressed keychain row changed between replacement preparation and its store update."""
+
+
+def _encrypted_replacement_payload(kc, label, entry_type, fields, username):
+ """Validate and encrypt through ``core.keychain.add_entry`` without writing a tenant row.
+
+ ``add_entry`` is the keychain's one validation, preview and Fernet implementation. A tiny
+ memory-only runtime lets this route reuse it while discarding the temporary identity it mints;
+ the tenant store sees only the later, single-row payload swap.
+ """
+ class _Stage:
+ def __init__(self):
+ self.bucket = {}
+
+ def get(self, name):
+ return self.bucket if name == kc.KEY else {}
+
+ def update(self, name, fn, flush="sync"):
+ if name != kc.KEY:
+ raise RuntimeError("the keychain encryptor wrote an unexpected bucket")
+ updated = fn(self.bucket)
+ self.bucket = updated if updated is not None else self.bucket
+ return self.bucket
+
+ stage = _Stage()
+ temporary = kc.add_entry(stage, label, entry_type, fields, username)
+ row = ((stage.bucket.get("entries") or {}).get(str(temporary.get("id") or "")) or {})
+ if not row.get("enc"):
+ raise RuntimeError("the keychain encryptor returned no encrypted payload")
+ return {"enc": str(row["enc"]), "preview": str(row.get("preview") or "")}
+
+
+def _replace_connector_key(connector_key, entry_id, body, session):
+ """Replace only one connector entry's declared secrets while preserving its identity.
+
+ The existing row remains untouched through validation, decryption, merge and encryption. The
+ final store update compares the complete old row before swapping only ``enc`` and ``preview``;
+ a concurrent rename or credential change therefore conflicts instead of being overwritten.
+ Scope and owner live in a separate bucket and are never written by this operation.
+ """
+ if not session.admin:
+ raise err(403, "not_admin",
+ "only an administrator can replace a workspace connection key")
+ if not session.runtime.available():
+ raise err(503, "store_unavailable", "the tenant store is unavailable")
+
+ key = str(connector_key or "").strip()
+ connector = next((row for row in directory(session.runtime, session.uname, True)
+ if str(row.get("key") or "") == key), None)
+ entry_type = _entry_type_for(key)
+ if connector is None or not entry_type:
+ raise err(404, "unknown_connector", "this workspace has no connector with that key")
+ if str(connector.get("manage") or "") not in ("keychain", "keychain_personal"):
+ raise err(403, "replacement_unavailable",
+ "this connector has no replaceable keychain credential")
+
+ import routes_keychain as rk # noqa: PLC0415 - circular at import
+ from core import keychain as kc # noqa: PLC0415 - keep boot lean
+ visible = rk.visible_entries(session.runtime, session.uname, True)
+ entry = next((row for row in visible
+ if str(row.get("id") or "") == str(entry_id)
+ and str(row.get("type") or "") == entry_type), None)
+ if entry is None:
+ # One 404 covers missing, cross-tenant, another user's personal entry and a real id bound
+ # to another connector. The mismatch itself is information this route does not disclose.
+ raise err(404, "no_entry", "no such key for this connector")
+
+ secret_specs = _replacement_field_specs(entry_type)
+ secret_keys = [str(field["key"]) for field in secret_specs]
+ request = body if isinstance(body, dict) else {}
+ supplied = request.get("fields")
+ if set(request) != {"fields"} or not isinstance(supplied, dict):
+ raise err(400, "bad_replacement",
+ "send only the connector's new secret fields")
+ if set(supplied) != set(secret_keys):
+ raise err(400, "bad_replacement",
+ "send every new secret field and no account or server settings")
+ replacements = {}
+ for field in secret_keys:
+ value = supplied.get(field)
+ if not isinstance(value, str) or not value.strip():
+ raise err(400, "bad_replacement", "a replacement secret cannot be blank")
+ replacements[field] = value.strip()
+
+ try:
+ current_fields = kc.read_fields(session.runtime, entry_id)
+ except kc.KeychainLocked as exc:
+ raise err(503, "keychain_locked",
+ f"the keychain is locked: {exc}. Nothing was changed.")
+ except Exception: # noqa: BLE001
+ raise err(503, "store_unavailable",
+ "the current key could not be read. Nothing was changed.")
+ if not isinstance(current_fields, dict) or not current_fields:
+ raise err(409, "credential_unreadable",
+ "the stored credential is incomplete. Nothing was changed.")
+
+ merged_fields = {**current_fields, **replacements}
+ raw_bucket = session.runtime.get(kc.KEY) or {}
+ original = ((raw_bucket.get("entries") or {}).get(str(entry_id)))
+ if not isinstance(original, dict):
+ raise err(409, "credential_changed",
+ "the stored credential changed while replacement was prepared. Reload it.")
+ original = dict(original)
+ try:
+ encrypted = _encrypted_replacement_payload(
+ kc, entry.get("label"), entry_type, merged_fields, session.uname)
+ except kc.KeychainLocked as exc:
+ raise err(503, "keychain_locked",
+ f"the keychain is locked: {exc}. Nothing was changed.")
+ except ValueError as exc:
+ raise err(400, "bad_replacement", str(exc))
+ except Exception: # noqa: BLE001
+ raise err(503, "replacement_not_stored",
+ "the replacement could not be encrypted. The current key is unchanged.")
+
+ def _swap(cur):
+ entries = cur.get("entries") if isinstance(cur, dict) else None
+ stored = entries.get(str(entry_id)) if isinstance(entries, dict) else None
+ if not isinstance(stored, dict) or stored != original:
+ raise _ReplacementConflict()
+ replacement = dict(stored)
+ replacement["enc"] = encrypted["enc"]
+ replacement["preview"] = encrypted["preview"]
+ entries[str(entry_id)] = replacement
+ return cur
+
+ try:
+ session.runtime.update(kc.KEY, _swap, flush="sync")
+ except _ReplacementConflict:
+ raise err(409, "credential_changed",
+ "the stored credential changed while replacement was prepared. Reload it.")
+ except Exception: # noqa: BLE001
+ # A remote store can fail after accepting a write. Claiming either outcome would be a lie;
+ # the safe next act is a fresh detail read, never an automatic retry or delete.
+ raise err(503, "replacement_unconfirmed",
+ "the server could not confirm whether the replacement landed. Reload this "
+ "connector before trying again.")
+ return {"ok": True}
+
+
+@router.post("/connectors/{connector_key}/keychain/{entry_id}/replace")
+def replace_connector_key(connector_key: str, entry_id: str,
+ body: dict = Body(default=None),
+ session: Session = Depends(require_session)):
+ """Admin-only, write-only replacement for one visible connector credential."""
+ return _replace_connector_key(connector_key, entry_id, body, session)
+
+
# ⚠ FIVE SEGMENTS, so it can collide with nothing already declared here: the literal Odoo routes
# are four (`/connectors/odoo/schema/{field_key}`) and `/detail` is three.
@router.patch("/connectors/{connector_key}/databases/{database_key}/name")
diff --git a/api/routes_nav.py b/api/routes_nav.py
index 07546b1ae869a147d1313e294b97f45b192b8867..13162190d3882c910b5a4e657df93f7f218306d6 100644
--- a/api/routes_nav.py
+++ b/api/routes_nav.py
@@ -15,6 +15,7 @@ import time
from fastapi import APIRouter, Body, Depends
from deps import Session, err, perms, require_session
+import application_registry
router = APIRouter(prefix="/api/v1")
@@ -1281,3 +1282,40 @@ def update_schema_map_setup(key: str, body: dict = Body(default=None),
return {"map": {"canConfigure": True,
"fields": map_payload.get("fields") or [],
**active}}
+
+
+@router.get("/nav/application-templates")
+def application_templates(session: Session = Depends(require_session)):
+ """The trusted template contracts the App creation flow may offer."""
+ return {"templates": application_registry.template_contracts()}
+
+
+@router.post("/nav/applications", status_code=201)
+def create_nav_application(body: dict = Body(default=None),
+ session: Session = Depends(require_session)):
+ """Create one tenant Application from the caller's permission-filtered database schema.
+
+ This is a thin nav/schema adapter over the existing Application registry writer. It does not
+ create a View or code module, and it deliberately calls ``nav_schema`` before persistence so
+ a field hidden from this caller cannot be smuggled into an Application definition.
+ """
+ payload = body if isinstance(body, dict) else {}
+ source = str(payload.get("sourceDatabase") or "").strip()
+ if not source:
+ raise err(400, "bad_application", "sourceDatabase is required")
+ schema = nav_schema(source, session)
+ fields = schema.get("fields") if isinstance(schema, dict) else None
+ if not session.runtime.available():
+ raise err(503, "store_unavailable", "the tenant store is unavailable. Nothing was saved.")
+ try:
+ application = application_registry.create(
+ session.runtime, session.tenant, session.uname, payload,
+ field_contracts={source: fields if isinstance(fields, list) else []},
+ allowed_databases={source})
+ except PermissionError as exc:
+ raise err(403, "forbidden", str(exc))
+ except application_registry.ApplicationError as exc:
+ raise err(400, "bad_application", str(exc))
+ except Exception:
+ raise err(503, "store_unavailable", "the Application was not saved.")
+ return {"application": application}
diff --git a/api/routes_odoo_tables.py b/api/routes_odoo_tables.py
index d86d71073e6354bf0de1177ea943207ff94cdea8..025d65118a21cdce083f070823f0f2dd54ac028c 100644
--- a/api/routes_odoo_tables.py
+++ b/api/routes_odoo_tables.py
@@ -24,10 +24,10 @@ import hmac
import json
import time
-from fastapi import Body, Depends
+from fastapi import Body, Depends, HTTPException
from fastapi import APIRouter, Query
-from deps import Session, err, require_session
+from deps import (Session, err, module_cache_rows, module_cache_source, require_session)
router = APIRouter(prefix="/api/v1")
@@ -1128,7 +1128,14 @@ def _source_for(cur, table_key):
DIFFERENT QUESTION and keeps its existing answer: `tables`/`table` must all resolve, and a
spec whose base table the mirror lacks is no binding at all (None, and the caller refuses).
"""
- spec = _sources().get(str(table_key or ""))
+ key = str(table_key or "")
+ # Registry-module pools are databases, but never mirror bindings. In particular,
+ # `product_data` must be reached through its scoped product pool after a relation has resolved
+ # target ids; letting it fall into `_sources()` makes a cache alias look like an absent Odoo
+ # table and turns Products ordered into the wrong 404.
+ if module_cache_source(key) is not None:
+ return None
+ spec = _sources().get(key)
if not spec:
return None
from harness import datastore
@@ -1509,6 +1516,151 @@ def _related_source_value(session, entry, record):
return None
+def _cache_relation_plan(session, source, via, target):
+ """The offered module link and its explicit bridge, or a cause-specific refusal.
+
+ A module/cache target is resolved from its module field declaration because the public
+ relation entry intentionally carries only the edge needed by ordinary one-hop pins. The
+ `through` metadata is not a second inferred graph: it is the exact link bag that declared
+ Products ordered. Resolving against `related_entries` first keeps hidden link fields outside
+ this door just as they are outside the drawer's tab list.
+ """
+ import core.relations as relations
+ from routes_grid import _may_open, related_entries
+
+ source = str(source or "")
+ target = str(target or "")
+ via = str(via or "")
+ if relations.is_retired_table(target):
+ raise err(404, "relation_target_retired",
+ f"'{target}' is retired and is no longer a relation target in this workspace")
+ if module_cache_source(target) is None:
+ raise err(404, "relation_target_missing",
+ f"'{target}' is not a current module/cache relation target in this workspace")
+ if not _may_open(session, source):
+ raise err(403, "not_permitted",
+ f"'{source}' could not be opened for your account, so this relation cannot "
+ "be followed")
+
+ offered = next((entry for entry in related_entries(session, source)
+ if str(entry.get("key") or "") == via
+ and str(entry.get("target") or "") == target
+ and str((entry.get("via") or {}).get("direction") or "") == "forward"),
+ None)
+ if offered is None:
+ raise err(400, "unknown_relation",
+ f"'{via}' is not an available relation from '{source}' to '{target}'")
+
+ field = next((item for item in _rel().module_link_fields(source)
+ if str(item.get("key") or "") == via), None)
+ link = (field or {}).get("link") if isinstance(field, dict) else None
+ if not isinstance(link, dict) or str(link.get("table") or "") != target:
+ raise err(404, "relation_target_missing",
+ f"the relation '{via}' no longer has a current target in this workspace")
+ through = str(link.get("through") or "")
+ through_on = str(link.get("throughOn") or "")
+ through_to = str(link.get("throughTo") or "")
+ on = str(link.get("on") or relations.IDENTITY_COL)
+ if not through or not through_on or not through_to:
+ raise err(409, "relation_target_unavailable",
+ f"the relation '{via}' has no complete stored path to '{target}' right now")
+ if relations.is_retired_table(through):
+ raise err(404, "relation_target_retired",
+ f"'{through}' is retired, so the relation to '{target}' is no longer available")
+ if not _may_open(session, through):
+ raise err(403, "forbidden_table",
+ f"the relation to '{target}' crosses '{through}', which your account cannot "
+ "open")
+ if not _may_open(session, target):
+ raise err(403, "forbidden_table",
+ f"the relation ends at '{target}', which your account cannot open")
+ return dict(offered, __source__=source), link, through, through_on, through_to, on
+
+
+def _cache_relation_source_value(session, entry, record):
+ """Read a cache-backed source value only from a row visible to this session."""
+ import core.relations as relations
+
+ source = str(entry.get("__source__") or "")
+ if module_cache_source(source) is None:
+ return _related_source_value(session, entry, record)
+ try:
+ rows = module_cache_rows(session, source)
+ except HTTPException:
+ raise
+ except Exception as exc: # noqa: BLE001
+ raise err(503, "relation_source_unavailable",
+ f"'{source}' could not be read right now; try this relation again") from exc
+ row = next((item for item in rows if str(item.get("pid")) == str(record)), None)
+ if row is None:
+ raise err(404, "relation_source_missing",
+ f"record {record} is no longer available in '{source}'")
+ frm = str((entry.get("via") or {}).get("from") or relations.IDENTITY_COL)
+ value = row.get("pid") if frm == relations.IDENTITY_COL else row.get(frm)
+ return value if value not in (None, "") else None
+
+
+def _cache_relation_target_ids(session, source, record, via, target):
+ """Resolve one explicit source -> mirror bridge -> module-cache path to target row pids."""
+ entry, _link, through, through_on, through_to, on = _cache_relation_plan(
+ session, source, via, target)
+ source_value = _cache_relation_source_value(session, entry, record)
+ if source_value in (None, ""):
+ raise err(400, "unknown_relation",
+ f"record {record} has no readable source value for relation '{via}'")
+
+ compiled = _compiled_read(through, session)
+ spec = compiled["spec"]
+ left = (spec.get("cols") or {}).get(through_on)
+ right = (spec.get("cols") or {}).get(through_to)
+ if not left or not right:
+ raise err(409, "relation_target_unavailable",
+ f"the stored path through '{through}' is missing a required join column")
+ try:
+ source_value = left[1](source_value)
+ except Exception: # noqa: BLE001
+ source_value = str(source_value)
+
+ frm = spec.get("from_sql") or spec.get("table")
+ where = str(compiled.get("where") or "").strip()
+ params = list(compiled.get("params") or ())
+ predicate = f"({where}) AND " if where else ""
+ sql = (f"SELECT DISTINCT {right[0]} AS related_value FROM {frm} WHERE "
+ f"{predicate}{left[0]} = ? AND {right[0]} IS NOT NULL")
+ values = {str(row[0]) for row in compiled["cur"].execute(
+ sql, params + [source_value]).fetchall() if row and row[0] not in (None, "")}
+
+ try:
+ target_rows = module_cache_rows(session, target)
+ except HTTPException:
+ raise
+ except Exception as exc: # noqa: BLE001
+ raise err(503, "relation_target_unavailable",
+ f"'{target}' could not be read right now; try this relation again") from exc
+ ids = []
+ seen = set()
+ for row in target_rows:
+ if str(row.get(on)) not in values:
+ continue
+ try:
+ pid = int(row.get("pid"))
+ except (TypeError, ValueError):
+ continue
+ if pid > 0 and pid not in seen:
+ seen.add(pid)
+ ids.append(pid)
+ return {"ok": True, "sourceKind": "module_cache", "target": str(target),
+ "ids": ids, "path": [str(source), through, str(target)]}
+
+
+@router.get("/odoo-tables/relation-targets")
+def odoo_relation_targets(source: str = Query(...), record: int = Query(..., ge=1),
+ via: str = Query(...), target: str = Query(...),
+ session: Session = Depends(require_session)):
+ """Target pids for a declared relation whose destination is a runtime-cache database."""
+ return _cache_relation_target_ids(session, source, record, via, target)
+
+
def _via_path(via):
"""The list of EDGE KEYS a `via` names, or None when it is one edge's bag instead.
diff --git a/api/routes_sheet.py b/api/routes_sheet.py
index f4267e8ea022ab2d5fed606802157e0b353adc60..c1b7e7b231b2d4ad0dc600b3c3e67f9aefb06342 100644
--- a/api/routes_sheet.py
+++ b/api/routes_sheet.py
@@ -591,6 +591,22 @@ def _view_filter_once(session: Session, database: str, view_id: str, view_name:
return rot._fe().tree_parts(sheets_mod.adopted_scope_filter(view))
+def _materialize_copy_binding(raw_binding, filter_tree):
+ """A copied saved-View binding with its own filter, without mutating either input.
+
+ R5 is deliberately a COPY-TIME action. The source cell keeps following its saved View, while
+ the copy receives a deep local shadow and can step a chosen leaf without editing shared View
+ state. A binding already scoped to a local filter passes through the normal cleaner unchanged.
+ """
+ from modules import sheet as sheet_mod
+ import copy as _copy
+
+ binding = sheet_mod.clean_binding(raw_binding)
+ if not binding["scope"].get("view_id"):
+ return binding
+ return {**binding, "scope": {"filter": _copy.deepcopy(filter_tree)}}
+
+
#: ⛔ THE TWO CAP CODES ANSWER 413, NOT 400 (contract C3). A 400 says the request was malformed and
#: sends a client looking for a typo; these two say the request was perfectly well formed and the
#: DOCUMENT it would produce cannot be stored, which is what 413 means and is the only status a
@@ -1913,6 +1929,59 @@ def preview_cell(workbook_id: str, addr: str, body: dict = Body(default=None),
"limits": out["limits"]}
+@router.post("/sheets/{workbook_id}/binding-shadows")
+def binding_shadows(workbook_id: str, body: dict = Body(default=None),
+ session: Session = Depends(require_session)):
+ """Canonical saved-View filters needed before copied bindings step (C5, R5).
+
+ request: `{"bindings": [, ...]}`
+ response: `{"shadows": [{database, viewId, filter}, ...]}`
+
+ The source bindings and saved Views are read only. The browser materialises each returned tree
+ into the copied binding, commits the stale cells immediately, then schedules Save's evaluator.
+ The editor wall is intentional: this door exists only to prepare a workbook write, and a
+ viewer must never turn a reader-specific filter into the owner's stored document.
+ """
+ from core import sheets
+ from modules import sheet as sheet_mod
+
+ try:
+ book = sheets.get_workbook(_store(session), workbook_id)
+ _require_editor(session, book)
+ except sheets.SheetRefusal as exc:
+ raise _refuse(exc)
+
+ raw_bindings = (body or {}).get("bindings")
+ if not isinstance(raw_bindings, list):
+ raise err(400, "sheet_bindings_required",
+ "Choose the database cells whose saved Views should be copied.")
+
+ shadows = []
+ seen = set()
+ view_memo = {}
+ for raw in raw_bindings:
+ try:
+ binding = sheet_mod.clean_binding(raw)
+ except sheet_mod.SheetRefusal as exc:
+ raise err(400, exc.code, exc.message)
+ scope = binding["scope"]
+ view_id = str(scope.get("view_id") or "")
+ if not view_id:
+ continue
+ database = _require_database(session, binding["database"])
+ slot = (database, view_id)
+ if slot in seen:
+ continue
+ seen.add(slot)
+ nodes, conj = _view_filter(session, database, view_id, scope.get("view_name", ""),
+ memo=view_memo)
+ local = _materialize_copy_binding(
+ binding, {"conj": conj, "nodes": nodes})
+ shadows.append({"database": database, "viewId": view_id,
+ "filter": local["scope"]["filter"]})
+ return {"shadows": shadows}
+
+
@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)):
diff --git a/platform/core/connector_spec.py b/platform/core/connector_spec.py
index 38aba5c3667a4443a40f4945310c9cd21b24ae4e..45aa4249d8573e27187f5bd0800b37185f73d06c 100644
--- a/platform/core/connector_spec.py
+++ b/platform/core/connector_spec.py
@@ -49,12 +49,40 @@ because a tautology is exactly what catches a hand edit that re-introduces a lit
no `"odoo"` entry and no stub for one; `edges_for("odoo")` returns `[]` until that ticket lands.
"""
from dataclasses import dataclass, replace
+import hashlib
+import re
#: ⭐ THE CARDINALITY VOCABULARY, AS A CONSTANT SO EVERY CONSUMER CHECKS MEMBERSHIP RATHER THAN
#: SPELLING. The relation wire (W53-T17) and the parity gate both read this set; a fifth value
#: added by hand in a link tuple goes red instead of travelling silently to a screen.
CARDINALITIES = ("many_to_one", "one_to_many", "one_to_one", "many_to_many")
+# The discoverable Odoo catalogue is runtime data, because two API accounts can read different
+# installed modules. Only its stable naming rule belongs in this tenant-independent spec layer.
+# A digest closes the otherwise-real collision between model names such as ``x.a_b`` and
+# ``x_a.b`` after punctuation is normalised for a ``ut_*`` key.
+ODOO_MODEL_TABLE_PREFIX = "ut_odoo_model_"
+
+
+def odoo_model_table_key(model):
+ """Stable ``ut_*`` key for one vendor model name; blank/invalid input is refused."""
+ native = str(model or "").strip().lower()
+ if not native or not re.fullmatch(r"[a-z0-9_.]+", native):
+ raise ValueError("an Odoo model name may contain only lowercase letters, digits, dots and underscores")
+ # 18 + the 14-character prefix + separator + digest leaves room for the connector's
+ # ``__k_<12 hex>`` namespace under user_tables' 60-character key ceiling.
+ stem = re.sub(r"[^a-z0-9]+", "_", native).strip("_")[:18] or "model"
+ digest = hashlib.sha256(native.encode("utf-8")).hexdigest()[:10]
+ return f"{ODOO_MODEL_TABLE_PREFIX}{stem}_{digest}"
+
+
+def odoo_model_label(model, vendor_label=""):
+ """Our default database label, while preserving Odoo's own label when it supplied one."""
+ label = " ".join(str(vendor_label or "").split())
+ if label:
+ return label[:80]
+ return str(model or "").replace(".", " ").replace("_", " ").strip().capitalize()[:80]
+
@dataclass(frozen=True)
class ConnectorTableSpec:
@@ -391,5 +419,6 @@ register("amazon", AMAZON_TABLES)
register("meta", META_TABLES)
__all__ = ["CARDINALITIES", "ConnectorTableSpec", "SPECS", "AMAZON_TABLES", "META_TABLES",
+ "ODOO_MODEL_TABLE_PREFIX", "odoo_model_table_key", "odoo_model_label",
"register", "connectors", "tables_for", "all_specs", "spec_for", "connector_of",
"edges_for"]
diff --git a/web/src/connectors/ConnectorModal.tsx b/web/src/connectors/ConnectorModal.tsx
index e481847f96ad7ff559c2d5c060e513278861395a..79316f5f733391f56a2b5aa11442b8007dee8785 100644
--- a/web/src/connectors/ConnectorModal.tsx
+++ b/web/src/connectors/ConnectorModal.tsx
@@ -63,6 +63,7 @@ import type { ConnectorRelationshipGraph, ConnectorRow } from "./ConnectorsPage"
import { parseRelationshipGraph } from "./ConnectorsPage";
import "../styles/wave49/connectors.css";
import "../styles/wave52/connectors.css";
+import "../styles/wave55/connectors.css";
/** R26's original four, plus "cadence" (W52-T04, the done-when's "sync cadence" section). */
export type ConnectorTab = "overview" | "keychain" | "databases" | "relationships" | "cadence";
@@ -126,6 +127,8 @@ export interface ConnectorKeychainEntry {
masked: string;
scope: string;
testable: boolean;
+ /** Server-owned admin permission for the write-only replacement flow. */
+ replaceable: boolean;
}
/**
@@ -233,10 +236,24 @@ export interface ConnectorIntrospection {
excludedBasis: string;
}
+/** W55-T19 / R7 — one provider's own database-enablement door. */
+export interface ConnectorEnablement {
+ /** Must match the connector detail envelope that carried it. */
+ provider: string;
+ /** Read as a string so a future provider mode fails closed instead of widening this UI. */
+ mode: string;
+ canManage: boolean;
+ updatePath: string;
+ /** The Amazon route changes only config; stored database rows remain in place. */
+ preservesData: boolean;
+ available: boolean;
+}
+
export interface ConnectorDetail {
overview: ConnectorOverview;
keychain: ConnectorKeychainHalf;
databases: ConnectorDatabase[];
+ enablement: ConnectorEnablement | null;
introspection: ConnectorIntrospection;
relationships: ConnectorRelationshipGraph;
}
@@ -265,6 +282,7 @@ function parseKeychainHalf(raw: unknown): ConnectorKeychainHalf {
masked: str(entry.masked),
scope: str(entry.scope).trim(),
testable: entry.testable === true,
+ replaceable: entry.replaceable === true,
});
}
return {
@@ -381,6 +399,36 @@ function parseIntrospection(raw: unknown): ConnectorIntrospection {
};
}
+/**
+ * Parse a provider capability bound to the selected connector, or refuse it.
+ *
+ * A path is actionable only when it stays under this provider and carries the one database-key
+ * slot the server declared. Missing, cross-provider and unknown modes render no control; the API
+ * remains the permission boundary, but the modal never paints a button it knows cannot work.
+ */
+export function parseConnectorEnablement(
+ raw: unknown,
+ selectedKey: string
+): ConnectorEnablement | null {
+ const source = obj(raw);
+ const provider = str(source.provider).trim();
+ const mode = str(source.mode).trim();
+ if (provider !== selectedKey || mode !== "database" || source.preservesData !== true) return null;
+ const updatePath = str(source.updatePath).trim();
+ const expectedPrefix = `/connectors/${encodeURIComponent(provider)}/databases/`;
+ const validPath = updatePath.startsWith(expectedPrefix) && updatePath.endsWith("/enablement")
+ && updatePath.includes("{databaseKey}");
+ const canManage = source.canManage === true && source.available === true && validPath;
+ return {
+ provider,
+ mode,
+ canManage,
+ updatePath: canManage ? updatePath : "",
+ preservesData: true,
+ available: source.available === true,
+ };
+}
+
/**
* Read the detail payload for the card that was actually clicked.
*
@@ -405,6 +453,7 @@ export function parseConnectorDetail(body: unknown, selectedKey: string): Connec
},
keychain: parseKeychainHalf(source.keychain),
databases: parseDatabases(source.databases),
+ enablement: parseConnectorEnablement(source.enablement, selectedKey),
introspection: parseIntrospection(source.introspection),
relationships: parseRelationshipGraph(source.relationships, selectedKey),
};
@@ -529,6 +578,96 @@ export function ConnectorOverviewPanel({
);
}
+/** Amazon's provider-specific administrator controls, separate from Odoo's model catalogue. */
+export function ProviderEnablementPanel({
+ detail,
+ onChanged,
+}: {
+ detail: ConnectorDetail;
+ onChanged: () => void;
+}) {
+ const capability = detail.enablement;
+ const [busyKey, setBusyKey] = useState("");
+ const [message, setMessage] = useState("");
+ if (!capability?.canManage || !capability.updatePath) return null;
+
+ const setEnabled = async (database: ConnectorDatabase, enabled: boolean) => {
+ const path = capability.updatePath.replace(
+ "{databaseKey}",
+ encodeURIComponent(database.key)
+ );
+ if (path === capability.updatePath) {
+ setMessage("This provider did not return a usable enablement path.");
+ return;
+ }
+ setBusyKey(database.key);
+ setMessage("");
+ let saved = false;
+ try {
+ const res = await fetch(`${API_V1}${path}`, {
+ method: "PATCH",
+ credentials: CREDENTIALS,
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ enabled }),
+ });
+ const body = (await res.json().catch(() => null)) as
+ | { error?: { message?: string } }
+ | null;
+ if (!res.ok) {
+ setMessage(body?.error?.message || `The server answered ${res.status}.`);
+ return;
+ }
+ saved = true;
+ onChanged();
+ } catch {
+ setMessage("Cannot reach the server.");
+ } finally {
+ // A successful write immediately asks the modal to re-read and leaves the old switches
+ // disabled until that load guard replaces them. An error keeps the current detail and must
+ // release the control for a retry.
+ if (!saved) setBusyKey("");
+ }
+ };
+
+ return (
+
+
+
Enablement
+
Choose which Amazon databases are enabled. Switching one off keeps its stored rows.
+
+
+ {detail.databases.map((database) => (
+
+ {database.label}
+
+ {database.enabled ? "On" : "Off"}
+ void setEnabled(database, !database.enabled)}
+ >
+
+
+
+
+ ))}
+
+
+ {message}
+
+
+ );
+}
+
// ── The three tabs that are not built yet. ⛔ EACH IS ITS OWN COMPONENT SLOT so W49-T13, T14 and
// T15 replace a named component rather than editing a sentence out of a branch, and the switch
// below never has to change shape. Plain sentences, no dashes, no emojis.
@@ -708,7 +847,12 @@ export default function ConnectorModal({
return ;
}
if (tab === "databases") {
- return ;
+ return (
+ <>
+
+
+ >
+ );
}
if (tab === "relationships") {
return ;
diff --git a/web/src/connectors/DatabasesTab.tsx b/web/src/connectors/DatabasesTab.tsx
index 2486d50000b6f3a228ffb0bbbc2c417d40bcd097..0f706dc6a60be958771ba075e3da8eb490652656 100644
--- a/web/src/connectors/DatabasesTab.tsx
+++ b/web/src/connectors/DatabasesTab.tsx
@@ -402,6 +402,17 @@ export default function DatabasesTab({
for (const database of databases) out[database.key] = database.label;
return out;
}, [databases]);
+ const orderedDatabases = useMemo(
+ () =>
+ databases
+ .map((database, index) => ({ database, index }))
+ .sort(
+ (a, b) =>
+ Number(b.database.enabled) - Number(a.database.enabled) || a.index - b.index
+ )
+ .map(({ database }) => database),
+ [databases]
+ );
/**
* ⛔⛔ R23's ENFORCEMENT, AND TODAY IT LIVES HERE. The write door is
@@ -514,8 +525,8 @@ export default function DatabasesTab({
) : null}
- {databases.length} databases are created from this
- connection.
+ {databases.length} databases are available from this
+ connection. Enabled databases are first.
{/* ⛔ THE IDENTITY BLOCK IS EXPLAINED, NOT INFERRED FROM A GREYED CONTROL. Which of the
three names is ours, which is theirs and which one a rename touches is the question this
@@ -535,7 +546,7 @@ export default function DatabasesTab({
Enabled
- {databases.map((database) => {
+ {orderedDatabases.map((database) => {
const isOpen = open[database.key] === true;
const refusal = refusals[database.key] || "";
return (
diff --git a/web/src/connectors/KeychainTab.tsx b/web/src/connectors/KeychainTab.tsx
index 7db5228f1249c189e21e378d76df96231ccc5ef3..0a7bcb2c11b1e0f27452162dd1c7472ce731ec4e 100644
--- a/web/src/connectors/KeychainTab.tsx
+++ b/web/src/connectors/KeychainTab.tsx
@@ -75,9 +75,7 @@ async function post(path: string, body?: unknown): Promise {
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body ?? {}),
});
- const payload = (await res.json().catch(() => null)) as
- | { error?: { message?: string } }
- | null;
+ const payload = (await res.json().catch(() => null)) as { error?: { message?: string } } | null;
if (!res.ok) return payload?.error?.message || `The server answered ${res.status}.`;
return "";
} catch {
@@ -220,6 +218,100 @@ function ConnectForm({
);
}
+/**
+ * A stored credential is never opened into this form. Every field starts empty and the current
+ * key remains active while the server validates, merges and encrypts the replacement. Only the
+ * server-declared secret fields render; account, server and database settings never cross back
+ * through the browser.
+ */
+function ReplaceForm({
+ connectorKey,
+ spec,
+ entry,
+ onDone,
+ onCancel,
+}: {
+ connectorKey: string;
+ spec: ConnectorConnectSpec;
+ entry: ConnectorKeychainEntry;
+ onDone: () => void;
+ onCancel: () => void;
+}) {
+ const [values, setValues] = useState>({});
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const fields = spec.fields.filter((field) => field.secret);
+ const complete =
+ fields.length > 0 && fields.every((field) => Boolean((values[field.key] || "").trim()));
+
+ const save = async () => {
+ if (busy || !complete) return;
+ setBusy(true);
+ setError("");
+ const replacement = Object.fromEntries(
+ fields.map((field) => [field.key, (values[field.key] || "").trim()])
+ );
+ const message = await post(
+ `/connectors/${encodeURIComponent(connectorKey)}/keychain/${encodeURIComponent(entry.id)}/replace`,
+ { fields: replacement }
+ );
+ if (message) {
+ setError(message);
+ setBusy(false);
+ return;
+ }
+ // Dropping this component clears every write-only value from React state before the detail
+ // payload is fetched again. No submitted credential is copied into a response-facing model.
+ onDone();
+ };
+
+ return (
+
+
Replace key
+
+ The current key stays unchanged until the complete replacement is stored.
+
+ {fields.map((field) => (
+
+
+ {`New ${field.label.toLocaleLowerCase()}`}
+
+
+ setValues((current) => ({ ...current, [field.key]: event.target.value }))
+ }
+ />
+
+ ))}
+
+ {error ? (
+
+ {error}
+
+ ) : null}
+
+
+
+ Cancel
+
+ void save()}
+ >
+ {busy ? "Replacing" : "Store replacement"}
+
+
+
+ );
+}
+
/**
* ⭐ THE PANEL, PURE AND EXPORTED, for the reason `ConnectorOverviewPanel` is: the modal fetches
* on mount and `renderToStaticMarkup` runs no effects, so a static proof of this tab has to be
@@ -240,6 +332,7 @@ export default function KeychainTab({
const [tested, setTested] = useState>({});
const [error, setError] = useState("");
const [adding, setAdding] = useState(false);
+ const [replacing, setReplacing] = useState(null);
const runTest = useCallback(async (entry: ConnectorKeychainEntry) => {
setTested((current) => ({ ...current, [entry.id]: "Testing" }));
@@ -322,6 +415,21 @@ export default function KeychainTab({
);
}
+ if (replacing && keychain.connect) {
+ return (
+ setReplacing(null)}
+ onDone={() => {
+ setReplacing(null);
+ onChanged();
+ }}
+ />
+ );
+ }
+
return (
{error ? (
@@ -339,7 +447,7 @@ export default function KeychainTab({
{/* An empty preview is a RULE, not a gap: R4 withholds the last four characters
of a business key from a member who did not store it, and saying so is
better than an empty cell that reads as a bug. */}
- {entry.masked || "The preview is hidden for connections you did not add"}
+ {entry.masked ? `Stored key ${entry.masked}` : "Stored key. Preview hidden"}
{" · "}
{scopeLabel(entry.scope)}
@@ -350,6 +458,16 @@ export default function KeychainTab({
) : null}
+ {entry.replaceable && keychain.connect ? (
+
setReplacing(entry)}
+ >
+ Replace
+
+ ) : null}
{entry.testable ? (
void;
onReconnect: () => void;
}) {
- const grids = cfg.grids ?? [];
+ const grids = useMemo(
+ () =>
+ (cfg.grids ?? [])
+ .map((grid, index) => ({ grid, index }))
+ .sort(
+ (a, b) => Number(b.grid.enabled) - Number(a.grid.enabled) || a.index - b.index
+ )
+ .map(({ grid }) => grid),
+ [cfg.grids]
+ );
const options = cfg.syncOptions ?? [];
const on = grids.filter((g) => g.enabled).length;
return (
@@ -113,12 +125,17 @@ export default function OdooConfigPanel({
{/* ── the credential, as much of it as may be shown ────────────────────────────────── */}
- Key
+ Credential
{cfg.preview ? cfg.preview : "held on this deployment"}
- {cfg.apiUser ? " · " + cfg.apiUser : ""}
+ {cfg.apiUser ? (
+
+ Account
+ {cfg.apiUser}
+
+ ) : null}
{cfg.serverUrl ? (
Server
@@ -143,7 +160,7 @@ export default function OdooConfigPanel({
/>
) : (
- {cfg.serverDb || "—"}
+ {cfg.serverDb || "Not set"}
{/* R6's second sentence: a thing you cannot change says WHY, not nothing. */}
(set on this deployment, not in this workspace)
@@ -152,7 +169,7 @@ export default function OdooConfigPanel({
{/* ── R9's second reading: WHICH grids this workspace materialises ─────────────────── */}
- Databases to build {on} of {grids.length}
+ Databases available {on} of {grids.length} enabled
{grids.map((g) => (
@@ -171,25 +188,32 @@ export default function OdooConfigPanel({
database; it does not delete the one you already have. A checkbox that silently threw
away rows would be the worst control on this page. */}
- Unticking one stops it being rebuilt on the next sync. Nothing you already have is
- deleted.
+ Switching one off stops its next refresh. Its rows, fields, and access stay in this
+ workspace.
{/* ── R11: the cadence, from the server's own preset list, floor included ──────────── */}
-
How often to sync
-
onSyncEvery(e.target.value)}
- >
- {options.map((o) => (
-
- {everyLabel(o)}
-
- ))}
-
+
+ Sync
+ onSyncEvery(e.target.value)}
+ >
+ {options.map((o) => (
+
+ {everyLabel(o)}
+
+ ))}
+
+ {cfg.syncFloorSeconds ? (
+
+ Minimum {Math.ceil(cfg.syncFloorSeconds / 60)} minutes
+
+ ) : null}
+
{/* ── R10: off, and back on ────────────────────────────────────────────────────────── */}
{cfg.frozen ? (
diff --git a/web/src/connectors/RelationshipDiagram.tsx b/web/src/connectors/RelationshipDiagram.tsx
index 4f07b476ef4690f386aad8cb4d56eed66807f7cf..d83bd9471f6f83648b309255761c0693403523f9 100644
--- a/web/src/connectors/RelationshipDiagram.tsx
+++ b/web/src/connectors/RelationshipDiagram.tsx
@@ -51,7 +51,7 @@
// constant here to the `--lp-fs-*` token used by the matching rule.
// ---------------------------------------------------------------------------
-import { useCallback, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ConnectorRelationshipGraph } from "./ConnectorsPage";
import "../styles/wave49/connectors.css";
@@ -246,7 +246,11 @@ function moreLabel(hidden: number, expanded: boolean): string {
* function under node and proves the geometry over its return value, so every
* number a reader sees on the screen is a number the gate has checked.
*/
-export function relationshipLayout(graph: DiagramInput, expandedKeys: string[] = []): DiagramLayout {
+export function relationshipLayout(
+ graph: DiagramInput,
+ expandedKeys: string[] = [],
+ availableWidth = 0
+): DiagramLayout {
const expanded = new Set(expandedKeys);
const tables = graph.tables.slice();
const relationships = graph.relationships.slice();
@@ -398,7 +402,13 @@ export function relationshipLayout(graph: DiagramInput, expandedKeys: string[] =
// ---- the tables no relationship touches, in a wrapped grid under the bands.
const singles = tables.filter((table) => !linkedTables.has(table.key));
const linkedWidth = bandMembers.length ? CARD_W * 2 + GUTTER : CARD_W * 3 + SINGLE_GAP * 2;
- const perRow = Math.max(1, Math.floor((linkedWidth + SINGLE_GAP) / (CARD_W + SINGLE_GAP)));
+ // T17 can add any number of readable models. Use the measured viewport when it exists so
+ // those server-owned nodes consume the room the modal actually has instead of remaining in a
+ // fixed three-card canvas. The default preserves deterministic bare-node gate geometry.
+ const singlesWidth = availableWidth > 0
+ ? Math.max(CARD_W, availableWidth - PAD * 2)
+ : linkedWidth;
+ const perRow = Math.max(1, Math.floor((singlesWidth + SINGLE_GAP) / (CARD_W + SINGLE_GAP)));
let singleRowTop = cursorY;
let rowHeight = 0;
singles.forEach((table, index) => {
@@ -612,6 +622,7 @@ export function relationshipLayout(graph: DiagramInput, expandedKeys: string[] =
for (const card of cards) width = Math.max(width, card.x + card.width);
for (const edge of edges) width = Math.max(width, edge.corridorX);
for (const text of texts) width = Math.max(width, text.x + text.width);
+ if (availableWidth > 0) width = Math.max(width, availableWidth - PAD);
let height = PAD;
for (const card of cards) height = Math.max(height, card.y + card.height);
for (const text of texts) height = Math.max(height, text.y + text.height);
@@ -679,9 +690,27 @@ export default function RelationshipDiagram({
graph: ConnectorRelationshipGraph;
}) {
const [expandedKeys, setExpandedKeys] = useState
([]);
+ const scrollRef = useRef(null);
+ const [availableWidth, setAvailableWidth] = useState(0);
// ⚠ HOOKS BEFORE ANY EARLY RETURN. A refused graph must not change the hook
// order between renders ([[react-hooks-order-gate]]).
- const layout = useMemo(() => relationshipLayout(graph, expandedKeys), [graph, expandedKeys]);
+ useEffect(() => {
+ const surface = scrollRef.current;
+ if (!surface) return;
+ const measure = () => setAvailableWidth(Math.max(0, Math.floor(surface.clientWidth)));
+ measure();
+ if (typeof ResizeObserver === "undefined") {
+ window.addEventListener("resize", measure);
+ return () => window.removeEventListener("resize", measure);
+ }
+ const observer = new ResizeObserver(measure);
+ observer.observe(surface);
+ return () => observer.disconnect();
+ }, []);
+ const layout = useMemo(
+ () => relationshipLayout(graph, expandedKeys, availableWidth),
+ [availableWidth, graph, expandedKeys]
+ );
const toggle = useCallback((key: string) => {
setExpandedKeys((keys) => (keys.includes(key) ? keys.filter((k) => k !== key) : keys.concat(key)));
}, []);
@@ -699,7 +728,7 @@ export default function RelationshipDiagram({
return (
-
+
void;
+}) {
+ const items = useMemo(
+ () => catalogApplicationItems(rows, definition.fieldMap),
+ [rows, definition.fieldMap],
+ );
+ return (
+
+
+
+
Catalog app
+
{definition.name}
+
+
+ {items.length.toLocaleString()} {items.length === 1 ? "record" : "records"}
+
+
+ {items.length ? (
+
+ {items.map((item) => (
+
onOpen(item.pid)}
+ aria-label={`Open ${item.title}`}
+ >
+
+ {item.image ? (
+
+ ) : (
+ No image
+ )}
+
+
+ {item.title}
+ {item.key}
+
+
+ ))}
+
+ ) : (
+ No records have a value in the mapped key field.
+ )}
+
+ );
+});
+
// ------------------------------------------------------------------- marks
const STROKE = {
diff --git a/web/src/customer-grid/MapView.tsx b/web/src/customer-grid/MapView.tsx
index b37391820f8a789c5d31896bb45781a51a46c8e7..e5ab5d4c66b215aa3db92a50a183d9e8cce353a2 100644
--- a/web/src/customer-grid/MapView.tsx
+++ b/web/src/customer-grid/MapView.tsx
@@ -55,8 +55,12 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from "react";
import type { Field, Row, ViewConfig } from "./types";
-import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
+import { API_V1, CREDENTIALS, NAV_MINIMIZE_EVENT, signal } from "../apiContract";
import { formatDisplay } from "./cells";
+import { readDataPath } from "./dataPath";
+import { CatalogApplicationView } from "./CatalogView";
+import type { CatalogApplicationDefinition } from "./CatalogView";
+import { applicationTemplateSurface } from "./viewModes";
import { LAND_PATH, LAKE_PATHS } from "./mapGeometry";
import {
BASEMAP_DETAIL_K,
@@ -641,7 +645,7 @@ function DrawZoneIcon() {
);
}
-export function MapView({
+function MapViewSurface({
rows,
field,
coordinateFields,
@@ -659,6 +663,7 @@ export function MapView({
tableKey,
onManagedRouteViewState,
onZoneChanged,
+ applicationName,
}: {
/** DISTINCT data rows from the full pipeline, overlay edits layered — the
* calendar/kanban contract, verbatim. */
@@ -708,6 +713,9 @@ export function MapView({
/** Customer Zones also project into the read-only grid field, so a successful normalized
* mutation invalidates the host row payload instead of leaving that projection stale. */
onZoneChanged?: () => void;
+ /** Saved Routing Application identity, shown in the route navigator without changing the
+ * existing View or its route assets. */
+ applicationName?: string;
/**
* ⭐⭐ OWNER ITEM 9 — THE WHOLE BOOK, so a stop can be added that the VIEW filtered out.
*
@@ -3580,7 +3588,7 @@ export function MapView({
if (!view || !fit) {
return (
-
+
No records with a location to map yet. Set latitude and longitude fields in View schema to plot records.
{noCoords > 0 &&
` ${noCoords.toLocaleString()} matching record${noCoords === 1 ? "" : "s"} have no location.`}
@@ -3667,7 +3675,7 @@ export function MapView({
return (
+ {applicationName ? (
+
Routing app {applicationName}
+ ) : null}
{/* The count is "N of M", never a bare N: a pin can only be drawn for a
row the host geocoded, and a lone "1,402" silently redefines the
toolbar's 1,550 ([[no-unverifiable-aggregates]]). */}
@@ -4598,6 +4609,7 @@ export function MapView({
is already loaded here to draw the map, so RouteNav gets a pass-through and
never a second fetch of its own. */}
);
}
+
+type MapViewProps = Parameters[0];
+
+interface RegistryTemplateApplication {
+ id: string;
+ name: string;
+ type: string;
+ templateKind?: unknown;
+ sourceDatabase?: unknown;
+ fieldMap?: unknown;
+ openTarget?: { database?: unknown };
+ compatibleDatabases?: unknown[];
+}
+
+type TemplateApplicationState =
+ | { phase: "idle" }
+ | { phase: "loading"; key: string }
+ | { phase: "ready"; key: string; application: RegistryTemplateApplication | null }
+ | { phase: "error"; key: string; message: string };
+
+/** Resolve an Application deep link from the registry before selecting a specialized renderer.
+ * CustomerGrid still applies the definition's ordinary display config; this wrapper only handles
+ * the route and catalog discriminators which deliberately share the trusted Map mode. */
+export function MapView(props: MapViewProps) {
+ const target = readDataPath();
+ const applicationId = target?.application ?? "";
+ const database = target?.database ?? "";
+ const requestKey = applicationId && database ? `${database}::${applicationId}` : "";
+ const [state, setState] = useState(() => requestKey
+ ? { phase: "loading", key: requestKey }
+ : { phase: "idle" });
+ const requestGeneration = useRef(0);
+
+ useEffect(() => {
+ const mine = ++requestGeneration.current;
+ if (!applicationId || !database) {
+ setState({ phase: "idle" });
+ return;
+ }
+ const controller = new AbortController();
+ setState({ phase: "loading", key: requestKey });
+ void fetch(`${API_V1}/applications?database=${encodeURIComponent(database)}`, {
+ credentials: CREDENTIALS,
+ signal: controller.signal,
+ }).then(async (response) => {
+ const body = await response.json().catch(() => ({}));
+ if (!response.ok) {
+ throw new Error(String(
+ body?.detail?.message ?? body?.detail ?? "The Application could not be loaded.",
+ ));
+ }
+ const applications = Array.isArray(body?.applications)
+ ? body.applications as RegistryTemplateApplication[]
+ : [];
+ const application = applications.find((candidate) => candidate.id === applicationId) ?? null;
+ if (!application) throw new Error("This Application is no longer available.");
+ const compatible = application.openTarget?.database === database ||
+ application.compatibleDatabases?.includes(database) === true;
+ if (!compatible) throw new Error("This Application cannot open this database.");
+ if (controller.signal.aborted || mine !== requestGeneration.current) return;
+ const live = readDataPath();
+ if (live?.application !== applicationId || live.database !== database) return;
+ setState({ phase: "ready", key: requestKey, application });
+ }).catch((error: unknown) => {
+ if (controller.signal.aborted || mine !== requestGeneration.current) return;
+ setState({
+ phase: "error",
+ key: requestKey,
+ message: error instanceof Error ? error.message : "The Application could not be loaded.",
+ });
+ });
+ return () => controller.abort();
+ }, [applicationId, database, requestKey]);
+
+ if (applicationId && (state.phase === "idle" || state.key !== requestKey || state.phase === "loading")) {
+ return (
+
+
+
+
+
+ );
+ }
+ if (applicationId && state.phase === "error" && state.key === requestKey) {
+ return {state.message}
;
+ }
+
+ const application = state.phase === "ready" && state.key === requestKey ? state.application : null;
+ const surface = applicationTemplateSurface(application);
+ const fieldMap = application?.fieldMap && typeof application.fieldMap === "object" &&
+ !Array.isArray(application.fieldMap)
+ ? application.fieldMap as Record
+ : {};
+
+ if (surface === "catalog") {
+ const key = String(fieldMap.key ?? "");
+ const title = String(fieldMap.title ?? "");
+ if (!application || !key || !title) {
+ return The Catalog field mapping is incomplete.
;
+ }
+ const definition: CatalogApplicationDefinition = {
+ id: application.id,
+ name: application.name,
+ templateKind: "catalog",
+ sourceDatabase: String(application.sourceDatabase ?? database),
+ fieldMap: {
+ key,
+ title,
+ ...(fieldMap.image ? { image: String(fieldMap.image) } : {}),
+ },
+ };
+ return ;
+ }
+
+ if (surface === "route" && application) {
+ const titleKey = String(fieldMap.title ?? "");
+ const latitudeKey = String(fieldMap.latitude ?? "");
+ const longitudeKey = String(fieldMap.longitude ?? "");
+ const coordinateFields = latitudeKey && longitudeKey
+ ? {
+ latitude: { ...props.field, key: latitudeKey, label: "Latitude" },
+ longitude: { ...props.field, key: longitudeKey, label: "Longitude" },
+ }
+ : props.coordinateFields;
+ return (
+
+ );
+ }
+
+ return ;
+}
diff --git a/web/src/customer-grid/RecordDetail.css b/web/src/customer-grid/RecordDetail.css
index dc0a98d659d273395b71ff1d831f30892bf290aa..d9844a9d97ba43e25c09ebda1b64b90fff380591 100644
--- a/web/src/customer-grid/RecordDetail.css
+++ b/web/src/customer-grid/RecordDetail.css
@@ -892,6 +892,83 @@
opacity: 0.6;
}
+/* W55-T15: one compact control row above every related projection. It reserves the same height
+ before and after a mode change, and the hairline is the drawer's only internal separator. */
+.cg-record-related-modebar {
+ flex: 0 0 40px;
+ min-width: 0;
+ min-height: 40px;
+ display: flex;
+ align-items: center;
+ padding: 0 12px;
+ border-bottom: 1px solid var(--lp-line);
+ background: var(--lp-surface);
+}
+
+.cg-record-related-modebar .cg-modes,
+.cg-record-related-modebar .cg-tb-btn,
+.cg-record-related-modebar .cg-mode-field {
+ min-height: 28px;
+ align-items: center;
+ line-height: 1;
+}
+
+/* The canonical projection owns its scrolling while this host owns the bounded drawer slot. */
+.cg-record-related-modebody,
+.cg-record-mode-skeleton {
+ flex: 1 1 auto;
+ min-width: 0;
+ min-height: 0;
+}
+
+.cg-record-related-modebody {
+ overflow: auto;
+ background: var(--lp-surface);
+ animation: cg-record-mode-arrive 160ms ease-out both;
+}
+
+/* Stable geometry replaces the requested projection immediately. No previous row content remains
+ underneath it, and the five row bars keep the body height unchanged while the read settles. */
+.cg-record-mode-skeleton {
+ display: grid;
+ grid-template-rows: 24px repeat(5, 36px) minmax(0, 1fr);
+ gap: 8px;
+ overflow: hidden;
+ padding: 16px;
+ background: var(--lp-surface);
+ animation: cg-record-mode-arrive 160ms ease-out both;
+}
+
+.cg-record-mode-skeleton-head,
+.cg-record-mode-skeleton-row {
+ display: block;
+ border-radius: 4px;
+ background: var(--lp-surface-2);
+}
+
+.cg-record-mode-skeleton-head {
+ width: min(220px, 36%);
+}
+
+.cg-record-mode-skeleton-row {
+ width: 100%;
+}
+
+.cg-record-mode-skeleton-row.is-short {
+ width: 72%;
+}
+
+@keyframes cg-record-mode-arrive {
+ from {
+ opacity: 0.58;
+ transform: translateY(4px);
+ }
+ to {
+ opacity: 1;
+ transform: translateY(0);
+ }
+}
+
/* 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. */
@@ -1183,6 +1260,19 @@
white-space: nowrap;
}
+/* W55-T16: the position keeps its footprint while a latest-intent navigation settles. */
+.cg-record-modal .cg-detail-pos-skeleton {
+ flex: 0 0 112px;
+ width: 112px;
+ height: 8px;
+ border-radius: 4px;
+ background: var(--lp-surface-2);
+ animation-name: cg-record-mode-arrive;
+ animation-duration: 160ms;
+ animation-timing-function: ease-out;
+ animation-fill-mode: both;
+}
+
.cg-record-comment-compose-foot span {
min-width: 0;
overflow: hidden;
@@ -1460,6 +1550,12 @@
}
@media (prefers-reduced-motion: reduce) {
+ .cg-record-related-modebody,
+ .cg-record-mode-skeleton,
+ .cg-detail-pos-skeleton {
+ animation: none;
+ }
+
.cg-refusal-sum::before {
transition: none;
}
diff --git a/web/src/customer-grid/RecordDetail.tsx b/web/src/customer-grid/RecordDetail.tsx
index 69167199bad6c31ccf216e3c614c2d7ef3c839fa..19f63b9e70bef2e39fc912bda55fb212ea7ddb69 100644
--- a/web/src/customer-grid/RecordDetail.tsx
+++ b/web/src/customer-grid/RecordDetail.tsx
@@ -49,18 +49,19 @@ import { AI_STATE_PREFIX, choiceOptions, codeLanguageOf, isPickType, mayEditFiel
[[two-lanes-one-contract-dead-feature]]. */
import { CUSTOMER_TOPIC, PRODUCT_TOPIC, RELATED_REFUSAL, relatedTabs, skeletonTabs,
topicForScope } from "./types";
-import type { CustomerDoc, Field, RelatedEntry, RelatedPin, RelatedRefusal, RelatedVia, Row,
- Viewer } from "./types";
-/* ⭐ THE THREE DOORS THIS PANEL ASKS, ALL OF THEM ALREADY OWNED BY `apiBridge`: what is related
- to this table, what the databases are called, and whether an edge's pinned read can be served
- today. No `fetch` is written here — `apiBridge` owns the credential mode, the session handling
- and the refusal reading, and a fourth copy of that in a drawer is how one surface stops
- noticing an expired cookie. */
+import type { CustomerDoc, DisplayMode, Field, RelatedEntry, RelatedPin, RelatedRefusal,
+ RelatedVia, Row, Viewer } from "./types";
+/* ⭐ THE THREE GENERAL GRID DOORS THIS PANEL ASKS ARE OWNED BY `apiBridge`: what is related to
+ this table, what the databases are called, and whether an edge's pinned read can be served.
+ The narrow cache-target resolver below is local because its endpoint belongs only to this
+ drawer; it still imports the shared credential, tenant and session signals from `apiContract`,
+ so it cannot drift on the boundaries that matter. */
/* ⭐ W53-T22 adds a FOURTH and a FIFTH, and for the same reason: `fetchTableWindow` +
`WINDOW_ROWS` are the one windowed read this product owns, and the sibling set a pushed
frame's chevrons page is that read with the frame's own pin on it. */
-import { fetchLinkTargets, fetchRelated, fetchTableWindow, probeRelatedRead, readThroughTables,
- WINDOW_ROWS } from "./apiBridge";
+import { fetchLinkTargets, fetchRelated, fetchTableWindow, fetchTopicRows, probeRelatedRead,
+ readThroughTables, WINDOW_ROWS } from "./apiBridge";
+import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../apiContract";
/**
* ⭐⭐ WAVE-34 (owner ruling R13) — whose value sits in this enrichment cell, in words.
@@ -130,6 +131,7 @@ import RecordComments from "./RecordComments";
// (`tab`/`activeTab`/`setTab`, unchanged below), a different DOM shape: a `cg-views` nav down the
// side instead of a tablist strip under the title. See RecordRail.tsx's own header for why.
import RecordRail from "./RecordRail";
+import { ModeSwitch, RECORD_DETAIL_MODES, RecordRelatedModeView } from "./viewModes";
import { isStreamlitComponent } from "./hostBridge";
// ⚠ ALIASED for the same reason `CustomerGrid` aliases it: `./Stars`'s `StarIcon` is the RATING
// atom and this one is the record MARK. Two meanings, one noun, both reachable in this tree.
@@ -466,9 +468,69 @@ function ChoiceCreateInput({
type RelatedTabState =
| { status: "probing" }
| { status: "ready" }
- | { status: "projected" }
+ | { status: "projected"; ids: number[] }
| { status: "refused"; reason: string; code: string; table?: string; hop?: string };
+const PROBING_TAB_STATE: RelatedTabState = { status: "probing" };
+
+interface RelatedTabRequest {
+ key: string;
+ sequence: number;
+ entry: RelatedEntry;
+ pin: RelatedPin;
+ projectedIds: number[] | null;
+}
+
+type RecordModeProjection =
+ | { key: string; status: "idle" | "loading" }
+ | { key: string; status: "error"; message: string }
+ | { key: string; status: "ready"; rows: Row[]; fields: Field[]; today?: string;
+ notice?: string };
+
+interface RecordModeRequest {
+ key: string;
+ sequence: number;
+ target: string;
+ source: "pinned" | "projected";
+ pin?: RelatedPin;
+ ids?: number[];
+}
+
+/** The latest Previous/Next target whose record-owned reads still have to settle. */
+interface RecordNavigationIntent {
+ sequence: number;
+ fromPid: number;
+ targetPid?: number;
+}
+
+const RECORD_MODE_WINDOW = 5000;
+
+/** A fixed-height stand-in for every related projection, so a new intent never paints old rows. */
+function RecordModeSkeleton({
+ mode,
+ label = "Loading related records",
+}: {
+ mode: DisplayMode;
+ label?: string;
+}) {
+ return (
+
+
+
+
+
+
+
+
+ );
+}
+
/**
* ⭐⭐ W53-T24 · R13 — **WHO THE REFUSAL IS ABOUT**, and it is the SERVER'S OWN DATUM every time.
*
@@ -779,6 +841,102 @@ function linkedPids(value: unknown): number[] {
return [...seen];
}
+interface RelationTargetAnswer {
+ ok: boolean;
+ ids: number[];
+ code: string;
+ reason: string;
+}
+
+/** Resolve a declared bridge onto a registry-module pool without pretending the pool is a mirror. */
+async function fetchModuleRelationTargets(
+ source: string,
+ record: number,
+ entry: RelatedEntry,
+): Promise {
+ const query = new URLSearchParams({
+ source,
+ record: String(record),
+ via: entry.key,
+ target: entry.target,
+ });
+ try {
+ const res = await fetch(`${API_V1}/odoo-tables/relation-targets?${query.toString()}`, {
+ credentials: CREDENTIALS,
+ });
+ if (checkTenant(res)) return { ok: false, ids: [], code: "", reason: "" };
+ if (res.status === 401) {
+ signal(UNAUTHORIZED_EVENT);
+ return { ok: false, ids: [], code: "", reason: "Your session ended. Sign in again." };
+ }
+ let body: unknown = null;
+ try { body = await res.json(); } catch { body = null; }
+ if (res.ok) {
+ const ids = (body as { ids?: unknown } | null)?.ids;
+ return Array.isArray(ids)
+ ? { ok: true, ids: linkedPids(ids.join(",")), code: "", reason: "" }
+ : { ok: false, ids: [], code: "relation_target_unavailable",
+ reason: "The related database returned an unreadable answer. Try again." };
+ }
+ const envelope = body as {
+ error?: { code?: unknown; message?: unknown };
+ detail?: { error?: { code?: unknown; message?: unknown } };
+ } | null;
+ const refusal = envelope?.error ?? envelope?.detail?.error;
+ return {
+ ok: false,
+ ids: [],
+ code: String(refusal?.code ?? "relation_target_unavailable"),
+ reason: String(refusal?.message ?? "This relation could not be read right now. Try again."),
+ };
+ } catch {
+ return { ok: false, ids: [], code: "relation_target_unavailable",
+ reason: "This relation could not be reached right now. Try again." };
+ }
+}
+
+interface NormalizedRelationRoutes {
+ entries: RelatedEntry[];
+ aliases: Map;
+ values: Map;
+ byValue: Map;
+}
+
+/** A route's user-visible meaning, independent of an incidental intermediate jump. */
+function relationSemanticValue(entry: RelatedEntry): string {
+ const label = String(entry.label || entry.target)
+ .replace(/\s+via\s+.+$/i, "")
+ .trim()
+ .toLowerCase();
+ return `${entry.target}\u001f${label}`;
+}
+
+/** Keep one closest route per meaning and retain aliases for a selection made before refresh. */
+function normalizeRelationRoutes(entries: RelatedEntry[]): NormalizedRelationRoutes {
+ const best = new Map();
+ for (const candidate of entries) {
+ const value = relationSemanticValue(candidate);
+ const current = best.get(value);
+ if (!current || candidate.hops < current.hops) best.set(value, candidate);
+ }
+ const aliases = new Map();
+ const values = new Map();
+ const byValue = new Map();
+ for (const candidate of entries) {
+ const value = relationSemanticValue(candidate);
+ const canonical = best.get(value) as RelatedEntry;
+ aliases.set(candidate.key, canonical.key);
+ values.set(canonical.key, value);
+ byValue.set(value, canonical.key);
+ }
+ return {
+ entries: entries.filter((candidate) => best.get(relationSemanticValue(candidate)) === candidate),
+ aliases,
+ values,
+ byValue,
+ };
+}
+
function relatedScope(target: string): SurfaceScope {
if (target === CUSTOMER_TOPIC.key) return CUSTOMER_TOPIC.scope as SurfaceScope;
if (target === PRODUCT_TOPIC.key) return PRODUCT_TOPIC.scope as SurfaceScope;
@@ -831,6 +989,13 @@ export default function RecordDetail({
*/
const [stack, setStack] = useState([]);
const frame = stack.length > 0 ? stack[stack.length - 1] : null;
+ const navigationSequence = useRef(0);
+ const [recordNavigation, setRecordNavigation] = useState(null);
+ const beginRecordNavigation = useCallback((fromPid: number, targetPid?: number) => {
+ const sequence = navigationSequence.current + 1;
+ navigationSequence.current = sequence;
+ setRecordNavigation({ sequence, fromPid, targetPid });
+ }, []);
/**
* ⛔⛔ THE SHADOW IS THE WHOLE MECHANISM, AND IT IS DELIBERATE RATHER THAN CLEVER. Every one of
* the ~40 references below (`renderRow`, the ordering, the editors, the viewers) reads `fields`
@@ -1131,17 +1296,18 @@ export default function RecordDetail({
* ⛔ 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 relationRoutes = useMemo(() => normalizeRelationRoutes(entries), [entries]);
const tabs = useMemo(
() => (relatedPending && !entries.length
? skeletonTabs()
- : relatedTabs(entries, (target) => tableLabels[target] ?? "")),
- [entries, tableLabels, relatedPending]
+ : relatedTabs(relationRoutes.entries, (target) => tableLabels[target] ?? "")),
+ [entries.length, relationRoutes.entries, tableLabels, relatedPending]
);
/**
- * Which tab is open, by EDGE KEY. `"fields"` is the default and the fallback: a tab whose edge
- * has disappeared (a link column deleted while the drawer was open) drops back to Fields
- * rather than rendering a panel for an edge that is no longer offered.
+ * Which tab is open, by EDGE KEY plus its semantic value. `"fields"` is the default and the
+ * fallback: a route key may be replaced while the drawer is open and then follows the same
+ * value, while a meaning that genuinely disappeared drops back to Fields.
*/
/* ⭐⭐ W53-T22 — STAMPED WITH ITS TABLE, THE SAME WAY `related` IS, AND FOR THE SAME RENDER.
An edge key belongs to ONE database's relation list; carried across a hop it names an edge
@@ -1150,13 +1316,21 @@ export default function RecordDetail({
parent's selection at all.
⚠ `setTab` STAYS A `(tab: string) => void`, so `RecordRail`'s props do not change and the
mount below stays byte-identical to what `verify_wiring.py` asserts. */
- const [tabSel, setTabSel] = useState<{ table: string; key: string }>(
- { table: "", key: "fields" }
+ const [tabSel, setTabSel] = useState<{ table: string; key: string; value: string }>(
+ { table: "", key: "fields", value: "" }
);
- const tab = tabSel.table === recordTable ? tabSel.key : "fields";
+ const tab = tabSel.table === recordTable
+ ? (relationRoutes.aliases.get(tabSel.key)
+ ?? relationRoutes.byValue.get(tabSel.value)
+ ?? tabSel.key)
+ : "fields";
const setTab = useCallback(
- (next: string) => setTabSel({ table: recordTable, key: next }),
- [recordTable]
+ (next: string) => setTabSel({
+ table: recordTable,
+ key: next,
+ value: relationRoutes.values.get(next) ?? "",
+ }),
+ [recordTable, relationRoutes.values]
);
const activeTab = tabs.some((entry) => entry.entry.key === tab) ? tab : "fields";
const activeRelated = tabs.find((entry) => entry.entry.key === activeTab) ?? null;
@@ -1164,18 +1338,47 @@ export default function RecordDetail({
/**
* ⭐⭐ CLAUSE 10 — THE LAST-OPENED VIEW **PER TAB**, PER PERSON, IN `localStorage`.
*
- * ⛔ PER TAB, NOT PER DATABASE. R2 gives two links between the same pair two tabs, so two tabs
- * can point at one database; a memory keyed by the target alone would make each of them reopen
- * on the other's view. The key is `:`, and the EDGE KEY is what makes it
- * unique: `relations._entry`'s own note says the entry key is the only member of `via` that
- * identifies an edge on its own, precisely because `{direction, on}` does not.
+ * ⛔ PER SEMANTIC TAB, NOT PER DATABASE. R2 gives two genuinely different links between the
+ * same pair two tabs, so a memory keyed by target alone still merges too much. An incidental
+ * intermediate route is different: when it collapses onto a closer path, the meaning remains
+ * the same and its remembered view must follow it. The key therefore carries this table plus
+ * the normalized target-and-label value, never an unstable route key.
* ⚠ `writeTabViews` runs inside the updater rather than beside it, so the write and the
* decision that there IS something to write are one expression. Under StrictMode the updater
* is invoked twice in development, which writes the same value twice; the write is idempotent
* and that is cheaper than a second effect whose only job is to mirror this state.
*/
const [tabViews, setTabViews] = useState>(readTabViews);
- const tabViewKey = activeRelated ? `${recordTable}:${activeRelated.entry.key}` : "";
+ /* Keep the pre-normalization edge key as a read fallback. Wave 55 made route selection
+ semantic so a shorter equivalent path can replace a longer one without losing the open tab,
+ but existing browsers may still hold the earlier edge-keyed preference. */
+ const legacyTabViewKey = activeRelated
+ ? `${recordTable}:${activeRelated.entry.key}`
+ : "";
+ const tabViewKey = activeRelated
+ ? `${recordTable}:${relationSemanticValue(activeRelated.entry)}`
+ : "";
+ const [recordModes, setRecordModes] = useState>({});
+ const relatedMode = tabViewKey ? recordModes[tabViewKey] ?? "grid" : "grid";
+ const chooseRecordMode = useCallback((next: DisplayMode) => {
+ if (!tabViewKey || !RECORD_DETAIL_MODES.includes(next)) return;
+ setRecordModes((prev) => (prev[tabViewKey] === next
+ ? prev
+ : { ...prev, [tabViewKey]: next }));
+ }, [tabViewKey]);
+ const [recordModeFields, setRecordModeFields] = useState<
+ Record
+ >({});
+ const chooseRecordModeField = useCallback(
+ (kind: "dateField" | "stackField", key: string) => {
+ if (!tabViewKey) return;
+ setRecordModeFields((prev) => ({
+ ...prev,
+ [tabViewKey]: { ...prev[tabViewKey], [kind]: key },
+ }));
+ },
+ [tabViewKey]
+ );
const rememberTabView = useCallback(
(viewId: string) => {
if (!tabViewKey) return;
@@ -1319,6 +1522,11 @@ export default function RecordDetail({
const [siblings, setSiblings] = useState<{ key: string; rows: Row[]; fields: Field[] }>(
{ key: "", rows: EMPTY_ROWS, fields: EMPTY_FIELDS }
);
+ /* W55-T16 / R12: clicks use the last requested sibling index, not the last PAINTED one. React
+ may batch several pointer events before `frame` changes; anchoring every click to
+ `siblingIndex` would turn Next, Next, Previous into one Next. The ref advances synchronously,
+ while the state update below gives React only the final target to paint. */
+ const frameIntent = useRef<{ key: string; index: number; pid: number } | null>(null);
useEffect(() => {
if (!framePinKey) return;
const asked = JSON.parse(framePinKey) as { table: string; pin: RelatedPin };
@@ -1343,8 +1551,13 @@ export default function RecordDetail({
const siblingIndex = frame
? siblingRows.findIndex((row) => Number(row.pid) === frame.pid)
: -1;
- const frameCanPrev = siblingIndex > 0;
- const frameCanNext = siblingIndex >= 0 && siblingIndex < siblingRows.length - 1;
+ const pendingFrame = frameIntent.current;
+ const queuedFrameIndex = pendingFrame?.key === framePinKey
+ && Number(siblingRows[pendingFrame.index]?.pid) === pendingFrame.pid
+ ? pendingFrame.index
+ : siblingIndex;
+ const frameCanPrev = queuedFrameIndex > 0;
+ const frameCanNext = queuedFrameIndex >= 0 && queuedFrameIndex < siblingRows.length - 1;
/**
* One step along the frame's own row set. It REPLACES the top frame rather than pushing one,
* so paging orders inside a customer leaves the breadcrumb reading `Customer / Order` at the
@@ -1355,11 +1568,23 @@ export default function RecordDetail({
const stepFrame = useCallback(
(delta: number) => {
if (!frame || siblingIndex < 0) return;
- const next = siblingRows[siblingIndex + delta];
+ const pending = frameIntent.current;
+ const queued = pending?.key === framePinKey
+ && Number(siblingRows[pending.index]?.pid) === pending.pid
+ ? pending.index
+ : siblingIndex;
+ const nextIndex = Math.max(0, Math.min(siblingRows.length - 1, queued + delta));
+ const next = siblingRows[nextIndex];
if (!next) return;
const first = siblings.fields[0];
const named = first ? String(next[first.key] ?? "") : "";
const pid = Number(next.pid);
+ const currentPid = queued === pending?.index && pending?.key === framePinKey
+ ? pending.pid
+ : Number(frame.pid);
+ if (!Number.isFinite(pid) || pid === currentPid) return;
+ frameIntent.current = { key: framePinKey, index: nextIndex, pid };
+ beginRecordNavigation(currentPid, pid);
setStack((prev) => (prev.length === 0 ? prev : [...prev.slice(0, -1), {
table: frame.table,
pid,
@@ -1369,7 +1594,15 @@ export default function RecordDetail({
pin: frame.pin,
}]));
},
- [frame, siblingIndex, siblingRows, siblings.fields]
+ [beginRecordNavigation, frame, framePinKey, siblingIndex, siblingRows, siblings.fields]
+ );
+ const stepBase = useCallback(
+ (delta: -1 | 1) => {
+ beginRecordNavigation(Number(baseRecord.pid));
+ if (delta < 0) onPrev();
+ else onNext();
+ },
+ [baseRecord.pid, beginRecordNavigation, onNext, onPrev]
);
/**
* The frame's own caption, in the host's shape (`Record 3 of 3,673`) with the DATABASE's name
@@ -1428,72 +1661,285 @@ export default function RecordDetail({
* fetch the server's sentence for the state, and `unpinnableNote` covers the one state that
* has no server sentence (the roster says no while the door answers 200).
*/
- const [tabState, setTabState] = useState({ status: "probing" });
+ const [tabStateResult, setTabState] = useState(PROBING_TAB_STATE);
+ const [tabStateStamp, setTabStateStamp] = useState("");
+ const tabState = tabStateStamp === relatedPinKey ? tabStateResult : PROBING_TAB_STATE;
+ const tabRequest = useRef<{
+ mounted: boolean;
+ running: boolean;
+ sequence: number;
+ wanted: RelatedTabRequest | null;
+ }>({ mounted: true, running: false, sequence: 0, wanted: null });
useEffect(() => {
+ tabRequest.current.mounted = true;
+ return () => {
+ tabRequest.current.mounted = false;
+ tabRequest.current.wanted = null;
+ tabRequest.current.sequence += 1;
+ };
+ }, []);
+ useEffect(() => {
+ const coordinator = tabRequest.current;
+ const sequence = coordinator.sequence + 1;
+ coordinator.sequence = sequence;
if (!activeRelated || !relatedPin) {
- setTabState({ status: "probing" });
+ coordinator.wanted = null;
+ setTabStateStamp("");
+ setTabState(PROBING_TAB_STATE);
return;
}
- let live = true;
- setTabState({ status: "probing" });
- const target = activeRelated.entry.target;
- const pin = { table: relatedPin.table, record: relatedPin.record, via: relatedPin.via };
- void (async () => {
- const through = await readThroughTables();
- if (!live) return;
- // ⛔ THE ONE MOUNT CONDITION, and it is the read path's own. See the note above.
- const pinnable = activeRelated.entry.served && through.has(target);
- if (pinnable) {
- setTabState({ status: "ready" });
- return;
- }
- /* ⭐⭐ W53-T25 · D-657 — THE THIRD OUTCOME, AND THE ROSTER IS STILL WHAT SEPARATES IT FROM
- THE FIRST. `through.has(target)` is asked again rather than inferred from `!pinnable`,
- because those two come apart on exactly the edge that matters: a target the roster DOES
- name whose entry is `served: false` is a read-through table, and pulling one whole is the
- standing-rule-1 violation this branch must never commit. Not on the roster ⇒ the whole
- table is what its own Data page reads anyway, through the same door, under the same
- reported cap. See `RelatedTabState` and `projectedIds`. */
- if (!through.has(target) && projectedIds) {
- setTabState({ status: "projected" });
- return;
+ setTabStateStamp(relatedPinKey);
+ setTabState(PROBING_TAB_STATE);
+ const request: RelatedTabRequest = {
+ key: relatedPinKey,
+ sequence,
+ entry: activeRelated.entry,
+ pin: { table: relatedPin.table, record: relatedPin.record, via: relatedPin.via },
+ projectedIds,
+ };
+ /* W55-T16 / R12: one slot, replaced rather than appended. If a bridge query is already in
+ flight it may finish, but every intermediate record disappears from this slot before the
+ next compiled query is chosen. */
+ coordinator.wanted = { ...request };
+
+ const current = (asked: RelatedTabRequest) => coordinator.mounted
+ && coordinator.sequence === asked.sequence;
+ const commit = (asked: RelatedTabRequest, answer: RelatedTabState) => {
+ if (!current(asked)) return;
+ setTabStateStamp(asked.key);
+ setTabState(answer);
+ };
+ const drain = async () => {
+ if (coordinator.running === true) return;
+ coordinator.running = true;
+ try {
+ while (coordinator.mounted && coordinator.wanted) {
+ const asked = coordinator.wanted;
+ coordinator.wanted = null;
+ /* Freeze the active relation to this queued request. Reading the render's current
+ `activeRelated` here would let a later click rewrite an earlier in-flight request. */
+ const activeRelated = asked;
+ const target = activeRelated.entry.target;
+ const through = await readThroughTables();
+ /* The roster read is cheap and shared. This check is deliberately BEFORE either route
+ that can compile a relation query, so a burst pays for the running intent and the
+ final intent, never for the records superseded between them. */
+ if (!current(asked)) continue;
+ const pinnable = activeRelated.entry.served && through.has(target);
+ if (pinnable) {
+ commit(asked, { status: "ready" });
+ continue;
+ }
+ if (!through.has(target) && asked.projectedIds) {
+ commit(asked, { status: "projected", ids: asked.projectedIds });
+ continue;
+ }
+ const isModuleCache = target === CUSTOMER_TOPIC.key || target === PRODUCT_TOPIC.key;
+ if (!through.has(target) && isModuleCache
+ && asked.entry.via.direction === "forward") {
+ const answer = await fetchModuleRelationTargets(
+ asked.pin.table, asked.pin.record, asked.entry);
+ if (!current(asked)) continue;
+ if (answer.ok) {
+ setTabStateStamp(asked.key);
+ setTabState({ status: "projected", ids: answer.ids });
+ } else {
+ commit(asked, {
+ status: "refused",
+ reason: answer.reason,
+ code: answer.code,
+ table: target,
+ });
+ }
+ continue;
+ }
+ const refused = through.has(target) ? await probeRelatedRead(target, asked.pin) : null;
+ if (!current(asked)) continue;
+ commit(asked, {
+ status: "refused",
+ reason: refused?.reason ?? unpinnableNote(target),
+ code: refused?.code ?? "",
+ table: refused?.table ?? target,
+ hop: refused?.hop,
+ });
+ }
+ } finally {
+ coordinator.running = false;
}
- /* ⭐⭐ 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
- either. `""` sends it down the plain branch, which is exactly where it belongs. */
- setTabState({
- status: "refused",
- reason: refused?.reason ?? unpinnableNote(target),
- code: refused?.code ?? "",
- /* ⭐ 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,
+ };
+ void drain();
+ }, [activeRelated, relatedPin, projectedIds]);
+
+ /* W55-T15 / C8: non-Grid projections use a stamped, single-flight reader. A new tab or mode
+ replaces `wanted` immediately; the running request is allowed to finish but cannot paint,
+ then only the final queued intent is read. This keeps one request in flight without showing
+ the prior relation as the newly requested one. */
+ const recordProjectionKey = useMemo(() => {
+ if (!activeRelated || !relatedPin) return "";
+ if (tabState.status === "ready") {
+ return JSON.stringify({
+ tab: tabViewKey,
+ target: activeRelated.entry.target,
+ source: "pinned",
+ pin: relatedPin,
});
- })();
+ }
+ if (tabState.status === "projected" && tabState.ids.length > 0) {
+ return JSON.stringify({
+ tab: tabViewKey,
+ target: activeRelated.entry.target,
+ source: "projected",
+ ids: tabState.ids,
+ });
+ }
+ return "";
+ }, [activeRelated, relatedPin, tabState, tabViewKey]);
+ const [recordProjection, setRecordProjection] = useState(
+ { key: "", status: "idle" }
+ );
+ const recordProjectionCache = useRef(new Map>());
+ const recordRequest = useRef<{
+ mounted: boolean;
+ running: boolean;
+ sequence: number;
+ wanted: RecordModeRequest | null;
+ }>({ mounted: true, running: false, sequence: 0, wanted: null });
+ useEffect(() => {
+ recordRequest.current.mounted = true;
return () => {
- live = false;
+ recordRequest.current.mounted = false;
+ recordRequest.current.wanted = null;
+ recordRequest.current.sequence += 1;
};
- }, [activeRelated, relatedPin, projectedIds]);
+ }, []);
+ useEffect(() => {
+ const coordinator = recordRequest.current;
+ const sequence = coordinator.sequence + 1;
+ coordinator.sequence = sequence;
+ if (relatedMode === "grid" || !recordProjectionKey || !activeRelated || !relatedPin) {
+ coordinator.wanted = null;
+ setRecordProjection({ key: "", status: "idle" });
+ return;
+ }
+
+ const cached = recordProjectionCache.current.get(recordProjectionKey);
+ if (cached) {
+ coordinator.wanted = null;
+ setRecordProjection(cached);
+ return;
+ }
+ const request: RecordModeRequest = {
+ key: recordProjectionKey,
+ sequence,
+ target: activeRelated.entry.target,
+ source: tabState.status === "ready" ? "pinned" : "projected",
+ pin: tabState.status === "ready" ? relatedPin : undefined,
+ ids: tabState.status === "projected" ? tabState.ids : undefined,
+ };
+ coordinator.wanted = request;
+ setRecordProjection({ key: recordProjectionKey, status: "loading" });
+
+ const drain = async () => {
+ if (coordinator.running) return;
+ coordinator.running = true;
+ try {
+ while (coordinator.mounted && coordinator.wanted) {
+ const asked = coordinator.wanted;
+ coordinator.wanted = null;
+ const payload = asked.source === "pinned" && asked.pin
+ ? await fetchTableWindow(asked.target, {
+ offset: 0,
+ limit: RECORD_MODE_WINDOW,
+ related: asked.pin,
+ })
+ : await fetchTopicRows(topicForScope(relatedScope(asked.target)));
+ if (!coordinator.mounted || coordinator.sequence !== asked.sequence) continue;
+ if (!payload) {
+ setRecordProjection({
+ key: asked.key,
+ status: "error",
+ message: "This view could not load. Return to Grid or try again.",
+ });
+ continue;
+ }
+
+ let rows = payload.rows;
+ let notice: string | undefined;
+ if (asked.source === "pinned") {
+ if ((payload.counts?.matched ?? rows.length) > rows.length) {
+ setRecordProjection({
+ key: asked.key,
+ status: "error",
+ message: "This related set is too large for this view. Use Grid to reach every record.",
+ });
+ continue;
+ }
+ } else {
+ const ids = new Set(asked.ids ?? []);
+ rows = payload.rows.filter((row) => ids.has(Number(row.pid)));
+ const found = new Set(rows.map((row) => Number(row.pid)));
+ const missing = [...ids].filter((pid) => !found.has(pid)).length;
+ const wholeSource = !payload.counts
+ || (payload.counts.shown ?? payload.rows.length) >= payload.counts.matched;
+ if (missing > 0 && !wholeSource) {
+ setRecordProjection({
+ key: asked.key,
+ status: "error",
+ message: "This linked set is outside the loaded window. Use Grid to reach every record.",
+ });
+ continue;
+ }
+ if (missing > 0) notice = "Some linked records are no longer available.";
+ }
+ const ready: Extract = {
+ key: asked.key,
+ status: "ready",
+ rows,
+ fields: payload.fields,
+ today: payload.today,
+ notice,
+ };
+ recordProjectionCache.current.set(asked.key, ready);
+ setRecordProjection(ready);
+ }
+ } finally {
+ coordinator.running = false;
+ }
+ };
+ void drain();
+ }, [activeRelated, recordProjectionKey, relatedMode, relatedPin, tabState]);
+
+ const visibleRecordProjection = recordProjection.key === recordProjectionKey
+ && recordProjection.status === "ready" ? recordProjection : null;
+ const navigationRecordArrived = !recordNavigation
+ || (recordNavigation.targetPid == null
+ ? Number(baseRecord.pid) !== recordNavigation.fromPid
+ : Number(record.pid) === recordNavigation.targetPid);
+ const navigationReadSettled = !activeRelated
+ || tabState.status === "refused"
+ || (tabState.status === "projected" && tabState.ids.length === 0)
+ || (tabState.status !== "probing" && relatedMode === "grid")
+ || (Object.is(recordProjection.key, recordProjectionKey)
+ && (recordProjection.status === "ready" || recordProjection.status === "error"));
+ const recordNavigationBusy = Boolean(
+ recordNavigation && (!navigationRecordArrived || !navigationReadSettled)
+ );
+ useEffect(() => {
+ if (!recordNavigation || recordNavigationBusy) return;
+ const settledSequence = recordNavigation.sequence;
+ setRecordNavigation((current) => current?.sequence === settledSequence ? null : current);
+ }, [recordNavigation, recordNavigationBusy]);
+ const recordModeChoices = visibleRecordProjection?.fields ?? EMPTY_FIELDS;
+ const recordModePrefs = recordModeFields[tabViewKey] ?? {};
+ const recordStackChoices = useMemo(
+ () => recordModeChoices.filter((field) => field.type === "select" || field.type === "status"),
+ [recordModeChoices]
+ );
+ const recordStackField = recordStackChoices.find(
+ (field) => field.key === recordModePrefs.stackField
+ ) ?? recordStackChoices[0];
/** ⭐ W54-T38 — the listing's refusals, one row per distinct sentence. See `groupRefusals`. */
const groupedRefusals = useMemo(() => groupRefusals(refusals), [refusals]);
@@ -2183,6 +2629,37 @@ export default function RecordDetail({
);
};
+ const recordProjectionFailure = recordProjection.key === recordProjectionKey
+ && recordProjection.status === "error" ? recordProjection.message : "";
+ const recordProjectionPanel = activeRelated && visibleRecordProjection ? (
+
+
pushFrame(
+ pid,
+ activeRelated.entry.target,
+ selected,
+ selectedFields
+ )}
+ />
+ {visibleRecordProjection.notice ? (
+
+ {visibleRecordProjection.notice}
+
+ ) : null}
+
+ ) : null;
+
// One modal surface is shared by Grid, List, Calendar, Kanban, and Map.
// Focus stays inside it, then returns to the exact opener on close.
/* ⭐⭐ W53-T22 (R4) — **ESCAPE GOES UP ONE LEVEL** while a frame is on screen, and closes the
@@ -2226,7 +2703,7 @@ export default function RecordDetail({
-
+
{/* ⭐⭐ W53-T22 (OWNER RULING R4) — TWO CHEVRONS, ALWAYS, AND THEY ALWAYS PAGE
SIBLINGS OF WHAT IS ON SCREEN.
⛔ WHAT WAS HERE AND WHY IT WENT. W51-T06 replaced this pair with a single
@@ -2242,7 +2719,7 @@ export default function RecordDetail({
stepFrame(-1) : onPrev}
+ onClick={frame ? () => stepFrame(-1) : () => stepBase(-1)}
disabled={frame ? !frameCanPrev : !canPrev}
aria-label="Previous record"
title="Previous record"
@@ -2252,7 +2729,7 @@ export default function RecordDetail({
stepFrame(1) : onNext}
+ onClick={frame ? () => stepFrame(1) : () => stepBase(1)}
disabled={frame ? !frameCanNext : !canNext}
aria-label="Next record"
title="Next record"
@@ -2295,7 +2772,15 @@ export default function RecordDetail({
reads one: `Orders 3 of 12`, the host's own shape with the database's name where
the host says "Record". It falls back to silence, not to a guess, whenever the
sibling set could not be read (see `framePositionLabel`). */}
- {frame ? framePositionLabel : positionLabel}
+ {recordNavigationBusy ? (
+
+ ) : (
+ {frame ? framePositionLabel : positionLabel}
+ )}
- {activeRelated && relatedPin && scope ? (
+
+ {recordNavigationBusy ? (
+
+ ) : activeRelated && relatedPin && scope ? (
+
+
+
{/* ⭐⭐ CLAUSES 4 + 6 + 7 — THE TARGET DATABASE'S OWN GRID, over rows the SERVER
narrowed to this record.
⛔ NO `embedded` AND NO `embeddedRecordIds` **ON THIS MOUNT**. That pair is the
@@ -2461,12 +2962,7 @@ export default function RecordDetail({
details={EMPTY_DIAGNOSES}
/>
) : 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
- (C-SPIN). */
-
-
-
+
) : tabState.status === "projected" ? (
/* ⭐⭐ W53-T25 · D-657 — **THE ROWS AGAIN**, on a related tab whose target is an
ordinary user table. This is wave 27's `LinkedGrid` mount, which W51-T06
@@ -2485,23 +2981,27 @@ export default function RecordDetail({
that carries every other "why is this number what it is" sentence. A second
cap sentence written here would be this file inventing a limit the wire did
not declare, which is the opposite of standing rule 1's second sentence. */
- projectedIds && projectedIds.length > 0 ? (
-
-
-
- }
- >
-
-
+ tabState.ids.length > 0 ? (
+ relatedMode === "grid" ? (
+
}>
+
+
+ ) : recordProjectionPanel ? (
+ recordProjectionPanel
+ ) : recordProjectionFailure ? (
+
+ {recordProjectionFailure}
+
+ ) : (
+
+ )
) : (
/* An empty link cell is an ANSWER. See `emptyLinkNote`. `role="status"` for
the same reason the refusal above uses it: a reported state, not a failure.
@@ -2518,24 +3018,28 @@ export default function RecordDetail({
)
) : (
-
-
-
- }
- >
-
-
+ relatedMode === "grid" ? (
+
}>
+
+
+ ) : recordProjectionPanel ? (
+ recordProjectionPanel
+ ) : recordProjectionFailure ? (
+
+ {recordProjectionFailure}
+
+ ) : (
+
+ )
)}
{/* ⭐⭐ W53-T24 · R13 — **WHAT THE LISTING WOULD NOT SHOW YOU**, said out loud. A
diff --git a/web/src/customer-grid/RouteNav.tsx b/web/src/customer-grid/RouteNav.tsx
index 4eccea03f5f2bc2afc63ac6568e13c9e5ebadbad..76bf1e7a89d8018374ca055a76ad1ca8024e5152 100644
--- a/web/src/customer-grid/RouteNav.tsx
+++ b/web/src/customer-grid/RouteNav.tsx
@@ -154,7 +154,8 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
stopCoords = {},
onFolderCreate, onFolderUpdate, onFolderDelete, onFolderReorder, onCreateStart, mapLinks, mapLinkRefusal, deliveries, onSchedule,
onDeleteDelivery, assignees, routeToday, assigneeError, zones = [],
- roundTrip = false, onRoundTripChange, routeStartPid = null, routeEndPid = null, onRouteStartChange, onRouteEndChange, onStopAdded }: {
+ roundTrip = false, onRoundTripChange, routeStartPid = null, routeEndPid = null, onRouteStartChange, onRouteEndChange, onStopAdded,
+ applicationName = "" }: {
routes: MapRouteDto[];
folders: MapRouteFolderDto[];
selectedIds: ReadonlySet
;
@@ -218,6 +219,8 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
/** The Route the membership door answered with, so the host's read model gains the new stop
* without a second fetch. Mirrors what `moveNamedRouteStop` already does on a reorder. */
onStopAdded?: (route: MapRouteDto) => void;
+ /** Present only when this trusted route surface was launched by a saved Application. */
+ applicationName?: string;
}) {
/* ⭐⭐ OWNER 2026-08-31 item 3 - THE ROUTES RAIL IS THE VIEWS RAIL, NOT A COUSIN OF IT.
Owner: *"I need the routes LIST navigation and the routes itself to have the exact same
@@ -1924,6 +1927,9 @@ export function RouteNav({ routes, folders, selectedIds, activeRouteId, sources,
const rows = renderLevel(ROOT_LEVEL, 0);
return (
+ {applicationName ? (
+ Routing app {applicationName}
+ ) : null}
{/* Owner item 3 - the SAME create door the Views rail mounts (`.cg-create-new` /
`.cg-create-btn` are a shared contract, see `ViewSidebar.tsx`'s note on them), with the
two things a Routes rail can make behind it. */}
diff --git a/web/src/customer-grid/SwipeView.tsx b/web/src/customer-grid/SwipeView.tsx
index 165ace02a327b0e38f81b4b7f098f8c456cd9622..3ebf842db63a602cc0c906fcdf9734bef2d96313 100644
--- a/web/src/customer-grid/SwipeView.tsx
+++ b/web/src/customer-grid/SwipeView.tsx
@@ -1,586 +1,586 @@
-// ---------------------------------------------------------------------------
-// customer-grid / SwipeView.tsx
-// ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) — the SWIPE deck.
-//
-// One record at a time, decided left or right into two options of ONE
-// single-select. R2 fixes the shape and it is narrow on purpose:
-// · SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.
-// · the deck holds only the records whose bound field is EMPTY — a record
-// that already has a value has been decided, and re-asking is not triage.
-// · a swipe writes through the NORMAL cell door (`onSwipe`, which the host
-// maps to the same `patchAndRecord` a kanban card move uses), so undo,
-// echo-suppression and the permission wall all hold without being
-// re-implemented here.
-//
-// Honesty rules carried from the other modes:
-// · nothing is silently hidden — the deck states what is left, and the
-// empty state names the bound field rather than saying "all done".
-// · a lost binding is SHOWN, never repaired by guessing. `_clean_display`
-// validates that `fieldKey` names a field the table HAS and stops there;
-// it cannot know the field is still a select, or that the two options are
-// still in its vocabulary (its docstring draws that line explicitly). So
-// those three losses land here, and each one says what happened and
-// re-opens the picker — the `viewModes.tsx:190-194` rule, which exists
-// because the wave-7 trap was a picker silently falling back to its first
-// option.
-// ---------------------------------------------------------------------------
-
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-// ⭐⭐ W41-T48 (owner instruction 22) — opening a record from the swipe deck folds the shell's
-// navigation rail exactly as a grid cell click does. Guard rationale: `MapView.tsx:2755`.
-import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
-import { choiceOptions } from "./types";
-import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
-// ⚠ `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is
-// loaded here) — the same import `RecordComments` takes for the same prop.
-import type { SurfaceScope } from "./apiBridge";
-import RecordComments from "./RecordComments";
-import { Documents } from "./Documents";
-import { formatDisplay } from "./cells";
-import { actionHref } from "./display";
-import { optionTint } from "./choiceColors";
-import { ModeIcon } from "./icons";
-// ⭐ W29-T73 — the line its three siblings all have, and the one this file shipped without.
-// `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered
-// unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right —
-// a partially-styled surface reads as a design choice, which is why nobody reported it and no
-// gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).
-import "./SwipeView.css";
-
-export type SwipeSpec = NonNullable;
-
-/** The three ways a stored binding can rot that the host cannot see (see the header note). */
-type BindingFault =
- | { kind: "unbound" }
- | { kind: "field-gone"; fieldKey: string }
- | { kind: "not-select"; field: Field }
- | { kind: "option-gone"; field: Field; missing: string[] };
-
-function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map):
- { ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {
- if (!spec) return { ok: false, fault: { kind: "unbound" } };
- const field = fieldByKey.get(spec.fieldKey);
- if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };
- // R2 — SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,
- // so "write this option" would mean append-or-replace, and a triage gesture that sometimes
- // adds and sometimes overwrites is two gestures wearing one button.
- if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };
- const options = choiceOptions(field);
- const has = new Set(options.map((o) => o.toLowerCase()));
- const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));
- if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };
- return { ok: true, field, spec };
-}
-
-/** The bound cell is EMPTY — the one predicate that decides deck membership (R2). */
-const isUndecided = (row: Row, key: string): boolean =>
- String(row[key] ?? "").trim() === "";
-
-export function SwipeView({
- rows,
- fields,
- fieldByKey,
- spec,
- cardKeys,
- detailKeys,
- scope,
- viewer,
- docs,
- docPayload,
- onDocAdd,
- onDocFetch,
- onDocDelete,
- titleKey,
- canWrite,
- readOnlyReason,
- canBind,
- onSpec,
- onSwipe,
- onOpen,
-}: {
- /** DISTINCT data rows from the full pipeline, overlay edits layered — the kanban's contract.
- * The deck re-derives from these, so a written record leaves it as soon as the optimistic
- * patch lands; there is no local cursor to drift out of step with the data. */
- rows: Row[];
- /** Every field, for the picker's field list. */
- fields: Field[];
- fieldByKey: Map;
- /** The stored binding, or undefined for a deck nobody has configured yet. */
- spec: SwipeSpec | undefined;
- /** The handful of visible fields the card lists under its title. */
- cardKeys: string[];
- titleKey: string;
- /** May this viewer write the BOUND field's value? (the kanban's `canMove`) */
- canWrite: boolean;
- /** Stated when the deck cannot be decided — permissions, or a computed column. */
- readOnlyReason: string | null;
- /** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the
- * view-editing permission and NOT `canWrite` — conflating the two is
- * [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does
- * nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */
- canBind: boolean;
- /** `undefined` DELETES the binding — absent is the honest unconfigured state, and storing a
- * half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */
- onSpec: (next: SwipeSpec | undefined) => void;
- onSwipe: (pid: number, value: string) => void;
- onOpen: (pid: number) => void;
- /**
- * ⭐⭐ WAVE-29 T26 (owner R9) — WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY.
- *
- * R9: *"the swipe CARD itself renders the record detail inline — fields, comments and
- * attachments — so a reviewer decides without leaving the deck."* Everything below is that,
- * and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply
- * different amounts. A card must render with none of them rather than throw — the standalone
- * embed has no `scope`, and a deployment with no document storage serves no handlers.
- */
- /** Every field the VIEW shows, in its order — not the three-key card summary. */
- detailKeys?: string[];
- /** The surface these records live on. Comments are keyed by it; absent ⇒ no comments section,
- * which is the pre-existing precondition `RecordDetail` already carries. */
- scope?: SurfaceScope;
- viewer?: Viewer;
- /** This record's attachments, and the plumbing. Handlers absent ⇒ the section is not rendered
- * at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app
- * cannot keep). */
- /** Keyed by pid, because a deck shows many records — `RecordDetail` takes ONE record's list
- * and that shape cannot serve a deck. */
- docs?: Record;
- docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string };
- /** ⚠ EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE
- * open record. A deck paints many records at once, so a handler bound to a single pid would
- * attach every reviewer's upload to whichever card happened to be open. */
- onDocAdd?: (
- pid: number,
- file: { name: string; mime: string; size: number; data_b64: string }
- ) => void;
- onDocFetch?: (pid: number, docId: string) => void;
- onDocDelete?: (pid: number, docId: string) => void;
-}) {
- // "Later" — session-only, never stored. A deck with no way past a record you cannot decide
- // blocks on that record forever, so this is navigation WITHIN the deck rather than a third
- // gesture: it writes nothing, survives no reload, and the count is disclosed in the empty
- // state rather than quietly shrinking the deck (rule 8b).
- const [later, setLater] = useState>(new Set());
- const deckRef = useRef(null);
-
- const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);
- const boundKey = binding.ok ? binding.field.key : null;
-
- const undecided = useMemo(
- () => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),
- [rows, boundKey]
- );
- const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);
- const card = deck[0];
-
- // A record decided elsewhere (the grid, another user's echo) must not stay "later" forever —
- // otherwise the disclosed skip count drifts away from what is actually on the deck.
- useEffect(() => {
- setLater((prev) => {
- if (prev.size === 0) return prev;
- const live = new Set(undecided.map((r) => r.pid));
- const next = new Set([...prev].filter((pid) => live.has(pid)));
- return next.size === prev.size ? prev : next;
- });
- }, [undecided]);
-
- const decide = useCallback(
- (value: string) => {
- if (!card || !canWrite) return;
- onSwipe(card.pid, value);
- },
- [card, canWrite, onSwipe]
- );
-
- // ← / → decide, and they are the SAME two actions the buttons are rather than a second code
- // path: the whole point of the mode is that one hand can clear a queue.
- useEffect(() => {
- if (!binding.ok || !canWrite || !card) return;
- const onKey = (e: KeyboardEvent) => {
- if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
- const el = document.activeElement as HTMLElement | null;
- // Never steal an arrow key from a text field or a native control the user is inside.
- if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))
- return;
- if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;
- e.preventDefault();
- decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);
- };
- window.addEventListener("keydown", onKey);
- return () => window.removeEventListener("keydown", onKey);
- }, [binding, canWrite, card, decide]);
-
- if (!binding.ok) {
- return (
-
-
-
- );
- }
-
- const { field } = binding;
- const leftTint = optionTint(field, binding.spec.leftOption);
- const rightTint = optionTint(field, binding.spec.rightOption);
-
- return (
-
-
-
-
- Sorting into {field.label}
-
-
- {deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort
-
- {canBind && (
- onSpec(undefined)}
- title="Choose a different field or different options for this deck"
- >
- Change
-
- )}
-
- {readOnlyReason &&
{readOnlyReason}
}
- {card ? (
-
-
decide(binding.spec.leftOption)}
- title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}
- >
-
-
-
-
-
- {binding.spec.leftOption}
-
-
{
- // ⭐ W41-T48 — the card IS the deck's record open, so it folds the rail.
- // ⚠ Nothing that is NOT an open can reach this line: every control inside the
- // card (a url cell, the comments box, the document tray) already stops its own
- // click, and the left/right decision buttons are siblings of the card, not
- // children of it. The deck also has no pointer drag to disambiguate — its swipe
- // is the two buttons and the arrow keys, neither of which opens anything.
- // ⚠ ``, not a native button, so a keyboard activation
- // never arrives here as a synthetic click; the keydown path below is the whole
- // keyboard story and the two cannot both fire for one gesture.
- if (e.detail <= 1) signal(NAV_MINIMIZE_EVENT);
- onOpen(card.pid);
- }}
- onKeyDown={(e) => {
- if (e.key !== "Enter" && e.key !== " ") return;
- e.preventDefault();
- // W41-T48 — `!e.repeat` is this path's `e.detail <= 1`: a HELD Enter or Space
- // auto-repeats keydown, and every one of those repeats is the SAME gesture.
- if (!e.repeat) signal(NAV_MINIMIZE_EVENT);
- onOpen(card.pid);
- }}
- >
- {String(card[titleKey] ?? "")}
-
- {/* ⭐ WAVE-29 T26 (R9) — the RECORD's visible fields, not the three-key summary the
- kanban card lends. `detailKeys` falls back to `cardKeys` so a host that has not
- been widened yet renders exactly what it rendered before. */}
- {(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => {
- const f = fieldByKey.get(k);
- if (!f) return null;
- const text = formatDisplay(f, card[k]);
- if (!text) return null;
- // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one
- // scheme guard — and every gesture that reaches it must be stopped from also
- // reaching the card, which is a button (the kanban card's note, same trap).
- const href = actionHref(f, card[k]);
- return (
-
- );
- })}
-
- {/* ⭐ R9's other two thirds. Both stop their own events: the card is a `role="button"`
- that opens the record, and a click on a comment box or an upload control must not
- also open the modal it exists to make unnecessary (the kanban card's link trap,
- one surface over). */}
- {onDocAdd && onDocFetch && onDocDelete && (
- e.stopPropagation()}
- onKeyDown={(e) => e.stopPropagation()}
- role="presentation"
- >
- onDocAdd(card.pid, file)}
- onFetch={(docId) => onDocFetch(card.pid, docId)}
- onDelete={(docId) => onDocDelete(card.pid, docId)}
- />
-
- )}
- {scope != null && (
- e.stopPropagation()}
- onKeyDown={(e) => e.stopPropagation()}
- role="presentation"
- >
- {/* ⚠ KEYED ON scope+pid, the same key `RecordDetail` uses: without it React
- reuses the mounted instance across a card change and paints one record's
- comments under another's name until the fetch returns. */}
-
-
- )}
- {canWrite && (
- {
- e.stopPropagation();
- setLater((prev) => new Set(prev).add(card.pid));
- }}
- >
- Decide later
-
- )}
-
- decide(binding.spec.rightOption)}
- title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}
- >
- {binding.spec.rightOption}
-
-
-
-
-
-
-
- ) : (
- // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous
- // between "the deck is finished" and "the filter hid everything", and the two want
- // different next actions. `later` is disclosed rather than quietly subtracted.
-
- {later.size > 0 ? (
- <>
-
- {later.size.toLocaleString()}{" "}
- {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else
- in this view is missing a {field.label} .
-
-
setLater(new Set())}>
- Bring them back
-
- >
- ) : (
-
- Every record in this view already has a {field.label} . Widen the
- view's filters to sort more.
-
- )}
-
- )}
-
- );
-}
-
-/**
- * The binding picker: field + two options. It is also the surface every LOST binding lands on,
- * with the loss stated above it — one place that answers "what is this deck for", rather than an
- * error screen beside a separate setup screen.
- */
-function SwipeBinder({
- fault,
- fields,
- fieldByKey,
- spec,
- canBind,
- onSpec,
-}: {
- fault: BindingFault;
- fields: Field[];
- fieldByKey: Map;
- spec: SwipeSpec | undefined;
- canBind: boolean;
- onSpec: (next: SwipeSpec | undefined) => void;
-}) {
- const selects = useMemo(
- () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),
- [fields]
- );
- const [fieldKey, setFieldKey] = useState(() => {
- if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;
- return selects[0]?.key ?? "";
- });
- const chosen = fieldByKey.get(fieldKey);
- const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);
- const [left, setLeft] = useState("");
- const [right, setRight] = useState("");
-
- // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's
- // pick survives re-renders, and reset whenever the field changes — carrying an option from the
- // previous field would offer a value the new field cannot hold.
- useEffect(() => {
- setLeft(options[0] ?? "");
- setRight(options.find((o) => o !== options[0]) ?? "");
- }, [options]);
-
- const message = ((): string => {
- switch (fault.kind) {
- case "field-gone":
- return "The field this deck sorted into has been deleted. Pick another one.";
- case "not-select":
- return `“${fault.field.label}” is no longer a single-select, so it has no options to`
- + " sort into. Pick another field.";
- case "option-gone":
- return `${fault.missing.map((m) => `“${m}”`).join(" and ")} ${
- fault.missing.length === 1 ? "is" : "are"
- } no longer ${fault.missing.length === 1 ? "an option" : "options"} on “${
- fault.field.label
- }”. Pick the sides again.`;
- default:
- return "Sort records one at a time into two options of a single-select field.";
- }
- })();
-
- if (!canBind) {
- return (
-
-
{message}
-
Its creator or an admin can set this view up.
-
- );
- }
- if (selects.length === 0) {
- // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the
- // requirement is what turns a dead end into a next action.
- return (
-
-
- A swipe deck sorts into a single-select field with at least two options. This database
- does not have one yet — add a single-select column, then come back.
-
-
- );
- }
- const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();
- return (
-
-
{message}
-
- Sort into
- setFieldKey(e.target.value)}
- >
- {/* Every option carries an explicit `value`: a whose value names nothing
- renders its FIRST option and reports a choice the user never made
- ([[cg-condition-builder-items]]). */}
- {selects.map((f) => (
-
- {f.label}
-
- ))}
-
-
-
-
- Swipe left
- setLeft(e.target.value)}>
- {options.map((o) => (
-
- {o}
-
- ))}
-
-
-
- Swipe right
- setRight(e.target.value)}>
- {options.map((o) => (
-
- {o}
-
- ))}
-
-
-
- {!ready && left && right && (
- // Stated, not silently refused: both engines DROP a binding whose sides are the same
- // option, so a Save that looked like it worked would simply not persist.
-
- The two sides must be different options — otherwise both gestures do the same thing.
-
- )}
-
- chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })
- }
- >
- Start sorting
-
-
- );
-}
-
-export default SwipeView;
+// ---------------------------------------------------------------------------
+// customer-grid / SwipeView.tsx
+// ⭐ WAVE-27 item 8 (owner ruling R2, contract C3) — the SWIPE deck.
+//
+// One record at a time, decided left or right into two options of ONE
+// single-select. R2 fixes the shape and it is narrow on purpose:
+// · SINGLE-SELECT ONLY, one field, two of its options. No checkbox binding.
+// · the deck holds only the records whose bound field is EMPTY — a record
+// that already has a value has been decided, and re-asking is not triage.
+// · a swipe writes through the NORMAL cell door (`onSwipe`, which the host
+// maps to the same `patchAndRecord` a kanban card move uses), so undo,
+// echo-suppression and the permission wall all hold without being
+// re-implemented here.
+//
+// Honesty rules carried from the other modes:
+// · nothing is silently hidden — the deck states what is left, and the
+// empty state names the bound field rather than saying "all done".
+// · a lost binding is SHOWN, never repaired by guessing. `_clean_display`
+// validates that `fieldKey` names a field the table HAS and stops there;
+// it cannot know the field is still a select, or that the two options are
+// still in its vocabulary (its docstring draws that line explicitly). So
+// those three losses land here, and each one says what happened and
+// re-opens the picker — the `viewModes.tsx:190-194` rule, which exists
+// because the wave-7 trap was a picker silently falling back to its first
+// option.
+// ---------------------------------------------------------------------------
+
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+// ⭐⭐ W41-T48 (owner instruction 22) — opening a record from the swipe deck folds the shell's
+// navigation rail exactly as a grid cell click does. Guard rationale: `MapView.tsx:2755`.
+import { NAV_MINIMIZE_EVENT, signal } from "../apiContract";
+import { choiceOptions } from "./types";
+import type { CustomerDoc, DisplaySpec, Field, Row, Viewer } from "./types";
+// ⚠ `SurfaceScope` is `apiBridge`'s (a TYPE-only import, so nothing of that module is
+// loaded here) — the same import `RecordComments` takes for the same prop.
+import type { SurfaceScope } from "./apiBridge";
+import RecordComments from "./RecordComments";
+import { Documents } from "./Documents";
+import { formatDisplay } from "./cells";
+import { actionHref } from "./display";
+import { optionTint } from "./choiceColors";
+import { ModeIcon } from "./icons";
+// ⭐ W29-T73 — the line its three siblings all have, and the one this file shipped without.
+// `SwipeView.css` had ZERO references anywhere in `src/`, so T26's two new sections rendered
+// unstyled while `.cg-swipe-card` (which lives in `index.css`) kept the card looking right —
+// a partially-styled surface reads as a design choice, which is why nobody reported it and no
+// gate could see it: a side-effect import references no symbol ([[artifact-with-no-importer]]).
+import "./SwipeView.css";
+
+export type SwipeSpec = NonNullable;
+
+/** The three ways a stored binding can rot that the host cannot see (see the header note). */
+type BindingFault =
+ | { kind: "unbound" }
+ | { kind: "field-gone"; fieldKey: string }
+ | { kind: "not-select"; field: Field }
+ | { kind: "option-gone"; field: Field; missing: string[] };
+
+function readBinding(spec: SwipeSpec | undefined, fieldByKey: Map):
+ { ok: true; field: Field; spec: SwipeSpec } | { ok: false; fault: BindingFault } {
+ if (!spec) return { ok: false, fault: { kind: "unbound" } };
+ const field = fieldByKey.get(spec.fieldKey);
+ if (!field) return { ok: false, fault: { kind: "field-gone", fieldKey: spec.fieldKey } };
+ // R2 — SINGLE-select only. `multiselect` is deliberately not accepted: its cell holds a SET,
+ // so "write this option" would mean append-or-replace, and a triage gesture that sometimes
+ // adds and sometimes overwrites is two gestures wearing one button.
+ if (field.type !== "select") return { ok: false, fault: { kind: "not-select", field } };
+ const options = choiceOptions(field);
+ const has = new Set(options.map((o) => o.toLowerCase()));
+ const missing = [spec.leftOption, spec.rightOption].filter((o) => !has.has(o.toLowerCase()));
+ if (missing.length) return { ok: false, fault: { kind: "option-gone", field, missing } };
+ return { ok: true, field, spec };
+}
+
+/** The bound cell is EMPTY — the one predicate that decides deck membership (R2). */
+const isUndecided = (row: Row, key: string): boolean =>
+ String(row[key] ?? "").trim() === "";
+
+export function SwipeView({
+ rows,
+ fields,
+ fieldByKey,
+ spec,
+ cardKeys,
+ detailKeys,
+ scope,
+ viewer,
+ docs,
+ docPayload,
+ onDocAdd,
+ onDocFetch,
+ onDocDelete,
+ titleKey,
+ canWrite,
+ readOnlyReason,
+ canBind,
+ onSpec,
+ onSwipe,
+ onOpen,
+}: {
+ /** DISTINCT data rows from the full pipeline, overlay edits layered — the kanban's contract.
+ * The deck re-derives from these, so a written record leaves it as soon as the optimistic
+ * patch lands; there is no local cursor to drift out of step with the data. */
+ rows: Row[];
+ /** Every field, for the picker's field list. */
+ fields: Field[];
+ fieldByKey: Map;
+ /** The stored binding, or undefined for a deck nobody has configured yet. */
+ spec: SwipeSpec | undefined;
+ /** The handful of visible fields the card lists under its title. */
+ cardKeys: string[];
+ titleKey: string;
+ /** May this viewer write the BOUND field's value? (the kanban's `canMove`) */
+ canWrite: boolean;
+ /** Stated when the deck cannot be decided — permissions, or a computed column. */
+ readOnlyReason: string | null;
+ /** May this viewer change what the deck is bound TO? A VIEW-config act, so it is the
+ * view-editing permission and NOT `canWrite` — conflating the two is
+ * [[schema-role-is-not-a-value-wall]]. REQUIRED, because a picker that silently does
+ * nothing is worse than no picker ([[wrong-parent-not-broken-control]]). */
+ canBind: boolean;
+ /** `undefined` DELETES the binding — absent is the honest unconfigured state, and storing a
+ * half-binding is what `cleanDisplay` drops on both engines (the `kanbanClamp` law). */
+ onSpec: (next: SwipeSpec | undefined) => void;
+ onSwipe: (pid: number, value: string) => void;
+ onOpen: (pid: number) => void;
+ /**
+ * ⭐⭐ WAVE-29 T26 (owner R9) — WHAT MAKES THE CARD A RECORD RATHER THAN A SUMMARY.
+ *
+ * R9: *"the swipe CARD itself renders the record detail inline — fields, comments and
+ * attachments — so a reviewer decides without leaving the deck."* Everything below is that,
+ * and every one of them is OPTIONAL for one reason: this deck runs on hosts that supply
+ * different amounts. A card must render with none of them rather than throw — the standalone
+ * embed has no `scope`, and a deployment with no document storage serves no handlers.
+ */
+ /** Every field the VIEW shows, in its order — not the three-key card summary. */
+ detailKeys?: string[];
+ /** The surface these records live on. Comments are keyed by it; absent ⇒ no comments section,
+ * which is the pre-existing precondition `RecordDetail` already carries. */
+ scope?: SurfaceScope;
+ viewer?: Viewer;
+ /** This record's attachments, and the plumbing. Handlers absent ⇒ the section is not rendered
+ * at all, exactly as `RecordDetail` decides it (a dead upload control is a promise the app
+ * cannot keep). */
+ /** Keyed by pid, because a deck shows many records — `RecordDetail` takes ONE record's list
+ * and that shape cannot serve a deck. */
+ docs?: Record;
+ docPayload?: { pid: number; docId: string; name: string; mime: string; data_b64: string };
+ /** ⚠ EVERY HANDLER TAKES THE PID, unlike `RecordDetail`'s, whose host closes over the ONE
+ * open record. A deck paints many records at once, so a handler bound to a single pid would
+ * attach every reviewer's upload to whichever card happened to be open. */
+ onDocAdd?: (
+ pid: number,
+ file: { name: string; mime: string; size: number; data_b64: string }
+ ) => void;
+ onDocFetch?: (pid: number, docId: string) => void;
+ onDocDelete?: (pid: number, docId: string) => void;
+}) {
+ // "Later" — session-only, never stored. A deck with no way past a record you cannot decide
+ // blocks on that record forever, so this is navigation WITHIN the deck rather than a third
+ // gesture: it writes nothing, survives no reload, and the count is disclosed in the empty
+ // state rather than quietly shrinking the deck (rule 8b).
+ const [later, setLater] = useState>(new Set());
+ const deckRef = useRef(null);
+
+ const binding = useMemo(() => readBinding(spec, fieldByKey), [spec, fieldByKey]);
+ const boundKey = binding.ok ? binding.field.key : null;
+
+ const undecided = useMemo(
+ () => (boundKey ? rows.filter((r) => isUndecided(r, boundKey)) : []),
+ [rows, boundKey]
+ );
+ const deck = useMemo(() => undecided.filter((r) => !later.has(r.pid)), [undecided, later]);
+ const card = deck[0];
+
+ // A record decided elsewhere (the grid, another user's echo) must not stay "later" forever —
+ // otherwise the disclosed skip count drifts away from what is actually on the deck.
+ useEffect(() => {
+ setLater((prev) => {
+ if (prev.size === 0) return prev;
+ const live = new Set(undecided.map((r) => r.pid));
+ const next = new Set([...prev].filter((pid) => live.has(pid)));
+ return next.size === prev.size ? prev : next;
+ });
+ }, [undecided]);
+
+ const decide = useCallback(
+ (value: string) => {
+ if (!card || !canWrite) return;
+ onSwipe(card.pid, value);
+ },
+ [card, canWrite, onSwipe]
+ );
+
+ // ← / → decide, and they are the SAME two actions the buttons are rather than a second code
+ // path: the whole point of the mode is that one hand can clear a queue.
+ useEffect(() => {
+ if (!binding.ok || !canWrite || !card) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key !== "ArrowLeft" && e.key !== "ArrowRight") return;
+ const el = document.activeElement as HTMLElement | null;
+ // Never steal an arrow key from a text field or a native control the user is inside.
+ if (el && (el.tagName === "INPUT" || el.tagName === "SELECT" || el.tagName === "TEXTAREA"))
+ return;
+ if (!deckRef.current?.contains(el ?? null) && el !== document.body) return;
+ e.preventDefault();
+ decide(e.key === "ArrowLeft" ? binding.spec.leftOption : binding.spec.rightOption);
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [binding, canWrite, card, decide]);
+
+ if (!binding.ok) {
+ return (
+
+
+
+ );
+ }
+
+ const { field } = binding;
+ const leftTint = optionTint(field, binding.spec.leftOption);
+ const rightTint = optionTint(field, binding.spec.rightOption);
+
+ return (
+
+
+
+
+ Sorting into {field.label}
+
+
+ {deck.length.toLocaleString()} {deck.length === 1 ? "record" : "records"} to sort
+
+ {canBind && (
+ onSpec(undefined)}
+ title="Choose a different field or different options for this deck"
+ >
+ Change
+
+ )}
+
+ {readOnlyReason &&
{readOnlyReason}
}
+ {card ? (
+
+
decide(binding.spec.leftOption)}
+ title={`Set ${field.label} to ${binding.spec.leftOption} (left arrow key)`}
+ >
+
+
+
+
+
+ {binding.spec.leftOption}
+
+
{
+ // ⭐ W41-T48 — the card IS the deck's record open, so it folds the rail.
+ // ⚠ Nothing that is NOT an open can reach this line: every control inside the
+ // card (a url cell, the comments box, the document tray) already stops its own
+ // click, and the left/right decision buttons are siblings of the card, not
+ // children of it. The deck also has no pointer drag to disambiguate — its swipe
+ // is the two buttons and the arrow keys, neither of which opens anything.
+ // ⚠ ``, not a native button, so a keyboard activation
+ // never arrives here as a synthetic click; the keydown path below is the whole
+ // keyboard story and the two cannot both fire for one gesture.
+ if (e.detail <= 1) signal(NAV_MINIMIZE_EVENT);
+ onOpen(card.pid);
+ }}
+ onKeyDown={(e) => {
+ if (e.key !== "Enter" && e.key !== " ") return;
+ e.preventDefault();
+ // W41-T48 — `!e.repeat` is this path's `e.detail <= 1`: a HELD Enter or Space
+ // auto-repeats keydown, and every one of those repeats is the SAME gesture.
+ if (!e.repeat) signal(NAV_MINIMIZE_EVENT);
+ onOpen(card.pid);
+ }}
+ >
+ {String(card[titleKey] ?? "")}
+
+ {/* ⭐ WAVE-29 T26 (R9) — the RECORD's visible fields, not the three-key summary the
+ kanban card lends. `detailKeys` falls back to `cardKeys` so a host that has not
+ been widened yet renders exactly what it rendered before. */}
+ {(detailKeys && detailKeys.length ? detailKeys : cardKeys).map((k) => {
+ const f = fieldByKey.get(k);
+ if (!f) return null;
+ const text = formatDisplay(f, card[k]);
+ if (!text) return null;
+ // A url cell is a LINK here too (wave-26 item 11), through `display.ts`'s one
+ // scheme guard — and every gesture that reaches it must be stopped from also
+ // reaching the card, which is a button (the kanban card's note, same trap).
+ const href = actionHref(f, card[k]);
+ return (
+
+ );
+ })}
+
+ {/* ⭐ R9's other two thirds. Both stop their own events: the card is a `role="button"`
+ that opens the record, and a click on a comment box or an upload control must not
+ also open the modal it exists to make unnecessary (the kanban card's link trap,
+ one surface over). */}
+ {onDocAdd && onDocFetch && onDocDelete && (
+ e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ role="presentation"
+ >
+ onDocAdd(card.pid, file)}
+ onFetch={(docId) => onDocFetch(card.pid, docId)}
+ onDelete={(docId) => onDocDelete(card.pid, docId)}
+ />
+
+ )}
+ {scope != null && (
+ e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ role="presentation"
+ >
+ {/* ⚠ KEYED ON scope+pid, the same key `RecordDetail` uses: without it React
+ reuses the mounted instance across a card change and paints one record's
+ comments under another's name until the fetch returns. */}
+
+
+ )}
+ {canWrite && (
+ {
+ e.stopPropagation();
+ setLater((prev) => new Set(prev).add(card.pid));
+ }}
+ >
+ Decide later
+
+ )}
+
+ decide(binding.spec.rightOption)}
+ title={`Set ${field.label} to ${binding.spec.rightOption} (right arrow key)`}
+ >
+ {binding.spec.rightOption}
+
+
+
+
+
+
+
+ ) : (
+ // The empty state NAMES the bound field (C3), because "nothing to sort" is ambiguous
+ // between "the deck is finished" and "the filter hid everything", and the two want
+ // different next actions. `later` is disclosed rather than quietly subtracted.
+
+ {later.size > 0 ? (
+ <>
+
+ {later.size.toLocaleString()}{" "}
+ {later.size === 1 ? "record is" : "records are"} set aside for later. Nothing else
+ in this view is missing a {field.label} .
+
+
setLater(new Set())}>
+ Bring them back
+
+ >
+ ) : (
+
+ Every record in this view already has a {field.label} . Widen the
+ view's filters to sort more.
+
+ )}
+
+ )}
+
+ );
+}
+
+/**
+ * The binding picker: field + two options. It is also the surface every LOST binding lands on,
+ * with the loss stated above it — one place that answers "what is this deck for", rather than an
+ * error screen beside a separate setup screen.
+ */
+function SwipeBinder({
+ fault,
+ fields,
+ fieldByKey,
+ spec,
+ canBind,
+ onSpec,
+}: {
+ fault: BindingFault;
+ fields: Field[];
+ fieldByKey: Map;
+ spec: SwipeSpec | undefined;
+ canBind: boolean;
+ onSpec: (next: SwipeSpec | undefined) => void;
+}) {
+ const selects = useMemo(
+ () => fields.filter((f) => f.type === "select" && choiceOptions(f).length >= 2),
+ [fields]
+ );
+ const [fieldKey, setFieldKey] = useState(() => {
+ if (spec && fieldByKey.get(spec.fieldKey)?.type === "select") return spec.fieldKey;
+ return selects[0]?.key ?? "";
+ });
+ const chosen = fieldByKey.get(fieldKey);
+ const options = useMemo(() => (chosen ? choiceOptions(chosen) : []), [chosen]);
+ const [left, setLeft] = useState("");
+ const [right, setRight] = useState("");
+
+ // The two option selects follow the FIELD. Kept in an effect rather than derived so the user's
+ // pick survives re-renders, and reset whenever the field changes — carrying an option from the
+ // previous field would offer a value the new field cannot hold.
+ useEffect(() => {
+ setLeft(options[0] ?? "");
+ setRight(options.find((o) => o !== options[0]) ?? "");
+ }, [options]);
+
+ const message = ((): string => {
+ switch (fault.kind) {
+ case "field-gone":
+ return "The field this deck sorted into has been deleted. Pick another one.";
+ case "not-select":
+ return `“${fault.field.label}” is no longer a single-select, so it has no options to`
+ + " sort into. Pick another field.";
+ case "option-gone":
+ return `${fault.missing.map((m) => `“${m}”`).join(" and ")} ${
+ fault.missing.length === 1 ? "is" : "are"
+ } no longer ${fault.missing.length === 1 ? "an option" : "options"} on “${
+ fault.field.label
+ }”. Pick the sides again.`;
+ default:
+ return "Sort records one at a time into two options of a single-select field.";
+ }
+ })();
+
+ if (!canBind) {
+ return (
+
+
{message}
+
Its creator or an admin can set this view up.
+
+ );
+ }
+ if (selects.length === 0) {
+ // Honest and specific: the mode is not broken, the TABLE has nothing to bind to. Naming the
+ // requirement is what turns a dead end into a next action.
+ return (
+
+
+ A swipe deck sorts into a single-select field with at least two options. This database
+ does not have one yet — add a single-select column, then come back.
+
+
+ );
+ }
+ const ready = !!chosen && !!left && !!right && left.toLowerCase() !== right.toLowerCase();
+ return (
+
+
{message}
+
+ Sort into
+ setFieldKey(e.target.value)}
+ >
+ {/* Every option carries an explicit `value`: a whose value names nothing
+ renders its FIRST option and reports a choice the user never made
+ ([[cg-condition-builder-items]]). */}
+ {selects.map((f) => (
+
+ {f.label}
+
+ ))}
+
+
+
+
+ Swipe left
+ setLeft(e.target.value)}>
+ {options.map((o) => (
+
+ {o}
+
+ ))}
+
+
+
+ Swipe right
+ setRight(e.target.value)}>
+ {options.map((o) => (
+
+ {o}
+
+ ))}
+
+
+
+ {!ready && left && right && (
+ // Stated, not silently refused: both engines DROP a binding whose sides are the same
+ // option, so a Save that looked like it worked would simply not persist.
+
+ The two sides must be different options — otherwise both gestures do the same thing.
+
+ )}
+
+ chosen && onSpec({ fieldKey: chosen.key, leftOption: left, rightOption: right })
+ }
+ >
+ Start sorting
+
+
+ );
+}
+
+export default SwipeView;
diff --git a/web/src/customer-grid/viewModes.tsx b/web/src/customer-grid/viewModes.tsx
index 119b5174e693faf8e9acd0602faac4d324ea2b67..7d2c18db1e98b7bc9729ef6e069ffcf153a9d47a 100644
--- a/web/src/customer-grid/viewModes.tsx
+++ b/web/src/customer-grid/viewModes.tsx
@@ -60,6 +60,20 @@ import { useScrollBox, windowRange } from "./GalleryTimelineViews";
// wave52-owned sheet instead of being added there.
import "../styles/wave52/timeline.css";
+/** The two template-backed surfaces which may be launched through the ordinary Map mode.
+ * The registry object is the discriminator: a name, hash fragment, or client-side template
+ * draft is never allowed to choose the renderer after the Application has been saved. */
+export type ApplicationTemplateSurface = "route" | "catalog" | null;
+
+export function applicationTemplateSurface(application: unknown): ApplicationTemplateSurface {
+ if (!application || typeof application !== "object" || Array.isArray(application)) return null;
+ const row = application as { templateKind?: unknown; fieldMap?: unknown };
+ if (!row.fieldMap || typeof row.fieldMap !== "object" || Array.isArray(row.fieldMap)) return null;
+ return row.templateKind === "route" || row.templateKind === "catalog"
+ ? row.templateKind
+ : null;
+}
+
/** Item 4 — plain words for the aggregates. "avg" is jargon in a picker aimed at a day cell. */
const AGG_LABELS: Record = {
sum: "Total",
@@ -229,6 +243,7 @@ export function ModeSwitch({
mode,
onMode,
locked = false,
+ allowedModes,
stackField,
stackChoices,
onPickField,
@@ -244,6 +259,8 @@ export function ModeSwitch({
* stay editable"), so removing those too would be a broader lock than the contract grants.
*/
locked?: boolean;
+ /** A host may expose only the projections it can render without weakening their data contract. */
+ allowedModes?: readonly DisplayMode[];
/** The kanban's effective stack field (resolved by the caller). */
stackField?: Field;
stackChoices: Field[];
@@ -265,6 +282,13 @@ export function ModeSwitch({
metricChoices?: Field[];
onCalendarMetrics?: (next: { id: string; field: string; agg: string }[]) => void;
}) {
+ const offeredGroups = CREATABLE_GROUPS.map((group) => ({
+ ...group,
+ modes: allowedModes
+ ? group.modes.filter((candidate) => allowedModes.includes(candidate))
+ : group.modes,
+ }))
+ .filter((group) => group.modes.length > 0);
// Wave-7 item W12: the switcher is a DROPDOWN in the toolbar-button family — the
// same Popover component Fields/Filter/Sort use, radio rows inside (the Rows/Color
// panel pattern), with the current mode named on the trigger chip.
@@ -326,7 +350,7 @@ export function ModeSwitch({
alignItems: "flex-start",
}}
>
- {CREATABLE_GROUPS.map((group) => (
+ {offeredGroups.map((group) => (
{group.label}
{group.modes.map((m) => (
@@ -1669,3 +1693,106 @@ function KanbanLane({
);
}
+/**
+ * The projections a linked database can safely host inside Record detail. This is a subset of the
+ * canonical display-mode registry: labels, icons, grouping, and renderers remain owned by this
+ * module rather than being copied into the drawer.
+ */
+export const RECORD_DETAIL_MODES: readonly DisplayMode[] = [
+ "grid",
+ "list",
+ "calendar",
+ "kanban",
+];
+
+const ignoreRecordGroup = (_groupKey: string) => undefined;
+const ignoreRecordMove = (_pid: number, _value: string) => undefined;
+
+/** Render a complete, already-authorized linked row set through the ordinary mode components. */
+export function RecordRelatedModeView({
+ mode,
+ rows,
+ fields,
+ dateFieldKey,
+ stackFieldKey,
+ today,
+ scope,
+ onOpen,
+}: {
+ mode: DisplayMode;
+ rows: Row[];
+ fields: Field[];
+ dateFieldKey?: string;
+ stackFieldKey?: string;
+ today?: string;
+ scope: SurfaceScope;
+ onOpen: (pid: number, record: Row, fields: Field[]) => void;
+}) {
+ const fieldByKey = useMemo(
+ () => new Map(fields.map((field) => [field.key, field])),
+ [fields]
+ );
+ const titleKey = fields[0]?.key ?? "pid";
+ const visibleKeys = useMemo(() => fields.slice(0, 5).map((field) => field.key), [fields]);
+ const visibleRows = useMemo
(
+ () => rows.map((record) => ({ kind: "data", record })),
+ [rows]
+ );
+ const dateField = fields.find((field) => field.key === dateFieldKey)
+ ?? fields.find((field) => field.type === "date");
+ const stackField = fields.find((field) => field.key === stackFieldKey)
+ ?? fields.find((field) => field.type === "select" || field.type === "status");
+ const openRecord = (pid: number) => {
+ const selected = rows.find((record) => Number(record.pid) === pid);
+ if (selected) onOpen(pid, selected, fields);
+ };
+
+ if (mode === "list") {
+ return (
+
+ );
+ }
+ if (mode === "calendar") {
+ return dateField ? (
+
+ ) : (
+ This database has no date field to place records by.
+ );
+ }
+ if (mode === "kanban") {
+ return stackField ? (
+ key !== titleKey && key !== stackField.key).slice(0, 3)}
+ titleKey={titleKey}
+ canMove={false}
+ readOnlyReason={null}
+ onMove={ignoreRecordMove}
+ onOpen={openRecord}
+ onAddOption={null}
+ />
+ ) : (
+
+ This database has no status or single-select field to stack by.
+
+ );
+ }
+ return Choose List, Calendar, or Kanban.
;
+}
diff --git a/web/src/home/HomePage.tsx b/web/src/home/HomePage.tsx
index 4c15dea9a8396eb77ff811b5ab736e98d97ff471..a6453c28c6a64128f97a58026be540b4168e6bfd 100644
--- a/web/src/home/HomePage.tsx
+++ b/web/src/home/HomePage.tsx
@@ -15,9 +15,9 @@
// key is not in them), and the four cards open doors the rail already offered.
// There is no payload here that `GET /nav` did not send.
//
-// It holds NO state of its own beyond the layout toggle. The recents come down
-// with the nav; the four actions are the frame's, because the frame owns the
-// dialogs and the hash.
+// It keeps display state for layout and the starred-only filter. Recents and
+// grants still come down with the nav; Application definitions are read from
+// their governed tenant registry and reuse the existing tile star control.
// ---------------------------------------------------------------------------
import { useEffect, useState } from "react";
@@ -47,15 +47,18 @@ import { API_V1, CREDENTIALS } from "../apiContract";
// worn by both surfaces. R4 makes star and "mark important" one idea and one flag; a second star
// component here would be the "one mark, one meaning" failure DESIGN.md 4 names, and `useStarred`
// is what keeps Home and Starred from ending up with different ideas of what is starred.
-import { StarButton, Tile } from "../starred/StarredPage";
+import { QueryIcon, StarButton, Tile } from "../starred/StarredPage";
import { shapeStarred, useStarred, viewCount, viewCountKey } from "../starred/starredApi";
import type { StarKind, Starred, StarredCounts, StarredLoad } from "../starred/starredApi";
+import { StarIcon } from "../ui/icons";
import {
HOME_LAYOUT_KEY,
+ applyHomeFilter,
allDatabases,
+ parseHomeFilter,
parseLayout,
} from "./homeModel";
-import type { AutomationTile, HomeLayout } from "./homeModel";
+import type { AutomationTile, HomeFilter, HomeLayout } from "./homeModel";
// ── the four quick-start marks ───────────────────────────────────────────────────────────────
//
@@ -145,6 +148,27 @@ function GridIcon() {
);
}
+/** Applications use one quiet four-pane mark, in the shell's existing stroke vocabulary. */
+function ApplicationIcon() {
+ return (
+
+
+
+
+ );
+}
+
+interface ApplicationTile {
+ id: string;
+ name: string;
+ type: string;
+ templateKind?: string;
+ compatibleDatabases?: string[];
+ openTarget?: { database?: string };
+ starred?: boolean;
+ capabilities?: { star?: boolean };
+}
+
/**
* One quick-start card. A `` — every one of these opens a dialog or a wizard rather
* than navigating, and a link that does not link is a lie the browser's status bar tells.
@@ -179,6 +203,10 @@ function QuickCard({
/** What the FRAME hands Home. Unchanged by the wave-35 split, and named so both halves take
* exactly the same shape rather than drifting. */
export interface HomeProps {
+ /** App reuses Home's tile vocabulary without becoming a second shell. */
+ mode?: "home" | "app";
+ /** Compatibility entry for a retired `#/starred` bookmark. */
+ initialStarredOnly?: boolean;
/**
* The SHAPED, server-filtered nav. The only thing a tile may be drawn from.
*
@@ -224,6 +252,8 @@ export interface HomeProps {
* a view opened from one cannot behave differently from the same view opened from the other.
*/
onOpenView: (database: string, viewId: string) => void;
+ /** Queries remain reachable after Starred leaves the rail. */
+ onOpenQuery?: (queryId: string) => void;
}
/**
@@ -236,9 +266,12 @@ export interface HomeProps {
* a person can SEE without a server. `inbox/_inbox_shot.tsx` paid for this lesson first; the same
* split is now on `StarredSurface`.
*
- * ⚠ THE DEFAULT EXPORT'S PROPS ARE UNCHANGED, so the frame's mount is untouched by this.
+ * Wave 55 adds optional Home/App mode and compatibility-filter props; the original callers keep
+ * their existing Home behavior by default.
*/
export function HomeSurface({
+ mode = "home",
+ initialStarredOnly = false,
entries,
recents,
automations,
@@ -247,16 +280,25 @@ export function HomeSurface({
onConnectors,
onOpenAutomation,
onOpenView,
+ onOpenQuery = () => undefined,
folders = [],
folderPlacement = {},
applications = [],
+ applicationsKnown = true,
+ applicationsError = "",
+ applicationBusy = new Set(),
+ onToggleApplication = () => undefined,
starLoad,
starred,
busy,
counts,
toggle,
}: HomeProps & {
- applications?: Array<{ id: string; name: string; type: string; compatibleDatabases?: string[]; openTarget?: { database?: string } }>;
+ applications?: ApplicationTile[];
+ applicationsKnown?: boolean;
+ applicationsError?: string;
+ applicationBusy?: ReadonlySet;
+ onToggleApplication?: (application: ApplicationTile, on: boolean) => void;
starLoad: StarredLoad;
starred: Starred;
busy: boolean;
@@ -278,6 +320,11 @@ export function HomeSurface({
// storage can be blocked; the toggle still works for this session
}
}, [layout]);
+ const [filter, setFilter] = useState(() =>
+ parseHomeFilter(initialStarredOnly ? "starred" : "all"));
+ useEffect(() => {
+ setFilter(parseHomeFilter(initialStarredOnly ? "starred" : "all"));
+ }, [initialStarredOnly]);
// ⚠ THE CLOCK IS READ ONCE, HERE, AND HANDED IN AS A NUMBER. `homeModel` stays pure so a gate
// can assert the ordering rather than whatever today happens to be.
@@ -295,6 +342,21 @@ export function HomeSurface({
const known = starLoad.phase === "ready";
const dbStarred = new Set(starred.databases);
const agentStarred = new Set(starred.agents);
+ const visibleDatabases = applyHomeFilter(
+ databases,
+ filter,
+ (database) => dbStarred.has(database.key),
+ );
+ const visibleAutomations = applyHomeFilter(
+ automations,
+ filter,
+ (automation) => agentStarred.has(automation.id),
+ );
+ const visibleApplications = applyHomeFilter(
+ applications,
+ mode === "app" ? "all" : filter,
+ (application) => application.starred === true,
+ );
// ⭐ WAVE 35 · W35-T16 (owner item 9) — the starred VIEWS, resolved by the SAME function
// Starred uses. Item 9 asks for these views on Home and under Starred; running them through one
@@ -303,13 +365,23 @@ export function HomeSurface({
// ⛔ AND THE DROP RULE COMES WITH IT: `shapeStarred` refuses a view whose database is not in
// `entries`, so a star that outlived its database (deleted, or a grant revoked) draws NOTHING
// rather than a tile that lands the reader in a 403.
- const starredViews = shapeStarred(starred, entries, automations).views;
+ const starredRows = shapeStarred(starred, entries, automations);
+ const starredViews = starredRows.views;
+ const starredQueries = starredRows.queries;
+ const starredOnly = mode === "home" && filter === "starred";
return (
-
Home
+
+
{mode === "app" ? "App" : "Home"}
+ {mode === "app" ? (
+
+ Create new
+
+ ) : null}
+
-
+ {mode === "home" ?
{/* ⚠ THE DETAIL LINES ARE BYTE-IDENTICAL TO THE DIALOG'S ROWS, and that is deliberate
rather than lazy. Each of these cards opens the same door as a row in the
New-database dialog, and the first draft described the same two things in four
@@ -356,7 +428,7 @@ export function HomeSurface({
detail="Browse the connectors this workspace can use."
onClick={onConnectors}
/>
-
+
: null}
{/* The reference puts an "Opened anytime" filter here. We do not have one and do not
@@ -383,10 +455,24 @@ export function HomeSurface({
>
+ {mode === "home" ? (
+ setFilter(starredOnly ? "all" : "starred")}
+ >
+
+ Starred only
+
+ ) : null}
- {databases.length === 0 ? (
+ {mode === "home" && !starredOnly && databases.length === 0 ? (
// ⛔ ONE LINE, AND IT NAMES THE DOOR THAT FILLS IT (DESIGN.md 4 / R13). This is also
// where wave 18's tenant hero went: a workspace with no databases lands here, and the
// cards above ARE the "create your first database" affordance the hero carried. Two
@@ -395,10 +481,10 @@ export function HomeSurface({
// described a state that can no longer exist — every granted database is drawn whether it
// has been opened or not, so an empty list now means exactly one thing.
- This workspace has no databases yet — create one above, or connect a source.
+ This workspace has no databases yet. Create one above, or connect a source.
- ) : (
- [{ id: "databases", title: "Databases", tiles: databases }].map((section) => (
+ ) : mode === "home" && visibleDatabases.length ? (
+ [{ id: "databases", title: "Databases", tiles: visibleDatabases }].map((section) => (
{section.title}
@@ -469,9 +555,61 @@ export function HomeSurface({
))
- )}
- {folders.length > 0 && }
- {applications.length > 0 && }
+ ) : null}
+ {mode === "home" && !starredOnly && folders.length > 0 && }
+ {applicationsError ? (
+ {applicationsError}
+ ) : null}
+ {visibleApplications.length > 0 ? (
+
+ Applications
+
+ {visibleApplications.map((application) => {
+ const database = application.openTarget?.database
+ ?? application.compatibleDatabases?.[0]
+ ?? "";
+ const kind = application.templateKind === "catalog"
+ ? "Catalog"
+ : application.templateKind === "route"
+ ? "Routing"
+ : application.type.slice(0, 1).toUpperCase() + application.type.slice(1);
+ return (
+
+ );
+ })}
+
+
+ ) : mode === "app" && applicationsKnown && !applicationsError ? (
+ No applications yet. Create one to add it here.
+ ) : mode === "app" && !applicationsKnown ? (
+
+
+
+ ) : null}
{/* ⭐ WAVE 24 item 13 (R10) — THE AUTOMATIONS SECTION.
Same tiles, same rhythm.
@@ -495,6 +633,7 @@ export function HomeSurface({
turns a 403 into `[]`) — and a heading over nothing says "there should be something
here", which is a different and false statement. */}
{automations.length ? (
+ mode === "home" && visibleAutomations.length ? (
{/* ⛔ W34-T40's `done-when` names FOUR surfaces that must read Agents, and this was the
one that did not: a hardcoded `"Automations"` that never consulted the module label.
@@ -506,7 +645,7 @@ export function HomeSurface({
here would have left the next rename in exactly the same trap. */}
{AGENTS_MODULE_LABEL}
- {automations.map((a) => (
+ {visibleAutomations.map((a) => (
+ ) : null
) : null}
{/* ⭐ WAVE 35 · W35-T16 (owner item 9) — THE STARRED VIEWS.
@@ -551,7 +691,7 @@ export function HomeSurface({
⚠ EMPTY RENDERS NOTHING, like every other section here: no starred views is a real
answer, and a heading over nothing says "there should be something here", which is a
different and false statement. */}
- {starredViews.length ? (
+ {mode === "home" && starredViews.length ? (
Starred views
@@ -576,6 +716,42 @@ export function HomeSurface({
) : null}
+ {starredOnly && starredQueries.length ? (
+
+ Starred queries
+
+ {starredQueries.map((row) => (
+ }
+ star={
+ known ? (
+ toggle("query", row.id, false)}
+ />
+ ) : undefined
+ }
+ onOpen={() => onOpenQuery(row.id)}
+ />
+ ))}
+
+
+ ) : null}
+ {known
+ && applicationsKnown
+ && !applicationsError
+ && starredOnly
+ && visibleDatabases.length === 0
+ && visibleAutomations.length === 0
+ && visibleApplications.length === 0
+ && starredViews.length === 0
+ && starredQueries.length === 0 ? (
+ Nothing starred yet.
+ ) : null}
);
}
@@ -593,8 +769,65 @@ export function HomeSurface({
*/
export default function HomePage(props: HomeProps) {
const { load: starLoad, starred, busy, counts, toggle } = useStarred();
- const [applications, setApplications] = useState
>([]);
- useEffect(() => { const controller = new AbortController(); void fetch(`${API_V1}/applications`, { credentials: CREDENTIALS, signal: controller.signal }).then(async (response) => response.ok ? response.json() : { applications: [] }).then((body) => { if (!controller.signal.aborted) setApplications(Array.isArray(body?.applications) ? body.applications : []); }).catch(() => undefined); return () => controller.abort(); }, []);
+ const [applications, setApplications] = useState([]);
+ const [applicationsKnown, setApplicationsKnown] = useState(false);
+ const [applicationsError, setApplicationsError] = useState("");
+ const [applicationBusy, setApplicationBusy] = useState>(() => new Set());
+ useEffect(() => {
+ const controller = new AbortController();
+ void fetch(`${API_V1}/applications`, {
+ credentials: CREDENTIALS,
+ signal: controller.signal,
+ })
+ .then(async (response) => {
+ if (!response.ok) throw new Error("application_list_failed");
+ return response.json();
+ })
+ .then((body) => {
+ if (!controller.signal.aborted) {
+ setApplications(Array.isArray(body?.applications) ? body.applications : []);
+ setApplicationsKnown(true);
+ }
+ })
+ .catch(() => {
+ if (!controller.signal.aborted) {
+ setApplicationsKnown(true);
+ setApplicationsError("Applications could not be loaded. Reload to retry.");
+ }
+ });
+ return () => controller.abort();
+ }, []);
+
+ const toggleApplication = (application: ApplicationTile, on: boolean) => {
+ if (applicationBusy.has(application.id)) return;
+ setApplicationsError("");
+ setApplicationBusy((current) => new Set(current).add(application.id));
+ void fetch(`${API_V1}/applications/${encodeURIComponent(application.id)}`, {
+ method: "PATCH",
+ credentials: CREDENTIALS,
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ starred: on }),
+ })
+ .then(async (response) => {
+ if (!response.ok) throw new Error("application_star_failed");
+ const body = await response.json();
+ return body?.application as ApplicationTile | undefined;
+ })
+ .then((landed) => {
+ if (!landed) return;
+ setApplications((current) => current.map((row) => row.id === landed.id ? landed : row));
+ })
+ .catch(() => {
+ setApplicationsError("The Application could not be updated. Try again.");
+ })
+ .finally(() => {
+ setApplicationBusy((current) => {
+ const next = new Set(current);
+ next.delete(application.id);
+ return next;
+ });
+ });
+ };
return (
);
}
diff --git a/web/src/home/homeModel.ts b/web/src/home/homeModel.ts
index d7befd268dd00cfaeed8f84dd648b87028a8ece8..1594a080c6a231564f344e10d00395b840cc8f62 100644
--- a/web/src/home/homeModel.ts
+++ b/web/src/home/homeModel.ts
@@ -210,3 +210,21 @@ export const HOME_LAYOUT_KEY = "aios-home-layout";
export function parseLayout(raw: unknown): HomeLayout {
return raw === "list" ? "list" : "grid";
}
+
+// ── WAVE 55: Home's starred-only filter ───────────────────────────────────────────────────
+
+export type HomeFilter = "all" | "starred";
+
+/** An old `#/starred` bookmark is rewritten to Home with this query value. */
+export function parseHomeFilter(raw: unknown): HomeFilter {
+ return raw === "starred" ? "starred" : "all";
+}
+
+/** One pure filter for every Home tile species, so the toggle cannot mean different things. */
+export function applyHomeFilter(
+ rows: T[],
+ filter: HomeFilter,
+ isStarred: (row: T) => boolean,
+): T[] {
+ return filter === "starred" ? rows.filter(isStarred) : rows;
+}
diff --git a/web/src/sheet/BindingEditor.tsx b/web/src/sheet/BindingEditor.tsx
index c31f5b97faefa909a53ffe4dc3990d4bcabfdd8e..46415973b37589415c5f80a38ef6b0a61d9bd201 100644
--- a/web/src/sheet/BindingEditor.tsx
+++ b/web/src/sheet/BindingEditor.tsx
@@ -51,6 +51,7 @@ import { countConditions, isNumericType } from "../filter-kit/ops";
import { SheetFilterPopup } from "../filter-kit/SheetFilterPopup";
import { useEscapeClose } from "../ui/useEscapeClose";
import { previewCell } from "./sheetApi";
+import { bindingDisplay } from "./types";
const AGGREGATES = [
{ fn: "sum", label: "Sum" },
@@ -928,6 +929,8 @@ export default function BindingEditor({
* 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]);
+ /** Metric columns step their period; every other aggregate steps one chosen filter driver. */
+ const chosenIsMetric = Boolean(chosenField && isMetricField(chosenField));
/** 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. */
@@ -943,6 +946,10 @@ export default function BindingEditor({
const adopted = (initial?.scope as Record | undefined)?.adoptedFrom;
if (scopeKind === "filter" && adopted) scope.adoptedFrom = adopted;
const out: Record = { database, aggregate: agg, scope };
+ // W55-T07 / R6: re-saving what this cell points at must not reset how its View drawer opens.
+ // The display bag belongs to this binding, not to the saved View and not to localStorage.
+ const display = bindingDisplay(initial);
+ if (display) out.display = display;
// C2's period, spelled the contract's way. R14: a period SOURCE is a `$`-anchored cell
// reference; the A1 resolver reads it BEFORE the query is built, so it is an INPUT to the
// filter and never a post-filter. It rides ALONGSIDE the unit and the start rather than
@@ -952,14 +959,18 @@ export default function BindingEditor({
// stamped to this month's default, and turning the switch off drops the key rather than writing
// an empty period the server would have to guess about.
if (periodOn) {
- const period: Record = { unit, start, locked };
+ const period: Record = {
+ unit, start, locked: chosenIsMetric ? locked : true,
+ };
if (refOpen && periodRef.trim()) period.ref = periodRef.trim();
out.period = period;
}
- out.onDrag = { across, down: downField ? { field: downField } : "none" };
+ out.onDrag = chosenIsMetric
+ ? { across: periodOn && !locked ? across : "none", down: "none" }
+ : { across: "none", down: downField ? { field: downField } : "none" };
return out;
}, [database, fn, field, scopeKind, viewId, views, tree, initial,
- unit, start, locked, refOpen, periodRef, periodOn, across, downField]);
+ unit, start, locked, refOpen, periodRef, periodOn, across, downField, chosenIsMetric]);
// ⭐ THE NUMBER APPEARS BEFORE SAVING. `preview` evaluates the binding without persisting it,
// which is what lets someone see whether they picked the right thing while they can still change
@@ -1294,24 +1305,34 @@ export default function BindingEditor({
{/* ⭐ 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. */}
-
-
setLocked((v) => !v)}
- >
-
- Lock this period
-
+ {chosenIsMetric ? (
+
+
{
+ const next = !locked;
+ setLocked(next);
+ setAcross(next ? "none" : "period");
+ }}
+ >
+
+ Lock this period
+
+
+ {locked
+ ? "Locked, so any copy of this cell keeps this period."
+ : `Not locked, so a stepped copy moves by one ${UNIT_NOUN[unit]} per cell. `
+ + "Right and down move forward. Left and up move backward."}
+
+
+ ) : (
- {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."}
+ This period stays fixed when copied. The filter driver below is what changes.
-
+ )}
{/* ⭐ "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
@@ -1342,39 +1363,60 @@ export default function BindingEditor({
{/* ══ R10: THE DRAG RULES ═════════════════════════════════════════════════════════════ */}
- When dragged
+ When copied
-
- Across
- setAcross(e.target.value === "none" ? "none" : "period")}
- >
- Period
- Nothing
-
-
-
-
- Down
- setDownField(e.target.value)}
- >
- Nothing
- {dragDownFields.map((f) => (
- {`Next value of ${f.label}`}
- ))}
-
-
-
- {dragDownFields.length === 0 && (
-
- This database has no single select or link column to walk, so dragging down repeats
- the same rows.
-
+ {chosenIsMetric ? (
+ periodOn ? (
+ <>
+
+ Period
+ {
+ const step = e.target.value === "period";
+ setAcross(step ? "period" : "none");
+ setLocked(!step);
+ }}
+ >
+ {`Step by ${UNIT_NOUN[unit]}`}
+ Keep this period
+
+
+
+ Right and down move forward. Left and up move backward.
+
+ >
+ ) : (
+
+ This metric is all time, so copied cells keep the same all-time period.
+
+ )
+ ) : (
+ <>
+
+ Filter driver
+ setDownField(e.target.value)}
+ >
+ Keep this filter
+ {dragDownFields.map((f) => (
+ {`Step by ${f.label}`}
+ ))}
+
+
+ {dragDownFields.length === 0 ? (
+
+ This database has no single select or link field with ordered options.
+
+ ) : (
+
+ Right and down choose later options. Left and up choose earlier options.
+
+ )}
+ >
)}
diff --git a/web/src/sheet/ChartDialog.tsx b/web/src/sheet/ChartDialog.tsx
index 2f961f2f261cb8fa839fd981b23f8dd408aa8c6b..fa1b8f3c27a40ddc0029f7865ce1f104588ee07d 100644
--- a/web/src/sheet/ChartDialog.tsx
+++ b/web/src/sheet/ChartDialog.tsx
@@ -48,14 +48,10 @@ 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";
+import { parseRange } from "./rules";
+import type { Cell, SheetChartRange, SheetChartSpec } from "./types";
-export interface ChartRange {
- col0: number;
- row0: number;
- col1: number;
- row1: number;
-}
+export type ChartRange = SheetChartRange;
/**
* ⭐ THE EIGHT KINDS THE DOCUMENT CARRIES. `types.ts::SheetChartSpec` declares all eight and
@@ -173,6 +169,13 @@ export function chartRangeOf(sel: ChartRange | null): ChartRange {
return { col0, row0, col1: col0 + CHART_COLS - 1, row1: row0 + CHART_ROWS - 1 };
}
+/** A chart range as one editable A1 expression. */
+export function chartRangeText(range: ChartRange): string {
+ const first = addressOf(Math.min(range.col0, range.col1), Math.min(range.row0, range.row1));
+ const last = addressOf(Math.max(range.col0, range.col1), Math.max(range.row0, range.row1));
+ return first === last ? first : `${first}:${last}`;
+}
+
/** 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 };
@@ -309,27 +312,43 @@ const SOURCE_TABS: { id: SourceTab; label: string }[] = [
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. */
+ /** Present when this is the same dialog reopened for an existing chart. */
+ chart?: SheetChartSpec;
+ /** Escape, the close mark, or Cancel. All converge on 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: (
+ onCreate?: (
kind: SheetChartSpec["kind"],
range: ChartRange,
cells?: Record,
) => void;
+ /** The existing chart's one persisted settings write. */
+ onUpdate?: (chart: SheetChartSpec) => void;
+ /** Ribbon openers restore themselves; a chart settings button delegates restoration here. */
+ restoreFocus?: boolean;
}
-export default function ChartDialog({ selection, onClose, onCreate }: ChartDialogProps) {
+export default function ChartDialog({
+ selection,
+ chart,
+ onClose,
+ onCreate,
+ onUpdate,
+ restoreFocus = false,
+}: ChartDialogProps) {
const panelRef = useRef(null);
const titleId = useId();
+ const editing = chart !== undefined;
+ const seedRange = chart?.range ?? chartRangeOf(selection);
const [tab, setTab] = useState("range");
- const [kind, setKind] = useState("bar");
+ const [kind, setKind] = useState(chart?.kind ?? "bar");
+ const [rangeDraft, setRangeDraft] = useState(() => chartRangeText(seedRange));
const [databases, setDatabases] = useState<{ key: string; label: string }[]>([]);
- const [loading, setLoading] = useState(true);
+ const [loading, setLoading] = useState(!editing);
const [database, setDatabase] = useState("");
const [fn, setFn] = useState("count");
const [field, setField] = useState("");
@@ -343,9 +362,10 @@ export default function ChartDialog({ selection, onClose, onCreate }: ChartDialo
useOverlayLayer({
panelRef,
onDismiss: onClose,
- dismissOnOutside: true,
+ // This is a modal settings surface. A stray click must not discard a half-edited range.
+ dismissOnOutside: false,
initialFocus: "first",
- restoreFocus: false,
+ restoreFocus,
trapFocus: true,
});
@@ -356,6 +376,7 @@ export default function ChartDialog({ selection, onClose, onCreate }: ChartDialo
* dialog is not.
*/
useEffect(() => {
+ if (editing) return undefined;
let live = true;
(async () => {
try {
@@ -375,20 +396,23 @@ export default function ChartDialog({ selection, onClose, onCreate }: ChartDialo
}
})();
return () => { live = false; };
- }, []);
+ }, [editing]);
- const range = useMemo(() => chartRangeOf(selection), [selection]);
- const rangeSentence = `The chart will cover ${addressOf(range.col0, range.row0)} to `
- + `${addressOf(range.col1, range.row1)}.`;
+ const range = useMemo(() => parseRange(rangeDraft), [rangeDraft]);
const wantsField = fn !== "count";
const ready = tab === "range"
- ? true
+ ? range !== null
: Boolean(database) && (!wantsField || field.trim().length > 0);
const create = () => {
+ if (editing) {
+ if (!range || !chart || !onUpdate) return;
+ onUpdate({ ...chart, kind, range });
+ return;
+ }
if (tab === "range") {
- onCreate(kind, range);
+ if (range) onCreate?.(kind, range);
return;
}
if (!ready) return;
@@ -400,9 +424,29 @@ export default function ChartDialog({ selection, onClose, onCreate }: ChartDialo
unit,
periods: Number(periods),
});
- onCreate(kind, plan.range, plan.cells);
+ onCreate?.(kind, plan.range, plan.cells);
};
+ const rangeField = (
+
+
Cell range
+
setRangeDraft(event.target.value)}
+ />
+ {range === null ? (
+
+ Enter a cell range such as B2:E8.
+
+ ) : null}
+
+ );
+
const kindPicker = (
{CHART_KINDS.map((entry) => (
@@ -435,7 +479,9 @@ export default function ChartDialog({ selection, onClose, onCreate }: ChartDialo
data-overlay-kind="sheet-chart"
>
-
Insert a chart
+
+ {editing ? "Chart settings" : "Insert a chart"}
+
-
- {SOURCE_TABS.map((entry) => (
- setTab(entry.id)}
- >
- {entry.label}
-
- ))}
-
+ {!editing ? (
+
+ {SOURCE_TABS.map((entry) => (
+ setTab(entry.id)}
+ >
+ {entry.label}
+
+ ))}
+
+ ) : null}
{tab === "range" ? (
<>
-
{rangeSentence}
+ {rangeField}
{kindPicker}
>
) : (
@@ -583,7 +631,7 @@ export default function ChartDialog({ selection, onClose, onCreate }: ChartDialo
disabled={!ready}
onClick={create}
>
- Insert chart
+ {editing ? "Save chart" : "Insert chart"}
diff --git a/web/src/sheet/DrillModal.tsx b/web/src/sheet/DrillModal.tsx
index 6c5b92f5c3c67f44b7503eb32271ee5e8b21b3ba..0da26ab7c2ea154c380d5a66e473c9b41cbbc3c8 100644
--- a/web/src/sheet/DrillModal.tsx
+++ b/web/src/sheet/DrillModal.tsx
@@ -38,8 +38,9 @@
// 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.
+// recorded beside the code that answers it: the BAND (`DrillFilterBand`) states it, the top-right
+// Edit filter action opens the shared `SheetFilterDialog`, 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
@@ -59,19 +60,25 @@
// 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 { Suspense, lazy, useCallback, useEffect, useMemo, 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 { dataPathHash } from "../customer-grid/dataPath";
+import { formatDisplay } from "../customer-grid/display";
+import { ModeIcon } from "../customer-grid/icons";
+import { AnchoredOverlay, OverlayProvider } from "../customer-grid/OverlaySurface";
+import type { Field, FilterTree, GridWorkspace, Row } from "../customer-grid/types";
+import { choiceVocabulary, mayEditField, topicForScope } from "../customer-grid/types";
import {
SheetFilterDialog, conditionCountLabel, filterSentence,
} from "../filter-kit/SheetFilterPopup";
import { useEscapeClose } from "../ui/useEscapeClose";
+import { cellViewVisibleKeys, filterFieldKeys } from "./bindingRefs";
import { drillCell } from "./sheetApi";
import type { CellDrill } from "./sheetApi";
+import { CELL_VIEW_MODES } from "./types";
+import type { BindingDisplay, CellViewMode } from "./types";
/**
* ⛔⛔ LAZY, AND THE BUILD IS WHAT SAID SO. A plain `import { LinkGridModal } from
@@ -107,6 +114,191 @@ const LinkGridModal = lazy(() =>
*/
const warmLinkChunk = () => import("../customer-grid/CustomerGrid");
+const CELL_VIEW_LABELS: Record = {
+ grid: "Grid",
+ list: "List",
+ map: "Map",
+};
+
+/** Compact Grid projection for a cell; values use the Data grid's one formatter. */
+function CellGridView(
+ { rows, fields, identityKey }: { rows: Row[]; fields: Field[]; identityKey: string },
+) {
+ return (
+
+
+ {fields.map((field) => {field.label} )}
+
+ {rows.map((row) => (
+
+ {fields.map((field) => (
+
+ {formatDisplay(field, row[field.key]) || " "}
+
+ ))}
+
+ ))}
+ {rows.length === 0 &&
No records match this cell.
}
+
+ );
+}
+
+/** List projection keeps one record together and labels every secondary value. */
+function CellListView(
+ { rows, fields, identityKey }: { rows: Row[]; fields: Field[]; identityKey: string },
+) {
+ const identity = fields.find((field) => field.key === identityKey) ?? fields[0] ?? null;
+ const details = fields.filter((field) => field.key !== identity?.key);
+ return (
+
+ {rows.map((row) => (
+
+ {identity ? formatDisplay(identity, row[identity.key]) : `Record ${row.pid}`}
+
+ {details.map((field) => (
+
+ {field.label}
+
+ {formatDisplay(field, row[field.key]) || " "}
+
+
+ ))}
+
+
+ ))}
+ {rows.length === 0 &&
No records match this cell.
}
+
+ );
+}
+
+interface CellMapAssets {
+ land: string;
+ lakes: string[];
+ project: (lon: number, lat: number) => { x: number; y: number };
+ parse: (value: unknown) => { lat: number; lon: number } | null;
+}
+
+interface CellMapSetup {
+ latField?: string;
+ lonField?: string;
+ coordField?: string;
+}
+
+const numberAt = (value: unknown): number | null => {
+ if (value == null || value === "") return null;
+ const number = typeof value === "number" ? value : Number(value);
+ return Number.isFinite(number) ? number : null;
+};
+
+/** The ordinary map projection, narrowed to the cell's exact row ids and without route writers. */
+function CellMapView({
+ rows, identityKey, setup, assets,
+}: {
+ rows: Row[];
+ identityKey: string;
+ setup: CellMapSetup | null;
+ assets: CellMapAssets | null;
+}) {
+ if (!assets) {
+ return (
+
+
+
+ );
+ }
+ const points: { pid: number; title: string; x: number; y: number }[] = [];
+ for (const row of rows) {
+ let at: { lat: number; lon: number } | null = null;
+ if (setup?.latField && setup.lonField) {
+ const lat = numberAt(row[setup.latField]);
+ const lon = numberAt(row[setup.lonField]);
+ if (lat != null && lon != null) at = { lat, lon };
+ } else if (setup?.coordField) {
+ at = assets.parse(row[setup.coordField]);
+ } else {
+ const lat = numberAt(row.lat);
+ const lon = numberAt(row.lon);
+ if (lat != null && lon != null) at = { lat, lon };
+ }
+ if (!at || Math.abs(at.lat) > 85.05112878 || Math.abs(at.lon) > 180) continue;
+ const projected = assets.project(at.lon, at.lat);
+ points.push({
+ pid: row.pid,
+ title: String(row[identityKey] ?? `Record ${row.pid}`),
+ x: projected.x,
+ y: projected.y,
+ });
+ }
+
+ let minX = 0;
+ let minY = 850;
+ let width = 4096;
+ let height = 1450;
+ if (points.length) {
+ const xs = points.map((point) => point.x);
+ const ys = points.map((point) => point.y);
+ minX = Math.min(...xs);
+ minY = Math.min(...ys);
+ width = Math.max(420, Math.max(...xs) - minX);
+ height = Math.max(260, Math.max(...ys) - minY);
+ const pad = Math.max(width, height) * 0.18;
+ minX -= pad;
+ minY -= pad;
+ width += pad * 2;
+ height += pad * 2;
+ const ratio = 1.72;
+ if (width / height < ratio) {
+ const next = height * ratio;
+ minX -= (next - width) / 2;
+ width = next;
+ } else {
+ const next = width / ratio;
+ minY -= (next - height) / 2;
+ height = next;
+ }
+ }
+ const radius = Math.max(width, height) / 125;
+ const missing = rows.length - points.length;
+ return (
+
+
+
+
+ {assets.lakes.map((path, index) => (
+
+ ))}
+ {points.map((point) => (
+
+ {point.title}
+
+ ))}
+
+ {missing > 0 && (
+
+ {`${missing.toLocaleString()} matching ${missing === 1 ? "record has" : "records have"} no location`}
+
+ )}
+ {rows.length === 0 &&
No records match this cell.
}
+
+ );
+}
+
/**
* 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.
@@ -178,9 +370,14 @@ function DrillSkeleton(
* 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 };
+export type DrillCellScope = (
+ | { kind: "filter"; tree: FilterTree }
+ | { kind: "view"; name: string }
+ )
+ & {
+ /** W55-T07: the cell binding's own display bag, never the saved View's config. */
+ display?: BindingDisplay;
+ };
/** What the drill's own answer says about the scope, for a caller that passed none. */
function scopeFromDrill(drill: CellDrill | null): DrillCellScope | null {
@@ -203,14 +400,13 @@ const sameTree = (a: FilterTree | null, b: FilterTree | null): boolean =>
/**
* ⭐⭐ 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.
+ * 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`. W55-T07 moves Edit filter to the top-right toolbar and leaves this band one
+ * statement with one job.
*/
function DrillFilterBand(
- { text, onEdit, editing }: { text: string; onEdit: (() => void) | null; editing: boolean },
+ { text }: { text: string },
) {
return (
{text}
- {onEdit && (
-
- Edit the filter
-
- )}
);
}
@@ -284,10 +464,18 @@ export interface DrillModalProps {
* over the new filter.
*/
onFilterChange?: (addr: string, tree: FilterTree) => void | Promise;
+ /**
+ * W55-T07 / R6: persist presentation on this cell's binding. The current Sheet host does not
+ * expose this writer yet, so absence leaves a working session-local switch and no false save
+ * claim; the typed seam is what the host must connect to its existing one-cell binding writer.
+ */
+ onDisplayChange?: (addr: string, display: BindingDisplay) => void | Promise;
}
export default function DrillModal(
- { workbookId, addr, label, onClose, onSettled, cellScope, onFilterChange }: DrillModalProps,
+ {
+ workbookId, addr, label, onClose, onSettled, cellScope, onFilterChange, onDisplayChange,
+ }: DrillModalProps,
) {
const [drill, setDrill] = useState(null);
const [error, setError] = useState("");
@@ -302,6 +490,28 @@ export default function DrillModal(
/** Same reason, one ticket later: the page hands this an inline arrow too. */
const filterChangeRef = useRef(onFilterChange);
filterChangeRef.current = onFilterChange;
+ const displayChangeRef = useRef(onDisplayChange);
+ displayChangeRef.current = onDisplayChange;
+
+ // R6: hydrate from the binding seam, not from a database View and not from localStorage.
+ const displayKey = JSON.stringify(cellScope?.display ?? null);
+ const hydratedDisplayRef = useRef("");
+ const [cellDisplay, setCellDisplay] = useState(
+ () => cellScope?.display ?? { mode: "grid", visible: [] },
+ );
+ useEffect(() => {
+ const key = `${workbookId}:${addr}:${displayKey}`;
+ if (hydratedDisplayRef.current === key) return;
+ hydratedDisplayRef.current = key;
+ setCellDisplay(cellScope?.display ?? { mode: "grid", visible: [] });
+ }, [addr, cellScope?.display, displayKey, workbookId]);
+
+ const changeDisplay = useCallback((next: BindingDisplay) => {
+ setCellDisplay(next);
+ // No callback means no durable writer. The switch still answers the current gesture, but it
+ // never falls back to a second browser store that would violate R6's cell-local contract.
+ void Promise.resolve(displayChangeRef.current?.(addr, next));
+ }, [addr]);
// ── W54-T35 state ─────────────────────────────────────────────────────────────────────────
/** Is the centred filter dialog on screen? */
@@ -336,6 +546,14 @@ export default function DrillModal(
/** The filter kit's two vocabularies for this database. Fetched once the drill has answered. */
const [fields, setFields] = useState([]);
const [statusValues, setStatusValues] = useState>({});
+ /** Raw, permission-scoped rows back the List, Map and export projections. */
+ const [rawRows, setRawRows] = useState([]);
+ const [workspace, setWorkspace] = useState(null);
+ const [rowsResolved, setRowsResolved] = useState(false);
+ const [rowsError, setRowsError] = useState("");
+ const [today, setToday] = useState(undefined);
+ const [mapAssets, setMapAssets] = useState(null);
+ const [mapError, setMapError] = useState(false);
useEffect(() => {
let live = true;
@@ -438,17 +656,28 @@ export default function DrillModal(
* against the list, so a minutes-old field list cannot paint a configuration nobody saved.
*/
useEffect(() => {
- if (!scope || shownKind !== "filter") return;
+ if (!scope) return;
let live = true;
+ setRowsResolved(false);
+ setRowsError("");
+ setFields([]);
+ setRawRows([]);
+ setWorkspace(null);
+ setToday(undefined);
(async () => {
const [ws, rowsPayload] = await Promise.all([
fetchWorkspace(scope, { allowCached: true }),
fetchTopicRows(topicForScope(scope)),
]);
- if (!live || !ws) return;
- const list = (ws.fields ?? []) as Field[];
+ if (!live) return;
+ if (!ws && !rowsPayload) {
+ setRowsError("These records could not be loaded for List, Map or Export.");
+ setRowsResolved(true);
+ return;
+ }
+ const list = ((rowsPayload?.fields?.length ? rowsPayload.fields : ws?.fields) ?? []) as Field[];
const rows: Row[] = rowsPayload?.rows ?? [];
- const options: string[] = rowsPayload?.userOptions ?? ws.userOptions ?? [];
+ 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.
@@ -460,14 +689,35 @@ export default function DrillModal(
if (f.type === "select" || f.type === "multiselect" || f.type === "status")
map[f.key] = choiceVocabulary(f, rows);
}
+ setWorkspace(ws);
setFields(list);
+ setRawRows(rows);
setStatusValues(map);
+ setToday(rowsPayload?.today);
+ setRowsResolved(true);
})();
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]);
+ }, [scope]);
+
+ /** Load only the two leaf geometry modules when Map is actually selected. */
+ useEffect(() => {
+ if (cellDisplay.mode !== "map" || mapAssets) return;
+ let live = true;
+ setMapError(false);
+ void Promise.all([
+ import("../customer-grid/mapGeometry"),
+ import("../customer-grid/mapProjection"),
+ ]).then(([geometry, projection]) => {
+ if (!live) return;
+ setMapAssets({
+ land: geometry.LAND_PATH,
+ lakes: geometry.LAKE_PATHS,
+ project: projection.project,
+ parse: (value) => projection.parseLatLon(value as Row[keyof Row]),
+ });
+ }, () => { if (live) setMapError(true); });
+ return () => { live = false; };
+ }, [cellDisplay.mode, mapAssets]);
/** Persist a tree through the page's one binding writer, then read the rows again. */
const applyTree = useCallback(async (tree: FilterTree) => {
@@ -577,6 +827,103 @@ export default function DrillModal(
return () => window.cancelAnimationFrame(frame);
}, [showRows]);
+ const headerHost = host?.querySelector(".cg-link-grid-head") ?? null;
+ const bodyHost = host?.querySelector(".cg-link-grid-body") ?? null;
+ useEffect(() => {
+ if (!bodyHost) return;
+ bodyHost.classList.add("sheet-cell-view-custom");
+ return () => bodyHost.classList.remove("sheet-cell-view-custom");
+ }, [bodyHost]);
+
+ /** Exact record order from the drill answer; a topic payload is only the row book. */
+ const recordRows = useMemo(() => {
+ if (!drill) return [];
+ const byPid = new Map(rawRows.map((row) => [row.pid, row]));
+ return drill.record_ids.map((pid) => byPid.get(pid)).filter((row): row is Row => Boolean(row));
+ }, [drill, rawRows]);
+
+ const identityField = fields.find((field) => field.pinned) ?? fields[0] ?? null;
+ const savedView = drill?.view_id
+ ? workspace?.views?.find((view) => view.id === drill.view_id) ?? null
+ : null;
+ const fieldFilter: FilterTree | null = shown?.kind === "filter"
+ ? shown.tree
+ : savedView
+ ? { conj: savedView.config.filterConj, nodes: savedView.config.filters }
+ : null;
+ const forcedFieldKeys = filterFieldKeys(fieldFilter);
+ const defaultFieldKeys = fields
+ .filter((field) => field.default !== false && field.custom !== true && field.shared !== true)
+ .map((field) => field.key);
+ const visibleKeys = cellViewVisibleKeys(
+ defaultFieldKeys,
+ cellDisplay.visible,
+ forcedFieldKeys,
+ fields.map((field) => field.key),
+ identityField?.key ?? "",
+ );
+ const visibleFields = visibleKeys
+ .map((key) => fields.find((field) => field.key === key))
+ .filter((field): field is Field => Boolean(field));
+ const mapSetup = (workspace?.mapSetup ?? null) as CellMapSetup | null;
+ const fieldKeys = new Set(fields.map((field) => field.key));
+ const mapSupported = Boolean(
+ (mapSetup?.latField && mapSetup.lonField
+ && fieldKeys.has(mapSetup.latField) && fieldKeys.has(mapSetup.lonField))
+ || (mapSetup?.coordField && fieldKeys.has(mapSetup.coordField))
+ || (fieldKeys.has("lat") && fieldKeys.has("lon")),
+ );
+
+ // CustomerGrid's own value-edit predicate. It distinguishes source-locked values, machine-
+ // written pre-set fields and viewer grants field by field instead of inventing one read-only flag.
+ const canEditRows = Boolean(
+ rowsResolved && !rowsError && fields.some((field) => mayEditField(field, workspace?.viewer)),
+ );
+ const allRowsLoaded = rowsResolved
+ && (drill?.record_ids.length ?? 0) === recordRows.length;
+ const editInData = useCallback(() => {
+ if (!drill || !canEditRows) return;
+ onClose();
+ window.location.hash = dataPathHash({
+ database: drill.database,
+ ...(drill.view_id ? { view: drill.view_id } : {}),
+ });
+ }, [canEditRows, drill, onClose]);
+
+ const fieldsButtonRef = useRef(null);
+ const exportButtonRef = useRef(null);
+ const [fieldsOpen, setFieldsOpen] = useState(false);
+ const [exportOpen, setExportOpen] = useState(false);
+ const [exporting, setExporting] = useState(false);
+
+ const setMode = useCallback((mode: CellViewMode) => {
+ if (mode === "map" && rowsResolved && !mapSupported) return;
+ changeDisplay({ ...cellDisplay, mode });
+ }, [cellDisplay, changeDisplay, mapSupported, rowsResolved]);
+
+ const setFieldVisible = useCallback((key: string, checked: boolean) => {
+ if (!identityField || forcedFieldKeys.includes(key) || key === identityField.key) return;
+ const chosen = new Set(visibleKeys);
+ if (checked) chosen.add(key);
+ else chosen.delete(key);
+ changeDisplay({
+ ...cellDisplay,
+ visible: fields.map((field) => field.key).filter((fieldKey) => chosen.has(fieldKey)),
+ });
+ }, [cellDisplay, changeDisplay, fields, forcedFieldKeys, identityField, visibleKeys]);
+
+ const exportCell = useCallback(async (format: "csv" | "xlsx" | "pdf" | "json") => {
+ if (!allRowsLoaded || exporting) return;
+ setExportOpen(false);
+ setExporting(true);
+ try {
+ const exporter = await import("../customer-grid/export");
+ exporter.runExport(format, `${label} records`, today, visibleFields, recordRows);
+ } finally {
+ setExporting(false);
+ }
+ }, [allRowsLoaded, exporting, label, recordRows, today, visibleFields]);
+
/**
* 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
@@ -649,8 +996,8 @@ export default function DrillModal(
* ⛔ 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.
+ * closes the drill. The band claims nothing: it is a statement inside the card, not an
+ * overlay, so the "exactly one claimant" property W51-T12 bought is unspent.
*/
}>
@@ -662,14 +1009,193 @@ export default function DrillModal(
onClose={onClose}
/>
+ {headerHost && createPortal(
+
+
+ {CELL_VIEW_MODES.map((mode) => {
+ const unavailable = mode === "map" && (!rowsResolved || !mapSupported);
+ return (
+ setMode(mode)}
+ key={mode}
+ >
+
+ {CELL_VIEW_LABELS[mode]}
+
+ );
+ })}
+
+
{ setExportOpen(false); setFieldsOpen((open) => !open); }}
+ >
+
+
+
+ Fields
+
+
+
+
+
+ Edit filter
+
+ {canEditRows && (
+
+
+
+
+ Edit rows
+
+ )}
+
{ setFieldsOpen(false); setExportOpen((open) => !open); }}
+ >
+
+
+
+ {exporting ? "Preparing" : "Export"}
+
+
,
+ headerHost,
+ )}
+ {bodyHost && createPortal(
+
+ {!rowsResolved ? (
+
+
+
+ ) : rowsError ? (
+
{rowsError}
+ ) : cellDisplay.mode === "grid" ? (
+
+ ) : cellDisplay.mode === "list" ? (
+
+ ) : mapSupported && mapError ? (
+
+ Map could not be loaded.
+
+ ) : mapSupported ? (
+
+ ) : (
+
+ Map needs latitude and longitude fields in this database.
+
+ )}
+ {rowsResolved && !rowsError && !allRowsLoaded && (
+
+ {`${recordRows.length.toLocaleString()} of ${(drill?.record_ids.length ?? 0).toLocaleString()} matching records are loaded.`}
+
+ )}
+
,
+ bodyHost,
+ )}
+ {fieldsOpen && fieldsButtonRef.current && (
+ setFieldsOpen(false)}
+ role="dialog"
+ ariaLabel="Fields shown in this cell"
+ dataKind="sheet-cell-fields"
+ >
+ Fields shown in this cell
+
+ {fields.map((field) => {
+ const forced = field.key === identityField?.key || forcedFieldKeys.includes(field.key);
+ return (
+
+ setFieldVisible(field.key, event.target.checked)}
+ />
+ {field.label}
+ {forcedFieldKeys.includes(field.key)
+ ? Used by filter
+ : field.key === identityField?.key
+ ? Identity
+ : null}
+
+ );
+ })}
+
+
+ )}
+ {exportOpen && exportButtonRef.current && (
+ setExportOpen(false)}
+ role="menu"
+ ariaLabel="Export matching records"
+ dataKind="sheet-cell-export"
+ >
+ {(["csv", "xlsx", "pdf", "json"] as const).map((format) => (
+ { void exportCell(format); }}
+ key={format}
+ >
+ {format === "xlsx" ? "Excel" : format === "pdf" ? "PDF" : format.toUpperCase()}
+
+ ))}
+
+ )}
{host && bandText && createPortal(
- ,
+ ,
host,
)}
{filterOpen && draft && (
diff --git a/web/src/sheet/KeyTips.tsx b/web/src/sheet/KeyTips.tsx
index 644a2dc170300ba89fe13b9aa664bd1163e6589c..bf75a02d024c3f1f39f4cd542f336e5552cb1e7f 100644
--- a/web/src/sheet/KeyTips.tsx
+++ b/web/src/sheet/KeyTips.tsx
@@ -30,8 +30,9 @@
// fresh badge set from whatever `.sheet-ribbon-pop` is now open (KT-11).
//
// ⚠ SCOPE, STATED HONESTLY (the ticket's own "best effort" clause for the third level). The first
-// two levels — Alt -> Home tab badge, H -> every Home control badge, prefix match, arrow/Enter
-// nav, Escape/Alt exit — are built to the full spec. The THIRD level (inside an opened gallery) is
+// two levels — Alt -> Home tab badge, H -> every Home control badge, prefix match, Left/Right and
+// Enter nav, Escape/Alt exit — are built to the full spec. Wave 55 gives Up/Down back to the grid
+// immediately. The THIRD level (inside an opened gallery) is
// exercised to full fidelity for Borders only (`Ribbon.tsx`'s `BORDERS` array now carries its own
// one-letter `data-kt` per entry, plus "No border"). Every OTHER gallery (Insert, Delete, Format,
// Clear, Fill/Text colour, Font size, Number format) still gets Escape-to-close and generic
@@ -40,6 +41,7 @@
// no letter badges yet. That gap is booked in the ticket's HANDOFF, not hidden here.
import { useCallback, useEffect, useReducer, useRef } from "react";
import type { RefObject } from "react";
+import { KEY_TIP_GRID_ARROW_EVENT, keyTipGridArrow } from "./shortcuts";
type Depth = "tabs" | "home" | "gallery";
@@ -190,11 +192,11 @@ export default function KeyTips({ containerRef }: KeyTipsProps) {
el.classList.add("sheet-kt-flash");
}, []);
- const deactivateAll = useCallback(() => {
+ const deactivateAll = useCallback((restoreFocus = true) => {
const el = previousFocusRef.current;
previousFocusRef.current = null;
setKt(INITIAL);
- requestAnimationFrame(() => el?.focus?.());
+ if (restoreFocus) requestAnimationFrame(() => el?.focus?.());
}, [setKt]);
const activateFirstLevel = useCallback(() => {
@@ -314,7 +316,21 @@ export default function KeyTips({ containerRef }: KeyTipsProps) {
stepBack();
return;
}
- if (e.key === "ArrowRight" || e.key === "ArrowDown") {
+ // W55-T05 / R4: Up and Down leave the Alt path instead of walking its badges. The original
+ // document-capture key cannot reach Glide because focus currently belongs to the ribbon, so
+ // consume it once, close synchronously, and hand one semantic arrow to this ribbon's own
+ // SheetGrid wrapper. That wrapper owns selection and focus; no global key listener competes
+ // with the shared overlay/Escape stack.
+ const gridArrow = keyTipGridArrow(e.key);
+ if (gridArrow) {
+ e.preventDefault(); e.stopPropagation();
+ deactivateAll(false);
+ containerRef.current?.closest(".sheet-grid-wrap")?.dispatchEvent(
+ new CustomEvent(KEY_TIP_GRID_ARROW_EVENT, { detail: { key: gridArrow } }),
+ );
+ return;
+ }
+ if (e.key === "ArrowRight") {
e.preventDefault(); e.stopPropagation();
if (targets.length) {
const next = (st.focusedIdx + 1) % targets.length;
@@ -323,7 +339,7 @@ export default function KeyTips({ containerRef }: KeyTipsProps) {
}
return;
}
- if (e.key === "ArrowLeft" || e.key === "ArrowUp") {
+ if (e.key === "ArrowLeft") {
e.preventDefault(); e.stopPropagation();
if (targets.length) {
const next = (st.focusedIdx - 1 + targets.length) % targets.length;
@@ -354,7 +370,8 @@ 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, activateFirstLevel, containerRef, flash, handleCharacter, stepBack, setKt]);
+ }, [activate, activateFirstLevel, containerRef, deactivateAll, flash, handleCharacter,
+ stepBack, setKt]);
const onDocKeyUp = useCallback((e: KeyboardEvent) => {
if (e.key !== "Alt") return;
diff --git a/web/src/sheet/Ribbon.tsx b/web/src/sheet/Ribbon.tsx
index 7ebd75be6786a63cea61fbeb47fcd784f964b93a..bf1d816db5c64e8d86b35eb0a5513489b0fdc7f0 100644
--- a/web/src/sheet/Ribbon.tsx
+++ b/web/src/sheet/Ribbon.tsx
@@ -59,6 +59,12 @@ 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";
+// W55-T06 adopts the public Excel audit's tab grouping through Loopable's existing ribbon
+// registry and command vocabulary. The tab modules cite the audit and keep unsupported commands
+// visibly unavailable rather than widening SheetGrid's closed action union.
+import { FORMULAS_TAB } from "./ribbonFormulas";
+import { DATA_TAB } from "./ribbonData";
+import { VIEW_TAB } from "./ribbonView";
// ⭐⭐ 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
@@ -190,7 +196,7 @@ export interface RibbonProps {
* `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 TABS = [HOME_TAB, INSERT_TAB, FORMULAS_TAB, DATA_TAB, VIEW_TAB] as const;
/**
* ⭐⭐ W52-T15 (instruction 14, contract C4) — IMPORT, REFRESH AND FULL SCREEN LIVE IN THE TAB
@@ -250,6 +256,11 @@ export interface RibbonTabContext {
onApply: (patch: CellStylePatch) => void;
apply: (patch: CellStylePatch) => void;
act: (kind: RibbonActionKind, arg?: string | number) => void;
+ /** View-only state owned by the ribbon shell, with no new document or SheetGrid action. */
+ fullscreen: boolean;
+ toggleFullscreen: () => void;
+ formulaBarVisible: boolean;
+ toggleFormulaBar: () => void;
openPop: (which: Popover) => (event: ReactMouseEvent) => void;
closePop: () => void;
control: (
@@ -264,6 +275,8 @@ export interface RibbonTabContext {
) => ReactNode;
group: (name: string, body: ReactNode, extra?: string) => ReactNode;
word: (text: string) => ReactNode;
+ /** A command the current Sheet door cannot execute, stated visibly instead of acting dead. */
+ unavailable: (label: string, body: ReactNode) => 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
@@ -279,6 +292,7 @@ export interface RibbonTabContext {
* the state that shows every control rather than the state that hides them.
*/
const COLLAPSE_KEY = "aios.sheet.ribbon.collapsed";
+const FORMULA_BAR_KEY = "aios.sheet.ribbon.formula-bar";
const readCollapsed = (): boolean => {
try {
@@ -296,6 +310,22 @@ const writeCollapsed = (next: boolean) => {
}
};
+const readFormulaBar = (): boolean => {
+ try {
+ return window.localStorage.getItem(FORMULA_BAR_KEY) !== "0";
+ } catch {
+ return true;
+ }
+};
+
+const writeFormulaBar = (visible: boolean) => {
+ try {
+ window.localStorage.setItem(FORMULA_BAR_KEY, visible ? "1" : "0");
+ } catch {
+ // A refused storage write affects persistence only; the current view still changes.
+ }
+};
+
function IconRefresh() {
return (
@@ -346,9 +376,24 @@ export default function Ribbon({
*/
const [anchorEl, setAnchorEl] = useState(null);
const [collapsed, setCollapsed] = useState(readCollapsed);
+ const [formulaBarVisible, setFormulaBarVisible] = useState(readFormulaBar);
const rootRef = useRef(null);
- /** Which tab is showing. One registered tab today, so this never changes hands yet. */
+ useEffect(() => {
+ const wrap = rootRef.current?.closest(".sheet-grid-wrap");
+ wrap?.classList.toggle("is-formula-bar-hidden", !formulaBarVisible);
+ return () => wrap?.classList.remove("is-formula-bar-hidden");
+ }, [formulaBarVisible]);
+
+ const toggleFormulaBar = useCallback(() => {
+ setFormulaBarVisible((was) => {
+ const next = !was;
+ writeFormulaBar(next);
+ return next;
+ });
+ }, []);
+
+ /** Which registered tab is showing. */
const [active, setActive] = useState(TABS[0].id);
const activeTab = TABS.find((tab) => tab.id === active) ?? TABS[0];
@@ -554,6 +599,23 @@ export default function Ribbon({
/** A plain word inside a control. A ribbon is not an icon quiz. */
const word = (text: string) => {text} ;
+ /**
+ * A disabled command is intentionally outside the roving registry. Native `disabled` keeps it
+ * inert; the visible status and accessible name explain why it does not receive focus or fire.
+ */
+ const unavailable = (label: string, body: ReactNode) => (
+
+ {body}
+ Unavailable
+
+ );
+
// ⭐ W52-T17 — the optional 5th argument `kt` is the THIRD-LEVEL key-tip badge (KT-11): a
// gallery item painted with its own letter once the gallery that owns it is open. Additive and
// undefined everywhere this ticket did not touch, so every existing `item(...)` call site keeps
@@ -577,8 +639,9 @@ export default function Ribbon({
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,
+ style, frozen, open, anchorEl, onApply, apply, act,
+ fullscreen, toggleFullscreen, formulaBarVisible, toggleFormulaBar,
+ openPop, closePop, control, group, word, unavailable, item, insert,
};
return (
diff --git a/web/src/sheet/SheetChart.tsx b/web/src/sheet/SheetChart.tsx
index 18e0b39c4451ee4f312fb9249605e10c0ccc2023..ce23d08682a9a5fcc09e7d738cd1e8c8b8c9b6fe 100644
--- a/web/src/sheet/SheetChart.tsx
+++ b/web/src/sheet/SheetChart.tsx
@@ -65,13 +65,15 @@ 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, SheetChartDrawnKind, SheetChartSpec } from "./types";
+import type {
+ CellMap, SheetChartDrawnKind, SheetChartRange, 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 };
+ range: SheetChartRange;
cells: CellMap;
kind?: SheetChartSpec["kind"];
/** Rendered size in px. The SVG scales to it; the renderer is not resized. */
@@ -85,8 +87,16 @@ export interface SheetChartProps {
* ⚠ 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;
+ onMove?: (dx: number, dy: number) => ChartAnchorDelta;
+ onResize?: (dx: number, dy: number) => ChartAnchorDelta;
+ /** Reopens this chart's persisted kind and range in the shared chart dialog. */
+ onEdit?: () => void;
+}
+
+/** How far the persisted cell anchor actually moved after a pointer gesture snapped to the grid. */
+export interface ChartAnchorDelta {
+ dx: number;
+ dy: number;
}
/** A cell's text, however it is stored. A chart reads what the sheet SHOWS. */
@@ -94,20 +104,158 @@ const textAt = (cells: CellMap, col: number, row: number): string => {
const cell = cells[addressOf(col, row)];
if (!cell) return "";
if (cell.state === "refused") return "";
- return cell.display ?? (cell.value == null ? "" : String(cell.value));
+ return cell.display ?? (cell.value == null ? (cell.text ?? "") : String(cell.value));
};
/**
- * A column is numeric when EVERY non-blank value in it parses as a number.
+ * The numeric value of a cell. The stored value wins over presentation, so applying Currency or
+ * Percent never turns a number into a text column. A typed string remains eligible, including
+ * grouped, currency and percent text, because literal cells intentionally keep what was typed.
+ */
+const numberAt = (cells: CellMap, col: number, row: number): number | null => {
+ const cell = cells[addressOf(col, row)];
+ if (!cell || cell.state === "refused") return null;
+ const raw = cell.value ?? cell.text ?? cell.display;
+ if (typeof raw === "number") return Number.isFinite(raw) ? raw : null;
+ if (typeof raw !== "string") return null;
+ let text = raw.trim();
+ if (!text) return null;
+ const negative = text.startsWith("(") && text.endsWith(")");
+ if (negative) text = text.slice(1, -1).trim();
+ const percent = text.endsWith("%");
+ if (percent) text = text.slice(0, -1).trim();
+ text = text.replace(/[,\s]/g, "").replace(/^([$€£])/, "");
+ if (!/^[-+]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(text)) return null;
+ const value = Number(text);
+ if (!Number.isFinite(value)) return null;
+ return (negative ? -value : value) / (percent ? 100 : 1);
+};
+
+interface ChartCellValue {
+ text: string;
+ number: number | null;
+ col: number;
+ row: number;
+}
+
+export interface SheetChartData {
+ fields: WireField[];
+ rows: Row[];
+ series: { y: string; label: string }[];
+}
+
+const valueColumn = (values: ChartCellValue[]): boolean => {
+ const filled = values.filter((value) => value.text.trim() !== "" || value.number !== null);
+ return filled.length > 0 && filled.every((value) => value.number !== null);
+};
+
+/**
+ * Turn any selected numeric rectangle into the chart engine's category plus series shape.
*
- * ⚠ "every", not "any". One numeric-looking value in a column of labels would otherwise retype the
- * whole column and the axis would render nonsense. A wholly blank column stays text, because there
- * is no evidence for anything else.
+ * A labelled table keeps Excel's first-row/first-column convention. A numeric-only row, column,
+ * or block has no labels to infer, so cell addresses become its categories and column letters its
+ * series names. This is the missing path that used to make a perfectly valid numeric selection
+ * render the empty-chart refusal. The ninth numeric series and everything after it fold into one
+ * `Other` series, as DESIGN.md section 3 requires.
*/
-const columnType = (values: string[]): string => {
- const filled = values.filter((v) => v.trim() !== "");
- if (!filled.length) return "text";
- return filled.every((v) => Number.isFinite(Number(v))) ? "int" : "text";
+export const chartDataForRange = (cells: CellMap, range: SheetChartRange): SheetChartData => {
+ const loCol = Math.min(range.col0, range.col1);
+ const hiCol = Math.max(range.col0, range.col1);
+ const loRow = Math.min(range.row0, range.row1);
+ const hiRow = Math.max(range.row0, range.row1);
+ const matrix: ChartCellValue[][] = [];
+ for (let row = loRow; row <= hiRow; row += 1) {
+ const line: ChartCellValue[] = [];
+ for (let col = loCol; col <= hiCol; col += 1) {
+ line.push({ text: textAt(cells, col, row), number: numberAt(cells, col, row), col, row });
+ }
+ matrix.push(line);
+ }
+
+ const empty: SheetChartData = { fields: [], rows: [], series: [] };
+ if (!matrix.length || !matrix[0]?.length) return empty;
+
+ // A horizontal numeric run is one measure observed across the selected cells.
+ if (matrix.length === 1) {
+ const numeric = matrix[0].filter((value) => value.number !== null);
+ if (!numeric.length) return empty;
+ const named = matrix[0].find((value) => value.number === null && value.text.trim() !== "");
+ const fields: WireField[] = [
+ { key: "category", label: "Cell", type: "text" },
+ { key: "value", label: named?.text ?? "Values", type: "int" },
+ ];
+ const rows = numeric.map((value, index) => ({
+ pid: index + 1,
+ category: addressOf(value.col, value.row),
+ value: value.number,
+ } as unknown as Row));
+ return { fields, rows, series: [{ y: "value", label: fields[1].label }] };
+ }
+
+ // A vertical numeric run is the same shape, with row addresses as its category axis.
+ if (matrix[0].length === 1) {
+ const first = matrix[0][0];
+ const header = first.number === null && first.text.trim() !== "" ? first.text : "Values";
+ const numeric = matrix.slice(first.number === null ? 1 : 0)
+ .map((line) => line[0])
+ .filter((value) => value.number !== null);
+ if (!numeric.length) return empty;
+ const fields: WireField[] = [
+ { key: "category", label: "Cell", type: "text" },
+ { key: "value", label: header, type: "int" },
+ ];
+ const rows = numeric.map((value, index) => ({
+ pid: index + 1,
+ category: addressOf(value.col, value.row),
+ value: value.number,
+ } as unknown as Row));
+ return { fields, rows, series: [{ y: "value", label: fields[1].label }] };
+ }
+
+ const laterHasNumber = matrix.slice(1).some((line) => line.some((value) => value.number !== null));
+ const headerRow = laterHasNumber
+ && matrix[0].some((value) => value.text.trim() !== "" && value.number === null);
+ const body = matrix.slice(headerRow ? 1 : 0);
+ if (!body.length) return empty;
+
+ const numericCols: number[] = [];
+ for (let col = 0; col < matrix[0].length; col += 1) {
+ if (valueColumn(body.map((line) => line[col]))) numericCols.push(col);
+ }
+ if (!numericCols.length) return empty;
+ const categoryCol = numericCols.includes(0) ? null : 0;
+ const sourceCols = numericCols.filter((col) => col !== categoryCol);
+ if (!sourceCols.length) return empty;
+
+ const kept = sourceCols.slice(0, 8);
+ const folded = sourceCols.slice(8);
+ const seriesFields: WireField[] = kept.map((source, index) => ({
+ key: `value${index}`,
+ label: headerRow
+ ? (matrix[0][source].text || addressOf(loCol + source, loRow).replace(/[0-9]+$/, ""))
+ : addressOf(loCol + source, loRow).replace(/[0-9]+$/, ""),
+ type: "int",
+ }));
+ if (folded.length) seriesFields.push({ key: "other", label: "Other", type: "int" });
+ const fields: WireField[] = [{ key: "category", label: "Cell", type: "text" }, ...seriesFields];
+ const rows = body.map((line, index) => {
+ const out: Record = {
+ pid: index + 1,
+ category: categoryCol === null
+ ? addressOf(loCol, line[0].row)
+ : (line[categoryCol].text || addressOf(line[categoryCol].col, line[categoryCol].row)),
+ };
+ kept.forEach((source, slot) => { out[`value${slot}`] = line[source].number ?? 0; });
+ if (folded.length) {
+ out.other = folded.reduce((total, source) => total + (line[source].number ?? 0), 0);
+ }
+ return out as unknown as Row;
+ });
+ return {
+ fields,
+ rows,
+ series: seriesFields.map((field) => ({ y: field.key, label: field.label })),
+ };
};
/**
@@ -650,51 +798,12 @@ export default function SheetChart({
height,
onMove,
onResize,
+ onEdit,
}: SheetChartProps) {
- const { fields, rows, series } = useMemo(() => {
- const { col0, row0, col1, row1 } = range;
- const loCol = Math.min(col0, col1);
- const hiCol = Math.max(col0, col1);
- const loRow = Math.min(row0, row1);
- const hiRow = Math.max(row0, row1);
-
- // R15: the header ROW names the columns. A blank header still gets a key, because a column
- // with no name is still a column and dropping it would silently narrow the chart.
- const headers: string[] = [];
- for (let c = loCol; c <= hiCol; c += 1) {
- headers.push(textAt(cells, c, loRow) || addressOf(c, loRow).replace(/[0-9]+$/, ""));
- }
-
- const body: string[][] = [];
- for (let r = loRow + 1; r <= hiRow; r += 1) {
- const line: string[] = [];
- for (let c = loCol; c <= hiCol; c += 1) line.push(textAt(cells, c, r));
- body.push(line);
- }
-
- const keys = headers.map((_h, i) => `c${i}`);
- const wire: WireField[] = headers.map((label, i) => ({
- key: keys[i],
- label,
- type: columnType(body.map((line) => line[i] ?? "")),
- }));
-
- const asRows: Row[] = body.map((line, i) => {
- const row: Record = { pid: i + 1 };
- line.forEach((value, c) => {
- row[keys[c]] = wire[c].type === "int" && value.trim() !== "" ? Number(value) : value;
- });
- return row as unknown as Row;
- });
-
- // The first column is the x bucket; every numeric column after it is a series.
- const valueFields = wire.slice(1).filter((f) => f.type === "int");
- return {
- fields: wire,
- rows: asRows,
- series: valueFields.map((f) => ({ y: f.key, label: f.label })),
- };
- }, [range, cells]);
+ const { fields, rows, series } = useMemo(
+ () => chartDataForRange(cells, range),
+ [cells, range],
+ );
const delegated = useMemo(() => {
const viz = VIZ_KIND[kind];
@@ -714,7 +823,14 @@ export default function SheetChart({
const [nudge, setNudge] = useState(ZERO);
const [flash, setFlash] = useState(false);
- const grab = useRef<{ x: number; y: number; mode: "move" | "resize" } | null>(null);
+ const grab = useRef<{
+ pointerId: number;
+ originLeft: number;
+ originTop: number;
+ offsetX: number;
+ offsetY: number;
+ mode: "move" | "resize";
+ } | null>(null);
const frame = useRef(null);
const stopSettle = useCallback(() => {
@@ -772,18 +888,26 @@ export default function SheetChart({
event.preventDefault();
event.stopPropagation();
stopSettle();
- grab.current = { x: event.clientX, y: event.clientY, mode };
+ const rect = event.currentTarget.getBoundingClientRect();
+ grab.current = {
+ pointerId: event.pointerId,
+ originLeft: rect.left,
+ originTop: rect.top,
+ offsetX: event.clientX - rect.left,
+ offsetY: event.clientY - rect.top,
+ mode,
+ };
event.currentTarget.setPointerCapture(event.pointerId);
setNudge(ZERO);
}, [stopSettle]);
const duringDrag = useCallback((event: React.PointerEvent) => {
const held = grab.current;
- if (!held) return;
+ if (!held || held.pointerId !== event.pointerId) 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;
+ const dx = event.clientX - held.offsetX - held.originLeft;
+ const dy = event.clientY - held.offsetY - held.originTop;
setNudge(held.mode === "move"
? { dx, dy, dw: 0, dh: 0 }
: { dx: 0, dy: 0, dw: dx, dh: dy });
@@ -791,20 +915,34 @@ export default function SheetChart({
const endDrag = useCallback((event: React.PointerEvent) => {
const held = grab.current;
- if (!held) return;
+ if (!held || held.pointerId !== event.pointerId) 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);
+ const dx = event.clientX - held.offsetX - held.originLeft;
+ const dy = event.clientY - held.offsetY - held.originTop;
+ const snapped = held.mode === "move" ? onMove?.(dx, dy) : onResize?.(dx, dy);
+ // The persisted anchor changes in the same release. Keep only the UNSNAPPED residual in the
+ // presentation value, so old anchor + pointer travel equals new anchor + residual and there is
+ // no release-frame jump or double movement.
+ const residualX = dx - (snapped?.dx ?? 0);
+ const residualY = dy - (snapped?.dy ?? 0);
settle(held.mode === "move"
- ? { dx, dy, dw: 0, dh: 0 }
- : { dx: 0, dy: 0, dw: dx, dh: dy });
+ ? { dx: residualX, dy: residualY, dw: 0, dh: 0 }
+ : { dx: 0, dy: 0, dw: residualX, dh: residualY });
}, [onMove, onResize, settle]);
+ const cancelDrag = useCallback((event: React.PointerEvent) => {
+ const held = grab.current;
+ if (!held || held.pointerId !== event.pointerId) return;
+ grab.current = null;
+ if (event.currentTarget.hasPointerCapture(event.pointerId)) {
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ }
+ settle(nudge);
+ }, [nudge, 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
@@ -824,17 +962,18 @@ export default function SheetChart({
event.preventDefault();
}, [onMove, onResize, stepX, stepY]);
- const tools = (onMove || onResize) ? (
+ const tools = (onMove || onResize || onEdit) ? (
{onMove ? (
{/* Four arrows from one centre: the existing set's stroke weight and round caps. */}
@@ -844,6 +983,23 @@ export default function SheetChart({
) : null}
+ {onEdit ? (
+
event.stopPropagation()}
+ onClick={(event) => {
+ event.stopPropagation();
+ onEdit();
+ }}
+ >
+
+
+
+
+ ) : null}
{onResize ? (
{/* The corner angle, the same two-stroke glyph the grid's own edge affordances use. */}
diff --git a/web/src/sheet/SheetGrid.tsx b/web/src/sheet/SheetGrid.tsx
index b933a2a2fb31111726c1fc3fa12412c4bf2e8227..db7379d8b33b73f9e7ab9b86906e669be452a266 100644
--- a/web/src/sheet/SheetGrid.tsx
+++ b/web/src/sheet/SheetGrid.tsx
@@ -137,7 +137,9 @@ import Ribbon from "./Ribbon";
// 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 ChartDialog from "./ChartDialog";
import SheetChart from "./SheetChart";
+import type { ChartAnchorDelta } from "./SheetChart";
import ShortcutsPanel from "./ShortcutsPanel";
import { colToIndex, indexToCol } from "./a1";
// ⛔⛔ W51-T18 — THE RULE ENGINE AND THE VALIDATION CHECKER ARE PURE AND SHEET LOCAL, and that is
@@ -155,7 +157,8 @@ import {
// 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 { buildCopyPayload, pasteModeFrom, runCopySelection } from "./clipboardOps";
+import type { PasteMode } 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
@@ -167,6 +170,7 @@ import {
} from "./validation";
import {
fontPx, fontStack, formatCellText, stylePaints, sheetExtent,
+ chartRangeAfterStructure,
DEFAULT_COL_WIDTH, DEFAULT_SHEET_COLS, DEFAULT_SHEET_ROWS,
MAX_CELL_INDENT, MAX_COL_WIDTH, MIN_COL_WIDTH,
} from "./types";
@@ -174,25 +178,26 @@ import type {
Cell, CellStyle, CellStylePatch, CellValign, SheetChartSpec, SheetRule, SheetTab, Workbook,
} from "./types";
import {
- addressOf, appendLineBreak, autoSumFormula, boundDragLabel, cellAt,
+ addressOf, appendLineBreak, applyStructure, autoSumFormula, boundDragLabel, cellAt,
cellShiftLabel, cellToValue, clearAll, recalcDependents,
clearCells, clearFormats, commitTyped, cycleAnchors, dateStamp, displayText, drillAffordance,
editableText, fillCells, fillDown, fillRight, findMatches,
isFilled, markOf, noMatchLabel, nothingHiddenLabel, paintPatch, pasteCells,
frozenBandSize, lockstepScrollX,
rememberCut, setFormula, shiftCells, splitAddress, styleCells, styleOf, usedExtent,
- viewIndexOf,
+ structureRefusal, viewIndexOf,
visibleIndices, withHidden,
} from "./sheetState";
import type {
CellRange, DragContext, FillEdit, OptionCatalogue, StructureOp,
} from "./sheetState";
+import type { SavedViewShadow } from "./bindingRefs";
// ⛔⛔ 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, commitDirection, commitTarget, edgeIndex, edgeStart,
- extendEdgeRect, isArrowKey, matchShortcut, rowBand, shortcutOwner, structureAxis,
- tabRunOrigin } from "./shortcuts";
+ extendEdgeRect, isArrowKey, KEY_TIP_GRID_ARROW_EVENT, keyTipGridArrow, matchShortcut,
+ rowBand, shortcutOwner, structureAxis, tabRunOrigin } from "./shortcuts";
import type { SelectionAxis, SelectionRect, ShortcutId } from "./shortcuts";
/**
@@ -364,6 +369,12 @@ export interface SheetGridProps {
onUndo: () => void;
onRedo: () => void;
onNotice: (message: string) => void;
+ /**
+ * C5's post-commit evaluator. Each entry is the exact bound cell object just landed, so the
+ * page can flush the save, compute through Save's one-cell door, and ignore an answer whose
+ * binding identity no longer matches.
+ */
+ onEvaluateBindings?: (request: BoundEvaluationRequest) => void;
// ── W50-T20 ────────────────────────────────────────────────────────────────────────────────
/**
@@ -436,19 +447,24 @@ export interface SheetGridProps {
// ── W51-T19, contract C2, rulings R9 and R10 ───────────────────────────────────────────────
/**
- * ⭐⭐ THE OPTION ORDER A `down` DRAG WALKS, AND IT IS A SEAM RATHER THAN A FETCH. R10 says a
- * bound cell dragged DOWN steps its chosen filter to the next option "in the field's option
- * order, or the linked table's view order", which is schema, and THIS COMPONENT IS
+ * ⭐⭐ THE OPTION ORDER A NON-METRIC COPY WALKS, AND IT IS A SEAM RATHER THAN A FETCH.
+ * R13 applies the chosen driver's option order in every signed direction, which is schema, and
+ * THIS COMPONENT IS
* DELIBERATELY SCHEMA FREE: its own head note says so, and reaching for `fetchWorkspace` here
* would make the grid know about databases so that one drag could work.
*
- * ⚠ SO IT IS UNDEFINED TODAY, AND THAT IS SPECIFIED BEHAVIOUR RATHER THAN A SHORTFALL. With no
- * catalogue a `down` drag copies the filter unchanged and STATES that the options have not
- * loaded ({@link boundDragLabel}). It never wraps to the first option and it never sits silent,
- * which is the honest degradation the ruling asks for. The engine itself is complete: pass a
- * catalogue and the walk happens, which is what `_test/sheetDrag.test.ts` proves.
+ * The page loads this alongside `viewShadows`; absence is an explicit incomplete copy reported
+ * by {@link boundDragLabel}, never a reason to guess an option or wrap to the beginning.
*/
options?: OptionCatalogue;
+ /** Canonical saved-View filters loaded before a copy, for R5's local shadow materialisation. */
+ viewShadows?: readonly SavedViewShadow[];
+}
+
+/** The copied cells that must take the same save-then-compute path as Binding editor Save. */
+export interface BoundEvaluationRequest {
+ tabId: string;
+ cells: Readonly>;
}
/** The corner mark each of R19's three states wears, plus the refusal. Colour rides a token; the
@@ -597,10 +613,10 @@ interface FormulaEditState {
export default function SheetGrid({
workbook, tab, busy = false, onEdit, onViewRows,
formulaBar, onRefresh, onSaveNow, onOpenImport,
- onCommit, onUndo, onRedo, onNotice,
+ onCommit, onUndo, onRedo, onNotice, onEvaluateBindings,
onSelect, onStructure, onGrow, onFreeze, onColumnWidth, onHideBands, onRules, onCharts,
onSelectTab,
- options,
+ options, viewShadows,
}: SheetGridProps) {
const [selection, setSelection] = useState(undefined);
/**
@@ -720,6 +736,8 @@ export default function SheetGrid({
*/
const [chartsLocal, setChartsLocal] =
useState<{ tabId: string; charts: SheetChartSpec[] } | null>(null);
+ /** The one existing chart whose persisted range and kind are open in the shared dialog. */
+ const [chartEditId, setChartEditId] = useState(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);
@@ -833,6 +851,23 @@ export default function SheetGrid({
// writer produced it.
const localCharts = chartsLocal?.tabId === tab.id ? chartsLocal.charts : tab.charts;
const charts = (onCharts ? tab.charts : localCharts) ?? [];
+ const editingChart = charts.find((chart) => chart.id === chartEditId) ?? null;
+
+ /**
+ * The one chart writer. Insert, settings, drag and structure all replace the same tab-level list,
+ * so a local fallback cannot disagree with the document depending on which gesture produced it.
+ */
+ 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]);
+
+ useEffect(() => setChartEditId(null), [tab.id]);
// ⚠ 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
@@ -954,6 +989,59 @@ export default function SheetGrid({
const cells = tab.cells ?? {};
+ /**
+ * A structural write can be accepted immediately, refused, or pause in the page's bound-cell
+ * confirmation. Remember the exact expected cell map and update chart anchors only after the
+ * accepted structure paints back. Comparing the contents as well as the addresses means a
+ * cancelled confirmation followed by an ordinary edit cannot masquerade as acceptance. This
+ * retains the page as the one refusal/confirmation authority.
+ */
+ const pendingChartStructure = useRef<{
+ tabId: string;
+ beforeCells: typeof cells;
+ expectedCells: string;
+ charts: SheetChartSpec[];
+ op: StructureOp;
+ } | null>(null);
+
+ useEffect(() => {
+ pendingChartStructure.current = null;
+ }, [tab.id]);
+
+ const requestStructure = useCallback((op: StructureOp) => {
+ pendingChartStructure.current = null;
+ if (charts.length > 0 && !structureRefusal(workbook, tab.id, op)) {
+ const expected = applyStructure(workbook, tab.id, op)
+ .find((candidate) => candidate.id === tab.id)?.cells ?? {};
+ pendingChartStructure.current = {
+ tabId: tab.id,
+ beforeCells: cells,
+ expectedCells: JSON.stringify(expected),
+ charts: [...charts],
+ op,
+ };
+ }
+ onStructure(op);
+ }, [cells, charts, onStructure, tab.id, workbook]);
+
+ useEffect(() => {
+ const pending = pendingChartStructure.current;
+ if (!pending || pending.tabId !== tab.id || pending.beforeCells === cells) return;
+ pendingChartStructure.current = null;
+ if (JSON.stringify(cells) !== pending.expectedCells) return;
+ const next = pending.charts.map((chart) => ({
+ ...chart,
+ range: chartRangeAfterStructure(chart.range, pending.op, extent),
+ }));
+ const changed = next.some((chart, index) => {
+ const before = pending.charts[index].range;
+ const after = chart.range;
+ return before.col0 !== after.col0 || before.col1 !== after.col1
+ || before.row0 !== after.row0 || before.row1 !== after.row1;
+ });
+ if (changed) writeCharts(next);
+ }, [cells, extent, tab.id, writeCharts]);
+
// ═══════════════════════════════════════════════════════════════════════════════════════════
// ⭐⭐ W53-T01 / RULING R2 / INSTRUCTION 19 — THE IN-CELL SHIMMER, AND WHY IT IS DRIVEN RATHER
// THAN DECLARED.
@@ -1864,12 +1952,21 @@ export default function SheetGrid({
const copiedBlock = useCallback(
(values: readonly (readonly string[])[]): DragContext | undefined => {
const held = copiedRef.current;
- if (!held) return options ? { catalogue: options } : undefined;
+ if (!held) {
+ return options || viewShadows ? { catalogue: options, shadows: viewShadows } : undefined;
+ }
const text = values.map((row) => row.join("\t")).join("\n");
- if (text !== held.text) return options ? { catalogue: options } : undefined;
- return { catalogue: options, cells: held.cells, from: { col: held.col, row: held.row } };
+ if (text !== held.text) {
+ return options || viewShadows
+ ? { catalogue: options, shadows: viewShadows }
+ : undefined;
+ }
+ return {
+ catalogue: options, shadows: viewShadows,
+ cells: held.cells, from: { col: held.col, row: held.row },
+ };
},
- [options],
+ [options, viewShadows],
);
/**
@@ -1922,13 +2019,24 @@ export default function SheetGrid({
const edits = { ...dragged, ...screened.edits };
// ⭐ W53-T01: a fill or a paste can change a cell some OTHER formula reads, so the landing
// door recalculates its dependents in the same commit every typed edit does.
- if (Object.keys(edits).length > 0) commitWithRecalc(edits);
+ if (Object.keys(edits).length > 0) {
+ commitWithRecalc(edits);
+ // C5: schedule only the bound cells that ACTUALLY landed. The page owns save ordering and
+ // revisions, so this seam carries identities instead of calling Refresh or a second writer.
+ const pending: Record = {};
+ for (const [addr, cell] of Object.entries(edits)) {
+ if (cell?.kind === "bound") pending[addr] = cell;
+ }
+ if (Object.keys(pending).length > 0) {
+ onEvaluateBindings?.({ tabId: tab.id, cells: pending });
+ }
+ }
const said = [
screened.refusals.length > 0 ? refusalLabel(screened.refusals) : "",
boundDragLabel(out),
].filter(Boolean).join(" ");
if (said) onNotice(said);
- }, [commitWithRecalc, onNotice, tab]);
+ }, [commitWithRecalc, onEvaluateBindings, onNotice, tab]);
/**
* ⭐ THE PASTE IS OURS, NOT GLIDE'S, AND IT RETURNS `false` DELIBERATELY. glide has already
@@ -2006,9 +2114,8 @@ export default function SheetGrid({
// FORMULA WORK BELOW THEM, and they are diverted INSIDE the one fill primitive rather
// than by a second pass here. `fillCells` decides on a bound pattern ahead of its
// formula branch and hands it to `dragBoundCell`; the fill handle, Ctrl+D, Ctrl+R and
- // the paste door all reach that same arithmetic, which is what makes "a locked period
- // copies verbatim through every door" one fact instead of four that agree today.
- { catalogue: options },
+ // paste therefore share R5's localisation and R13's signed stepping.
+ { catalogue: options, shadows: viewShadows },
// ⭐ W53-T01 / R2: a dragged formula shows its NUMBER when it lands, not its text.
cellValueGetter,
);
@@ -2016,7 +2123,7 @@ export default function SheetGrid({
// it on every cell it passes, list or no list, so it is screened exactly as the paste is.
landFill(out, true);
},
- [cellValueGetter, landFill, options, realCol, realRow, tab],
+ [cellValueGetter, landFill, options, realCol, realRow, tab, viewShadows],
);
/** Every address the selection covers, translated. `[]` when nothing is selected. */
@@ -2120,6 +2227,33 @@ export default function SheetGrid({
if (scroll && at[1] >= 0) gridRef.current?.scrollTo(at[0], at[1]);
}, [onSelectionChange]);
+ /**
+ * W55-T05 / R4: KeyTips consumes its capture-phase key while focus is on the ribbon, then
+ * dispatches one scoped semantic arrow on this wrapper. Move through `applySelection`, the same
+ * selection door used by every sheet-owned key, and return focus to the grid that owns the
+ * landing row. A component-scoped custom event avoids both a synthetic keyboard replay and the
+ * raw global key listener prohibited by the overlay contract.
+ */
+ useEffect(() => {
+ const host = wrapRef.current;
+ if (!host) return;
+ const moveFromKeyTips = (event: Event) => {
+ const key = keyTipGridArrow((event as CustomEvent<{ key?: string }>).detail?.key ?? "");
+ const current = selection?.current?.cell;
+ if (!key || !current) return;
+ const step = arrowStep(key);
+ if (!step) return;
+ const row = Math.max(
+ -bandRows,
+ Math.min(Math.max(0, visRows.length - 1), current[1] + step.dRow),
+ );
+ applySelection({ col0: current[0], row0: row, col1: current[0], row1: row });
+ (row < 0 ? bandGridRef : gridRef).current?.focus();
+ };
+ host.addEventListener(KEY_TIP_GRID_ARROW_EVENT, moveFromKeyTips);
+ return () => host.removeEventListener(KEY_TIP_GRID_ARROW_EVENT, moveFromKeyTips);
+ }, [applySelection, bandRows, selection, visRows.length]);
+
/**
* Ctrl+PgUp and Ctrl+PgDn. See `onSelectTab` in the props above for why there are two paths.
*
@@ -2321,7 +2455,7 @@ export default function SheetGrid({
const at = axis === "row"
? realRow(Math.min(range.row0, range.row1)) + 1
: realCol(Math.min(range.col0, range.col1)) + 1;
- onStructure({ axis, at, delta: insert ? span : -span });
+ requestStructure({ axis, at, delta: insert ? span : -span });
return;
}
const real: CellRange = {
@@ -2335,7 +2469,7 @@ export default function SheetGrid({
// dependents recompute in the same commit rather than at the next Refresh.
if (Object.keys(out.edits).length > 0) commitWithRecalc(out.edits);
onNotice(cellShiftLabel(insert, out.dropped));
- }, [commitWithRecalc, extent.rows, onNotice, onStructure, realCol, realRow, tab, viewRange,
+ }, [commitWithRecalc, extent.rows, onNotice, realCol, realRow, requestStructure, tab, viewRange,
visCols.length, visRows.length]);
/**
@@ -2469,8 +2603,8 @@ export default function SheetGrid({
return;
}
setMenu(null);
- onStructure({ axis, at: index, delta });
- }, [at, onNotice, onStructure]);
+ requestStructure({ axis, at: index, delta });
+ }, [at, onNotice, requestStructure]);
// ═══════════════════════════════════════════════════════════════════════════════════════════
// ⭐⭐ W51-T16 — THE ACTS THEMSELVES. Every one of them ends at `onCommit`, `onStructure`,
@@ -2505,7 +2639,7 @@ export default function SheetGrid({
* PASTE. glide already handles Ctrl+V through `onPaste`; this is the ribbon's own door, which
* has to read the clipboard itself because no paste event fired.
*/
- const pasteFromClipboard = useCallback(() => {
+ const pasteFromClipboard = useCallback((mode: PasteMode = "normal") => {
const range = viewRange();
if (!range) {
onNotice("Select the top left cell first, then paste.");
@@ -2527,12 +2661,17 @@ export default function SheetGrid({
{ cols: extent.cols, rows: extent.rows }, copiedBlock(values),
cellValueGetter,
{ col0: realCol(range.col0), row0: realRow(range.row0),
- col1: realCol(range.col1), row1: realRow(range.row1) });
+ col1: realCol(range.col1), row1: realRow(range.row1) },
+ mode);
+ if (out.layerRefusal) {
+ onNotice(out.layerRefusal);
+ return;
+ }
if (out.sizeRefusal) {
onNotice(out.sizeRefusal);
return;
}
- landFill(out, false);
+ landFill(out, mode === "values");
// ⭐ W52-T07: same highlight the glide door sets, from the ribbon's own paste path.
setPasteHighlight({ col: realCol(range.col0), row: realRow(range.row0),
cols: values[0]?.length ?? 0, rows: values.length });
@@ -2607,10 +2746,9 @@ export default function SheetGrid({
col0: realCol(range.col0), row0: realRow(range.row0),
col1: realCol(range.col1), row1: realRow(range.row1),
};
- // ⛔ W51-T19: Ctrl+D and Ctrl+R carry the SAME drag rules the fill handle does, because they
- // are the same operation through a different door. A bound cell filled down keeps its period
- // (R10's `down` defaults to Nothing) and one filled right walks it, whichever door was used.
- const rules: DragContext = { catalogue: options };
+ // Ctrl+D and Ctrl+R carry the same copy rules as the fill handle. R13 now advances periods
+ // and chosen filter options in either direction, whichever door was used.
+ const rules: DragContext = { catalogue: options, shadows: viewShadows };
const out = axis === "down" ? fillDown(tab, real, rules) : fillRight(tab, real, rules);
if (Object.keys(out.edits).length === 0) {
onNotice(axis === "down"
@@ -2619,7 +2757,7 @@ export default function SheetGrid({
return;
}
landFill(out, false);
- }, [landFill, onNotice, options, realCol, realRow, tab, viewRange]);
+ }, [landFill, onNotice, options, realCol, realRow, tab, viewRange, viewShadows]);
/** Clear formats, and clear all. Clear contents is `clearSelection`, which the Delete key uses. */
const clearSelectionWith = useCallback((which: "formats" | "all") => {
@@ -2940,7 +3078,7 @@ export default function SheetGrid({
case "import": onOpenImport?.(); return;
// -- Clipboard --------------------------------------------------------------------------
- case "paste": pasteFromClipboard(); return;
+ case "paste": pasteFromClipboard(pasteModeFrom(action.arg)); return;
case "cut": copySelection(true); return;
case "copy": copySelection(false); return;
case "format-painter": toggleFormatPainter(); return;
@@ -3429,7 +3567,7 @@ export default function SheetGrid({
// Ctrl+D and Ctrl+R do. A door that reached `fillCells` without them would drag a
// bound cell by a different rule from the one beside it, which is exactly the split
// "one primitive, every door" exists to prevent.
- { catalogue: options },
+ { catalogue: options, shadows: viewShadows },
cellValueGetter,
);
if (Object.keys(out.edits).length === 0) {
@@ -3509,9 +3647,9 @@ export default function SheetGrid({
},
[addrAt, anchorStyle, applySelection, applyStyle, bandRows, cellValueGetter, commitWithRecalc,
extent.cols, extent.rows,
- onCommit, onNotice, onRedo, onRibbonAction, onSaveNow, onUndo, openFormulaEditor,
+ onCommit, onNotice, onRedo, onRibbonAction, onSaveNow, onUndo, openFormulaEditor, options,
openNumberFormat, realCol, realRow, selection, structureForSelection, switchTab, tab,
- viewRange, viewRowOf, visCols, visRows],
+ viewRange, viewRowOf, viewShadows, visCols, visRows],
);
// ══════════════════════════════════════════════════════════════════════════════════════════
@@ -3575,7 +3713,20 @@ export default function SheetGrid({
// makes it a controlled horizontal position. Verified in `data-editor.js`.
// ══════════════════════════════════════════════════════════════════════════════════════════
const [bandScrollX, setBandScrollX] = useState(0);
- const onVisibleRegionChanged = useCallback((range: Rectangle, tx: number) => {
+ /** Glide's own scroll coordinates. Chart anchors consume the same x/y and sub-cell transforms. */
+ const [chartViewport, setChartViewport] = useState({ x: 0, y: 0, tx: 0, ty: 0 });
+ const onVisibleRegionChanged = useCallback((range: Rectangle, tx: number, ty: number) => {
+ const next = {
+ x: Math.max(0, range.x),
+ y: Math.max(0, range.y),
+ tx: Number.isFinite(tx) ? tx : 0,
+ ty: Number.isFinite(ty) ? ty : 0,
+ };
+ setChartViewport((before) => (
+ before.x === next.x && before.y === next.y && before.tx === next.tx && before.ty === next.ty
+ ? before
+ : next
+ ));
if (bandRows <= 0) return;
setBandScrollX(lockstepScrollX(columns.map((c) => c.width), frozenCols, range.x, tx));
}, [bandRows, columns, frozenCols]);
@@ -4085,21 +4236,27 @@ export default function SheetGrid({
[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.
+ * Every main-grid row boundary, cached because wrapped rows are not uniformly tall. Building
+ * this once makes each chart's scroll geometry and each pointer-release snap an O(1) lookup.
*/
- 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;
+ const chartRowOffsets = useMemo(() => {
+ const offsets = [0];
+ for (let row = 0; row < visRows.length; row += 1) {
+ offsets.push(offsets[row] + rowHeightAt(row));
}
- onCharts(next);
- }, [onCharts, onNotice, tab.id]);
-
+ return offsets;
+ }, [rowHeightAt, visRows.length]);
+ const chartRowY = useCallback(
+ (index: number) => chartRowOffsets[Math.max(0, Math.min(index, visRows.length))] ?? 0,
+ [chartRowOffsets, visRows.length],
+ );
+ const chartScrollX = useMemo(
+ () => lockstepScrollX(
+ columns.map((column) => column.width), frozenCols, chartViewport.x, chartViewport.tx,
+ ),
+ [chartViewport.tx, chartViewport.x, columns, frozenCols],
+ );
+ const chartScrollY = chartRowY(chartViewport.y) - chartViewport.ty;
/**
* ⭐⭐ W54-T12 / LANE B — A PIXEL DELTA BECOMES A CELL RANGE, AND ONLY THIS FILE CAN DO IT.
*
@@ -4117,7 +4274,12 @@ export default function SheetGrid({
* 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") => {
+ (
+ chart: SheetChartSpec,
+ dx: number,
+ dy: number,
+ mode: "move" | "resize",
+ ): ChartAnchorDelta => {
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);
@@ -4126,7 +4288,9 @@ export default function SheetGrid({
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;
+ if (viewLo < 0 || viewHi < 0 || viewTop < 0 || viewBottom < 0) {
+ return { dx: 0, dy: 0 };
+ }
const nearestView = (x: number) => {
let best = 0;
@@ -4137,6 +4301,24 @@ export default function SheetGrid({
}
return best;
};
+ const nearestColumnBoundary = (x: number) => {
+ let best = 0;
+ let bestGap = Infinity;
+ for (let col = 0; col <= visCols.length; col += 1) {
+ const gap = Math.abs(columnX(col) - x);
+ if (gap < bestGap) { bestGap = gap; best = col; }
+ }
+ return best;
+ };
+ const nearestRow = (y: number) => {
+ let best = 0;
+ let bestGap = Infinity;
+ for (let row = 0; row <= visRows.length; row += 1) {
+ const gap = Math.abs(chartRowY(row) - y);
+ if (gap < bestGap) { bestGap = gap; best = row; }
+ }
+ 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;
@@ -4150,25 +4332,41 @@ export default function SheetGrid({
nearestView(columnX(viewLo) + dx) - viewLo, -viewLo, lastCol - viewHi,
);
const stepRows = clamp(
- Math.round(dy / rowHeight), -viewTop, lastRow - viewBottom,
+ nearestRow(chartRowY(viewTop) + dy) - viewTop, -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);
+ nextHi = clamp(
+ nearestColumnBoundary(columnX(viewHi + 1) + dx) - 1, viewLo, lastCol,
+ );
+ nextBottom = clamp(
+ nearestRow(chartRowY(viewBottom + 1) + dy) - 1, 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;
+ && range.row0 === chart.range.row0 && range.row1 === chart.range.row1) {
+ return { dx: 0, dy: 0 };
+ }
+ const snapped = mode === "move"
+ ? {
+ dx: columnX(nextLo) - columnX(viewLo),
+ dy: chartRowY(nextTop) - chartRowY(viewTop),
+ }
+ : {
+ dx: columnX(nextHi + 1) - columnX(viewHi + 1),
+ dy: chartRowY(nextBottom + 1) - chartRowY(viewBottom + 1),
+ };
writeCharts(charts.map((c) => (c.id === chart.id ? { ...c, range } : c)));
+ return snapped;
},
- [charts, columnX, rowHeight, visCols, visRows, writeCharts],
+ [chartRowY, charts, columnX, visCols, visRows, writeCharts],
);
/**
@@ -4566,8 +4764,12 @@ export default function SheetGrid({
if (viewLo < 0 || viewHi < 0 || viewTop < 0 || viewBottom < 0) return null;
// ⚠ SUMMED, NOT MULTIPLIED (W50-T20). A column width is per column now, so
// `lo * COL_WIDTH` would drift as soon as anybody dragged one.
- const left = columnX(viewLo);
- const width = columnX(viewHi + 1) - left;
+ const left = columnX(viewLo) - (viewLo >= frozenCols ? chartScrollX : 0);
+ const right = columnX(viewHi + 1) - (viewHi >= frozenCols ? chartScrollX : 0);
+ const width = Math.max(24, right - left);
+ const topPx = HEADER_HEIGHT + bandRows * rowHeight
+ + chartRowY(viewTop) - chartScrollY;
+ const height = Math.max(24, chartRowY(viewBottom + 1) - chartRowY(viewTop));
return (
{/* ⭐ W54-T12 / lane B — THE KIND GOES THROUGH RAW. It used to be narrowed to the
@@ -4597,13 +4799,27 @@ export default function SheetGrid({
cells={cells}
kind={chart.kind}
width={width}
- height={(viewBottom - viewTop + 1) * rowHeight}
+ height={height}
onMove={(dx, dy) => nudgeChart(chart, dx, dy, "move")}
onResize={(dx, dy) => nudgeChart(chart, dx, dy, "resize")}
+ onEdit={() => setChartEditId(chart.id)}
/>
);
})}
+ {editingChart ? (
+ setChartEditId(null)}
+ onUpdate={(next) => {
+ writeCharts(charts.map((chart) => (chart.id === next.id ? next : chart)));
+ setChartEditId(null);
+ }}
+ />
+ ) : null}
{/* ⭐⭐ THE RIGHT-CLICK MENU, IN THE HOUSE OVERLAY VOCABULARY. `AnchoredOverlay` is what
diff --git a/web/src/sheet/SheetPage.tsx b/web/src/sheet/SheetPage.tsx
index a37be744eb1000f875866c293b726b8a15edea3c..9f5abf059b8c9553cc6feaceecf7704d8dd33773 100644
--- a/web/src/sheet/SheetPage.tsx
+++ b/web/src/sheet/SheetPage.tsx
@@ -36,9 +36,10 @@
// ---------------------------------------------------------------------------
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import type { ReactNode } from "react";
+import type { PointerEvent as ReactPointerEvent, ReactNode } from "react";
import "../styles/wave49/sheet.css";
import "../styles/wave50/sheet.css";
+import "../styles/wave55/sheet.css";
// ⛔⛔ W51-T09 — THE LAUNCHER'S OWN STYLESHEET, AND IT IS NOT OPTIONAL. `.cg-chat-toggle` and
// `.cg-chat-dock` live in `customer-grid/chatDock.css`, which until this ticket ONLY
// `CustomerGrid.tsx` imported. On a direct load of `#/sheet` that chunk is never fetched, so the
@@ -228,6 +229,29 @@ function repairSentence(repairs: readonly IndexRepair[] | undefined): string {
*/
const SAVE_DEBOUNCE_MS = 600;
+/**
+ * A workbook identity change may wait for persistence, but it may not strand the rail forever
+ * behind an unreachable store. On expiry the identity stays put and the in-flight save keeps its
+ * ordinary recovery path; the person can retry the switch after that path settles.
+ */
+const SAVE_FLUSH_TIMEOUT_MS = 5_000;
+
+/** A pointer drag starts only after ordinary click slop, so click and double click keep working. */
+const TAB_DRAG_SLOP_PX = 4;
+
+interface TabDrag {
+ workbookId: string;
+ tabId: string;
+ pointerId: number;
+ element: HTMLButtonElement;
+ originX: number;
+ grabOffsetX: number;
+ width: number;
+ startIndex: number;
+ targetIndex: number;
+ moved: boolean;
+}
+
/** The cache key for one tab's cells. Workbook scoped, so switching books cannot reuse them. */
const tabKeyOf = (workbookId: string, tabId: string): string => `${workbookId}:${tabId}`;
@@ -357,6 +381,20 @@ export default function SheetPage() {
const saveChainRef = useRef>(Promise.resolve());
/** Bumped by every local edit, so a save knows whether the tree moved under it. */
const editSeqRef = useRef(0);
+ /**
+ * A workbook identity transition is single-flight even though the rail stays interactive while
+ * the main pane shows its opening spinner. State alone cannot guard the second click: React may
+ * not have committed `opening` before another rail event runs, so this ref closes the boundary
+ * synchronously and prevents an older, slower read from winning after a newer choice.
+ */
+ const workbookTransitionRef = useRef(false);
+ /** The bottom tab strip and its one pointer-captured drag. High-frequency motion stays in DOM. */
+ const tabStripRef = useRef(null);
+ const tabDragRef = useRef(null);
+ /** A completed drag emits a click after pointerup; consume that click instead of opening twice. */
+ const suppressTabClickRef = useRef("");
+ /** Clears suppression when a browser emits no post-drag click (for example after release outside). */
+ const suppressTabClickTimerRef = useRef(null);
// ── W51-T11's five refs ────────────────────────────────────────────────────────────────────
@@ -723,10 +761,16 @@ export default function SheetPage() {
const sent = await patchTabCells(current.id, tabKey, {
cells, rev: tabRevOf(sheet, current),
});
+ // A workbook transition normally waits for this request. This identity fence is the
+ // second line of defence for a timed-out or overlapping transition: an old response may
+ // finish, but it can never lend its revision, notice or recovery tree to the new book.
+ if (bookRef.current?.id !== current.id) return "stopped";
if (sent.ok) {
patchModeRef.current = "patch";
const live = bookRef.current;
- if (live && sent.value.rev) applyLocal({ ...live, rev: sent.value.rev });
+ if (live?.id === current.id && sent.value.rev) {
+ applyLocal({ ...live, rev: sent.value.rev });
+ }
const refused = sent.value.refused ?? [];
if (refused.length > 0) {
savedCleanRef.current = false;
@@ -787,7 +831,9 @@ export default function SheetPage() {
// is not written at all.
const whole = await ensureTabs(opening.id, opening.sheets.map((t) => t.id));
const current = bookRef.current;
- if (!current) return;
+ // `ensureTabs` awaits network reads. If another transition won while those reads were away,
+ // never turn that newer workbook into the subject of this older drain.
+ if (!current || current.id !== opening.id) return;
if (!whole) {
// ⛔⛔ THE FLAG GOES BACK ON, AND THIS IS THE SAME RE-ARM DISCIPLINE THE DIRTY SET GETS.
// `drainSave` clears `structureDirtyRef` before the await, so a return from here without
@@ -807,18 +853,20 @@ export default function SheetPage() {
const saved = await writeWorkbook(current.id, {
name: current.name, sheets: current.sheets, rev: current.rev,
});
+ if (bookRef.current?.id !== current.id) return;
if (!saved.ok) {
// ⛔ A STALE REV IS NOT A DEAD SESSION. Leaving the local `rev` behind would make every
// later save stale too, so editing would be over until someone reloaded the page. The
// workbook is re-read instead, and the reader is told the edit did not land.
if (saved.code === "workbook_revision_stale") {
const fresh = await readWorkbook(current.id);
- if (fresh.ok) {
+ if (fresh.ok && bookRef.current?.id === current.id) {
historyRef.current = emptyHistory();
editSeqRef.current += 1;
markAllLoaded(fresh.value);
applyLocal(fresh.value);
}
+ if (bookRef.current?.id !== current.id) return;
// ⚠ AND HERE THE FLAG STAYS OFF, deliberately. The re-read REPLACED the tree the
// structure change was made in, so there is nothing left to re-send; the sentence above
// is what tells the reader their change did not land.
@@ -834,10 +882,11 @@ export default function SheetPage() {
setNotice(saved.message);
return;
}
+ if (bookRef.current?.id !== current.id) return;
if (editSeqRef.current === seq) {
markAllLoaded(saved.value);
applyLocal(saved.value);
- } else if (bookRef.current) {
+ } else if (bookRef.current?.id === current.id) {
applyLocal({ ...bookRef.current, rev: saved.value.rev, updated_at: saved.value.updated_at });
}
}, [applyLocal, ensureTabs, markAllLoaded]);
@@ -852,11 +901,16 @@ export default function SheetPage() {
const drainSave = useCallback(() => {
saveChainRef.current = saveChainRef.current.then(async () => {
if (!bookRef.current) return;
- savedCleanRef.current = true;
const structural = structureDirtyRef.current;
structureDirtyRef.current = false;
+ const hasPendingCells = dirtyRef.current.size > 0;
+ // A flush appends a drain behind any request already in flight. If that request refuses,
+ // the appended drain may find nothing to send; it must not turn the refusal back into a
+ // clean result merely by existing. Only a drain that owns real pending authored work may
+ // clear the prior failure, and each refusal path below sets it false again.
+ if (!structural && !hasPendingCells) return;
+ savedCleanRef.current = true;
if (!structural && patchModeRef.current !== "put") {
- if (dirtyRef.current.size === 0) return;
const outcome = await sendDirtyCells();
if (outcome === "stopped") savedCleanRef.current = false;
// ⛔ ONLY AN ABSENT ROUTE FALLS THROUGH TO THE PUT, and it falls through in THIS drain so
@@ -881,6 +935,10 @@ export default function SheetPage() {
saveTimerRef.current = null;
drainRef.current();
}
+ if (suppressTabClickTimerRef.current !== null) {
+ window.clearTimeout(suppressTabClickTimerRef.current);
+ suppressTabClickTimerRef.current = null;
+ }
}, []);
/** Drain now, cancelling any pending debounce, and answer when the write has finished. */
@@ -893,6 +951,38 @@ export default function SheetPage() {
return saveChainRef.current;
}, [drainSave]);
+ /**
+ * C2's bounded barrier before a workbook identity changes.
+ *
+ * `flushSave` is intentionally called before the target workbook is even requested or created:
+ * the old workbook must keep owning `bookRef`, its dirty addresses and its revision until the
+ * final queued write has settled. A timeout does not cancel that write. It leaves the current
+ * workbook in place, which lets the ordinary stale-revision/refusal recovery finish without a
+ * late response ever being adopted into a different workbook.
+ */
+ const flushBeforeWorkbookChange = useCallback(async (): Promise => {
+ const leavingId = bookRef.current?.id;
+ if (!leavingId) return true;
+ let timer: number | null = null;
+ const outcome = await Promise.race([
+ flushSave().then(() => "flushed" as const),
+ new Promise<"timeout">((resolve) => {
+ timer = window.setTimeout(() => resolve("timeout"), SAVE_FLUSH_TIMEOUT_MS);
+ }),
+ ]);
+ if (timer !== null) window.clearTimeout(timer);
+ if (outcome === "timeout") {
+ setNotice("This workbook is still saving. Wait for it to finish before opening another one.");
+ workbookTransitionRef.current = false;
+ return false;
+ }
+ // A refusal already left its exact sentence in `notice`. Do not hide it behind a generic
+ // transition error, and do not clear the dirty tree by adopting another workbook.
+ const mayChange = savedCleanRef.current && bookRef.current?.id === leavingId;
+ if (!mayChange) workbookTransitionRef.current = false;
+ return mayChange;
+ }, [flushSave]);
+
/**
* ⭐⭐ THE DEBOUNCE THE TICKET ASSUMED ALREADY EXISTED. Every commit, undo, redo, binding save
* and structure op calls this; the drain runs once the typing stops.
@@ -1118,6 +1208,93 @@ export default function SheetPage() {
if (base) commitSheets(moveTab(base, id, step));
}, [commitSheets]);
+ /** Capture the whole tab, preserving the exact point inside it that the pointer grabbed. */
+ const startTabDrag = useCallback((id: string, event: ReactPointerEvent) => {
+ if (event.button !== 0 || !bookRef.current || tabDragRef.current) return;
+ const element = event.currentTarget;
+ const rect = element.getBoundingClientRect();
+ const startIndex = bookRef.current.sheets.findIndex((sheet) => sheet.id === id);
+ if (startIndex < 0) return;
+ element.setPointerCapture(event.pointerId);
+ element.dataset.dragging = "true";
+ element.setAttribute("aria-grabbed", "true");
+ tabDragRef.current = {
+ workbookId: bookRef.current.id,
+ tabId: id,
+ pointerId: event.pointerId,
+ element,
+ originX: event.clientX,
+ grabOffsetX: event.clientX - rect.left,
+ width: rect.width,
+ startIndex,
+ targetIndex: startIndex,
+ moved: false,
+ };
+ }, []);
+
+ /**
+ * Gesture frames write only a transform and a target index. React state would re-layout the
+ * flex row on every pointermove; keeping siblings still gives the grabbed tab 1:1 tracking.
+ */
+ const moveTabDrag = useCallback((event: ReactPointerEvent) => {
+ const held = tabDragRef.current;
+ if (!held || held.pointerId !== event.pointerId) return;
+ const delta = event.clientX - held.originX;
+ if (!held.moved && Math.abs(delta) < TAB_DRAG_SLOP_PX) return;
+ held.moved = true;
+ event.preventDefault();
+ held.element.style.setProperty("--sheet-tab-drag-x", `${delta}px`);
+
+ const strip = tabStripRef.current;
+ if (!strip) return;
+ const draggedCenter = event.clientX - held.grabOffsetX + (held.width / 2);
+ const peers = Array.from(
+ strip.querySelectorAll("button[data-sheet-tab-id]"),
+ );
+ held.targetIndex = peers.reduce((index, peer) => {
+ if (peer === held.element) return index;
+ const box = peer.getBoundingClientRect();
+ return draggedCenter > box.left + (box.width / 2) ? index + 1 : index;
+ }, 0);
+ }, []);
+
+ const finishTabDrag = useCallback((
+ event: ReactPointerEvent, commit: boolean,
+ ) => {
+ const held = tabDragRef.current;
+ if (!held || held.pointerId !== event.pointerId) return;
+ tabDragRef.current = null;
+ delete held.element.dataset.dragging;
+ held.element.removeAttribute("aria-grabbed");
+ held.element.style.removeProperty("--sheet-tab-drag-x");
+ if (held.element.hasPointerCapture(held.pointerId)) {
+ held.element.releasePointerCapture(held.pointerId);
+ }
+ if (!commit || !held.moved) return;
+ suppressTabClickRef.current = held.tabId;
+ if (suppressTabClickTimerRef.current !== null) {
+ window.clearTimeout(suppressTabClickTimerRef.current);
+ }
+ // `click` normally follows this pointerup before the next task. If release happened outside
+ // and no click arrives, do not let a stale suppression consume the person's next real click.
+ suppressTabClickTimerRef.current = window.setTimeout(() => {
+ if (suppressTabClickRef.current === held.tabId) suppressTabClickRef.current = "";
+ suppressTabClickTimerRef.current = null;
+ }, 0);
+
+ const base = bookRef.current;
+ if (!base || base.id !== held.workbookId) return;
+ let at = base.sheets.findIndex((sheet) => sheet.id === held.tabId);
+ const target = Math.max(0, Math.min(held.targetIndex, base.sheets.length - 1));
+ let ordered = base.sheets;
+ while (at >= 0 && at !== target) {
+ const step = target > at ? 1 : -1;
+ ordered = moveTab({ ...base, sheets: ordered }, held.tabId, step);
+ at += step;
+ }
+ if (ordered !== base.sheets) commitSheets(ordered);
+ }, [commitSheets]);
+
const onRenameTab = useCallback(() => {
const pending = tabRename;
const base = bookRef.current;
@@ -1372,37 +1549,52 @@ export default function SheetPage() {
}, [applyLocal, markAllLoaded]);
const openWorkbook = useCallback(async (id: string) => {
- if (id === bookRef.current?.id) return;
+ if (id === bookRef.current?.id || workbookTransitionRef.current) return;
+ workbookTransitionRef.current = true;
setOpening(true);
setNotice("");
+ if (!await flushBeforeWorkbookChange()) {
+ setOpening(false);
+ return;
+ }
// ⭐ R4: one tab at a time here too. The meta read carries the tab list and the revision; the
// tab being opened is the only one whose cells are fetched.
const got = await readTabMeta(id);
if (!got.ok) {
setNotice(got.message);
+ workbookTransitionRef.current = false;
setOpening(false);
return;
}
adoptWorkbook(got.value, "meta");
const firstTab = got.value.sheets[0]?.id ?? "";
if (firstTab) await ensureTabs(got.value.id, [firstTab]);
+ workbookTransitionRef.current = false;
setOpening(false);
- }, [adoptWorkbook, ensureTabs]);
+ }, [adoptWorkbook, ensureTabs, flushBeforeWorkbookChange]);
/** R2's create door: made and OPENED in one act, with no name step in between. */
const createAndOpen = useCallback(async () => {
+ if (workbookTransitionRef.current) return;
+ workbookTransitionRef.current = true;
setOpening(true);
setNotice("");
+ if (!await flushBeforeWorkbookChange()) {
+ setOpening(false);
+ return;
+ }
const made = await createWorkbook("Untitled workbook");
if (!made.ok) {
setNotice(made.message);
+ workbookTransitionRef.current = false;
setOpening(false);
return;
}
adoptWorkbook(made.value, "all");
await refreshIndex();
+ workbookTransitionRef.current = false;
setOpening(false);
- }, [adoptWorkbook, refreshIndex]);
+ }, [adoptWorkbook, flushBeforeWorkbookChange, refreshIndex]);
/**
* ⭐ DUPLICATE IS COMPOSED, NOT ROUTED. Read the source, create an empty workbook, then write
@@ -1410,17 +1602,25 @@ export default function SheetPage() {
* would be refused as stale against a document that has only ever been at rev 1.
*/
const duplicateWorkbook = useCallback(async (id: string) => {
+ if (workbookTransitionRef.current) return;
+ workbookTransitionRef.current = true;
setOpening(true);
setNotice("");
+ if (!await flushBeforeWorkbookChange()) {
+ setOpening(false);
+ return;
+ }
const source = await readWorkbook(id);
if (!source.ok) {
setNotice(source.message);
+ workbookTransitionRef.current = false;
setOpening(false);
return;
}
const made = await createWorkbook(`${source.value.name} copy`);
if (!made.ok) {
setNotice(made.message);
+ workbookTransitionRef.current = false;
setOpening(false);
return;
}
@@ -1429,13 +1629,15 @@ export default function SheetPage() {
});
if (!filled.ok) {
setNotice(filled.message);
+ workbookTransitionRef.current = false;
setOpening(false);
return;
}
adoptWorkbook(filled.value, "all");
await refreshIndex();
+ workbookTransitionRef.current = false;
setOpening(false);
- }, [adoptWorkbook, refreshIndex]);
+ }, [adoptWorkbook, flushBeforeWorkbookChange, refreshIndex]);
/**
* ⛔ RENAMING THE OPEN WORKBOOK GOES THROUGH THE SAVE CHAIN, NOT AROUND IT. Reading the
@@ -1443,6 +1645,7 @@ export default function SheetPage() {
* and sending a second `rev` beside the queued one is exactly the race `put_workbook` refuses.
*/
const renameWorkbook = useCallback(async (id: string, name: string) => {
+ if (workbookTransitionRef.current) return;
setNotice("");
if (bookRef.current && bookRef.current.id === id) {
applyLocal({ ...bookRef.current, name });
@@ -1474,6 +1677,7 @@ export default function SheetPage() {
}, [applyLocal, flushSave, queueSave, refreshIndex]);
const removeWorkbook = useCallback(async (id: string) => {
+ if (workbookTransitionRef.current) return;
setNotice("");
const gone = await deleteWorkbook(id);
if (!gone.ok) {
@@ -1917,15 +2121,32 @@ export default function SheetPage() {
A tab bar that shrank the grid would read as "the Sheet broke again", so it takes its
content height and nothing more, exactly as `.sheet-fx` above it does. */}
{book && (
-
+
{book.sheets.map((t) => (
openTab(t.id)}
+ onClick={() => {
+ if (suppressTabClickRef.current === t.id) {
+ suppressTabClickRef.current = "";
+ return;
+ }
+ openTab(t.id);
+ }}
onDoubleClick={() => setTabRename({ id: t.id, name: t.name })}
+ onPointerDown={(event) => startTabDrag(t.id, event)}
+ onPointerMove={moveTabDrag}
+ onPointerUp={(event) => finishTabDrag(event, true)}
+ onPointerCancel={(event) => finishTabDrag(event, false)}
+ onLostPointerCapture={(event) => finishTabDrag(event, false)}
// ⚠ THE ELEMENT IS CAPTURED BEFORE THE UPDATER RUNS. Reading `e.currentTarget`
// inside a state updater is how this app lost an anchor before
// ([[react-event-currenttarget-updater]]); by then React has moved on.
@@ -1935,7 +2156,7 @@ export default function SheetPage() {
openTab(t.id);
setTabMenu({ id: t.id, el });
}}
- title="Click to open. Double click to rename. Right click for more."
+ title="Click to open. Drag to reorder. Double click to rename. Right click for more."
>
{t.name}
diff --git a/web/src/sheet/bindingRefs.ts b/web/src/sheet/bindingRefs.ts
index 5ec0fddadd84553ba3245d502069dd9d5aeaf333..c7b0fc6f520e009c38262a4db81efce7fe609f91 100644
--- a/web/src/sheet/bindingRefs.ts
+++ b/web/src/sheet/bindingRefs.ts
@@ -61,6 +61,8 @@ interface RefSlotSpec {
readonly path: readonly string[];
/** A path to a truthy value that freezes this slot. Absent means nothing freezes it. */
readonly pinnedAt?: readonly string[];
+ /** A binding-wide rule that freezes this slot even without a flag at its own path. */
+ readonly pinnedWhen?: (binding: Record
) => boolean;
}
/**
@@ -71,7 +73,17 @@ interface RefSlotSpec {
* and paste door starts shifting it correctly on the same commit.
*/
const REF_SLOTS: readonly RefSlotSpec[] = [
- { key: "period.ref", path: ["period", "ref"], pinnedAt: ["period", "locked"] },
+ {
+ key: "period.ref",
+ path: ["period", "ref"],
+ pinnedAt: ["period", "locked"],
+ // R13: turning period stepping off clones the WHOLE period, including a relative source ref.
+ pinnedWhen: (binding) => {
+ const rule = binding.onDrag;
+ return Boolean(rule && typeof rule === "object" && !Array.isArray(rule)
+ && (rule as Record).across === "none");
+ },
+ },
];
/** What one occupied slot IS, right now, with its anchoring already parsed out per axis. */
@@ -154,7 +166,7 @@ export const bindingRefSlots = (binding: unknown): BindingRefSlot[] => {
path: spec.path,
text,
parsed: parseRef(text),
- pinned: flagAt(record, spec.pinnedAt),
+ pinned: flagAt(record, spec.pinnedAt) || Boolean(spec.pinnedWhen?.(record)),
});
}
return out;
@@ -195,3 +207,112 @@ export const shiftBindingRefs = (
}
return { binding: out, changed: moved.length > 0, moved };
};
+
+// ── W55-T07, contract C6: fields a cell filter depends on ───────────────────────────────────
+//
+// This stays structural and import-free on purpose. `bindingRefs.ts` is a leaf used by the Sheet
+// node proofs, and importing the customer-grid filter types here would move tsc's emitted root.
+// The stored dialect is still the exact FilterTree dialect.
+
+// W55-T08 / C5: copied saved Views become local filters before their drivers step.
+/** One canonical saved-View filter returned by the Sheet server for copying. */
+export interface SavedViewShadow {
+ readonly database: string;
+ readonly viewId: string;
+ readonly filter: unknown;
+}
+
+/** What localising one binding did. Missing means the caller must not pretend R5 completed. */
+export interface LocalViewBinding {
+ readonly binding: Record;
+ readonly localized: boolean;
+ readonly missing: boolean;
+}
+
+/**
+ * Copy JSON-shaped filter state without sharing any record or array with the saved View snapshot.
+ * The filter language stays structural here so this leaf module does not import UI types.
+ */
+const copyJson = (value: unknown): unknown => {
+ if (Array.isArray(value)) return value.map(copyJson);
+ const record = asRecord(value);
+ if (!record) return value;
+ return Object.fromEntries(Object.entries(record).map(([key, child]) => [key, copyJson(child)]));
+};
+
+/**
+ * R5's materialisation boundary. A saved-View binding becomes a filter-scoped binding before any
+ * driver walks it. The original binding and the server-owned shadow are never mutated.
+ *
+ * A binding that is already local is returned untouched. A missing saved-View shadow is explicit
+ * so the copy door can say that it has not completed instead of silently retaining shared state.
+ */
+export const materializeLocalViewBinding = (
+ binding: Record, shadows: readonly SavedViewShadow[] | undefined,
+): LocalViewBinding => {
+ const scope = asRecord(binding.scope);
+ const viewId = typeof scope?.view_id === "string" ? scope.view_id.trim() : "";
+ if (!viewId) return { binding, localized: false, missing: false };
+ const database = typeof binding.database === "string" ? binding.database.trim() : "";
+ const found = (shadows ?? []).find(
+ (shadow) => shadow.database === database && shadow.viewId === viewId,
+ );
+ if (!found || !asRecord(found.filter)) {
+ return { binding, localized: false, missing: true };
+ }
+ return {
+ binding: { ...binding, scope: { filter: copyJson(found.filter) } },
+ localized: true,
+ missing: false,
+ };
+};
+
+// W55-T07 / C6 continues with the filter fields a cell View must show.
+/** Every real field key a filter names, including nested groups and right-hand field operands. */
+export const filterFieldKeys = (tree: unknown): string[] => {
+ const root = asRecord(tree);
+ const seen = new Set();
+ const add = (value: unknown) => {
+ const key = typeof value === "string" ? value.trim() : "";
+ // Cohort and View membership leaves are filter vocabulary, not database fields.
+ if (key && !key.startsWith("__")) seen.add(key);
+ };
+ const walk = (nodes: unknown) => {
+ if (!Array.isArray(nodes)) return;
+ for (const raw of nodes) {
+ const node = asRecord(raw);
+ if (!node) continue;
+ if (Array.isArray(node.children)) {
+ walk(node.children);
+ continue;
+ }
+ add(node.colId);
+ const rhs = asRecord(node.rhs);
+ if (rhs) add(rhs.colId);
+ }
+ };
+ walk(root?.nodes);
+ return [...seen];
+};
+
+/**
+ * C6's visible-field law: a person's ordered choice (or the database defaults) UNION every
+ * field the filter needs. Invalid/stale field keys are removed, and the identity key stays first.
+ */
+export const cellViewVisibleKeys = (
+ defaults: readonly string[],
+ preferred: readonly string[],
+ filterKeys: readonly string[],
+ available: readonly string[],
+ identity = "",
+): string[] => {
+ const valid = new Set(available);
+ const out: string[] = [];
+ const add = (key: string) => {
+ if (key && valid.has(key) && !out.includes(key)) out.push(key);
+ };
+ if (identity) add(identity);
+ for (const key of preferred.length ? preferred : defaults) add(key);
+ for (const key of filterKeys) add(key);
+ return out;
+};
diff --git a/web/src/sheet/cellBorders.ts b/web/src/sheet/cellBorders.ts
index abc601a825012a2ee29aa1bd043f895770869de2..021f009b9129543251451d6d3decd0f9a9c6b4a1 100644
--- a/web/src/sheet/cellBorders.ts
+++ b/web/src/sheet/cellBorders.ts
@@ -1,15 +1,13 @@
// ---------------------------------------------------------------------------------------------
// sheet/cellBorders.ts — THE PER-CELL BORDER PAINT, LIFTED OUT OF `SheetGrid.tsx`.
//
-// ⭐ WAVE 54 BASE KIT — this is a SEAM, not a redesign. Every line below was moved verbatim out of
-// `SheetGrid.tsx::paintCell` step 4 so that the border work and the rest of the hub file can be
-// edited by two different lanes at once. The move itself changed nothing; W54-T01 then changed the
-// LEFT and TOP geometry here, for the reason written on `paintCellBorders` below. Order of sides,
-// stroke colour, line width, the single stroke and the save/restore pair are all still the ones
-// that came over.
+// ⭐ WAVE 54 BASE KIT — this is the border seam lifted from `SheetGrid.tsx::paintCell`, so border
+// geometry can change without disturbing the grid's selection, chart, marquee or formula paint.
+// W55-T05 makes the live cell rectangle the source for four filled edge strips and gives inserted
+// borders their explicit black default. Both main and frozen grids still call this one paint door.
//
-// ⛔ `tokenColour` CAME ALONG, AND THAT IS A FENCE DECISION RATHER THAN A DESIGN ONE. The stroke
-// setup reads `--lp-line-strong` through `SheetGrid.tsx`'s own memoised token resolver, which was
+// ⛔ `tokenColour` CAME ALONG, AND THAT IS A FENCE DECISION RATHER THAN A DESIGN ONE. Border paint
+// and the grid's other canvas paint read CSS properties through one memoised resolver, which was
// a module-local `const` there and is not exported. The three ways out were: import it back from
// `SheetGrid.tsx` (a cycle, and a NEW export on the file this split exists to shrink), copy it
// (two caches for one palette), or move the definition here and let `SheetGrid.tsx` import it.
@@ -21,15 +19,15 @@
import type { CellBorder } from "./types";
/**
- * A `--lp-*` token name resolved to the hue the document currently gives it.
+ * A CSS custom-property name resolved to the hue the document currently gives it.
*
* ⭐ MEMOISED, BECAUSE `drawCell` RUNS PER CELL PER FRAME. `getComputedStyle` forces a style
* recalculation on every call, and a 26 by 40 viewport of styled cells would ask for it a
* thousand times a frame. The tokens are declared once on `:root` and nothing in this app swaps
* a palette at runtime, so one read each is the whole of it.
*
- * ⚠ THE FALLBACK IS THE INK, NOT BLACK. A token that has been renamed out of the palette must
- * still leave a readable cell rather than an invisible one.
+ * Each caller supplies its own safe fallback. Inserted cell borders deliberately supply black;
+ * other canvas paint keeps the existing palette fallbacks owned by `SheetGrid`.
*/
const TOKEN_CACHE = new Map();
export const tokenColour = (token: string, fallback: string): string => {
@@ -42,73 +40,47 @@ export const tokenColour = (token: string, fallback: string): string => {
return value || fallback;
};
+/** The executable default for an inserted border. The stylesheet publishes the same value. */
+export const DEFAULT_CELL_BORDER_COLOR = "#000000";
+
+export interface CellBorderRect { x: number; y: number; width: number; height: number }
+type BorderStrip = CellBorderRect;
+
/**
- * THE CELL'S OWN BORDERS, painted onto `rect`.
- *
- * ⛔⛔ THE INSET IS ASYMMETRIC ON PURPOSE: LEFT AND TOP SIT A PIXEL FURTHER IN THAN RIGHT AND
- * BOTTOM, AND TIDYING ALL FOUR BACK TO A SYMMETRIC HALF PIXEL RE-BREAKS THE FEATURE. Before
- * W54-T01 all four sides were laid on the cell's own edge at a half pixel, and "All sides" then
- * painted a visible right and bottom with NO left and NO top. Two independent mechanisms of the
- * grid library eat those two strokes, and both of them are escaped by the same one pixel move
- * inward:
- * 1. THE DAMAGE CLIP. `data-grid-render.cells` clips each cell to a box that starts at
- * `cellX + 1` and `drawY + 1` while running flush to the right and bottom edges, so
- * anything we draw left of `cellX + 1` or above `drawY + 1` is discarded outright. A nested
- * clip can only ever intersect that one, so it cannot be widened from in here.
- * 2. THE LIBRARY'S OWN GRID LINES. `data-grid-render` draws its light grid AFTER the cells, on
- * the same context, at exactly `cellX + 0.5` and `drawY + 0.5` in the theme's border
- * colour. Those are the very device pixels our left and top strokes used to occupy, so even
- * an unclipped stroke there would be painted over on every frame. The right stroke at
- * `width - 0.5` and the bottom at `height - 0.5` land a pixel inside and are never touched,
- * which is exactly why the bug looked like "only two sides work".
- *
- * ⚠ THE OFFSET IS 1.5 AND NOT 1.0. At 1.5 the stroke covers one whole device pixel column or row
- * inside the clip and clear of the library's line, at full intensity. At 1.0 a one pixel wide
- * stroke straddles the clip boundary: half of it is clipped away and the other half is overpainted
- * by the library's grid line, giving a faint smear rather than a border.
+ * Turn the current Glide cell rectangle into its four one-pixel inner edge strips.
*
- * ⚠ A STROKE POSITION IS NOT A RUN EXTENT, and conflating the two is what hid this for two waves.
- * `strokeX*` / `strokeY*` say WHERE a line lies along its own thin axis. `runFrom*` / `runTo*` say
- * how far it travels along the other axis. The runs start at the cell's own half pixel edge and
- * let the damage clip trim them, which is what makes all four corners meet on a fully covered
- * pixel with no antialiased gap.
- *
- * ⚠ THE CALLER PAINTS THIS OUTSIDE ITS TEXT CLIP, so a side lands on the cell edge rather than
- * deep inside it. That is the caller's business and the reason the call sits where it does in
- * `paintCell`; this function only assumes it is free to save and restore the context. The frozen
- * band needs no separate handling: `paintFrozenCell` delegates to `paintCell`, so it is the same
- * paint.
- *
- * ⚠ AN ABSENT `border` IS NOT AN ERROR, it is the ordinary case: {@link CellBorder} carries only
- * the sides that are ON, and a cell with no border at all has no `border` key. The early return
- * is the `if (border)` guard the call site used to hold, said one scope down.
+ * The cell rectangle is the source on every paint, so fractional scroll positions and browser
+ * zoom cannot leave a cached border behind. `+ 1` is Glide's first paintable coordinate during a
+ * damage repaint; the strip starts there and touches the grid line without the half-pixel stroke
+ * inset that made left/top visibly different from right/bottom. Filled strips avoid antialiasing
+ * and survive the light grid lines Glide paints after cell content.
*/
+export function cellBorderStrips(rect: CellBorderRect, border: CellBorder): BorderStrip[] {
+ const left = rect.x + 1;
+ const top = rect.y + 1;
+ const right = rect.x + rect.width;
+ const bottom = rect.y + rect.height;
+ const width = Math.max(0, right - left);
+ const height = Math.max(0, bottom - top);
+ const strips: BorderStrip[] = [];
+ if (border.top && width > 0) strips.push({ x: left, y: top, width, height: 1 });
+ if (border.right && height > 0) strips.push({ x: right - 1, y: top, width: 1, height });
+ if (border.bottom && width > 0) strips.push({ x: left, y: bottom - 1, width, height: 1 });
+ if (border.left && height > 0) strips.push({ x: left, y: top, width: 1, height });
+ return strips;
+}
+
+/** Paint the cell's own enabled edges outside the caller's text clip. */
export function paintCellBorders(
ctx: CanvasRenderingContext2D,
- rect: { x: number; y: number; width: number; height: number },
+ rect: CellBorderRect,
border: CellBorder | undefined,
): void {
if (!border) return;
+ const strips = cellBorderStrips(rect, border);
+ if (strips.length === 0) return;
ctx.save();
- ctx.strokeStyle = tokenColour("--lp-line-strong", "#c9ced8");
- ctx.lineWidth = 1;
- ctx.beginPath();
- // Where each side's thin line lies. Left and top are inset a further pixel to clear the damage
- // clip and the library's own grid line; right and bottom already sit inside both.
- const strokeXLeft = rect.x + 1.5;
- const strokeYTop = rect.y + 1.5;
- const strokeXRight = rect.x + rect.width - 0.5;
- const strokeYBottom = rect.y + rect.height - 0.5;
- // How far each side travels. Starts on the cell's own edge so the clip trims it to a whole
- // pixel and the corners meet the perpendicular stroke exactly.
- const runFromX = rect.x + 0.5;
- const runToX = strokeXRight;
- const runFromY = rect.y + 0.5;
- const runToY = strokeYBottom;
- if (border.top) { ctx.moveTo(runFromX, strokeYTop); ctx.lineTo(runToX, strokeYTop); }
- if (border.bottom) { ctx.moveTo(runFromX, strokeYBottom); ctx.lineTo(runToX, strokeYBottom); }
- if (border.left) { ctx.moveTo(strokeXLeft, runFromY); ctx.lineTo(strokeXLeft, runToY); }
- if (border.right) { ctx.moveTo(strokeXRight, runFromY); ctx.lineTo(strokeXRight, runToY); }
- ctx.stroke();
+ ctx.fillStyle = tokenColour("--sheet-cell-border", DEFAULT_CELL_BORDER_COLOR);
+ strips.forEach((strip) => ctx.fillRect(strip.x, strip.y, strip.width, strip.height));
ctx.restore();
}
diff --git a/web/src/sheet/cellStyleOps.ts b/web/src/sheet/cellStyleOps.ts
index 0cc934ea289668578fb1ed6957c9ba6441f0965e..39e83cc2d70ae61093c135c53e5c50b61ad9d5f1 100644
--- a/web/src/sheet/cellStyleOps.ts
+++ b/web/src/sheet/cellStyleOps.ts
@@ -139,6 +139,24 @@ export const clearAll = (
export const styleOf = (cell: Cell | null | undefined): CellStyle | null =>
cell?.style ? { ...cell.style } : null;
+/** Replace only a cell's formatting layer, preserving content and every other target layer. */
+export const replaceCellStyle = (
+ cell: Cell | null | undefined,
+ style: CellStyle | null | undefined,
+): Cell | null => {
+ if (style) {
+ const base: Cell = cell ?? { kind: "empty", state: "fresh" };
+ return { ...base, style: { ...style } };
+ }
+ if (!cell?.style) return cell ?? null;
+ const next: Cell = { ...cell };
+ delete next.style;
+ if (next.kind === "empty" && !next.validation && !next.link && !next.note && !next.sparkline) {
+ return null;
+ }
+ return next;
+};
+
/**
* ⛔⛔ EVERY KEY `CellStyle` CARRIES, AND A MISSING ONE IS A SILENT HALF-PAINT. The Format painter
* REPLACES a style rather than merging into it, so it has to say `null` for the keys the picked
diff --git a/web/src/sheet/clipboardOps.ts b/web/src/sheet/clipboardOps.ts
index c7dbf055ad781d0df8ae74bf7023ced5ce623d94..4a7d904b2c0e9ac8a05f02242b4e2ebd515f0a53 100644
--- a/web/src/sheet/clipboardOps.ts
+++ b/web/src/sheet/clipboardOps.ts
@@ -28,6 +28,14 @@ import { editableText, rawDisplayText, rememberCopy, rememberCut } from "./sheet
import type { Cell, CellMap } from "./types";
import { formatCellText } from "./types";
+/** The three clipboard layers a paste command may apply. Normal is the full cell payload. */
+export const PASTE_MODES = ["normal", "values", "formatting"] as const;
+export type PasteMode = (typeof PASTE_MODES)[number];
+
+/** Narrow a ribbon argument at the clipboard boundary; unknown arguments remain normal paste. */
+export const pasteModeFrom = (value: unknown): PasteMode =>
+ value === "values" || value === "formatting" ? value : "normal";
+
/**
* WHAT A COPY OF `range` PUTS ON THE CLIPBOARD, AND WHAT THE COMPONENT REMEMBERS ABOUT IT.
*
diff --git a/web/src/sheet/ribbonData.tsx b/web/src/sheet/ribbonData.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..d60bbd38d6d0d813a3624641fd65be28cbbf1e61
--- /dev/null
+++ b/web/src/sheet/ribbonData.tsx
@@ -0,0 +1,87 @@
+// Sheet Data ribbon, behaviorally adapted from the Wave 55 public Excel audit. The commands below
+// stay within Sheet's existing executable actions; unavailable audit commands remain visible and
+// honest rather than becoming no-op affordances.
+
+import type { RibbonTabContext } from "./Ribbon";
+
+const DATA = ["data-refresh"] as const;
+const OUTLINE = ["data-hide-rows", "data-hide-columns", "data-unhide"] as const;
+
+export const DATA_KEYS = [...DATA, ...OUTLINE] as const;
+
+function IconRefresh() {
+ return (
+
+
+
+
+ );
+}
+
+function IconBand({ column = false }: { column?: boolean }) {
+ return (
+
+
+ {column ? : }
+
+ );
+}
+
+export const dataGroups = (ctx: RibbonTabContext) => {
+ const { act, control, group, unavailable, word } = ctx;
+ return (
+ <>
+ {group("Data", (
+ <>
+ {control(
+ "data-refresh", "Refresh all", <> {word("Refresh all")}>,
+ () => act("refresh"), false, undefined, "R",
+ )}
+ {unavailable("Queries and connections", word("Queries and connections"))}
+ >
+ ))}
+ {group("Sort", (
+ <>
+ {unavailable("Sort ascending", word("Sort ascending"))}
+ {unavailable("Sort descending", word("Sort descending"))}
+ >
+ ))}
+ {group("Auto filter", unavailable("Filter", word("Filter")))}
+ {group("Data validation", unavailable("Data validation", word("Data validation")))}
+ {group("Data tools", (
+ <>
+ {unavailable("Split text to columns", word("Text to columns"))}
+ {unavailable("Flash fill", word("Flash fill"))}
+ {unavailable("Remove duplicates", word("Remove duplicates"))}
+ >
+ ))}
+ {group("Outline", (
+ <>
+ {control(
+ "data-hide-rows", "Hide rows", <> {word("Hide rows")}>,
+ () => act("hide-rows"), false, undefined, "HR",
+ )}
+ {control(
+ "data-hide-columns", "Hide columns", <> {word("Hide columns")}>,
+ () => act("hide-columns"), false, undefined, "HC",
+ )}
+ {control(
+ "data-unhide", "Unhide rows and columns", word("Unhide"),
+ () => act("unhide"), false, undefined, "U",
+ )}
+ >
+ ))}
+ >
+ );
+};
+
+export const DATA_TAB = {
+ id: "data",
+ key: "tab-data",
+ kt: "A",
+ label: "Data",
+ bodyClass: "sheet-ribbon-data",
+ toolbarLabel: "Data",
+ keys: DATA_KEYS,
+ groups: dataGroups,
+} as const;
diff --git a/web/src/sheet/ribbonFormulas.tsx b/web/src/sheet/ribbonFormulas.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..e87771a9f0200fe0002eac572e3ec9b705c96cbc
--- /dev/null
+++ b/web/src/sheet/ribbonFormulas.tsx
@@ -0,0 +1,61 @@
+// Sheet Formulas ribbon, adapted from the behavior and grouping recorded in
+// `.claude/wiki/waves/wave55/planning/excel-online-audit.md`. This is an original Loopable
+// expression: it reuses the ribbon primitives and closed action vocabulary, never external
+// source, assets, or private class names. Commands without an executable Sheet door say so.
+
+import type { RibbonTabContext } from "./Ribbon";
+import { IconAutoSum } from "./ribbonIcons";
+
+const FUNCTION_LIBRARY = ["formula-autosum"] as const;
+const DATA = ["formula-refresh"] as const;
+
+export const FORMULAS_KEYS = [...FUNCTION_LIBRARY, ...DATA] as const;
+
+function IconCalculate() {
+ return (
+
+
+
+
+ );
+}
+
+export const formulasGroups = (ctx: RibbonTabContext) => {
+ const { act, control, group, unavailable, word } = ctx;
+ return (
+ <>
+ {group("Function library", (
+ <>
+ {unavailable("Insert function", word("Insert function"))}
+ {control(
+ "formula-autosum", "AutoSum", <> {word("AutoSum")}>,
+ () => act("autosum"), false, undefined, "U",
+ )}
+ {unavailable("More functions", word("More functions"))}
+ >
+ ))}
+ {group("Name manager", unavailable("Name manager", word("Name manager")))}
+ {group("Show formulas", unavailable("Show formulas", word("Show formulas")))}
+ {group("Data", (
+ <>
+ {control(
+ "formula-refresh", "Calculate now", <> {word("Calculate now")}>,
+ () => act("refresh"), false, undefined, "C",
+ )}
+ {unavailable("Calculation options", word("Calculation options"))}
+ >
+ ))}
+ >
+ );
+};
+
+export const FORMULAS_TAB = {
+ id: "formulas",
+ key: "tab-formulas",
+ kt: "M",
+ label: "Formulas",
+ bodyClass: "sheet-ribbon-formulas",
+ toolbarLabel: "Formulas",
+ keys: FORMULAS_KEYS,
+ groups: formulasGroups,
+} as const;
diff --git a/web/src/sheet/ribbonHome.tsx b/web/src/sheet/ribbonHome.tsx
index 32eb4639b4004f8f719fa6cc4ead751f11598435..5c35de644aea14a3c9e05de614c0742c27aa26f1 100644
--- a/web/src/sheet/ribbonHome.tsx
+++ b/web/src/sheet/ribbonHome.tsx
@@ -509,20 +509,28 @@ export const homeGroups = (ctx: RibbonTabContext) => {
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. */}
+ The tall Paste control opens the existing anchored menu vocabulary. Normal paste and
+ both named paste-special layers still travel through the one `paste` act; its argument
+ selects the layer without widening the ribbon action union or adding a save path. */}
{group("Clipboard", (
{control("paste", "Paste", <>{ }{word("Paste")}>,
- () => act("paste"), false, undefined, "V")}
+ openPop("paste"), false, open === "paste", "V", "gallery")}
+ {open === "paste" && (
+
+ {item("Paste", () => act("paste", "normal"))}
+ {item("Paste values", () => act("paste", "values"))}
+ {item("Paste formatting", () => act("paste", "formatting"))}
+
+ )}
{/* ⭐⭐ 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
diff --git a/web/src/sheet/ribbonView.tsx b/web/src/sheet/ribbonView.tsx
new file mode 100644
index 0000000000000000000000000000000000000000..0172a40a80252c6de3a46da02052c23dca39f6b1
--- /dev/null
+++ b/web/src/sheet/ribbonView.tsx
@@ -0,0 +1,99 @@
+// Sheet View ribbon, adapted from the behavior and grouping in the Wave 55 public Excel audit.
+// Freeze, Formula bar, Full screen, and Go to use existing executable doors. Canvas gridline
+// visibility and the other unsupported commands are deliberately labelled unavailable.
+
+import type { RibbonTabContext } from "./Ribbon";
+
+const SHOW = ["view-formula-bar"] as const;
+const WINDOW = ["view-freeze", "view-fullscreen"] as const;
+const NAVIGATION = ["view-go-to"] as const;
+
+export const VIEW_KEYS = [...SHOW, ...WINDOW, ...NAVIGATION] as const;
+
+function IconFormulaBar() {
+ return (
+
+
+
+
+ );
+}
+
+function IconFreeze() {
+ return (
+
+
+
+
+ );
+}
+
+function IconFullScreen() {
+ return (
+
+
+
+ );
+}
+
+function IconGoTo() {
+ return (
+
+
+
+
+ );
+}
+
+export const viewGroups = (ctx: RibbonTabContext) => {
+ const {
+ act, control, formulaBarVisible, frozen, fullscreen, group,
+ toggleFormulaBar, toggleFullscreen, unavailable, word,
+ } = ctx;
+ const fullscreenLabel = fullscreen ? "Exit full screen" : "Full screen";
+ return (
+ <>
+ {group("Workbook views", unavailable("New window", word("New window")))}
+ {group("Show", (
+ <>
+ {control(
+ "view-formula-bar", "Formula bar", <>
{word("Formula bar")}>,
+ toggleFormulaBar, formulaBarVisible, undefined, "B",
+ )}
+ {unavailable("Gridlines", word("Gridlines"))}
+ {unavailable("Headings", word("Headings"))}
+ >
+ ))}
+ {group("Window", (
+ <>
+ {control(
+ "view-freeze", "Freeze panes", <>
{word("Freeze panes")}>,
+ () => act("freeze"), frozen, undefined, "F",
+ )}
+ {control(
+ "view-fullscreen", fullscreenLabel,
+ <>
{word(fullscreenLabel)}>,
+ toggleFullscreen, fullscreen, undefined, "U",
+ )}
+ >
+ ))}
+ {group("Zoom", unavailable("100%", word("100%")))}
+ {group("Navigation", control(
+ "view-go-to", "Go to", <>
{word("Go to")}>,
+ () => act("go-to"), false, undefined, "N",
+ ))}
+ {group("Sheet view", unavailable("Sheet view", word("Sheet view")))}
+ >
+ );
+};
+
+export const VIEW_TAB = {
+ id: "view",
+ key: "tab-view",
+ kt: "W",
+ label: "View",
+ bodyClass: "sheet-ribbon-view",
+ toolbarLabel: "View",
+ keys: VIEW_KEYS,
+ groups: viewGroups,
+} as const;
diff --git a/web/src/sheet/sheetState.ts b/web/src/sheet/sheetState.ts
index ee5bbb2833487f18791aa7d9d673f1dd1ce2bd6f..21e93ae9c4664b2c9f8fb0b60e79f75b885e6a74 100644
--- a/web/src/sheet/sheetState.ts
+++ b/web/src/sheet/sheetState.ts
@@ -30,7 +30,8 @@ import type { StructuralShift } from "./a1";
// (its registry) and HOW one moves (delegated straight to `a1.ts`, never re-derived). This file
// used to answer the first half inline, in two branches of `dragBoundCell`, which meant C3's
// second reference slot would have had to be added here as well as wherever it was declared.
-import { shiftBindingRefs, shiftRefText } from "./bindingRefs";
+import { materializeLocalViewBinding, shiftBindingRefs, shiftRefText } from "./bindingRefs";
+import type { SavedViewShadow } from "./bindingRefs";
// ⭐⭐ W53-T01 / CONTRACT C1 — THE ONE IMPORT THAT MAKES A COMMITTED FORMULA COMPUTE LOCALLY.
// `formulaEval.ts` imports nothing back from this file (see its own header): it takes a plain
// `get(addr) => CellValue` callback and knows nothing about a `Cell`. `cellToValue`, below, is the
@@ -39,6 +40,8 @@ import {
CYCLE_REFUSAL, cyclicAddresses, evaluateFormula, recalcOrder,
} from "./formulaEval";
import type { CellValue } from "./formulaEval";
+import { replaceCellStyle } from "./cellStyleOps";
+import type { PasteMode } from "./clipboardOps";
/** R19's three MARKS. `refused` is a fourth state and not one of the three: it replaces the value
* rather than qualifying it, so it gets its own treatment in the renderer. */
@@ -152,6 +155,7 @@ export const blankOf = (cell: Cell | null | undefined): Cell | null => {
*/
export const setLiteral = (cell: Cell | null | undefined, text: string): Cell => {
const rest = { ...(cell ?? { kind: "literal", state: "typed" as CellState }) } as Partial
;
+ delete rest.formula;
delete rest.binding;
delete rest.source;
delete rest.refusal;
@@ -667,21 +671,13 @@ export interface BulkEdit {
// ⛔⛔ THIS SECTION REVERSES A WAVE-49 DECISION ON PURPOSE, AND IT IS WRITTEN DOWN SO A LATER
// WAVE KNOWS IT IS CHANGING A DECISION RATHER THAN FIXING A BUG. `fillCells` used to refuse to
// copy a binding at all, and its reason was good at the time: "copying a binding would give
-// forty cells the same database read with no way to tell them apart". R9 and R10 give them a way
-// to tell each other apart. Dragging ACROSS columns walks the period one unit per column;
-// dragging DOWN rows walks a chosen filter to its next option; and a person who wants forty
-// identical reads now has to ask for them by setting both rules to Nothing.
+// forty cells the same database read with no way to tell them apart". W55 R5 and R13 finish the
+// answer: a saved View becomes local before it moves, a metric period uses the signed copy
+// direction, and a non-metric chosen field walks its ordered options in that same direction.
// [[two-gates-can-assert-opposite-things]]
//
-// ⛔⛔ THE TWO AXES NEVER FALL BACK ON EACH OTHER. `across` reads the COLUMN delta and only the
-// column delta; `down` reads the ROW delta and only the row delta. The defect this feature will
-// have if it has one is `steps = dCol || dRow`, or "if the column delta is zero, use the row
-// one": both make a cell dragged straight DOWN walk its period, which R10 says it must not, and
-// both look perfectly correct in any screenshot of a single row.
-//
-// ⛔ AND THE BOUND WALL STILL STANDS ON THE TARGET. A bulk door may now COPY a binding; it still
-// may not OVERWRITE one. Landing on a bound cell is still a skip that gets reported, because
-// nobody confirmed unbinding the cell that was already there (A2, R20).
+// ⛔ THE SIGN IS THE CONTRACT. Right and down advance; left and up retreat. A diagonal keeps
+// the horizontal distance, so one copied cell is never stepped once per axis.
//
// ⚠ NOTHING HERE IMPORTS THE FILTER LANGUAGE. `customer-grid/types.ts` owns `FilterTree`, and
// importing it would move tsc's emitted root and break every `require` path the battery's Sheet
@@ -690,7 +686,7 @@ export interface BulkEdit {
// ═════════════════════════════════════════════════════════════════════════════════════════════
/**
- * The option order a DOWN drag walks, keyed by field.
+ * The option order a copied non-metric binding walks, normally keyed by database and field.
*
* ⭐ ONE SHAPE SERVES BOTH OF R10's CASES. "The next value of a single select" is its option
* order; "the next linked record" is the linked table's view order. Both are an ordered list of
@@ -698,15 +694,22 @@ export interface BulkEdit {
*/
export type OptionCatalogue = Record;
+/** A database-qualified driver slot. The bare field key remains a legacy/test fallback. */
+export const bindingOptionKey = (database: string, field: string): string =>
+ JSON.stringify([String(database || ""), String(field || "")]);
+
/** What a bulk door needs to know to drag a BOUND cell. Every member is optional by design. */
export interface DragContext {
/**
- * The field option order. ABSENT IS THE ORDINARY CASE TODAY: `SheetGrid.tsx` is deliberately
- * schema free, so nothing has loaded a catalogue for it. A `down` rule then copies the filter
- * unchanged and SAYS SO through {@link boundDragLabel}, which is the honest degradation R10
- * asks for. It never wraps to the first option and it never sits silent.
+ * The field option order. `SheetGrid.tsx` stays schema free, so its page supplies this catalogue.
+ * When it is absent the filter stays unchanged and {@link boundDragLabel} says why.
*/
catalogue?: OptionCatalogue;
+ /**
+ * Canonical saved-View filters, loaded before the copy starts. R5 needs this snapshot to replace
+ * a shared View pointer with cell-local filter state before a chosen driver can walk it.
+ */
+ shadows?: readonly SavedViewShadow[];
/**
* PASTE ONLY: the cells the block was copied FROM, in the same shape as the pasted values, and
* the corner they came from. A clipboard round trip carries TEXT, so a pasted bound cell can
@@ -720,9 +723,11 @@ export interface DragContext {
export interface BoundDragTally {
/** Bound cells the rule wrote. Not a notice: a drag that worked says nothing. */
dragged: number;
- /** A `down` rule was asked for and no option order was available to walk. */
+ /** A chosen driver had no option order available to walk. */
noCatalogue: number;
- /** A `down` rule named a field the cell's own filter does not use. */
+ /** A copied saved View had no canonical local snapshot available. */
+ noViewShadow?: number;
+ /** A chosen driver named a field the cell's own filter does not use. */
noField: number;
/** The walk ran off the end of the option order, so the value stayed where it was. */
atEnd: number;
@@ -742,9 +747,13 @@ export interface FillEdit extends BulkEdit, BoundDragTally {}
export interface PasteEdit extends FillEdit {
/** Set when the target rectangle cannot hold whole copies of the block. `edits` is then empty. */
sizeRefusal?: string;
+ /** Set when a named paste layer is unavailable from the clipboard payload. */
+ layerRefusal?: string;
}
-const emptyTally = (): BoundDragTally => ({ dragged: 0, noCatalogue: 0, noField: 0, atEnd: 0 });
+const emptyTally = (): BoundDragTally => ({
+ dragged: 0, noCatalogue: 0, noViewShadow: 0, noField: 0, atEnd: 0,
+});
/** How many MONTHS one step of each unit is worth. `start` is `YYYY-MM` for all three (C2). */
const UNIT_MONTHS: Record = { month: 1, quarter: 3, year: 12 };
@@ -785,6 +794,12 @@ export const shiftPeriodStart = (
return `${String(outYear).padStart(4, "0")}-${String(outMonth).padStart(2, "0")}`;
};
+/**
+ * One signed copy distance for R13. Right and down are forward; left and up are backward.
+ * A diagonal keeps the horizontal distance, the established spreadsheet period-axis rule.
+ */
+export const signedCopyStep = (dCol: number, dRow: number): number => dCol || dRow;
+
/**
* Shift a period's `ref` the way a dragged formula reference shifts, `$` anchors honoured.
*
@@ -792,11 +807,8 @@ export const shiftPeriodStart = (
* ITSELF: `bindingRefs.ts::shiftRefText` is the one-reference rule now, so this name survives as
* the door its callers already know while there stays exactly ONE implementation underneath.
*
- * ⚠ THE REF SHIFTS ON BOTH AXES, WHILE THE PERIOD'S `start` SHIFTS ONLY ACROSS COLUMNS. They are
- * different things: a `start` is a period, and R9 says a period moves across and holds down; a
- * `ref` is a POINTER at a cell, and a pointer that did not follow the drag would point at the
- * same cell from forty different places. A reader who wants it fixed writes `$B$1`, which is the
- * control Excel already taught them, or locks the period.
+ * ⚠ The reference and period start both understand two axes, but anchoring is independent:
+ * `$B$1` stays fixed while `B1` follows the copied cell. Locking the period pins the slot too.
*/
export const shiftPeriodRef = (ref: string, dRow: number, dCol: number): string =>
shiftRefText(ref, dRow, dCol);
@@ -853,6 +865,7 @@ export interface BoundDrag {
/** The binding is not the one it was copied from. */
changed: boolean;
noCatalogue: boolean;
+ noViewShadow: boolean;
noField: boolean;
atEnd: boolean;
}
@@ -874,6 +887,7 @@ export interface BoundDrag {
*/
export const dragBoundCell = (
source: Cell, dCol: number, dRow: number, catalogue?: OptionCatalogue,
+ shadows?: readonly SavedViewShadow[],
): BoundDrag => {
const binding = (source.binding ?? null) as Record | null;
// ⭐ DESTRUCTURED RATHER THAN DELETED, which is this file's own idiom (`setLiteral`,
@@ -884,20 +898,33 @@ export const dragBoundCell = (
if (!binding) {
return {
cell: { ...kept, kind: "bound", state: "stale" },
- changed: false, noCatalogue: false, noField: false, atEnd: false,
+ changed: false, noCatalogue: false, noViewShadow: false, noField: false, atEnd: false,
+ };
+ }
+ // A zero delta is the paste door's CUT marker. A move retains the exact binding, including a
+ // saved-View pointer; only a copy materialises local state and applies copy stepping.
+ if (!dCol && !dRow) {
+ return {
+ cell: { ...kept, kind: "bound", state: "stale", binding },
+ changed: false, noCatalogue: false, noViewShadow: false, noField: false, atEnd: false,
};
}
const rules: BindingOnDrag = bindingOnDrag(binding);
const period: BindingPeriod | null = bindingPeriod(binding);
- let next: Record = { ...binding };
- let changed = false;
-
- // ── ACROSS COLUMNS (R9, R10): the period, and only ever the COLUMN delta ──────────────────
- if (period && !period.locked && rules.across === "period" && dCol !== 0 && period.start) {
- const start = shiftPeriodStart(period.start, period.unit, dCol);
+ const local = materializeLocalViewBinding(binding, shadows);
+ let next: Record = local.binding;
+ let changed = local.localized;
+ const step = signedCopyStep(dCol, dRow);
+
+ // R13: metric periods use the selected grain and signed copy direction on either axis.
+ if (period && !period.locked && rules.across === "period" && step !== 0 && period.start) {
+ const start = shiftPeriodStart(period.start, period.unit, step);
if (start !== period.start) {
- next.period = { ...(binding.period as Record), start };
+ next = {
+ ...next,
+ period: { ...(next.period as Record), start },
+ };
changed = true;
}
}
@@ -914,17 +941,21 @@ export const dragBoundCell = (
changed = true;
}
- // ── DOWN ROWS (R10): the chosen filter's value, and only ever the ROW delta ───────────────
+ // R5: a non-metric chosen driver walks the local filter in that signed direction.
let noCatalogue = false;
+ const noViewShadow = local.missing;
let noField = false;
let atEnd = false;
- if (rules.down !== "none" && dRow !== 0) {
+ if (rules.down !== "none" && step !== 0 && !noViewShadow) {
const field = rules.down.field;
- const options = catalogue ? catalogue[field] : undefined;
+ const database = typeof next.database === "string" ? next.database : "";
+ const options = catalogue
+ ? catalogue[bindingOptionKey(database, field)] ?? catalogue[field]
+ : undefined;
if (!options || options.length === 0) {
noCatalogue = true;
} else {
- const scope = (binding.scope ?? null) as Record | null;
+ const scope = (next.scope ?? null) as Record | null;
const tree = scope && typeof scope.filter === "object" && scope.filter
? (scope.filter as Record)
: null;
@@ -933,9 +964,9 @@ export const dragBoundCell = (
noField = true;
} else {
const walked = walkFilterNodes(nodes, field, (value) => {
- const step = walkOption(options, value, dRow);
- atEnd = atEnd || step.atEnd;
- return step.value;
+ const walkedOption = walkOption(options, value, step);
+ atEnd = atEnd || walkedOption.atEnd;
+ return walkedOption.value;
});
if (!walked.found) noField = true;
else {
@@ -952,7 +983,7 @@ export const dragBoundCell = (
const cell: Cell = changed
? { ...bare, kind: "bound", state: "stale", binding: next }
: { ...kept, kind: "bound", state: "stale", binding: next };
- return { cell, changed, noCatalogue, noField, atEnd };
+ return { cell, changed, noCatalogue, noViewShadow, noField, atEnd };
};
/**
@@ -966,6 +997,12 @@ export const dragBoundCell = (
*/
export const boundDragLabel = (tally: BoundDragTally): string => {
const parts: string[] = [];
+ const missingShadows = tally.noViewShadow ?? 0;
+ if (missingShadows > 0) {
+ parts.push(missingShadows === 1
+ ? "One saved View has not loaded, so its cell could not be copied yet."
+ : `${missingShadows} saved Views have not loaded, so their cells could not be copied yet.`);
+ }
if (tally.noCatalogue > 0) {
parts.push(tally.noCatalogue === 1
? "The list of options has not loaded, so one cell kept the filter it was copied from."
@@ -1143,7 +1180,7 @@ export const forgetCut = (): void => { pendingCut = null; };
const cutFingerprint = (cell: Cell | null | undefined): string =>
cell
? [cell.kind, cell.text ?? "", String(cell.value ?? ""), cell.display ?? "",
- cell.binding ? "bound" : ""].join(" ")
+ cell.binding ? "bound" : ""].join("\u0000")
: "";
/**
@@ -1223,16 +1260,43 @@ const clearCutSource = (
* ⚠ A STYLED BLANK STILL LANDS. Copying an empty cell that carries only a fill and pasting it
* paints that fill, which is why this may build a cell where {@link commitTyped} returned none.
*/
-const withSourceStyle = (landed: Cell | null, copied: Cell | null): Cell | null => {
- if (!copied) return landed;
- if (copied.style) {
- const base: Cell = landed ?? { kind: "empty", state: "fresh" };
- return { ...base, style: { ...copied.style } };
- }
- if (!landed?.style) return landed;
- const bare: Cell = { ...landed };
- delete bare.style;
- return bare;
+const withSourceStyle = (
+ landed: Cell | null,
+ copied: Cell | null,
+ sourceKnown = true,
+): Cell | null => sourceKnown ? replaceCellStyle(landed, copied?.style) : landed;
+
+/** Remove only value/formula/binding content, retaining the target's other cell layers. */
+const withoutValueLayer = (cell: Cell | null | undefined): Cell | null => {
+ if (!cell) return null;
+ const next: Cell = { ...cell, kind: "empty", state: "fresh" };
+ delete next.text;
+ delete next.formula;
+ delete next.value;
+ delete next.display;
+ delete next.binding;
+ delete next.source;
+ delete next.refusal;
+ delete next.refreshed_at;
+ return next.style || next.validation || next.link || next.note || next.sparkline ? next : null;
+};
+
+/** A copied cell's result as literal content. Formulas and bindings never survive Paste values. */
+const valueLayerText = (cell: Cell | null): string => {
+ if (!cell || cell.kind === "empty") return "";
+ if (cell.value != null) return String(cell.value);
+ if (cell.kind === "literal" && cell.text != null) return cell.text;
+ return rawDisplayText(cell);
+};
+
+const withValueLayer = (
+ target: Cell | null,
+ copied: Cell | null,
+ fallback: string,
+ sourceKnown: boolean,
+): Cell | null => {
+ const text = sourceKnown ? valueLayerText(copied) : fallback;
+ return text === "" ? withoutValueLayer(target) : setLiteral(target, text);
};
/**
@@ -1262,6 +1326,7 @@ export const pasteCells = (
* what every existing caller and every existing proof already expects.
*/
region?: CellRange,
+ mode: PasteMode = "normal",
): PasteEdit => {
const edits: Record = {};
const tally = emptyTally();
@@ -1287,12 +1352,19 @@ export const pasteCells = (
const pastedText = source.map((row) => row.join("\t")).join("\n");
// ⛔⛔ W54-T16 — A CUT IS A MOVE, AND A MOVE SHIFTS NOTHING. Answered ONCE, before any cell is
// built, because every landing cell in the block has to agree about it.
- const moving = completesCut(pastedText);
+ const moving = mode === "normal" && completesCut(pastedText);
const recalled = drag?.cells
? null
: recallCopy(pastedText);
const held = drag?.cells ?? recalled?.cells ?? null;
const heldFrom = drag?.from ?? (recalled ? { col: recalled.col, row: recalled.row } : null);
+ const sourceKnown = held !== null;
+ if (mode === "formatting" && !sourceKnown) {
+ return {
+ edits: {}, ...emptyTally(),
+ layerRefusal: "Copy cells from this sheet before pasting formatting.",
+ };
+ }
/**
* Land the copied block ONCE, with its top left corner at `originCol` / `originRow`.
*
@@ -1331,6 +1403,15 @@ export const pasteCells = (
// destination kept its own fill, borders and number format while the source's were
// dropped. {@link withSourceStyle} carries the style object across as a whole.
const copied = held?.[r]?.[c] ?? null;
+ if (mode === "formatting") {
+ const styled = withSourceStyle(cell, copied, true);
+ if (styled !== cell) edits[addr] = styled;
+ continue;
+ }
+ if (mode === "values") {
+ edits[addr] = withValueLayer(cell, copied, String(row[c] ?? ""), sourceKnown);
+ continue;
+ }
if (copied && copied.kind === "bound" && heldFrom) {
// ⛔⛔ W54-T16 — A CUT IS A MOVE, AND A MOVE SHIFTS NOTHING. Excel's rule, and the two
// halves of it are different acts: a COPY walks a binding's period and its cell
@@ -1347,8 +1428,12 @@ export const pasteCells = (
// cut whose source has since changed is still a MOVE for reference purposes.
const dCol = moving ? 0 : originCol - heldFrom.col;
const dRow = moving ? 0 : originRow - heldFrom.row;
- const out = dragBoundCell(copied, dCol, dRow, drag?.catalogue);
- edits[addr] = withSourceStyle(out.cell, copied);
+ const out = dragBoundCell(copied, dCol, dRow, drag?.catalogue, drag?.shadows);
+ if (out.noViewShadow) {
+ tally.noViewShadow = (tally.noViewShadow ?? 0) + 1;
+ continue;
+ }
+ edits[addr] = withSourceStyle(out.cell, copied, sourceKnown);
tally.dragged += 1;
if (out.noCatalogue) tally.noCatalogue += 1;
if (out.noField) tally.noField += 1;
@@ -1370,7 +1455,7 @@ export const pasteCells = (
// ⛔ AND THE NO SOURCE PATH IS UNTOUCHED. An external paste, or a registry miss, has no
// cell to ask, so it commits the clipboard string exactly as it always has.
const landing = copied ? editableText(copied) : String(row[c] ?? "");
- edits[addr] = withSourceStyle(commitTyped(cell, landing, read), copied);
+ edits[addr] = withSourceStyle(commitTyped(cell, landing, read), copied, sourceKnown);
}
}
};
@@ -1386,7 +1471,7 @@ export const pasteCells = (
// No drag, or one target cell: the block lands anchored where it was dropped, as it always has.
writeBlock(targetCol, targetRow);
// ⛔ W54-T16: AFTER the paste's own writes, so an overlapping cut keeps what just landed.
- clearCutSource(tab, edits, pastedText);
+ if (mode === "normal") clearCutSource(tab, edits, pastedText);
return { edits, ...tally };
}
if (wide % srcCols !== 0 || tall % srcRows !== 0) {
@@ -1403,7 +1488,7 @@ export const pasteCells = (
// ⛔ W54-T16: same rule on the tiled path, and after every tile - a cut tiled back over its own
// rectangle keeps the copies that landed there. A SIZE REFUSAL above wrote nothing and returned
// before this line, so a refused paste also leaves the cut armed for the paste that works.
- clearCutSource(tab, edits, pastedText);
+ if (mode === "normal") clearCutSource(tab, edits, pastedText);
return { edits, ...tally };
};
@@ -1471,7 +1556,13 @@ export const fillCells = (
// both spread the TARGET, so without {@link withSourceStyle} dragging a formatted cell
// across a range copied its value and left every destination wearing its own old format.
if (pattern.kind === "bound") {
- const dragged = dragBoundCell(pattern, col - srcCol, row - srcRow, drag?.catalogue);
+ const dragged = dragBoundCell(
+ pattern, col - srcCol, row - srcRow, drag?.catalogue, drag?.shadows,
+ );
+ if (dragged.noViewShadow) {
+ tally.noViewShadow = (tally.noViewShadow ?? 0) + 1;
+ continue;
+ }
edits[addr] = withSourceStyle(dragged.cell, pattern);
tally.dragged += 1;
if (dragged.noCatalogue) tally.noCatalogue += 1;
@@ -1870,7 +1961,7 @@ export const moveTab = (book: Workbook, tabId: string, step: number): SheetTab[]
// style act, and it belongs beside the other bulk value doors above.
// ════════════════════════════════════════════════════════════════════════════════════════
export {
- clearAll, clearFormats, paintPatch, styleCells, styleOf, STYLE_KEYS,
+ clearAll, clearFormats, paintPatch, replaceCellStyle, styleCells, styleOf, STYLE_KEYS,
} from "./cellStyleOps";
/** One selected rectangle, in the sheet's own zero based coordinates, inclusive of both corners. */
@@ -2125,9 +2216,11 @@ export const usedExtent = (
return col < 0 || row < 0 ? null : { col, row };
};
-/** Does this address hold anything at all? Ctrl+Arrow's occupancy test, said once. */
-export const isFilled = (tab: SheetTab | null | undefined, col: number, row: number): boolean =>
- cellAt(tab, addressOf(col, row)) !== null;
+/** Semantic occupancy for navigation: formatting alone does not make a cell filled. */
+export const isFilled = (tab: SheetTab | null | undefined, col: number, row: number): boolean => {
+ const kind = cellAt(tab, addressOf(col, row))?.kind;
+ return kind === "literal" || kind === "formula" || kind === "bound";
+};
/**
* ⭐ Ctrl+; — TODAY, AS AN UNAMBIGUOUS STRING.
diff --git a/web/src/sheet/shortcuts.ts b/web/src/sheet/shortcuts.ts
index ccadc5ded4a5713841d93c219d3cd2870a00aa46..59005dca7ac062a891cffeb3829cb108fb4303c4 100644
--- a/web/src/sheet/shortcuts.ts
+++ b/web/src/sheet/shortcuts.ts
@@ -358,11 +358,27 @@ export interface KeyChord {
altKey?: boolean;
}
+/** The vertical pair has one extra job: leaving an active KeyTips path for the grid. */
+const VERTICAL_ARROWS: Record = { ArrowUp: true, ArrowDown: true };
+
/** The four arrow keys, as a lookup rather than four comparisons in five places. */
const ARROWS: Record = {
- ArrowUp: true, ArrowDown: true, ArrowLeft: true, ArrowRight: true,
+ ...VERTICAL_ARROWS, ArrowLeft: true, ArrowRight: true,
};
+/**
+ * The scoped DOM event by which KeyTips hands one Up/Down press back to its containing grid.
+ * It is not a keyboard listener: the active overlay consumes the real key once, then emits this
+ * one semantic act on the nearest `.sheet-grid-wrap`, where the selection state already lives.
+ */
+export const KEY_TIP_GRID_ARROW_EVENT = "aios:sheet-key-tip-grid-arrow";
+
+export type KeyTipGridArrow = "ArrowUp" | "ArrowDown";
+
+/** Only Up/Down leave KeyTips for the selected cell under Wave 55 ruling R4. */
+export const keyTipGridArrow = (key: string): KeyTipGridArrow | null =>
+ (VERTICAL_ARROWS[key] === true ? key as KeyTipGridArrow : null);
+
/**
* ⭐⭐ W54-T19 (instruction 13) — IS THIS PRESS ONE OF THE FOUR ARROWS, ASKED ONCE.
*
diff --git a/web/src/sheet/types.ts b/web/src/sheet/types.ts
index e2dab25d8a4d1ea962e66307369bbed5c92ecd85..50952d6ddf554613e7ab3af975108e0e5d3e7940 100644
--- a/web/src/sheet/types.ts
+++ b/web/src/sheet/types.ts
@@ -74,6 +74,66 @@ export interface CellSource {
*/
export type CellBinding = Record;
+const asRecord = (value: unknown): Record | null =>
+ value && typeof value === "object" && !Array.isArray(value)
+ ? (value as Record)
+ : null;
+
+// ── W55-T07, contract C6: the CELL-LOCAL View presentation ────────────────────────────────
+//
+// A database View already has a `config.display`, but a bound Sheet cell is not that View. R6
+// makes the distinction durable: changing this drawer must not rewrite a shared View or seed a
+// browser-local preference bucket. The small display bag therefore rides on the binding itself.
+// `scope` continues to own which rows belong to the cell; this owns only how those rows are
+// presented when the cell is opened.
+
+/** The projections the compact Cell View can render without inventing mode-specific setup. */
+export const CELL_VIEW_MODES = ["grid", "list", "map"] as const;
+export type CellViewMode = (typeof CELL_VIEW_MODES)[number];
+
+/** R6's per-cell display state, stored as `binding.display`. */
+export interface BindingDisplay {
+ mode: CellViewMode;
+ /** Chosen field keys in display order. Filter fields are unioned at read time by C6. */
+ visible: string[];
+}
+
+/**
+ * Read a binding's display state without accepting an unknown renderer or duplicate field key.
+ *
+ * `null` means the binding predates W55-T07. Callers then use Grid plus the database's normally
+ * visible fields; absence stays absence until the person actually changes a display choice.
+ */
+export const bindingDisplay = (binding: unknown): BindingDisplay | null => {
+ const record = asRecord(binding);
+ const display = record && asRecord(record.display);
+ if (!display) return null;
+ const named = String(display.mode ?? "");
+ const mode = (CELL_VIEW_MODES as readonly string[]).includes(named)
+ ? (named as CellViewMode)
+ : "grid";
+ const visible: string[] = [];
+ if (Array.isArray(display.visible)) {
+ for (const value of display.visible) {
+ const key = typeof value === "string" ? value.trim() : "";
+ if (key && !visible.includes(key)) visible.push(key);
+ }
+ }
+ return { mode, visible };
+};
+
+/** Copy a binding with one validated cell-local display bag. */
+export const withBindingDisplay = (
+ binding: CellBinding,
+ display: BindingDisplay,
+): CellBinding => ({
+ ...binding,
+ display: {
+ mode: (CELL_VIEW_MODES as readonly string[]).includes(display.mode) ? display.mode : "grid",
+ visible: [...new Set(display.visible.map((key) => String(key).trim()).filter(Boolean))],
+ },
+});
+
// ── W51-T19, contract C2: the DRAG vocabulary (rulings R9 and R10) ──────────────────────────
//
// ⭐⭐ WHAT THESE NAMES ARE FOR. R9 and R10 make a bound cell DRAGGABLE: pulling it across
@@ -129,11 +189,6 @@ export interface BindingAdoptedFrom {
at: string;
}
-const asRecord = (value: unknown): Record | null =>
- value && typeof value === "object" && !Array.isArray(value)
- ? (value as Record)
- : null;
-
/**
* Read a binding's C2 period, or `null` when it carries none.
*
@@ -683,10 +738,21 @@ export type CellMap = Record;
* charts beside the cells also says something true: a chart has no value, no state and no binding,
* so every field a `Cell` carries would have been dead weight on it.
*/
+/**
+ * The one rectangle a chart stores. Pixels are deliberately absent: the grid derives them from
+ * these cell anchors every time it renders, scrolls, or changes structure.
+ */
+export interface SheetChartRange {
+ col0: number;
+ row0: number;
+ col1: number;
+ row1: number;
+}
+
export interface SheetChartSpec {
id: string;
/** Zero-based inclusive rectangle. The header ROW is the axis (R15). */
- range: { col0: number; row0: number; col1: number; row1: number };
+ range: SheetChartRange;
/**
* ⭐ WAVE 54 BASE KIT WIDENED THIS UNION, AND ALL EIGHT NAMES ARE REAL NOW.
*
@@ -703,6 +769,82 @@ export interface SheetChartSpec {
kind: "bar" | "line" | "area" | "donut" | "column" | "pie" | "scatter" | "combo";
}
+/** The structural vocabulary a chart anchor needs. `at` is 1 based, as the Sheet controls are. */
+export interface SheetChartStructure {
+ axis: "row" | "col";
+ at: number;
+ delta: number;
+}
+
+/** Keep a normalized inclusive interval inside the sheet without changing its span if it fits. */
+const clampChartAxis = (start: number, end: number, limit: number): [number, number] => {
+ const ceiling = Math.max(0, Math.round(limit) - 1);
+ let lo = Math.max(0, Math.min(start, end));
+ let hi = Math.max(lo, Math.max(start, end));
+ if (hi > ceiling) {
+ const overflow = hi - ceiling;
+ lo = Math.max(0, lo - overflow);
+ hi = ceiling;
+ }
+ return [Math.min(lo, ceiling), Math.min(Math.max(lo, hi), ceiling)];
+};
+
+/**
+ * Move one pair of cell anchors through an insert or delete.
+ *
+ * An insert before the range moves both anchors; an insert inside expands the far anchor. A delete
+ * keeps whichever anchored cells survive and collapses a fully deleted range onto the first cell
+ * of the removed band. That last case is still a real cell anchor, never an orphaned pixel box.
+ */
+const chartAxisAfterStructure = (
+ start: number,
+ end: number,
+ at: number,
+ delta: number,
+ limit: number,
+): [number, number] => {
+ const lo = Math.max(0, Math.min(Math.round(start), Math.round(end)));
+ const hi = Math.max(lo, Math.max(Math.round(start), Math.round(end)));
+ const point = Math.max(0, Math.round(at) - 1);
+ const step = Math.round(delta);
+ if (step === 0) return clampChartAxis(lo, hi, limit);
+
+ if (step > 0) {
+ if (point <= lo) return clampChartAxis(lo + step, hi + step, limit);
+ if (point <= hi) return clampChartAxis(lo, hi + step, limit);
+ return clampChartAxis(lo, hi, limit);
+ }
+
+ const count = -step;
+ const afterBand = point + count;
+ const hasBefore = lo < point;
+ const hasAfter = hi >= afterBand;
+ const nextLo = hasBefore ? lo : hasAfter ? Math.max(lo, afterBand) - count : point;
+ const nextHi = hasAfter ? hi - count : hasBefore ? Math.min(hi, point - 1) : point;
+ return clampChartAxis(nextLo, nextHi, limit);
+};
+
+/**
+ * Re-anchor a chart after Sheet structure changes. This is pure document arithmetic: callers save
+ * the returned range, while render and scroll continue to derive the current pixel box from it.
+ */
+export const chartRangeAfterStructure = (
+ range: SheetChartRange,
+ op: SheetChartStructure,
+ extent: { cols: number; rows: number },
+): SheetChartRange => {
+ if (op.axis === "col") {
+ const [col0, col1] = chartAxisAfterStructure(
+ range.col0, range.col1, op.at, op.delta, extent.cols,
+ );
+ return { ...range, col0, col1 };
+ }
+ const [row0, row1] = chartAxisAfterStructure(
+ range.row0, range.row1, op.at, op.delta, extent.rows,
+ );
+ return { ...range, row0, row1 };
+};
+
/**
* ⛔ THE FOUR THE SHARED VIZ RENDERER DRAWS, WHICH IS NO LONGER THE SAME QUESTION AS WHAT THE
* SERVER STORES. Every one of {@link SheetChartSpec.kind}'s eight names round trips (W54-T09);
diff --git a/web/src/shell/ShareDialog.tsx b/web/src/shell/ShareDialog.tsx
index 55137fd24adc9bb9b727952aacba8416a7d113af..93341935f97335d63385d4ed37ac41dd0ae2b3c4 100644
--- a/web/src/shell/ShareDialog.tsx
+++ b/web/src/shell/ShareDialog.tsx
@@ -12,15 +12,19 @@
// `shareModel.ts`, where the access gate can run it.
// ---------------------------------------------------------------------------
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { API_V1, CREDENTIALS } from "../apiContract";
import PublishPanel from "../publish/PublishPanel";
+import { useEscapeClose } from "../ui/useEscapeClose";
import {
+ EVERYONE,
+ EVERYONE_LABEL,
SHARE_ROLES,
addablePeople,
parseShare,
+ resolveShareRecipient,
+ shareAccessStatus,
sharePutBody,
- shareSummary,
withEntry,
withoutEntry,
} from "./shareModel";
@@ -230,8 +234,10 @@ export default function ShareDialog({
const [entries, setEntries] = useState([]);
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
- const [pick, setPick] = useState("");
+ const [recipientQuery, setRecipientQuery] = useState("");
const [pickRole, setPickRole] = useState("view");
+ const dialogRef = useRef(null);
+ const focusReturnRef = useRef(null);
// W42-T26 — the RESULT half: what the last successful save actually granted, and what it
// refused. Empty until a save answers, and empty again whenever one answers without the keys.
const [sharedFields, setSharedFields] = useState([]);
@@ -244,6 +250,17 @@ export default function ShareDialog({
const path = `${API_V1}/share/${encodeURIComponent(kind)}/${encodeURIComponent(id)}`;
+ useEffect(() => {
+ focusReturnRef.current = document.activeElement instanceof HTMLElement
+ ? document.activeElement
+ : null;
+ dialogRef.current?.focus();
+ return () => {
+ const opener = focusReturnRef.current;
+ if (opener?.isConnected) opener.focus();
+ };
+ }, []);
+
useEffect(() => {
let dead = false;
setError("");
@@ -298,15 +315,11 @@ export default function ShareDialog({
};
}, [path]);
- // ⛔ ESCAPE CLOSES A MODAL, or its scrim becomes a trap — the wave-18 lesson this
- // shell already carries at its other two dialogs.
- useEffect(() => {
- const onKey = (e: KeyboardEvent) => {
- if (e.key === "Escape" && !busy) onClose();
- };
- window.addEventListener("keydown", onKey);
- return () => window.removeEventListener("keydown", onKey);
- }, [busy, onClose]);
+ // The Share modal joins the one overlay stack. A local key listener races any picker or
+ // nested publish control mounted inside it and can close two surfaces from one Escape.
+ useEscapeClose(true, () => {
+ if (!busy) onClose();
+ }, { container: () => dialogRef.current });
const save = useCallback(
async (next: ShareEntry[]) => {
@@ -378,6 +391,10 @@ export default function ShareDialog({
finally { setBusy(false); }
}, [path, onToast]);
const options = state ? addablePeople(state.people, entries) : [];
+ const pick = state
+ ? resolveShareRecipient(state.people, entries, recipientQuery)
+ : null;
+ const canAddEveryone = !entries.some((entry) => entry.user === EVERYONE);
const nameOf = (user: string) =>
user === "*"
? "Everyone"
@@ -386,11 +403,14 @@ export default function ShareDialog({
: state?.people.find((p) => p.user === user)?.name ?? user;
return (
- (busy ? null : onClose())}>
+
e.stopPropagation()}
>
Share {KIND_WORD[kind]}
@@ -452,7 +472,10 @@ export default function ShareDialog({
question people open this for is "who has this already" — with the
one-line answer above it, since the fact that changes everything
("Everyone can edit") is the one a list of rows buries. */}
- {shareSummary(entries)}
+ Manage access
+
+ Workspace access: {shareAccessStatus(entries)}.
+
{/* ⭐⭐ W42-T26 / C7 — THE RESULT: which fields actually travelled, and which could not,
each with the reason the SERVER gave. Absent both keys this renders nothing at all
so an older server remains compatible.
@@ -556,26 +579,23 @@ export default function ShareDialog({
{mayAdminister ? (
- setPick(e.target.value)}
- >
- {/* ⚠ An explicit placeholder OPTION, not a blank first row: a
- whose value matches nothing renders its first option
- while holding "", so the box would read as a chosen person and
- the button beside it would grant somebody nobody picked
- ([[cg-condition-builder-items]]). */}
- Choose a person…
- Everyone in this workspace
+ aria-label="Search people to share with"
+ placeholder="Search people"
+ autoFocus
+ onChange={(e) => setRecipientQuery(e.target.value)}
+ />
+
+ {canAddEveryone ? : null}
{options.map((p) => (
-
- {p.name}
-
+
))}
-
+
{
+ if (!pick) return;
const next = withEntry(entries, pick, pickRole);
setEntries(next);
void save(next).then((ok) => {
@@ -606,12 +627,12 @@ export default function ShareDialog({
? `${nameOf(pick)} can now ${pickRole === "edit" ? "edit" : "view"} this field.`
: `${nameOf(pick)} can now ${pickRole} this ${KIND_WORD[kind]}.`
);
- setPick("");
+ setRecipientQuery("");
}
});
}}
>
- Share
+ Send
{ROLE_BLURB[kind][pickRole]}
{/* ⛔ W33-T30 / audit S-5 — `*` + `edit` IS A TENANT-WIDE WRITE GRANT AND LOOKED
@@ -631,7 +652,7 @@ export default function ShareDialog({
JSX pass skips any run containing a newline [[web-prose-blind-to-wrapped-jsx]].
REWRITTEN, not merely stripped — the comma keeps the contrast the sentence
exists to draw. */}
- {pick === "*" && pickRole === "edit" ? (
+ {pick === EVERYONE && pickRole === "edit" ? (
Everyone in this workspace will be able to change this {KIND_WORD[kind]},
not just open it.
@@ -669,7 +690,10 @@ export default function ShareDialog({
nothing if not — so "absent on non-interface views" is one evaluator, not two. */}
{kind === "view" && topic ? : null}
- {error ? {error} : null}
+ {error ? {error} : null}
+
+ Close
+
);
diff --git a/web/src/shell/Shell.tsx b/web/src/shell/Shell.tsx
index 40b73fc41423b39a836183961e87c5af55668a43..83ad95cded06a12c7dda1b0efdd17e6b3731e91e 100644
--- a/web/src/shell/Shell.tsx
+++ b/web/src/shell/Shell.tsx
@@ -48,7 +48,7 @@ import "./shell.css";
⚠ AND `npx tsc --noEmit` DID NOT CATCH IT — only `npm run build`'s `tsc -b` did. The two are not
the same check here; a lane that runs the first and skips the second gets a false green on every
symbol it orphans. */
-import type { MouseEvent as ReactMouseEvent, ReactNode } from "react";
+import type { MouseEvent as ReactMouseEvent, ReactNode, RefObject } from "react";
/**
* ⭐ WAVE-27 item 34 (I5) — ROUTE-LEVEL CODE SPLITTING.
*
@@ -78,6 +78,7 @@ import { clearCustomersCache, currentSurfaceScope } from "../customer-grid/apiBr
import { OverlayProvider } from "../customer-grid/OverlaySurface";
import { dataPathHash, readDataPath } from "../customer-grid/dataPath";
import type { DataDatabase } from "../customer-grid/dataPath";
+import "../styles/wave55/apps.css";
// ROWS_STALE_EVENT left with `addRecord` (wave 20 item 4): the shell no longer writes rows,
// so it no longer has to tell the grid that it did.
import { AGENTS_CHANGED, API_V1, AUTOMATION_OPEN_EVENT, CREDENTIALS, DATA_ERROR_EVENT, NAV_MINIMIZE_EVENT, TOAST_EVENT, UNAUTHORIZED_EVENT, VIEW_OPEN_EVENT, signal } from "../apiContract";
@@ -88,21 +89,20 @@ import type { SettingsSection } from "../settings/SettingsModal";
import { Brand } from "./Brand";
import { ErrorBoundary } from "./ErrorBoundary";
import LoginPage from "./LoginPage";
-import { ASSISTANT_ROUTE, CONNECTORS_ROUTE, EMPTY_NAV_PREFS, ENVELOPE_KEYS, FEEDBACK_ROUTE, HOME_ROUTE, INBOX_ROUTE, NO_SUBSCRIPTION_TENANT, STARRED_ROUTE, SUBSCRIPTION_ROUTE, USAGE_ROUTE, MAX_NAV_FOLDERS, NAV_STAYS_EXPANDED_ROUTES, NAV_TIMEOUT_STATUS, appLink, canonicalRoute, databaseEntries, defaultRoute, deleteTable, fetchNav, fetchNavPrefs, fetchTableFootprint, hasVisibleRailSlot, postOpened, QUERY_ROUTE, resolveRoute, rewrittenHash, routeKeyOf, saveNavMeta, saveNavPrefs, shapeNav, splitChrome } from "./nav";
-import type { NavEntry, NavMetaPatch, NavPage, NavPrefs, RailSlot, Recent } from "./nav";
+import { APP_ROUTE, ASSISTANT_ROUTE, CONNECTORS_ROUTE, EMPTY_NAV_PREFS, ENVELOPE_KEYS, FEEDBACK_ROUTE, HOME_ROUTE, INBOX_ROUTE, NO_SUBSCRIPTION_TENANT, SUBSCRIPTION_ROUTE, USAGE_ROUTE, MAX_NAV_FOLDERS, NAV_MALFORMED_STATUS, NAV_STAYS_EXPANDED_ROUTES, NAV_TIMEOUT_STATUS, appLink, canonicalRoute, databaseEntries, defaultRoute, deleteTable, fetchNav, fetchNavPrefs, fetchSchema, fetchTableFootprint, postOpened, QUERY_ROUTE, resolveRoute, rewrittenHash, routeKeyOf, saveNavMeta, saveNavPrefs, shapeNav, splitChrome } from "./nav";
+import type { NavEntry, NavMetaPatch, NavPage, NavPrefs, RailSlot, Recent, SchemaField, SchemaPayload } from "./nav";
// ⭐ 2026-08-14 — the database frame, extracted so the Query module can wear the SAME one.
// ⛔ W53-T35 — `DbIcon` IS NO LONGER IMPORTED HERE. The Data row wears `icons.tsx::DatabaseIcon`
// (owner instruction 26: the Home page's cylinder is the correct one), and `dbFrame.tsx` keeps
// exporting `DbIcon` for `query/queryParts.tsx`, which still draws the coin stack. Only
// `gridScopeFor` is read from this module now.
import { gridScopeFor } from "./dbFrame";
-/* ⭐ W35-T09 — the app's own star (B-3): one mark, one meaning (DESIGN.md §4). */
-import { StarIcon } from "../ui/icons";
// W51-T31 — the shell's overlays join the ONE Escape stack (C8 / DESIGN.md §4). Every
// registration below is gated on that overlay's OWN open flag, never on `true`: the arbiter
// preventDefaults and stops propagation on a claimed Escape, and Escape is also the browser's
// cancel-this-drag key for the rail's folder drag-and-drop.
import { useEscapeClose } from "../ui/useEscapeClose";
+import { useApplicationWizardOverlay } from "./useApplicationWizardOverlay";
/* ⭐ W35-T09 — the assistant's EXISTING door for opening an AI-built view: hash + a retry
ladder, returning a canceller. A second emit here would be a second answer. */
import { openBuiltView } from "../assistant/AssistantPage";
@@ -131,8 +131,6 @@ const ConnectorsPage = lazy(() => import("../connectors/ConnectorsPage"));
*/
import { SHEET_ROUTE } from "../sheet";
const SheetPage = lazy(() => import("../sheet/SheetPage"));
-/* ⭐ WAVE 35 · T09 (wiring W1) — the Starred surface, session B's tree. */
-const StarredPage = lazy(() => import("../starred/StarredPage"));
/* ⭐ WAVE 35 · T06 (contract C6, wiring W2) — the three account surfaces, session B's tree. Lazy
like every other page here: none of them is on the path to first paint, and all three are behind
a menu the user has to open. Default exports, as B published them — `lazy()` over a NAMED export
@@ -244,6 +242,349 @@ function Lazily({ children, surface }: { children: ReactNode; surface: string })
);
}
+type ApplicationTemplateKind = "route" | "catalog";
+
+interface ApplicationTemplateRole {
+ key: string;
+ label: string;
+ required: boolean;
+ types: string[];
+}
+
+interface ApplicationTemplate {
+ kind: ApplicationTemplateKind;
+ label: string;
+ applicationType: "route" | "map";
+ displayMode: "map";
+ fieldRoles: ApplicationTemplateRole[];
+ defaultPlacement: { section: "app"; order: number };
+}
+
+interface CreatedTemplateApplication {
+ id: string;
+ name: string;
+ type: string;
+ templateKind: ApplicationTemplateKind;
+ sourceDatabase: string;
+ fieldMap: Record ;
+ openTarget?: { database?: string };
+}
+
+type WizardLoad =
+ | { phase: "idle" }
+ | { phase: "loading" }
+ | { phase: "ready"; value: T }
+ | { phase: "error"; message: string };
+
+function TemplateRouteIcon() {
+ return (
+
+
+
+
+
+ );
+}
+
+function TemplateCatalogIcon() {
+ return (
+
+
+
+
+ );
+}
+
+function ApplicationWizard({
+ databases,
+ panelRef,
+ onClose,
+ onBusyChange,
+ onCreated,
+}: {
+ databases: DataDatabase[];
+ panelRef: RefObject;
+ onClose: () => void;
+ onBusyChange: (busy: boolean) => void;
+ onCreated: (application: CreatedTemplateApplication) => void;
+}) {
+ const [step, setStep] = useState(0);
+ const [templates, setTemplates] = useState>({ phase: "loading" });
+ const [templateKind, setTemplateKind] = useState("");
+ const [sourceDatabase, setSourceDatabase] = useState("");
+ const [schema, setSchema] = useState>({ phase: "idle" });
+ const [fieldMap, setFieldMap] = useState>({});
+ const [name, setName] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const schemaGeneration = useRef(0);
+
+ useEffect(() => {
+ const controller = new AbortController();
+ setTemplates({ phase: "loading" });
+ void fetch(`${API_V1}/nav/application-templates`, {
+ credentials: CREDENTIALS,
+ signal: controller.signal,
+ }).then(async (response) => {
+ const body = await response.json().catch(() => ({}));
+ if (!response.ok) throw new Error(String(
+ body?.detail?.message ?? body?.detail ?? "Application templates could not be loaded.",
+ ));
+ const offered = Array.isArray(body?.templates)
+ ? body.templates.filter((row: unknown): row is ApplicationTemplate => {
+ if (!row || typeof row !== "object" || Array.isArray(row)) return false;
+ const candidate = row as Partial;
+ return (candidate.kind === "route" || candidate.kind === "catalog") &&
+ Array.isArray(candidate.fieldRoles) && !!candidate.defaultPlacement;
+ })
+ : [];
+ if (!offered.length) throw new Error("No Application templates are available.");
+ if (!controller.signal.aborted) setTemplates({ phase: "ready", value: offered });
+ }).catch((reason: unknown) => {
+ if (!controller.signal.aborted) setTemplates({
+ phase: "error",
+ message: reason instanceof Error ? reason.message : "Application templates could not be loaded.",
+ });
+ });
+ return () => controller.abort();
+ }, []);
+
+ useEffect(() => {
+ onBusyChange(busy);
+ return () => onBusyChange(false);
+ }, [busy, onBusyChange]);
+
+ useEffect(() => {
+ const mine = ++schemaGeneration.current;
+ if (!sourceDatabase) {
+ setSchema({ phase: "idle" });
+ return;
+ }
+ setSchema({ phase: "loading" });
+ void fetchSchema(sourceDatabase).then((answer) => {
+ if (mine !== schemaGeneration.current) return;
+ setSchema(answer
+ ? { phase: "ready", value: answer }
+ : { phase: "error", message: "The database fields could not be loaded." });
+ });
+ return () => { schemaGeneration.current += 1; };
+ }, [sourceDatabase]);
+
+ useApplicationWizardOverlay(panelRef, onClose);
+
+ const template = templates.phase === "ready"
+ ? templates.value.find((candidate) => candidate.kind === templateKind) ?? null
+ : null;
+ const mappedLatitude = fieldMap.latitude ?? "";
+ const mappedLongitude = fieldMap.longitude ?? "";
+ const missingRequired = template?.fieldRoles.some(
+ (role) => role.required && !String(fieldMap[role.key] ?? "").trim(),
+ ) ?? true;
+ const coordinatePairError = templateKind === "route" && (
+ Boolean(mappedLatitude) !== Boolean(mappedLongitude) ||
+ Boolean(mappedLatitude && mappedLongitude && mappedLatitude === mappedLongitude)
+ );
+ const canContinue = step === 0
+ ? !!template
+ : step === 1
+ ? !!sourceDatabase && schema.phase === "ready"
+ : step === 2
+ ? !missingRequired && !coordinatePairError
+ : !!name.trim();
+
+ const chooseTemplate = (candidate: ApplicationTemplate) => {
+ setTemplateKind(candidate.kind);
+ setName(candidate.label);
+ setFieldMap({});
+ setError("");
+ };
+
+ const createApplication = async () => {
+ if (!template || schema.phase !== "ready" || !canContinue || busy) return;
+ setBusy(true);
+ setError("");
+ const mapped = Object.fromEntries(
+ Object.entries(fieldMap).filter(([, value]) => String(value).trim()),
+ );
+ try {
+ const response = await fetch(`${API_V1}/nav/applications`, {
+ method: "POST",
+ credentials: CREDENTIALS,
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ name: name.trim(),
+ templateKind: template.kind,
+ type: template.applicationType,
+ sourceDatabase,
+ fieldMap: mapped,
+ navPlacement: template.defaultPlacement,
+ }),
+ });
+ const body = await response.json().catch(() => ({}));
+ if (!response.ok || !body?.application?.id) {
+ throw new Error(String(
+ body?.detail?.message ?? body?.detail ?? "The Application was not saved.",
+ ));
+ }
+ onCreated(body.application as CreatedTemplateApplication);
+ } catch (reason: unknown) {
+ setError(reason instanceof Error ? reason.message : "The Application was not saved.");
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const headings = ["Choose a template", "Choose a database", "Map the fields", "Review and create"];
+ return (
+
+
+
+
+ New Application
+ {headings[step]}
+
+
+
+
+
+
+ {["Template", "Database", "Fields", "Review"].map((label, index) => (
+
+ {index + 1} {label}
+
+ ))}
+
+
+
+ {step === 0 ? (
+ templates.phase === "loading" ? (
+
+
+
+ ) : templates.phase === "error" ? (
+ {templates.message}
+ ) : templates.phase === "ready" ? (
+
+ {templates.value.map((candidate) => (
+ chooseTemplate(candidate)}
+ >
+
+ {candidate.kind === "route" ? : }
+
+ {candidate.label}
+ {candidate.kind === "route"
+ ? "Plan customer routes from mapped records."
+ : "Browse mapped records as a visual catalog."}
+
+
+ ))}
+
+ ) : null
+ ) : null}
+
+ {step === 1 ? (
+
+ Source database
+ {
+ setSourceDatabase(event.target.value);
+ setFieldMap({});
+ setError("");
+ }}>
+ Choose a database
+ {databases.map((database) => {database.label} )}
+
+ {schema.phase === "loading" ? Loading database fields... : null}
+ {schema.phase === "error" ? {schema.message} : null}
+
+ ) : null}
+
+ {step === 2 && template && schema.phase === "ready" ? (
+
+ Map each Application role to a field in {schema.value.label}.
+ {template.fieldRoles.map((role) => {
+ const options = schema.value.fields.filter((field) =>
+ !role.types.length || role.types.includes(field.type.toLowerCase()),
+ );
+ return (
+
+ {role.label}{role.required ? Required : Optional }
+ {
+ setFieldMap((current) => ({ ...current, [role.key]: event.target.value }));
+ setError("");
+ }}>
+ {role.required ? "Choose a field" : "Not mapped"}
+ {options.map((field: SchemaField) => (
+ {field.label}
+ ))}
+
+
+ );
+ })}
+ {coordinatePairError ? (
+
+ Routing needs both coordinate fields or neither, and they must be different.
+
+ ) : null}
+
+ ) : null}
+
+ {step === 3 && template ? (
+
+
+ Application name
+ { setName(event.target.value); setError(""); }} />
+
+
+
Template {template.label}
+
Database {schema.phase === "ready" ? schema.value.label : sourceDatabase}
+ {template.fieldRoles.filter((role) => fieldMap[role.key]).map((role) => (
+
{role.label} {
+ schema.phase === "ready"
+ ? schema.value.fields.find((field) => field.key === fieldMap[role.key])?.label ?? fieldMap[role.key]
+ : fieldMap[role.key]
+ }
+ ))}
+
+ This saves an Application definition in App and opens it with the selected database.
+
+ ) : null}
+
+
+ {error}
+
+
+
+
+ Cancel
+
+ {step > 0 ? (
+ { setStep((current) => current - 1); setError(""); }} disabled={busy}>Back
+ ) : null}
+ {step < 3 ? (
+ { setStep((current) => current + 1); setError(""); }}>Continue
+ ) : (
+ void createApplication()}>{busy ? "Creating..." : "Create and open"}
+ )}
+
+
+
+ );
+}
+
import { createAlert, fetchInbox } from "../alerts/alertsApi";
import {
ALERT_CREATE_EVENT,
@@ -364,7 +705,7 @@ type Nav =
/** ⛔ W31-T11 — parts of the payload the SERVER could not read. Not deliberate. */
degraded?: string[];
}
- | { phase: "error"; timedOut?: boolean };
+ | { phase: "error"; timedOut?: boolean; malformed?: boolean };
const NO_UTILITY: NavPage[] = [];
/** Stable identity, like `NO_ENTRIES` — a fresh `[]` per render would re-run Home's memo. */
@@ -440,15 +781,15 @@ const findAutomation = (entries: NavEntry[]) =>
* `degraded` are UNCHANGED: they draw the real rows with their unavailable arms, because there
* the answer has arrived and is bad news, which is a fact worth showing rather than a wait.
*
- * ⚠ The count is the rail's own maximum, not a guess. WAVE 34 R15/R23 took it from 7 to **6**:
- * Home · Inbox · Assistant · Agents · Database · Connectors. Query lost its row to the Chat/Query
- * toggle (R14), and there was never a seventh "Alerts" row — Inbox IS that surface.
+ * ⚠ The count is the rail's own maximum, not a guess. WAVE 55 instruction 2 fixes it at **8**:
+ * Home · Inbox · Assistant · Sheet · Data · Agents · App · Connectors. Starred moved into Home's
+ * filter, while App became the tenant Application directory.
* ⛔ KEEP THIS NUMBER >= THE SETTLED ROW COUNT AND NEVER BELOW IT. A skeleton one bar TALLER than
* the settled rail is a shrink, which is fine; one bar SHORTER is the appear-from-nowhere shove
* W33-T22 was written about, arriving by a different door. The two `.shell-nav-sep` hairlines are
* deliberately NOT counted: they are hidden by the same `is-rail-loading` rule as the rows.
*/
-const RAIL_SKELETON_ROWS = 6;
+const RAIL_SKELETON_ROWS = 8;
function RailSkeleton() {
return (
@@ -797,6 +1138,16 @@ function SheetIcon() {
);
}
+/** Tenant Apps: one window with four arranged parts, in the shell's existing stroke register. */
+function AppIcon() {
+ return (
+
+
+
+
+ );
+}
+
/** ⭐ WAVE 35 · T05 (owner item 6) — Templates. Owner, of Airtable's rail: *"a 'Templates and apps'
* section? I want our app to have it too but just call it Templates ... located just above our
* User button."* A sheet of cards, which is what a template gallery is: one outlined page with a
@@ -1552,7 +1903,8 @@ function ShellFrame() {
// conflating them would leave a signed-out user staring at a frame.
else if (r.status === 401) setSession({ phase: "anon" });
else setNav({ phase: "error",
- ...(r.status === NAV_TIMEOUT_STATUS ? { timedOut: true } : {}) });
+ ...(r.status === NAV_TIMEOUT_STATUS ? { timedOut: true } : {}),
+ ...(r.status === NAV_MALFORMED_STATUS ? { malformed: true } : {}) });
});
return () => {
dead = true;
@@ -1950,26 +2302,27 @@ function ShellFrame() {
// doc): the anon render mounted N hooks, the authed render mounted N+5, and React refuses
// a component whose hook count changes between renders. Every hook in this component stays
// above `if (session.phase …) return`, whatever lands here next wave.
- // (owner item 3): the assistant's under-construction note.
- // ⭐ WAVE 24 item 14 — it carries WHICH boarded door was knocked on, not just "open". Two
- // surfaces are now under construction (the assistant, and Home's templates card) and they are
- // the same dialog with a different sentence — a second near-identical modal would be the
- // "variety is a defect" failure, and a shared one that could not say which door you came
- // through would tell a reader about the wrong feature.
- /** ⭐ 2026-08-14 — `"assistant"` LEFT THIS UNION. The assistant is a route now, so the only
- * boarded door left behind this state is Templates. Narrowing the type rather than leaving the
- * dead member is what makes `setAssistOpen("assistant")` a compile error instead of a screen
- * nobody meant to be reachable. */
+ /** Templates, Home and App all open this one creation flow. The narrow state keeps unrelated
+ * overlays from drifting into the Application wizard. */
const [assistOpen, setAssistOpen] = useState(false);
- // ⛔ ESCAPE CLOSES A MODAL, or its scrim becomes a trap. The assistant note shipped with only
- // a scrim-click and a Close button, and the first close-out probe to press Escape found every
- // subsequent click swallowed by an invisible full-screen div — the
- // painted-but-unclickable failure [[ui-invisible-to-assertions]] names, in reverse. The
- // new-database dialog had Escape only while its INPUT held focus, which is not the same thing.
- //
- // W51-T31 — the registrations moved BELOW `newDb`'s declaration and onto `useEscapeClose`.
- // The window listener that used to sit here closed BOTH dialogs on one press, because it was
- // one handler reading two flags; the shared stack resolves to the topmost overlay instead.
+ const appWizardRef = useRef(null);
+ const appWizardBusy = useRef(false);
+ const openApplicationWizard = useCallback(() => {
+ setAssistOpen("templates");
+ }, []);
+ const closeApplicationWizard = useCallback(() => {
+ if (appWizardBusy.current) return;
+ setAssistOpen(false);
+ }, []);
+ const setApplicationWizardBusy = useCallback((busy: boolean) => {
+ appWizardBusy.current = busy;
+ }, []);
+ const launchCreatedApplication = useCallback((application: CreatedTemplateApplication) => {
+ appWizardBusy.current = false;
+ setAssistOpen(false);
+ const database = application.openTarget?.database || application.sourceDatabase;
+ window.location.hash = dataPathHash({ database, application: application.id });
+ }, []);
// (C3-UT): "+ New database" + the user-table Add-record bar.
//
// WAVE 23 C10 — the dialog grew a `mode`: blank, or from a template.
@@ -1987,8 +2340,8 @@ function ShellFrame() {
}>(null);
const newDbOpenRef = useRef(false);
newDbOpenRef.current = newDb !== null;
- // W51-T31 — the two shell dialogs, each its own entry on the ONE Escape stack.
- useEscapeClose(assistOpen !== false, () => setAssistOpen(false));
+ // ApplicationWizard joins the shared overlay layer itself so focus trap, restoration and
+ // Escape ordering are one contract. The older database dialog still needs this direct claim.
// ⛔ The busy guard is the same one the scrim keeps: a create already in flight is not
// cancellable, so Escape must leave the dialog standing rather than orphan the request.
useEscapeClose(newDb !== null, () => setNewDb((cur) => (cur && cur.busy ? cur : null)));
@@ -2294,6 +2647,13 @@ function ShellFrame() {
* about when the nav is settled [[one-question-two-normalizers]].
*/
const railLoading = nav.phase === "loading" || nav.phase === "idle";
+ const navFailureMessage = nav.phase !== "error"
+ ? ""
+ : nav.timedOut
+ ? "Navigation took too long to load. Try again."
+ : nav.malformed
+ ? "Navigation data could not be read. Try again."
+ : "Navigation unavailable. Try again.";
const railSlot = (present: boolean): RailSlot =>
present
? "row"
@@ -2304,10 +2664,6 @@ function ShellFrame() {
: "absent";
const automationSlot: RailSlot = railSlot(!!automation);
const analystSlot: RailSlot = railSlot(!!analyst);
- // C9: decide whether the AI section exists before rendering either separator.
- // A granted/unavailable module gets its normal group framing; known absence gets
- // neither a row nor vertical geometry, so Data follows Inbox without a dead band.
- const aiRailVisible = hasVisibleRailSlot([analystSlot, automationSlot]);
// WAVE 23 C10 — the flyout's search. A plain label substring, case-folded: this list is at
// most a few dozen rows, so anything cleverer (fuzzy, ranked) would be a scoring function
// nobody can predict over a set small enough to read.
@@ -2466,29 +2822,6 @@ function ShellFrame() {
Home
- {/* ⭐⭐ WAVE 35 · T09 (owner item 8, R4) — STARRED, directly under Home. Owner: *"Let's add
- a button under 'Home' called 'Starred' … only for Database/Agents/Queries/Marked
- important that the user has marked."*
- ⚠ IT TAKES THE SLOT INBOX HELD. Wave-34 R23 put Inbox *"right below Home"*; owner item
- 8 is later and explicit about this position, so Inbox moves down one. Both rulings are
- obeyed in their own order rather than one being quietly dropped.
- ⭐ THE SHARED `StarIcon`, not a fourth hand-drawn star (B-3). It is already the app's
- star — the view menu's and the grid's — and "one mark, one meaning" is DESIGN.md §4.
- ⚠ `nav.ts::CHROME_ROUTES` is what lets this render with no grant: the page lists only
- objects the caller was already given, so it shows nothing the server did not send. */}
-
-
- Starred
-
-
{/* ⭐⭐ WAVE 34 R15 + R23 — INBOX MOVED UP, directly under Home, and took a MAIL icon.
Owner, 2026-08-16: *"Home/Inbox (change the inbox logo to a mail icon) then a subtle
line separation. Then Assistant / Agents"* and, correcting the planner minutes later,
@@ -2521,16 +2854,7 @@ function ShellFrame() {
) : null}
- {/* The AI-group hairlines exist only when a settled Assistant or Agents slot is visible.
- A known-absent module is not a row and cannot leave a divider band behind it; an
- unavailable slot remains visible and therefore retains the honest group boundary.
- This stays a DIRECT CHILD of `.shell-nav`, so the whole-rail loading skeleton still
- hides it with every real row. */}
- {aiRailVisible ? (
-
- ) : null}
-
- {/* The Analyst slot, above the database list — the host's own IA
+ {/* The Analyst slot closes the first rail group: Home / Inbox / Assistant.
(app.py:8166 pins "AI assistant" over the nav tree, same label,
same sparkle). Wave 18 (owner item 3): the hand-off into Streamlit
is PAUSED — the click opens an in-app "under construction" note
@@ -2572,8 +2896,8 @@ function ShellFrame() {
@@ -2593,6 +2917,11 @@ function ShellFrame() {
/>
)}
+ {/* WAVE 55 instruction 2: the first group is complete even when Assistant is absent.
+ Home and Inbox remain real rows, so this boundary is stable rather than permission
+ dependent. */}
+
+
{/* ⛔ THE "AI agent" ROW WAS HERE AND IS DELETED (owner, 2026-08-14): *"AI assistant
module IS AI agent module. So no need to separate it like that."* Wave 33's own note
on this row had already argued the collapse and deferred it as ASK C-9 because
@@ -2616,78 +2945,9 @@ function ShellFrame() {
Found again at the close-out dead-code sweep, which greps every deleted symbol and
reads each survivor: this one was a stale CLAIM rather than a live caller. */}
- {/* WAVE 19 R10 / C3 — Automation, now AGENTS. An ` ` to the route it already had: the
- surface, its rail and its editor are another session's tree this wave and
- are not touched by any of this. The LABEL comes off the payload, never a
- literal here — the registry owns what this surface is called, and a client
- that hard-codes the word is the drift that outlives the row. */}
- {automation ? (
-
- {/* ⭐⭐ WAVE 51 · T30 (R15) — THE FLOW GLYPH, UNCONDITIONALLY.
- ⚠ THE MARK CHANGED, THE RULE DID NOT. W35-T04 shipped `RobotIcon` here on owner
- item 5 (*"let's just have it look like a robot"*); R15 replaces it with a
- two-node flow mark. What survives verbatim from that ticket, and what the gate
- actually guards, is the UNCONDITIONAL part below.
- ⛔ THIS WAS `automation.icon ? FolderMark : RobotIcon`, AND THAT TERNARY IS THE
- WHOLE DEFECT — not a missing glyph. `RobotIcon` had existed since wave 34 R15 and
- simply LOST: on any tenant that had ever chosen a mark for `automation`, the
- chosen coloured chip won and the robot never painted. So the bug reads as "the
- icon is wrong" while the code looks like it already does the right thing, which
- is why owner items 2 and 5 turned out to share one cause.
- ⚠ The wave-23 R8 note this replaces argued Automation is among the databases that
- may carry a chosen icon. R8 is not revoked for DATABASES; what changed is that
- Agents is a MODULE — a fixed rail row like Home or Connectors — and a module's
- glyph is the product's, not the tenant's. `FolderMark` is still how every real
- database draws its chosen mark. */}
-
- {automation.label}
-
- ) : automationSlot === "unavailable" ? (
- /* ⛔ W31-T11 — NOT LOADING, AND NOT ABSENT-ON-PURPOSE: the server said this payload
- is incomplete (`degraded`), or it never answered. The row states that rather than
- leaving a gap the reader has to interpret — which is the whole of owner item 6b. */
-
- ) : (
- /* Mirror Assistant's zero-geometry absent arm: actual permission absence is silent;
- only an incomplete navigation response renders the unavailable row above. */
-
- )}
-
- {/* Close the AI group only when it rendered at least one real/unavailable row. */}
- {aiRailVisible ? (
-
- ) : null}
-
- {/* ⭐⭐ WAVE 49 · T01 (rulings R1, R2, R30) — SHEET, AT THE HEAD OF THE DATA BAND.
- R30 fixes the whole rail: Home · Starred · Inbox | Assistant · Agents | Sheet · Data ·
- Connectors. So this row stands AFTER the AI group's closing separator and IMMEDIATELY
- BEFORE the Data button, and `verify_shell_rail.py::data_band_faults` asserts both the
- order and the adjacency rather than trusting this comment.
+ {/* WAVE 55 instruction 2: Sheet starts the application-building group and remains an
+ unconditional chrome destination. It is followed by Data, Agents and App. The gate
+ reads rendered JSX with comments removed, so this note cannot satisfy the order.
⛔ AN ` ` LIKE CONNECTORS, UNCONDITIONAL, AND BOTH HALVES MATTER. A `` would
be the Data affordance's shape (it opens a panel over a server-sent list); Sheet is a
@@ -2759,6 +3019,58 @@ function ShellFrame() {
Data
+ {/* Agents stays permission-aware, but its literal position is now after Data. The label
+ still comes from the server registry when present; the unavailable arm names the
+ intended destination without inventing access. */}
+ {automation ? (
+
+
+ {automation.label}
+
+ ) : automationSlot === "unavailable" ? (
+
+ ) : (
+
+ )}
+
+
+
+ App
+
+
+
+
{/* ⭐ WAVE 23 item 10 (R8, contract C11, wiring W23-W3) — CONNECTORS.
⭐ WAVE 24 item 1 — it moved BELOW Database. R8 put it above; the owner's wave-24
order puts the two destinations that open panels-over-server-data (Database, then
@@ -2791,12 +3103,7 @@ function ShellFrame() {
surfaces the server never granted. */}
{nav.phase === "error" ? (
- {nav.timedOut
- ? /* ⭐ W31-T11 — A DEADLINE IS A DIFFERENT FACT FROM A DEAD SERVER, and it earns
- its own sentence: before this ticket `fetchNav` had no timeout at all, so
- this state was UNREACHABLE and the rail waited for ever. */
- "Navigation took too long to load. Reload to retry."
- : "Navigation unavailable. Reload to retry."}
+ {navFailureMessage}
) : null}
{/* ⛔ W31-T11 — A 200 THAT COULD NOT READ THE DATABASES SAYS SO. This is the case that
@@ -2820,11 +3127,9 @@ function ShellFrame() {
) : null}
- {/* ⭐⭐ WAVE 35 · T05 (owner item 6) — TEMPLATES, DIRECTLY ABOVE THE USER BUTTON.
- ⛔ IT OPENS THE SAME DOOR HOME'S CARD OPENS — `setAssistOpen("templates")`, the exact
- handler passed to Home as `onTemplates`. A second under-construction note would be a
- second answer to one question, and the two would drift the day either is replaced by a
- real picker.
+ {/* ⭐⭐ WAVE 35 · T05 (owner item 6) — TEMPLATES, DIRECTLY ABOVE THE USER BUTTON.
+ It opens the same Application wizard as Home and App, so the three entry points share
+ one template, database and field-mapping contract.
⛔ A SIBLING OF `.shell-side-bottom`, NOT A CHILD, and that is behavioural rather than
cosmetic: that band carries an `onClickCapture` which, while collapsed, swallows the
click and expands the rail instead (the account POPOVER cannot fit in a 56px strip).
@@ -2849,7 +3154,7 @@ function ShellFrame() {
// W53-T33 — instruction 6 says "any of the icon". Templates opens an OVERLAY rather
// than a route, and the rail expanding behind it is what every other row now does.
expandOnNavClick();
- setAssistOpen("templates");
+ openApplicationWizard();
}}
onMouseEnter={navCollapsed ? tipEnter("Templates") : undefined}
onMouseLeave={navCollapsed ? tipLeave : undefined}
@@ -3028,33 +3333,6 @@ function ShellFrame() {
) : active ? (
- ) : route === STARRED_ROUTE ? (
- // ⭐⭐ WAVE 35 · T09 (owner item 8, wiring W1) — the Starred surface, session B's tree.
- // ⛔ `dbEntries`, NOT `entries`, and B's own note says so for the same reason Home's does:
- // the Agents SURFACE is a granted nav entry with an href, so `entries` would draw it a
- // tile under the heading "Databases", beside the section listing what it contains. That
- // was a real wave-24 defect, found by LOOKING rather than by any gate.
- // ⛔ EVERY CALLBACK IS REQUIRED, never optional: an optional one the frame forgot to pass
- // degrades to "clicking a starred thing does nothing", which is indistinguishable from
- // "the feature was never built" and is red in no gate.
- // ⚠ `onOpenQuery` calls the assistant's EXISTING `openBuiltView`, which already does hash
- // + a retry ladder and returns a canceller — a second emit here would be a second answer
- // to one question. Cancel any ladder still running, as the view path does.
-
- {
- window.location.hash = "#/automation";
- signal(AUTOMATION_OPEN_EVENT, { autoId });
- }}
- onOpenQuery={(qid) => {
- viewEmitCancel.current?.();
- viewEmitCancel.current = openBuiltView(qid);
- }}
- onOpenView={openViewInDatabase}
- />
-
) : route === FEEDBACK_ROUTE ? (
// ⭐⭐ WAVE 35 · T06 (owner item 13, R8, contract C6, wiring W2) — the three account
// surfaces. All three take NO props, on purpose and per B's published contract: Usage
@@ -3215,6 +3493,9 @@ function ShellFrame() {
// true by construction, and the build door re-checks with the same wall regardless.
) : nav.phase === "ready" ? (
+ // WAVE 55: Home and App share one tile vocabulary. App is chrome and therefore reaches
+ // this fallback without inventing a granted nav entry; `mode` decides which directory
+ // the surface renders. Home remains the fallback for empty, stale and unknown hashes.
// ⭐ WAVE 23 item 9 (R7, C10) — HOME, AND IT IS THE FALLBACK RATHER THAN A ROUTE MATCH.
//
// ⛔ WHY `!active` AND NOT `route === HOME_ROUTE`. Three states have to land here and
@@ -3233,8 +3514,10 @@ function ShellFrame() {
// hero's create door, and its empty line carries the hero's sentence (HomePage's
// `home-empty`, which branches on `entries.length === 0` for exactly this reason).
// Booked as a dated amendment in the wave doc, since it moves an R4 surface.
-
+
setAssistOpen("templates")}
+ // Home's Templates card and App's Create new button share this wizard door.
+ onTemplates={openApplicationWizard}
onNewDatabase={() => openNewDb("blank")}
/* ⛔ `onAutomated` LEFT WITH THE CARD IT OPENED (wave 25 item 5a, R8). */
onConnectors={() => {
@@ -3268,6 +3548,10 @@ function ShellFrame() {
view opened from Home and the same view opened from Starred must not behave
differently, and two copies of "route then ask" is how they would. */
onOpenView={openViewInDatabase}
+ onOpenQuery={(qid) => {
+ viewEmitCancel.current?.();
+ viewEmitCancel.current = openBuiltView(qid);
+ }}
/>
) : nav.phase === "error" ? (
@@ -3279,8 +3563,15 @@ function ShellFrame() {
// Home above (which welcomes an empty workspace properly), so this is only ever the
// nav that FAILED, and the nested ternary that used to sort the two is gone.
- Nothing to show
- The navigation service did not answer. Reload to retry.
+ Navigation unavailable
+ {navFailureMessage}
+ setNavEpoch((epoch) => epoch + 1)}
+ >
+ Try again
+
) : (
// Still asking (`loading`, or the `idle` beat before the effect runs).
@@ -3295,32 +3586,14 @@ function ShellFrame() {
{/* The server's own confirmation of a write (X2's `toast`). In standalone
it is the ONLY feedback for the events whose effect the payload does
not yet echo back — cohort membership, list adds, folder moves. */}
- {/* Wave 18 (owner item 3): the boarded door.
- ⭐ 2026-08-14 — IT IS THE TEMPLATES DOOR ONLY NOW. The assistant arm is gone with the
- boarding: that surface exists (`#/assistant`), so an "under construction" note for it
- would be a lie about a working feature. Templates is a SEPARATE boarded door (wave 24
- item 14) and is deliberately left exactly as it was — the owner unblocked the assistant,
- not the template picker. */}
{assistOpen ? (
- setAssistOpen(false)}>
- e.stopPropagation()}
- >
- Templates
-
- Under construction. Curated template sets are being built and will open here in
- a later release.
-
-
- setAssistOpen(false)}>
- Close
-
-
-
-
+
) : null}
{/* Wave 18 (C3-UT): the New-database dialog. Scrim click cancels unless mid-create. */}
diff --git a/web/src/shell/nav.ts b/web/src/shell/nav.ts
index 415a859a59b60976a37ed1fd9dc22775c22ca862..969cbbcdfcab1d39681bfe325ab96dd58770fd7f 100644
--- a/web/src/shell/nav.ts
+++ b/web/src/shell/nav.ts
@@ -10,10 +10,11 @@
// one end, permission-filtered at the other.
//
// ⚠ THERE IS NO CLIENT-SIDE FALLBACK LIST, deliberately. If `/api/v1/nav`
-// fails, the shell renders an honest empty nav — never a hard-coded one. A
-// fallback would put surfaces on screen that the server never authorised, which
-// is precisely the fail-closed rule the wave is built on ("an undeclared
-// surface is denied"), and it would mask a broken API as a working one.
+// fails or answers with a malformed envelope, the shell renders a bounded retry
+// state, never a hard-coded list. A fallback would put surfaces on screen that
+// the server never authorised, which is precisely the fail-closed rule the wave
+// is built on ("an undeclared surface is denied"), and it would mask a broken API
+// as a working one.
//
// No `import.meta` here either: `appBase` is a PARAMETER so this module
// compiles and runs under node in `verify_login.py` (see session.ts).
@@ -375,6 +376,27 @@ export const NAV_TIMEOUT_MS = 20_000;
/** Our encoding for "the deadline passed", distinct from 0 (transport) and any HTTP status. */
export const NAV_TIMEOUT_STATUS = -1;
+/** Our encoding for "the server answered, but not with a readable navigation envelope". */
+export const NAV_MALFORMED_STATUS = -2;
+
+/**
+ * A readable nav envelope has a pages list whose every destination carries a nonblank key and
+ * label. Optional decoration on a valid destination may still be pruned by `parsePages`, but a
+ * malformed destination cannot disappear into a confident partial rail. An empty list remains
+ * valid because a newly provisioned tenant can legitimately have no destinations yet.
+ */
+export function isReadableNavEnvelope(body: unknown): boolean {
+ if (!body || typeof body !== "object" || Array.isArray(body)) return false;
+ const raw = (body as { pages?: unknown }).pages;
+ if (!Array.isArray(raw)) return false;
+ return raw.every((item) => {
+ if (!item || typeof item !== "object" || Array.isArray(item)) return false;
+ const page = item as { key?: unknown; label?: unknown };
+ return typeof page.key === "string" && !!page.key.trim()
+ && typeof page.label === "string" && !!page.label.trim();
+ });
+}
+
/**
* `{recents:[…]}` → the list, fail-closed. An entry with no key or an unreadable stamp is
* DROPPED rather than rendered at the epoch, which would file it under "Older" for ever and
@@ -463,10 +485,19 @@ export async function fetchNav(timeoutMs: number = NAV_TIMEOUT_MS): Promise = new Set([
HOME_ROUTE,
+ APP_ROUTE,
CONNECTORS_ROUTE,
INBOX_ROUTE,
QUERY_ROUTE,
ASSISTANT_ROUTE,
- STARRED_ROUTE,
FEEDBACK_ROUTE,
USAGE_ROUTE,
SUBSCRIPTION_ROUTE,
@@ -1306,9 +1345,10 @@ export const CHROME_ROUTES: ReadonlySet = new Set([
* ⭐⭐ WAVE 53 · T32 (ruling R1) — THE SURFACES WHERE THE NAV NEVER FOLDS ITSELF. Owner,
* instruction 3, verbatim: *"When user first open the app and they're at home. Make sure the
* navigation is unminimized."* and *"Never collapse on home or starred UNLESS the user click the
- * minmize navigation button of course. Also apply this for inbox module."*
+ * minmize navigation button of course. Also apply this for inbox module."* Starred is now a Home
+ * filter, so HOME_ROUTE carries that earlier reading-surface behavior for both Home states.
*
- * These three are READING surfaces: Home, Starred and Inbox are lists of places to go, and a rail
+ * These two are READING surfaces: Home and Inbox are lists of places to go, and a rail
* that folds itself while you are choosing where to go has taken away the very thing the page is
* for. Every other route is a WORK surface, where the fold buys screen for the work — W38-T04's
* unconditional cell-click fold is untouched there and stays exactly as ruling R9 left it.
@@ -1322,7 +1362,6 @@ export const CHROME_ROUTES: ReadonlySet = new Set([
*/
export const NAV_STAYS_EXPANDED_ROUTES: ReadonlySet = new Set([
HOME_ROUTE,
- STARRED_ROUTE,
INBOX_ROUTE,
]);
@@ -1345,6 +1384,7 @@ export const NAV_STAYS_EXPANDED_ROUTES: ReadonlySet = new Set([
*/
export const LEGACY_ROUTES: Readonly> = {
alerts: INBOX_ROUTE,
+ [STARRED_ROUTE]: HOME_ROUTE,
/**
* ⭐ 2026-08-14 — `#/ai-agent` was a REAL route for one wave (wave 33 shipped it, and the
* owner's *"remove that AI agent module completely"* retires it). Unlike `alerts` above, this
@@ -1384,6 +1424,7 @@ export const LEGACY_ROUTES: Readonly> = {
*/
export const REWRITTEN_ROUTES: Readonly> = {
[QUERY_ROUTE]: `${ASSISTANT_ROUTE}?mode=query`,
+ [STARRED_ROUTE]: `${HOME_ROUTE}?filter=starred`,
};
/**
diff --git a/web/src/shell/shareModel.ts b/web/src/shell/shareModel.ts
index baa7e7eeae83608b460a2f50a4c64bfaddedfafd..f682b2811394a731c5b6e44bae3fbf8cc2a41928 100644
--- a/web/src/shell/shareModel.ts
+++ b/web/src/shell/shareModel.ts
@@ -52,6 +52,8 @@ export type ShareRole = (typeof SHARE_ROLES)[number];
/** The wildcard entry: "everyone who can already open this surface". */
export const EVERYONE = "*";
+/** The human-facing choice for the wildcard. Kept beside its stored value so search and status agree. */
+export const EVERYONE_LABEL = "Everyone in this workspace";
export interface ShareEntry {
user: string;
@@ -176,6 +178,47 @@ export function addablePeople(people: SharePerson[], entries: ShareEntry[]): Sha
return people.filter((p) => !taken.has(p.user));
}
+/**
+ * Resolve the recipient search only after it names one unshared account exactly.
+ *
+ * The picker is a search input rather than a select, so a half-typed display name must never be
+ * treated as authority to grant access. Usernames, display names and the datalist's combined
+ * `name (username)` value are accepted; a duplicated display name remains unresolved until the
+ * username disambiguates it. The wildcard follows the same rule and disappears once granted.
+ */
+export function resolveShareRecipient(
+ people: SharePerson[],
+ entries: ShareEntry[],
+ query: string,
+): string | null {
+ const wanted = str(query).toLowerCase();
+ if (!wanted) return null;
+ const taken = new Set(entries.map((entry) => entry.user));
+ if (wanted === EVERYONE_LABEL.toLowerCase() && !taken.has(EVERYONE)) return EVERYONE;
+ const matches = people.filter((person) => {
+ if (taken.has(person.user)) return false;
+ const combined = `${person.name} (${person.user})`.toLowerCase();
+ return wanted === person.user || wanted === person.name.toLowerCase() || wanted === combined;
+ });
+ const users = [...new Set(matches.map((person) => person.user))];
+ return users.length === 1 ? users[0] : null;
+}
+
+/** The current AIOS workspace-access state, in the same vocabulary as the role controls. */
+export function shareAccessStatus(entries: ShareEntry[]): string {
+ const everyone = entries.find((entry) => entry.user === EVERYONE);
+ if (everyone) {
+ return everyone.role === "edit"
+ ? "Everyone in this workspace can edit"
+ : "Everyone in this workspace can view";
+ }
+ if (!entries.length) return "Restricted";
+ const editors = entries.filter((entry) => entry.role === "edit").length;
+ const shared = entries.length === 1 ? "Shared with 1 person" : `Shared with ${entries.length} people`;
+ if (!editors) return shared;
+ return `${shared}, ${editors} can edit`;
+}
+
/**
* One sentence naming who can reach this object, for the row that opens the
* editor. Never a count on its own: "3 people" reads as reassurance, and the
diff --git a/web/src/shell/useApplicationWizardOverlay.ts b/web/src/shell/useApplicationWizardOverlay.ts
new file mode 100644
index 0000000000000000000000000000000000000000..103ccbd2b8db95eaf857e1adcb61d54c054eb676
--- /dev/null
+++ b/web/src/shell/useApplicationWizardOverlay.ts
@@ -0,0 +1,18 @@
+import type { RefObject } from "react";
+
+import { useOverlayLayer } from "../customer-grid/OverlaySurface";
+
+/** The Application wizard's modal interaction contract, kept out of the shell frame itself. */
+export function useApplicationWizardOverlay(
+ panelRef: RefObject,
+ onDismiss: () => void,
+): void {
+ useOverlayLayer({
+ panelRef,
+ onDismiss,
+ dismissOnOutside: false,
+ initialFocus: ".app-wizard-close",
+ restoreFocus: true,
+ trapFocus: true,
+ });
+}
diff --git a/web/src/starred/StarredPage.tsx b/web/src/starred/StarredPage.tsx
index 50d3c4e3bed1123795f37601012c3284d794eba5..7d18e1a5650e19e426a56beb9a6bc7560272bce6 100644
--- a/web/src/starred/StarredPage.tsx
+++ b/web/src/starred/StarredPage.tsx
@@ -1,5 +1,5 @@
// ---------------------------------------------------------------------------
-// starred/StarredPage.tsx — WAVE 35 · W35-T14 (owner item 8, ruling R4, C2).
+// starred/StarredPage.tsx — shared starred tile controls and the retained visual fixture.
//
// Owner item 8, verbatim: *"Let's add a button under 'Home' called 'Starred' …
// only for Database/Agents/Queries/Marked important that the user has marked."*
@@ -21,18 +21,13 @@
// ⛔ THE STAR LIST IS NOT A PERMISSION — `starredApi.shapeStarred` drops every
// starred object that is not in `entries`, the server-filtered nav. A star
// outlives its subject, and the shell's oldest law ("an undeclared surface is
-// denied") is what makes `#/starred` a legal chrome route at all: this page can
-// name nothing `GET /nav` did not send.
+// denied") means every consumer can name only what `GET /nav` sent. Wave 55
+// retires the standalone route and mounts the starred-only filter on Home.
//
-// ⛔ THE READ HAPPENS AFTER PAINT, AND THAT IS A MEASUREMENT, NOT A STYLE CHOICE.
-// `GET /starred` scans a view bucket per database because C2 forbids a second
-// store for the flag: 6.2 ms warm, **7,331 ms cold** on tenant #0 (mailbox E-2).
-// `useEffect` (never `useLayoutEffect`) is what keeps it off the paint path.
+// The live read now belongs to Home's `useStarred` hook. This file keeps the
+// shared Tile and StarButton vocabulary plus the static fixture surface.
// ---------------------------------------------------------------------------
-import { useEffect, useState } from "react";
-import { API_V1, CREDENTIALS } from "../apiContract";
-
import { FolderMark } from "../customer-grid/icons";
import { AGENTS_MODULE_LABEL } from "../inbox/inboxModel";
import { Mark } from "../shell/Brand";
@@ -45,7 +40,6 @@ import {
EMPTY_STARRED,
shapeStarred,
starredCount,
- useStarred,
viewCount,
viewCountKey,
} from "./starredApi";
@@ -60,10 +54,8 @@ import type {
} from "./starredApi";
import "./starred.css";
-/** A magnifier: Query's own mark since the AI surfaces split, drawn in the rail's 16px stroke
- * vocabulary. Local to this file, which is this tree's established pattern for a glyph with one
- * caller (Home draws its own four; the alerts pane draws its own bell). */
-function QueryIcon() {
+/** A magnifier shared by the retained fixture and Home's starred-query results. */
+export function QueryIcon() {
return (
@@ -485,34 +477,3 @@ export function StarredSurface({
);
}
-
-/**
- * The page the frame mounts at `#/starred`: the read, and the two pieces of state that go with it.
- *
- * Everything it holds is its own (which list arrived, which tab is selected). Nothing here is a
- * fact about the workspace that the frame already knows, which is why `entries` and `automations`
- * arrive as props rather than being fetched a second time.
- */
-export default function StarredPage(props: StarredProps) {
- // ⭐ THE SAME HOOK HOME USES, so the two surfaces cannot end up with different ideas about what
- // is starred or about what happens when a write is refused. Everything about the read (the
- // after-paint timing, the generation counter, the revert-and-say-so on a refusal) lives there.
- const { load, busy, counts, toggle, reload } = useStarred();
- const [filter, setFilter] = useState ("all");
- const [applications, setApplications] = useState>([]);
- useEffect(() => { const controller = new AbortController(); void fetch(`${API_V1}/applications?starred=true`, { credentials: CREDENTIALS, signal: controller.signal }).then(async (response) => response.ok ? response.json() : { applications: [] }).then((body) => { if (!controller.signal.aborted) setApplications(Array.isArray(body?.applications) ? body.applications : []); }).catch(() => undefined); return () => controller.abort(); }, []);
-
- return (
- toggle(kind, id, false, database)}
- applications={applications}
- />
- );
-}
diff --git a/web/src/styles/wave55/apps.css b/web/src/styles/wave55/apps.css
new file mode 100644
index 0000000000000000000000000000000000000000..6510772ff8b1afc33514a736ee469c7d6a386958
--- /dev/null
+++ b/web/src/styles/wave55/apps.css
@@ -0,0 +1,642 @@
+/* WAVE 55: Home and App share one quiet directory vocabulary. */
+
+.home-page-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ margin-bottom: 20px;
+}
+
+.home-page-head .home-title {
+ margin-bottom: 0;
+}
+
+.home-app-create {
+ height: 32px;
+ padding: 0 12px;
+ border: 0;
+ border-radius: var(--lp-r-md);
+ background: var(--lp-primary);
+ color: var(--lp-surface);
+ font: inherit;
+ font-size: var(--lp-fs-2xs);
+ font-weight: 600;
+ cursor: pointer;
+ transition:
+ background 140ms var(--lp-fold-e),
+ transform 140ms var(--lp-fold-e);
+}
+
+.home-app-create:hover {
+ background: var(--lp-primary-hover);
+}
+
+.home-app-create:active {
+ transform: translateY(1px);
+}
+
+.home-app-create:focus-visible,
+.home-starred-filter:focus-visible {
+ outline: 2px solid var(--lp-primary);
+ outline-offset: 2px;
+}
+
+.home-layout-btn.home-starred-filter {
+ width: auto;
+ gap: 6px;
+ padding: 0 10px;
+ white-space: nowrap;
+}
+
+.home-layout-btn.home-starred-filter:disabled {
+ cursor: default;
+ opacity: 0.55;
+}
+
+.home-app-glyph {
+ background: var(--lp-blue-tint);
+ color: var(--lp-primary);
+ font-weight: 400;
+}
+
+.home-app-icon {
+ width: 16px;
+ height: 16px;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.3;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+.home-app-note {
+ margin: 0 0 12px;
+ color: var(--lp-red-deep);
+ font-size: var(--lp-fs-2xs);
+}
+
+/* Routing and Catalog Application creation share one four-step dialog. */
+.shell-newdb.app-wizard {
+ width: min(720px, calc(100vw - 32px));
+ min-height: 548px;
+ max-height: calc(100vh - 48px);
+ padding: 0;
+ display: grid;
+ grid-template-rows: auto auto minmax(0, 1fr) auto;
+ overflow: hidden;
+ animation: app-wizard-in 160ms ease-out both;
+}
+
+.app-wizard-head,
+.app-wizard-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 20px 24px;
+}
+
+.app-wizard-head {
+ justify-content: space-between;
+}
+
+.app-wizard-head p,
+.app-wizard-head h2,
+.app-wizard-field-list > p,
+.app-wizard-review-note {
+ margin: 0;
+}
+
+.app-wizard-head p,
+.cg-app-catalog-kicker {
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-3xs);
+ font-weight: 600;
+}
+
+.app-wizard-head h2 {
+ margin-top: 4px;
+ color: var(--lp-ink);
+ font-size: var(--lp-fs-lg);
+ line-height: var(--lp-lh-tight);
+}
+
+.app-wizard-close {
+ width: 36px;
+ height: 36px;
+ display: grid;
+ place-items: center;
+ padding: 0;
+ border: 0;
+ border-radius: var(--lp-r-md);
+ background: transparent;
+ color: var(--lp-muted);
+ cursor: pointer;
+}
+
+.app-wizard-close:hover {
+ background: var(--lp-wash);
+ color: var(--lp-ink);
+}
+
+.app-wizard-close svg {
+ width: 16px;
+ height: 16px;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.5;
+ stroke-linecap: round;
+}
+
+.app-wizard-steps {
+ display: grid;
+ grid-template-columns: repeat(4, 1fr);
+ gap: 8px;
+ margin: 0;
+ padding: 12px 24px;
+ border-top: 1px solid var(--lp-line);
+ border-bottom: 1px solid var(--lp-line);
+ list-style: none;
+}
+
+.app-wizard-steps li {
+ min-width: 0;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-3xs);
+ font-weight: 600;
+}
+
+.app-wizard-steps li > span {
+ width: 24px;
+ height: 24px;
+ flex: 0 0 24px;
+ display: grid;
+ place-items: center;
+ border: 1px solid var(--lp-line-strong);
+ border-radius: var(--lp-r-pill);
+ background: var(--lp-surface);
+ font-size: var(--lp-fs-4xs);
+}
+
+.app-wizard-steps li.is-current,
+.app-wizard-steps li.is-done {
+ color: var(--lp-primary);
+}
+
+.app-wizard-steps li.is-current > span,
+.app-wizard-steps li.is-done > span {
+ border-color: var(--lp-primary);
+ background: var(--lp-primary-tint);
+}
+
+.app-wizard-body {
+ min-height: 0;
+ overflow: auto;
+ padding: 24px;
+}
+
+.app-wizard-template-grid {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 12px;
+}
+
+.app-wizard-template {
+ min-height: 144px;
+ display: flex;
+ align-items: flex-start;
+ gap: 16px;
+ padding: 20px;
+ border: 1px solid var(--lp-line);
+ border-radius: var(--lp-r-lg);
+ background: var(--lp-surface);
+ color: var(--lp-ink);
+ text-align: left;
+ font: inherit;
+ cursor: pointer;
+ transition: border-color 140ms ease-out, background 140ms ease-out, transform 140ms ease-out;
+}
+
+.app-wizard-template:hover {
+ border-color: var(--lp-line-strong);
+ transform: translateY(-1px);
+}
+
+.app-wizard-template.is-selected {
+ border-color: var(--lp-primary);
+ background: var(--lp-primary-tint);
+}
+
+.app-wizard-template:focus-visible,
+.app-wizard-close:focus-visible,
+.app-wizard-secondary:focus-visible,
+.cg-app-catalog-card:focus-visible {
+ outline: 2px solid var(--lp-primary);
+ outline-offset: 2px;
+}
+
+.app-wizard-template-icon {
+ width: 44px;
+ height: 44px;
+ flex: 0 0 44px;
+ display: grid;
+ place-items: center;
+ border-radius: var(--lp-r-md);
+ background: var(--lp-blue-tint);
+ color: var(--lp-primary);
+}
+
+.app-wizard-template-icon svg {
+ width: 24px;
+ height: 24px;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.5;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+.app-wizard-template strong,
+.app-wizard-template small {
+ display: block;
+}
+
+.app-wizard-template strong {
+ margin: 2px 0 6px;
+ font-size: var(--lp-fs-sm);
+}
+
+.app-wizard-template small,
+.app-wizard-field small,
+.app-wizard-field-list > p,
+.app-wizard-review-note {
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-2xs);
+ line-height: 1.45;
+}
+
+.app-wizard-field-list,
+.app-wizard-review {
+ display: grid;
+ gap: 16px;
+}
+
+.app-wizard-field {
+ display: grid;
+ gap: 8px;
+ color: var(--lp-ink);
+ font-size: var(--lp-fs-2xs);
+ font-weight: 600;
+}
+
+.app-wizard-field > span {
+ display: flex;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.app-wizard-field input,
+.app-wizard-field select {
+ width: 100%;
+ height: 36px;
+ padding: 0 10px;
+ border: 1px solid var(--lp-line-strong);
+ border-radius: var(--lp-r-md);
+ background: var(--lp-surface);
+ color: var(--lp-ink);
+ font: inherit;
+ font-size: var(--lp-fs-2xs);
+}
+
+.app-wizard-field input:focus,
+.app-wizard-field select:focus {
+ border-color: var(--lp-primary);
+ outline: 2px solid var(--lp-primary-tint);
+ outline-offset: 1px;
+}
+
+.app-wizard-review dl {
+ margin: 0;
+ border-top: 1px solid var(--lp-line);
+}
+
+.app-wizard-review dl > div {
+ min-height: 40px;
+ display: grid;
+ grid-template-columns: 140px minmax(0, 1fr);
+ align-items: center;
+ gap: 12px;
+ border-bottom: 1px solid var(--lp-line);
+ font-size: var(--lp-fs-2xs);
+}
+
+.app-wizard-review dt {
+ color: var(--lp-muted);
+}
+
+.app-wizard-review dd {
+ margin: 0;
+ color: var(--lp-ink);
+ font-weight: 600;
+}
+
+.app-wizard-message {
+ min-height: 20px;
+ margin: 16px 0 0;
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-2xs);
+}
+
+.app-wizard-message.is-error,
+.app-wizard-field small.is-error {
+ color: var(--lp-red-deep);
+}
+
+.app-wizard-loading {
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 12px;
+}
+
+.app-wizard-loading span {
+ height: 144px;
+ border-radius: var(--lp-r-lg);
+ background: var(--lp-wash);
+ animation: app-wizard-pulse 1.1s ease-in-out infinite alternate;
+}
+
+.app-wizard-actions {
+ border-top: 1px solid var(--lp-line);
+}
+
+.app-wizard-actions > span {
+ flex: 1;
+}
+
+.app-wizard-actions button {
+ min-width: 84px;
+ height: 36px;
+}
+
+.app-wizard-secondary {
+ padding: 0 12px;
+ border: 1px solid var(--lp-line-strong);
+ border-radius: var(--lp-r-md);
+ background: var(--lp-surface);
+ color: var(--lp-ink);
+ font: inherit;
+ font-size: var(--lp-fs-2xs);
+ font-weight: 600;
+ cursor: pointer;
+}
+
+.app-wizard-actions button:disabled,
+.app-wizard-close:disabled {
+ cursor: default;
+ opacity: 0.5;
+}
+
+/* Template-backed Catalog launch surface. */
+.cg-app-catalog {
+ height: 100%;
+ min-height: 0;
+ overflow: auto;
+ padding: 24px;
+ background: var(--lp-bg);
+}
+
+/* An Application definition fixes its trusted renderer. The ordinary View switch would be an
+ inert control here, and Catalog has no use for Map's secondary settings row. */
+.cg-main:has(.cg-app-catalog, .cg-app-route-surface) .cg-modes,
+.cg-main:has(.cg-app-catalog) .cg-map-settings {
+ display: none;
+}
+
+.cg-app-catalog-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ margin-bottom: 20px;
+}
+
+.cg-app-catalog-head h2,
+.cg-app-catalog-kicker {
+ margin: 0;
+}
+
+.cg-app-catalog-head h2 {
+ margin-top: 4px;
+ color: var(--lp-ink);
+ font-size: var(--lp-fs-lg);
+}
+
+.cg-app-catalog-count {
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-2xs);
+}
+
+.cg-app-catalog-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(184px, 1fr));
+ gap: 12px;
+}
+
+.cg-app-catalog-card {
+ min-width: 0;
+ padding: 0;
+ border: 1px solid var(--lp-line);
+ border-radius: var(--lp-r-lg);
+ overflow: hidden;
+ background: var(--lp-surface);
+ color: var(--lp-ink);
+ text-align: left;
+ font: inherit;
+ cursor: pointer;
+ transition: border-color 140ms ease-out, transform 140ms ease-out, box-shadow 140ms ease-out;
+}
+
+.cg-app-catalog-card:hover {
+ border-color: var(--lp-line-strong);
+ box-shadow: var(--lp-shadow-md);
+ transform: translateY(-1px);
+}
+
+.cg-app-catalog-image {
+ aspect-ratio: 4 / 3;
+ display: grid;
+ place-items: center;
+ overflow: hidden;
+ background: var(--lp-surface-2);
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-3xs);
+}
+
+.cg-app-catalog-image img {
+ width: 100%;
+ height: 100%;
+ display: block;
+ object-fit: contain;
+}
+
+.cg-app-catalog-copy {
+ display: grid;
+ gap: 4px;
+ padding: 12px;
+}
+
+.cg-app-catalog-copy strong,
+.cg-app-catalog-copy span {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.cg-app-catalog-copy strong {
+ font-size: var(--lp-fs-2xs);
+}
+
+.cg-app-catalog-copy span,
+.cg-app-catalog-empty {
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-3xs);
+}
+
+.cg-app-route-context {
+ display: grid;
+ gap: 2px;
+ margin: 0 0 12px;
+ padding: 0 8px;
+}
+
+.cg-app-map-name {
+ display: grid;
+ gap: 1px;
+ margin-right: 4px;
+ padding-right: 12px;
+ border-right: 1px solid var(--lp-line);
+}
+
+.cg-app-map-name small {
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-5xs);
+}
+
+.cg-app-map-name strong {
+ max-width: 240px;
+ color: var(--lp-ink);
+ font-size: var(--lp-fs-2xs);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.cg-app-route-context span {
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-4xs);
+}
+
+.cg-app-route-context strong {
+ color: var(--lp-ink);
+ font-size: var(--lp-fs-2xs);
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.cg-app-launch-state {
+ height: 100%;
+ min-height: 240px;
+ display: grid;
+ align-content: start;
+ gap: 12px;
+ padding: 24px;
+ background: var(--lp-bg);
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-2xs);
+}
+
+.cg-app-launch-state.is-error {
+ color: var(--lp-red-deep);
+}
+
+.cg-app-launch-line,
+.cg-app-launch-grid {
+ display: block;
+ border-radius: var(--lp-r-md);
+ background: var(--lp-wash);
+ animation: app-wizard-pulse 1.1s ease-in-out infinite alternate;
+}
+
+.cg-app-launch-line {
+ width: 180px;
+ height: 16px;
+}
+
+.cg-app-launch-line.is-wide {
+ width: 280px;
+ height: 24px;
+}
+
+.cg-app-launch-grid {
+ height: 240px;
+ margin-top: 8px;
+}
+
+@keyframes app-wizard-in {
+ from { opacity: 0; transform: translateY(6px); }
+ to { opacity: 1; transform: translateY(0); }
+}
+
+@keyframes app-wizard-pulse {
+ from { opacity: 0.55; }
+ to { opacity: 1; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .home-app-create,
+ .app-wizard-template,
+ .cg-app-catalog-card,
+ .shell-newdb.app-wizard,
+ .app-wizard-loading span,
+ .cg-app-launch-line,
+ .cg-app-launch-grid {
+ transition: none;
+ animation: none;
+ }
+}
+
+@media (max-width: 640px) {
+ .home-page-head {
+ align-items: flex-start;
+ }
+
+ .home-layout-btn.home-starred-filter span {
+ display: none;
+ }
+
+ .shell-newdb.app-wizard {
+ min-height: min(548px, calc(100vh - 24px));
+ }
+
+ .app-wizard-template-grid,
+ .app-wizard-loading {
+ grid-template-columns: 1fr;
+ }
+
+ .app-wizard-steps li {
+ justify-content: center;
+ font-size: 0;
+ }
+
+ .app-wizard-steps li > span {
+ font-size: var(--lp-fs-4xs);
+ }
+
+ .app-wizard-review dl > div {
+ grid-template-columns: 112px minmax(0, 1fr);
+ }
+}
diff --git a/web/src/styles/wave55/connectors.css b/web/src/styles/wave55/connectors.css
new file mode 100644
index 0000000000000000000000000000000000000000..8f64325735d347061a0a9d45c39e6fcb52e5ab32
--- /dev/null
+++ b/web/src/styles/wave55/connectors.css
@@ -0,0 +1,187 @@
+/* Wave 55 T18. Connector settings remains the existing centered modal species, with the
+ viewport itself as its vertical boundary. The header and tabs stay fixed while the body owns
+ the scroll, so long discovered-model catalogs never depend on document scrolling or clip the
+ active tab. */
+.conn-modal-backdrop {
+ padding: 16px;
+}
+
+.conn-modal {
+ width: min(1200px, calc(100vw - 32px));
+ height: calc(100dvh - 32px);
+ max-height: calc(100dvh - 32px);
+}
+
+.conn-modal-body {
+ overscroll-behavior: contain;
+ scrollbar-gutter: stable;
+}
+
+/* The graph stage is still computed solely from the server DTO. Its measured container width is
+ now a lower bound, allowing newly materialized model cards to wrap into the available room
+ while oversized relation bands retain their local horizontal scroll. */
+.conn-rd-scroll {
+ width: 100%;
+ max-width: 100%;
+ overscroll-behavior: contain;
+ scrollbar-gutter: stable;
+}
+
+.conn-rd-stage {
+ min-width: 100%;
+}
+
+/* Credential replacement is one compact write-only form. Nothing nests it in another card and
+ the status slot reserves its line so an error does not move the action row. */
+.conn-kc-replace {
+ width: min(720px, 100%);
+}
+
+.conn-kc-replace h3 {
+ margin: 0 0 8px;
+ color: var(--lp-ink);
+ font-size: var(--lp-fs-sm);
+ font-weight: 600;
+}
+
+.conn-kc-message-slot {
+ min-height: 1lh;
+ margin-bottom: 8px;
+}
+
+.conn-kc-message-slot .conn-kc-error {
+ margin-bottom: 0;
+}
+
+/* Amazon's provider-owned database controls sit above the existing disclosure without nesting a
+ second card. They reuse the established connector switch; this file only supplies the compact
+ list rhythm and the reserved response line. */
+.conn-provider-enable {
+ margin-bottom: 16px;
+}
+
+.conn-provider-enable-head {
+ display: grid;
+ gap: 4px;
+ margin-bottom: 8px;
+}
+
+.conn-provider-enable-head h3,
+.conn-provider-enable-head p {
+ margin: 0;
+}
+
+.conn-provider-enable-head h3 {
+ color: var(--lp-ink);
+ font-size: var(--lp-fs-sm);
+ font-weight: 600;
+}
+
+.conn-provider-enable-head p {
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-2xs);
+}
+
+.conn-provider-enable-list {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+ border-top: 1px solid var(--lp-line);
+ border-bottom: 1px solid var(--lp-line);
+}
+
+.conn-provider-enable-list li {
+ display: flex;
+ min-height: 40px;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 8px 0;
+ border-bottom: 1px solid var(--lp-line);
+ color: var(--lp-ink);
+ font-size: var(--lp-fs-2xs);
+}
+
+.conn-provider-enable-list li:last-child {
+ border-bottom: 0;
+}
+
+.conn-provider-enable-control {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.conn-provider-enable .conn-db-switch:disabled {
+ cursor: not-allowed;
+}
+
+.conn-provider-enable-status {
+ min-height: 1lh;
+ margin-top: 4px;
+ color: var(--lp-red-deep);
+ font-size: var(--lp-fs-3xs);
+}
+
+.conn-kc-field input:disabled,
+.conn-kc-field select:disabled,
+.conn-kc-btn:disabled {
+ opacity: 0.55;
+ cursor: not-allowed;
+}
+
+/* Cadence is a single aligned row: label, preset and the server-declared floor. Connection facts
+ above it use a wider shared label column so Credential and Account do not wrap into values. */
+.conn-odoo-row {
+ grid-template-columns: 96px minmax(0, 1fr);
+}
+
+.conn-cadence-row {
+ display: grid;
+ grid-template-columns: 96px minmax(220px, 320px) minmax(0, 1fr);
+ align-items: center;
+ gap: 8px;
+ padding: 8px 0;
+ border-top: 1px solid var(--lp-line);
+ border-bottom: 1px solid var(--lp-line);
+}
+
+.conn-cadence-row label {
+ color: var(--lp-ink);
+ font-size: var(--lp-fs-2xs);
+ font-weight: 600;
+}
+
+.conn-cadence-row .conn-odoo-every {
+ width: 100%;
+ min-height: 32px;
+}
+
+.conn-cadence-floor {
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-3xs);
+}
+
+.conn-odoo-grids {
+ grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
+}
+
+@media (max-width: 720px) {
+ .conn-modal-backdrop {
+ padding: 8px;
+ }
+
+ .conn-modal {
+ width: calc(100vw - 16px);
+ height: calc(100dvh - 16px);
+ max-height: calc(100dvh - 16px);
+ }
+
+ .conn-cadence-row {
+ grid-template-columns: 88px minmax(0, 1fr);
+ }
+
+ .conn-cadence-floor {
+ grid-column: 2;
+ }
+}
diff --git a/web/src/styles/wave55/sheet.css b/web/src/styles/wave55/sheet.css
new file mode 100644
index 0000000000000000000000000000000000000000..e99e4647f1d562aa1d3a48a3ff065000cdb48030
--- /dev/null
+++ b/web/src/styles/wave55/sheet.css
@@ -0,0 +1,490 @@
+/* Wave 55: Sheet-specific tokens and full-hit direct-manipulation tabs. */
+
+:root {
+ --sheet-cell-border: #000000;
+}
+
+.sheet-tab-strip {
+ gap: 4px;
+ overflow-x: auto;
+ overflow-y: hidden;
+ border-top: 1px solid var(--lp-line);
+ border-bottom: 0;
+ padding: 4px 8px;
+}
+
+.sheet-tab-strip .sheet-ribbon-btn[data-sheet-tab-id] {
+ position: relative;
+ flex: 0 0 auto;
+ min-width: 80px;
+ height: 36px;
+ padding: 0 12px;
+ touch-action: none;
+ user-select: none;
+ cursor: grab;
+ transform: translateX(var(--sheet-tab-drag-x, 0));
+ transition: opacity 150ms ease-out;
+}
+
+.sheet-tab-strip .sheet-ribbon-btn[data-sheet-tab-id][data-dragging="true"] {
+ z-index: var(--cg-z-menu);
+ cursor: grabbing;
+ opacity: 0.88;
+ transition: none;
+}
+
+.sheet-tab-strip .sheet-ribbon-label {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ pointer-events: none;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .sheet-tab-strip .sheet-ribbon-btn[data-sheet-tab-id] {
+ transition: none;
+ }
+}
+
+/* W55-T06: one deliberate 8px title gap on every ribbon tab. Home already owns the shared
+ control band; the new tabs declare the same band and reuse the same group/control vocabulary. */
+.sheet-ribbon.sheet-ribbon-home {
+ --sheet-ribbon-group-gap: 8px;
+}
+
+.sheet-ribbon.sheet-ribbon-formulas,
+.sheet-ribbon.sheet-ribbon-data,
+.sheet-ribbon.sheet-ribbon-view {
+ --sheet-ribbon-band: 52px;
+ --sheet-ribbon-group-gap: 8px;
+ align-items: stretch;
+ gap: 0;
+ padding: 4px 8px;
+}
+
+.sheet-ribbon.sheet-ribbon-formulas .sheet-ribbon-group,
+.sheet-ribbon.sheet-ribbon-data .sheet-ribbon-group,
+.sheet-ribbon.sheet-ribbon-view .sheet-ribbon-group {
+ justify-content: flex-start;
+ gap: var(--sheet-ribbon-group-gap);
+}
+
+.sheet-ribbon.sheet-ribbon-formulas .sheet-ribbon-group-controls,
+.sheet-ribbon.sheet-ribbon-data .sheet-ribbon-group-controls,
+.sheet-ribbon.sheet-ribbon-view .sheet-ribbon-group-controls {
+ height: var(--sheet-ribbon-band);
+}
+
+.sheet-ribbon.sheet-ribbon-formulas .sheet-ribbon-btn,
+.sheet-ribbon.sheet-ribbon-data .sheet-ribbon-btn,
+.sheet-ribbon.sheet-ribbon-view .sheet-ribbon-btn {
+ gap: 4px;
+}
+
+.sheet-ribbon.sheet-ribbon-formulas .sheet-ribbon-label,
+.sheet-ribbon.sheet-ribbon-data .sheet-ribbon-label,
+.sheet-ribbon.sheet-ribbon-view .sheet-ribbon-label {
+ white-space: nowrap;
+}
+
+/* Unsupported commands stay visible but cannot enter the roving order or pretend to execute. */
+.sheet-ribbon-unavailable:disabled {
+ cursor: not-allowed;
+}
+
+.sheet-ribbon-state {
+ font-size: var(--lp-fs-3xs);
+ color: var(--lp-muted);
+ white-space: nowrap;
+}
+
+/* Formula bar visibility is a view preference, so it changes layout without changing the sheet. */
+.sheet-grid-wrap.is-formula-bar-hidden > .sheet-fx {
+ display: none;
+}
+
+/* W55-T07: Cell View keeps the Link-field drawer and adds one compact control row inside its
+ existing header. No second card or floating toolbar competes with the drawer's containment. */
+.cg-link-grid-head > div:first-child {
+ min-width: 96px;
+}
+
+.sheet-cell-view-toolbar {
+ order: 2;
+ display: flex;
+ min-width: 0;
+ margin-left: auto;
+ align-items: center;
+ gap: 4px;
+ overflow-x: auto;
+ scrollbar-width: none;
+}
+
+.sheet-cell-view-toolbar::-webkit-scrollbar {
+ display: none;
+}
+
+.cg-link-grid-head > .cg-icon-btn {
+ order: 3;
+ flex: 0 0 auto;
+ margin-left: 4px;
+}
+
+.sheet-cell-view-modes {
+ display: flex;
+ flex: 0 0 auto;
+ align-items: center;
+ gap: 2px;
+ padding: 2px;
+ border: 1px solid var(--lp-line);
+ border-radius: var(--lp-r-md);
+ background: var(--lp-surface-2);
+}
+
+.sheet-cell-view-mode,
+.sheet-cell-view-action {
+ display: inline-flex;
+ flex: 0 0 auto;
+ height: 28px;
+ align-items: center;
+ justify-content: center;
+ gap: 4px;
+ border: 1px solid transparent;
+ border-radius: var(--lp-r-sm);
+ padding: 0 8px;
+ background: transparent;
+ color: var(--lp-muted);
+ font: inherit;
+ font-size: var(--lp-fs-2xs);
+ line-height: 1;
+ white-space: nowrap;
+ cursor: pointer;
+ transition: background-color 150ms ease-out, color 150ms ease-out,
+ border-color 150ms ease-out, opacity 150ms ease-out;
+}
+
+.sheet-cell-view-action {
+ color: var(--lp-text);
+}
+
+.sheet-cell-view-mode:hover:not(:disabled),
+.sheet-cell-view-action:hover:not(:disabled) {
+ background: var(--lp-primary-tint);
+ color: var(--lp-primary);
+}
+
+.sheet-cell-view-mode[data-active="true"] {
+ border-color: var(--lp-line-strong);
+ background: var(--lp-surface);
+ color: var(--lp-primary);
+}
+
+.sheet-cell-view-mode:disabled,
+.sheet-cell-view-action:disabled {
+ opacity: 0.42;
+ cursor: not-allowed;
+}
+
+.sheet-cell-view-action > svg {
+ width: 14px;
+ height: 14px;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.35;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+}
+
+/* The linked-record component continues to own the drawer, focus trap and dismissals. Its body
+ is replaced by the cell-local projection so Grid, List and Map share C6's visible-field law. */
+.cg-link-grid-body.sheet-cell-view-custom > :not(.sheet-cell-view-surface) {
+ display: none;
+}
+
+.sheet-cell-view-surface {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ min-height: 0;
+ overflow: auto;
+ background: var(--lp-surface);
+ color: var(--lp-text);
+ animation: sheet-cell-view-enter 150ms ease-out;
+}
+
+@keyframes sheet-cell-view-enter {
+ from { opacity: 0; transform: translateY(2px); }
+ to { opacity: 1; transform: translateY(0); }
+}
+
+.sheet-cell-grid {
+ min-width: max-content;
+ width: 100%;
+}
+
+.sheet-cell-grid-head,
+.sheet-cell-grid-row {
+ display: flex;
+ min-width: 100%;
+ border-bottom: 1px solid var(--lp-line);
+}
+
+.sheet-cell-grid-head {
+ position: sticky;
+ z-index: 1;
+ top: 0;
+ background: var(--lp-surface-2);
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-3xs);
+ font-weight: 600;
+}
+
+.sheet-cell-grid-head > span,
+.sheet-cell-grid-row > span {
+ flex: 1 0 168px;
+ min-width: 168px;
+ max-width: 280px;
+ padding: 8px 12px;
+ overflow: hidden;
+ border-right: 1px solid var(--lp-line);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.sheet-cell-grid-row > span {
+ min-height: calc(32px + 4px);
+ font-size: var(--lp-fs-2xs);
+}
+
+.sheet-cell-grid-row > span.is-identity {
+ color: var(--lp-ink);
+ font-weight: 600;
+}
+
+.sheet-cell-grid-row:hover {
+ background: var(--lp-wash);
+}
+
+.sheet-cell-list {
+ display: grid;
+ max-width: 920px;
+ gap: 8px;
+ margin: 0 auto;
+ padding: 12px;
+}
+
+.sheet-cell-list-row {
+ border: 1px solid var(--lp-line);
+ border-radius: var(--lp-r-md);
+ padding: 12px;
+ background: var(--lp-surface);
+}
+
+.sheet-cell-list-row > h3 {
+ margin: 0 0 8px;
+ color: var(--lp-ink);
+ font-size: var(--lp-fs-sm);
+ font-weight: 600;
+}
+
+.sheet-cell-list-fields {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
+ gap: 8px 16px;
+}
+
+.sheet-cell-list-fields > span {
+ display: grid;
+ min-width: 0;
+ gap: 2px;
+}
+
+.sheet-cell-list-fields small {
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-4xs);
+ font-weight: 500;
+}
+
+.sheet-cell-list-fields strong {
+ overflow: hidden;
+ color: var(--lp-text);
+ font-size: var(--lp-fs-2xs);
+ font-weight: 400;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.sheet-cell-map {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ min-height: 360px;
+ overflow: hidden;
+ background: var(--lp-blue-tint);
+}
+
+.sheet-cell-map-canvas {
+ display: block;
+ width: 100%;
+ height: 100%;
+}
+
+.sheet-cell-map-water {
+ fill: var(--lp-blue-tint);
+}
+
+.sheet-cell-map-land {
+ fill: var(--lp-surface-2);
+ stroke: var(--lp-line-strong);
+ stroke-width: 1.2;
+ vector-effect: non-scaling-stroke;
+}
+
+.sheet-cell-map-lake {
+ fill: var(--lp-blue-tint);
+ stroke: var(--lp-line);
+ stroke-width: 0.8;
+ vector-effect: non-scaling-stroke;
+}
+
+.sheet-cell-map-pin {
+ fill: var(--lp-primary);
+ stroke: var(--lp-surface);
+ stroke-width: 1.5;
+ vector-effect: non-scaling-stroke;
+}
+
+.sheet-cell-map-note,
+.sheet-cell-view-limit {
+ position: absolute;
+ left: 12px;
+ bottom: 12px;
+ padding: 6px 8px;
+ border: 1px solid var(--lp-line);
+ border-radius: var(--lp-r-pill);
+ background: var(--lp-surface);
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-3xs);
+}
+
+.sheet-cell-view-limit {
+ right: 12px;
+ left: auto;
+}
+
+.sheet-cell-view-empty {
+ display: grid;
+ min-height: 100%;
+ place-items: center;
+ padding: 24px;
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-sm);
+ text-align: center;
+}
+
+.sheet-cell-view-loading {
+ display: grid;
+ min-height: 100%;
+ grid-template-rows: repeat(4, 32px);
+ align-content: start;
+ gap: 8px;
+ padding: 16px;
+}
+
+.sheet-cell-view-loading > span {
+ display: block;
+ border-radius: var(--lp-r-sm);
+ background: var(--lp-surface-2);
+ opacity: 0.72;
+ transition: opacity 150ms ease-out;
+}
+
+.sheet-cell-fields-pop,
+.sheet-cell-export-pop {
+ border: 1px solid var(--lp-line);
+ border-radius: var(--lp-r-md);
+ background: var(--lp-surface);
+ box-shadow: var(--shell-shadow-overlay);
+}
+
+.sheet-cell-fields-pop {
+ width: 280px;
+ max-height: min(420px, calc(100vh - 32px));
+ padding: 8px;
+}
+
+.sheet-cell-fields-title {
+ padding: 4px 4px 8px;
+ color: var(--lp-ink);
+ font-size: var(--lp-fs-xs);
+ font-weight: 600;
+}
+
+.sheet-cell-fields-list {
+ max-height: 356px;
+ overflow: auto;
+}
+
+.sheet-cell-field-choice {
+ display: grid;
+ min-height: 32px;
+ grid-template-columns: 16px minmax(0, 1fr) auto;
+ align-items: center;
+ gap: 8px;
+ border-radius: var(--lp-r-sm);
+ padding: 4px 6px;
+ font-size: var(--lp-fs-2xs);
+}
+
+.sheet-cell-field-choice:hover {
+ background: var(--lp-wash);
+}
+
+.sheet-cell-field-choice > span {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.sheet-cell-field-choice > small {
+ color: var(--lp-muted);
+ font-size: var(--lp-fs-4xs);
+ white-space: nowrap;
+}
+
+.sheet-cell-export-pop {
+ display: grid;
+ min-width: 144px;
+ gap: 2px;
+ padding: 6px;
+}
+
+.sheet-cell-export-choice {
+ min-height: 32px;
+ border: 0;
+ border-radius: var(--lp-r-sm);
+ padding: 0 10px;
+ background: transparent;
+ color: var(--lp-text);
+ font: inherit;
+ font-size: var(--lp-fs-2xs);
+ text-align: left;
+ cursor: pointer;
+}
+
+.sheet-cell-export-choice:hover,
+.sheet-cell-export-choice:focus-visible {
+ background: var(--lp-primary-tint);
+ color: var(--lp-primary);
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .sheet-cell-view-mode,
+ .sheet-cell-view-action,
+ .sheet-cell-view-surface,
+ .sheet-cell-view-loading > span {
+ transition: none;
+ animation: none;
+ }
+}
|