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.

+
+ +
+ {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) => ( +
+ + + setValues((current) => ({ ...current, [field.key]: event.target.value })) + } + /> +
+ ))} +
+ {error ? ( +

+ {error} +

+ ) : null} +
+
+ + +
+
+ ); +} + /** * ⭐ 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 ? ( + + ) : null} {entry.testable ? ( + ))} +
+ ) : ( +

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({
- )} -
- {readOnlyReason &&
{readOnlyReason}
} - {card ? ( -
- -
{ - // ⭐ 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 && ( - - )} -
- -
- ) : ( - // 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}. -

- - - ) : ( -

- 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}

- -
- - -
- {!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. -

- )} - -
- ); -} - -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 && ( + + )} +
+ {readOnlyReason &&
{readOnlyReason}
} + {card ? ( +
+ +
{ + // ⭐ 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 && ( + + )} +
+ +
+ ) : ( + // 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}. +

+ + + ) : ( +

+ 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}

+ +
+ + +
+ {!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. +

+ )} + +
+ ); +} + +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 ` + ) : 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" ? ( + + ) : 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 &&

Folders

{folders.map((folder) => { const count = Object.values(folderPlacement).filter((id) => id === folder.id).length; return {folder.name}{count} database{count === 1 ? "" : "s"}; })}
} - {applications.length > 0 &&

Applications

{applications.map((application) => { const database = application.openTarget?.database ?? application.compatibleDatabases?.[0] ?? ""; return {application.type.slice(0, 1).toUpperCase()}{application.name}{application.type}; })}
} + ) : null} + {mode === "home" && !starredOnly && folders.length > 0 &&

Folders

{folders.map((folder) => { const count = Object.values(folderPlacement).filter((id) => id === folder.id).length; return {folder.name}{count} database{count === 1 ? "" : "s"}; })}
} + {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 ( +
+ + + + {application.name} + {kind} + + + {application.capabilities?.star !== false ? ( + onToggleApplication(application, application.starred !== true)} + /> + ) : null} +
+ ); + })} +
+
+ ) : 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. */} -
- + {chosenIsMetric ? ( +
+ +

+ {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 - - - - - {dragDownFields.length === 0 && ( -

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

+ {chosenIsMetric ? ( + periodOn ? ( + <> + +

+ Right and down move forward. Left and up move backward. +

+ + ) : ( +

+ This metric is all time, so copied cells keep the same all-time period. +

+ ) + ) : ( + <> + + {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 = ( +
+ + setRangeDraft(event.target.value)} + /> + {range === null ? ( + + ) : 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) => ( - - ))} -
+ {!editing ? ( +
+ {SOURCE_TABS.map((entry) => ( + + ))} +
+ ) : 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 && ( - - )}
); } @@ -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 ( + + ); + })} +
+ + + {canEditRows && ( + + )} + +
, + 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 ( + + ); + })} +
+
+ )} + {exportOpen && exportButtonRef.current && ( + setExportOpen(false)} + role="menu" + ariaLabel="Export matching records" + dataKind="sheet-cell-export" + > + {(["csv", "xlsx", "pdf", "json"] as const).map((format) => ( + + ))} + + )} {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 ( {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) => ( + + ); + // ⭐ 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 ? ( ) : null} + {onEdit ? ( + + ) : null} {onResize ? (
{/* ⭐⭐ 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) => ( 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 ( + + ); +} + +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 ? (
- 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]]). */} - - + aria-label="Search people to share with" + placeholder="Search people" + autoFocus + onChange={(e) => setRecipientQuery(e.target.value)} + /> + + {canAddEveryone ? + { + setSourceDatabase(event.target.value); + setFieldMap({}); + setError(""); + }}> + + {databases.map((database) => )} + + {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 ( + + ); + })} + {coordinatePairError ? ( +

+ Routing needs both coordinate fields or neither, and they must be different. +

+ ) : null} +
+ ) : null} + + {step === 3 && template ? ( +
+ +
+
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} +

+
+ +
+ + + {step > 0 ? ( + + ) : null} + {step < 3 ? ( + + ) : ( + + )} +
+
+
+ ); +} + 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. */ -
- - Agents -
- ) : ( - /* Mirror Assistant's zero-geometry absent arm: actual permission absence is silent; - only an incomplete navigation response renders the unavailable row above. */ -