Deploy AIOS web (React glide grid + FastAPI slice)
Browse files- RELEASES.json +1 -1
- VERSION +1 -1
- api/automation_worker.py +3 -1
- api/formula_runtime.py +5 -2
- api/routes_admin.py +23 -7
- api/routes_customers.py +98 -28
- api/routes_grid.py +36 -15
- api/routes_nav.py +7 -3
- api/routes_products.py +26 -18
- api/routes_sheet.py +50 -25
- api/routes_tables.py +25 -11
- platform/core/field_permissions.py +26 -1
- platform/core/grid_events.py +12 -2
- platform/core/shared_overlay.py +18 -1
- platform/core/sheets.py +3 -3
- platform/core/store.py +33 -0
- platform/core/store_backend.py +5 -0
- platform/core/store_pg.py +5 -0
- platform/core/table_store.py +6 -2
- platform/core/user_tables.py +19 -6
- platform/modules/product_data.py +14 -3
- web/public/AIOS_DEPLOY_RECEIPT +1 -1
- web/src/connectors/MonidRunDialog.tsx +2 -2
- web/src/customer-grid/CustomerGrid.tsx +31 -16
- web/src/customer-grid/JsonViewer.tsx +2 -2
- web/src/customer-grid/apiBridge.ts +63 -20
- web/src/customer-grid/formulaEngine.ts +33 -7
- web/src/customer-grid/useCustomerData.ts +9 -1
- web/src/filter-kit/SheetFilterPopup.tsx +2 -2
- web/src/inbox/InboxPage.tsx +10 -11
- web/src/sheet/BindingEditor.tsx +25 -17
- web/src/sheet/DrillModal.tsx +11 -8
- web/src/sheet/Ribbon.tsx +27 -11
- web/src/sheet/SheetGrid.tsx +94 -43
- web/src/sheet/SheetPage.tsx +22 -10
- web/src/sheet/formulaEval.ts +1 -1
- web/src/sheet/sheetState.ts +8 -6
- web/src/sheet/sparkline.ts +36 -60
- web/src/sheet/types.ts +4 -0
- web/src/ui/useEscapeClose.ts +5 -1
RELEASES.json
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
{
|
| 2 |
-
"current": "
|
| 3 |
"releases": []
|
| 4 |
}
|
|
|
|
| 1 |
{
|
| 2 |
+
"current": "ff856a9a",
|
| 3 |
"releases": []
|
| 4 |
}
|
VERSION
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
|
|
|
|
| 1 |
+
ff856a9a
|
api/automation_worker.py
CHANGED
|
@@ -67,7 +67,9 @@ def _claim(job: dict):
|
|
| 67 |
url = str(os.environ.get("DATABASE_URL") or "").strip()
|
| 68 |
if not url:
|
| 69 |
raise RuntimeError("DATABASE_URL is required")
|
| 70 |
-
|
|
|
|
|
|
|
| 71 |
lock_name = f"aios-automation:{job['tenant']}:{job['automationId'] or job['mode']}"
|
| 72 |
with con.cursor() as cur:
|
| 73 |
cur.execute("SELECT pg_try_advisory_lock(hashtextextended(%s, 0))", (lock_name,))
|
|
|
|
| 67 |
url = str(os.environ.get("DATABASE_URL") or "").strip()
|
| 68 |
if not url:
|
| 69 |
raise RuntimeError("DATABASE_URL is required")
|
| 70 |
+
ca = os.environ.get("AIOS_DATABASE_CA_PEM_B64")
|
| 71 |
+
options = {"sslrootcert": store_pg._database_ca_file(ca)} if ca is not None else {}
|
| 72 |
+
con = psycopg.connect(url, **options)
|
| 73 |
lock_name = f"aios-automation:{job['tenant']}:{job['automationId'] or job['mode']}"
|
| 74 |
with con.cursor() as cur:
|
| 75 |
cur.execute("SELECT pg_try_advisory_lock(hashtextextended(%s, 0))", (lock_name,))
|
api/formula_runtime.py
CHANGED
|
@@ -3110,7 +3110,7 @@ class _SheetInputs(dict):
|
|
| 3110 |
self.engine._consume(super().get(SHEET_ADDR_KEY), key)
|
| 3111 |
owner = self.engine.spill_parents.get(key)
|
| 3112 |
if owner in self.engine._pending: raise _NeedReference(owner)
|
| 3113 |
-
fault = key if key in self.engine.errors else None
|
| 3114 |
if not _occupied(self.engine.specs.get(key)):
|
| 3115 |
producers = self.engine.prospective.at(key, self.engine.stats)
|
| 3116 |
pending = producers & self.engine._pending
|
|
@@ -3123,6 +3123,8 @@ class _SheetInputs(dict):
|
|
| 3123 |
raise _ReferenceFault(fault)
|
| 3124 |
self.engine.stats["reads"] += 1
|
| 3125 |
if self.format_stack: self.format_stack[-1].append(self.engine.formats.get(key))
|
|
|
|
|
|
|
| 3126 |
return self.engine.values.get(key, default)
|
| 3127 |
|
| 3128 |
def range_values(self, bounds):
|
|
@@ -3783,7 +3785,7 @@ def recompute_document(book, *, cache_key=None, changes=None, today=None):
|
|
| 3783 |
projected += 1
|
| 3784 |
code = engine.errors.get(key)
|
| 3785 |
cell["value"] = engine.values.get(key)
|
| 3786 |
-
if code:
|
| 3787 |
message = _sheet_error_message(code)
|
| 3788 |
cell.update(state="refused", display="", refusal={"code": code, "message": message},
|
| 3789 |
error={"code": code, "message": message,
|
|
@@ -3791,6 +3793,7 @@ def recompute_document(book, *, cache_key=None, changes=None, today=None):
|
|
| 3791 |
excel = {**REFERENCE_ERRORS, "no_match": "#N/A", "bad_value": "#VALUE!", "div_zero": "#DIV/0!", "numeric_error": "#NUM!"}.get(code)
|
| 3792 |
if excel: cell["error"]["excelCode"] = excel
|
| 3793 |
else:
|
|
|
|
| 3794 |
cell.update(state="fresh", display=_display_text(cell["value"]))
|
| 3795 |
cell.pop("refusal", None)
|
| 3796 |
cell.pop("error", None)
|
|
|
|
| 3110 |
self.engine._consume(super().get(SHEET_ADDR_KEY), key)
|
| 3111 |
owner = self.engine.spill_parents.get(key)
|
| 3112 |
if owner in self.engine._pending: raise _NeedReference(owner)
|
| 3113 |
+
fault = key if key in self.engine.errors and self.engine.errors[key] != "blank" else None
|
| 3114 |
if not _occupied(self.engine.specs.get(key)):
|
| 3115 |
producers = self.engine.prospective.at(key, self.engine.stats)
|
| 3116 |
pending = producers & self.engine._pending
|
|
|
|
| 3123 |
raise _ReferenceFault(fault)
|
| 3124 |
self.engine.stats["reads"] += 1
|
| 3125 |
if self.format_stack: self.format_stack[-1].append(self.engine.formats.get(key))
|
| 3126 |
+
if self.engine.errors.get(key) == "blank":
|
| 3127 |
+
return ""
|
| 3128 |
return self.engine.values.get(key, default)
|
| 3129 |
|
| 3130 |
def range_values(self, bounds):
|
|
|
|
| 3785 |
projected += 1
|
| 3786 |
code = engine.errors.get(key)
|
| 3787 |
cell["value"] = engine.values.get(key)
|
| 3788 |
+
if code and code != "blank":
|
| 3789 |
message = _sheet_error_message(code)
|
| 3790 |
cell.update(state="refused", display="", refusal={"code": code, "message": message},
|
| 3791 |
error={"code": code, "message": message,
|
|
|
|
| 3793 |
excel = {**REFERENCE_ERRORS, "no_match": "#N/A", "bad_value": "#VALUE!", "div_zero": "#DIV/0!", "numeric_error": "#NUM!"}.get(code)
|
| 3794 |
if excel: cell["error"]["excelCode"] = excel
|
| 3795 |
else:
|
| 3796 |
+
if code == "blank": cell["value"] = ""
|
| 3797 |
cell.update(state="fresh", display=_display_text(cell["value"]))
|
| 3798 |
cell.pop("refusal", None)
|
| 3799 |
cell.pop("error", None)
|
api/routes_admin.py
CHANGED
|
@@ -734,7 +734,7 @@ def _apply_admin_only_filter_rule(row):
|
|
| 734 |
**{_FILTER_REASON_KEY: _ADMIN_ONLY_FILTER_REASON.format(owner=owner)})
|
| 735 |
|
| 736 |
|
| 737 |
-
def _admin_usernames():
|
| 738 |
"""Every account holding the `admin` role, lowercased — or `None` when that set could not be
|
| 739 |
established.
|
| 740 |
|
|
@@ -753,7 +753,7 @@ def _admin_usernames():
|
|
| 753 |
answer.
|
| 754 |
"""
|
| 755 |
try:
|
| 756 |
-
reg = users.registry() or {}
|
| 757 |
except Exception: # noqa: BLE001
|
| 758 |
return None
|
| 759 |
if not isinstance(reg, dict) or not reg:
|
|
@@ -808,7 +808,7 @@ def _field_provenance(src, key, session):
|
|
| 808 |
classes = {}
|
| 809 |
admins = None
|
| 810 |
if session is not None:
|
| 811 |
-
admins = _admin_usernames()
|
| 812 |
try:
|
| 813 |
# ⛔ `grant_topic` IS THE MODULE KEY, NOT THE STORE BUCKET. `shares.field_oid` namespaces
|
| 814 |
# a grant by the topic the write doors already use — `"customer_data"` /
|
|
@@ -901,7 +901,8 @@ def _module_fields(key, session=None, wall_verdicts=None):
|
|
| 901 |
f"{key!r} is not a database in this workspace")
|
| 902 |
src = defn.get("fields") or []
|
| 903 |
else:
|
| 904 |
-
|
|
|
|
| 905 |
if provider is None:
|
| 906 |
# Reached only by a caller that skipped `_perm_modules`. Loud, because the alternative
|
| 907 |
# (`[]`) is an empty option list read as an ANSWER — wave 26 item 24, `if ([])` is
|
|
@@ -1591,7 +1592,7 @@ def _stale_hidden_keys(key, hidden, session=None, fields=None):
|
|
| 1591 |
- {str(h) for h in (hidden or ()) if str(h).startswith(_mpre)})
|
| 1592 |
|
| 1593 |
|
| 1594 |
-
def _prune_stale_filters(block, session=None):
|
| 1595 |
"""`(block, {module: [dropped keys]})` — owner I16's cascade over a whole stored perms block.
|
| 1596 |
|
| 1597 |
⭐⭐ *"If the field is deleted, its permission filter goes with it."* Run at the ADMIN DOOR,
|
|
@@ -1610,7 +1611,8 @@ def _prune_stale_filters(block, session=None):
|
|
| 1610 |
for key, entry in (block or {}).items():
|
| 1611 |
if not isinstance(entry, dict) or not entry.get("filter"):
|
| 1612 |
continue
|
| 1613 |
-
vocab = _prunable_vocabulary(key, session=session
|
|
|
|
| 1614 |
if vocab is None:
|
| 1615 |
continue
|
| 1616 |
tree, gone = perm_scope.prune_filter_to_fields(entry["filter"], vocab)
|
|
@@ -2195,6 +2197,19 @@ def get_perms(username: str, session: Session = Depends(admin_gate)):
|
|
| 2195 |
# 404, never 403, because "that account exists in another company" is itself a leak.
|
| 2196 |
raise err(404, "no_such_user", f"no account named {uname!r}")
|
| 2197 |
import core.perm_scope as perm_scope
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2198 |
|
| 2199 |
rec = reg[uname]
|
| 2200 |
stored = rec.get("perms") or {}
|
|
@@ -2242,7 +2257,8 @@ def get_perms(username: str, session: Session = Depends(admin_gate)):
|
|
| 2242 |
# `stored` test alone would very nearly cover it (an un-migrated record carries no perms
|
| 2243 |
# block), so the marker is asked explicitly rather than inferred from an empty dict.
|
| 2244 |
if stored and perm_scope.is_migrated(rec):
|
| 2245 |
-
_pruned, _gone = _prune_stale_filters(stored, session=session
|
|
|
|
| 2246 |
if _gone:
|
| 2247 |
users.set_access(uname, perms=_pruned)
|
| 2248 |
# Re-read rather than trust the write: this route's whole job is to report what is
|
|
|
|
| 734 |
**{_FILTER_REASON_KEY: _ADMIN_ONLY_FILTER_REASON.format(owner=owner)})
|
| 735 |
|
| 736 |
|
| 737 |
+
def _admin_usernames(roster=None):
|
| 738 |
"""Every account holding the `admin` role, lowercased — or `None` when that set could not be
|
| 739 |
established.
|
| 740 |
|
|
|
|
| 753 |
answer.
|
| 754 |
"""
|
| 755 |
try:
|
| 756 |
+
reg = (users.registry() if roster is None else roster) or {}
|
| 757 |
except Exception: # noqa: BLE001
|
| 758 |
return None
|
| 759 |
if not isinstance(reg, dict) or not reg:
|
|
|
|
| 808 |
classes = {}
|
| 809 |
admins = None
|
| 810 |
if session is not None:
|
| 811 |
+
admins = _admin_usernames(getattr(session, "_permission_roster", None))
|
| 812 |
try:
|
| 813 |
# ⛔ `grant_topic` IS THE MODULE KEY, NOT THE STORE BUCKET. `shares.field_oid` namespaces
|
| 814 |
# a grant by the topic the write doors already use — `"customer_data"` /
|
|
|
|
| 901 |
f"{key!r} is not a database in this workspace")
|
| 902 |
src = defn.get("fields") or []
|
| 903 |
else:
|
| 904 |
+
providers = _static_field_providers()
|
| 905 |
+
provider = providers.get(key)
|
| 906 |
if provider is None:
|
| 907 |
# Reached only by a caller that skipped `_perm_modules`. Loud, because the alternative
|
| 908 |
# (`[]`) is an empty option list read as an ANSWER — wave 26 item 24, `if ([])` is
|
|
|
|
| 1592 |
- {str(h) for h in (hidden or ()) if str(h).startswith(_mpre)})
|
| 1593 |
|
| 1594 |
|
| 1595 |
+
def _prune_stale_filters(block, session=None, fields_by_module=None):
|
| 1596 |
"""`(block, {module: [dropped keys]})` — owner I16's cascade over a whole stored perms block.
|
| 1597 |
|
| 1598 |
⭐⭐ *"If the field is deleted, its permission filter goes with it."* Run at the ADMIN DOOR,
|
|
|
|
| 1611 |
for key, entry in (block or {}).items():
|
| 1612 |
if not isinstance(entry, dict) or not entry.get("filter"):
|
| 1613 |
continue
|
| 1614 |
+
vocab = _prunable_vocabulary(key, session=session,
|
| 1615 |
+
fields=(fields_by_module or {}).get(key))
|
| 1616 |
if vocab is None:
|
| 1617 |
continue
|
| 1618 |
tree, gone = perm_scope.prune_filter_to_fields(entry["filter"], vocab)
|
|
|
|
| 2197 |
# 404, never 403, because "that account exists in another company" is itself a leak.
|
| 2198 |
raise err(404, "no_such_user", f"no account named {uname!r}")
|
| 2199 |
import core.perm_scope as perm_scope
|
| 2200 |
+
from copy import copy
|
| 2201 |
+
from core import user_tables
|
| 2202 |
+
from routes_customers import _AssemblyStore
|
| 2203 |
+
|
| 2204 |
+
# One read-only request snapshot: definitions, grants and provenance are shared by the
|
| 2205 |
+
# picker and cascade. It never enters a write door or outlives this request. Global account
|
| 2206 |
+
# writes and their required post-write readback below continue through the original store.
|
| 2207 |
+
session = copy(session)
|
| 2208 |
+
session._permission_roster = reg
|
| 2209 |
+
try:
|
| 2210 |
+
session.runtime = user_tables.lend_defs(_AssemblyStore(session.runtime, schema_only=True))
|
| 2211 |
+
except Exception:
|
| 2212 |
+
raise err(503, "schema_unavailable", "The permission field definitions are unavailable. Try again.")
|
| 2213 |
|
| 2214 |
rec = reg[uname]
|
| 2215 |
stored = rec.get("perms") or {}
|
|
|
|
| 2257 |
# `stored` test alone would very nearly cover it (an un-migrated record carries no perms
|
| 2258 |
# block), so the marker is asked explicitly rather than inferred from an empty dict.
|
| 2259 |
if stored and perm_scope.is_migrated(rec):
|
| 2260 |
+
_pruned, _gone = _prune_stale_filters(stored, session=session,
|
| 2261 |
+
fields_by_module=fields_by_module)
|
| 2262 |
if _gone:
|
| 2263 |
users.set_access(uname, perms=_pruned)
|
| 2264 |
# Re-read rather than trust the write: this route's whole job is to report what is
|
api/routes_customers.py
CHANGED
|
@@ -22,7 +22,7 @@ owner-blocked on B-3), and no test here may claim read-your-writes ACROSS runtim
|
|
| 22 |
proof is single-process and would report green on exactly the thing that is still broken.
|
| 23 |
"""
|
| 24 |
import datetime as _dt
|
| 25 |
-
from copy import deepcopy
|
| 26 |
from dataclasses import is_dataclass, replace
|
| 27 |
import hashlib
|
| 28 |
import json
|
|
@@ -70,16 +70,42 @@ def _assembly_pg_store(st):
|
|
| 70 |
return handle if isinstance(handle, store_pg.PgStore) else None
|
| 71 |
|
| 72 |
|
| 73 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
"""Validate all tracked PostgreSQL documents in one round trip, with identical tokens."""
|
| 75 |
from core import store, store_pg
|
| 76 |
names = tuple(sorted(set(names)))
|
| 77 |
handle = _assembly_pg_store(runtime)
|
| 78 |
users_stamp = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
if handle is None:
|
| 80 |
tokens = {name: _assembly_revision(runtime, name) for name in names}
|
| 81 |
if uses_roster:
|
| 82 |
-
users_stamp = _assembly_revision(store, "users")
|
| 83 |
return tokens, users_stamp
|
| 84 |
|
| 85 |
key = getattr(runtime, "store_key", str)
|
|
@@ -111,8 +137,8 @@ def _assembly_revisions(runtime, names, uses_roster=False):
|
|
| 111 |
absent = {"rev": 0, "updated_at": None, "token": "pg:0"}
|
| 112 |
tokens = {name: dict(found.get(mapped, absent)) for name, mapped in keyed.items()}
|
| 113 |
if uses_roster:
|
| 114 |
-
users_stamp = (dict(found.get(roster_key, absent)) if same_roster
|
| 115 |
-
|
| 116 |
if isinstance(runtime, _AssemblyStore):
|
| 117 |
# The page may read these documents after its memo hit. Reuse this request's pre-read
|
| 118 |
# tokens without retaining any document bytes across requests.
|
|
@@ -269,13 +295,17 @@ def shared_fields(st=None):
|
|
| 269 |
"""
|
| 270 |
from core import field_permissions, shared_overlay
|
| 271 |
try:
|
|
|
|
| 272 |
field_permissions.migrate_legacy_fields(
|
| 273 |
-
_shared_key(), st=st, grant_topic="customer_data", shared_key=_shared_key()
|
| 274 |
-
|
|
|
|
| 275 |
# Normalized Routes use an invisible field-shaped bridge so the established Share dialog
|
| 276 |
# and grant registry can be reused. It is object metadata, never a customer column.
|
| 277 |
return {key: value for key, value in fields.items()
|
| 278 |
if not _is_route_share_bridge(value)}
|
|
|
|
|
|
|
| 279 |
except Exception: # noqa: BLE001
|
| 280 |
# Lenient like every other display read: an unreachable store degrades to "nothing is
|
| 281 |
# shared yet", never to a 500 on a grid that would otherwise render. The WALL does not
|
|
@@ -385,8 +415,9 @@ def _mark_offerability(fields):
|
|
| 385 |
|
| 386 |
class _AssemblyStore:
|
| 387 |
"""One build's borrowed reads and their pre-read revisions, never a second cache."""
|
| 388 |
-
def __init__(self, runtime):
|
| 389 |
self._runtime = runtime
|
|
|
|
| 390 |
self.docs, self.tokens = {}, {}
|
| 391 |
self._validated_tokens = {}
|
| 392 |
# A lent/test reader without its own coherent revision door can share a flight only.
|
|
@@ -408,12 +439,20 @@ class _AssemblyStore:
|
|
| 408 |
except AttributeError:
|
| 409 |
self.cacheable = False
|
| 410 |
key = (name, shape)
|
| 411 |
-
if fresh or not self.cacheable or key not in self.docs:
|
| 412 |
self.docs[key] = read()
|
| 413 |
# TableStore readers can mutate nested projections; lend an independent read each time.
|
| 414 |
return deepcopy(self.docs[key])
|
| 415 |
|
| 416 |
def get(self, name, fresh=False):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 417 |
return self._read(name, "whole", lambda: (
|
| 418 |
self._runtime.get(name, fresh=True) if fresh else self._runtime.get(name)), fresh=fresh)
|
| 419 |
|
|
@@ -422,10 +461,17 @@ class _AssemblyStore:
|
|
| 422 |
lambda: self._runtime.get_projection(name, drop=drop))
|
| 423 |
|
| 424 |
def get_entry(self, name, entry):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
return self._read(name, ("entry", str(entry)),
|
| 426 |
lambda: self._runtime.get_entry(name, entry))
|
| 427 |
|
| 428 |
def _read_strict(self, name):
|
|
|
|
|
|
|
| 429 |
reader = getattr(self._runtime, "_read_strict", self._runtime.get)
|
| 430 |
return self._read(name, "strict", lambda: reader(name))
|
| 431 |
|
|
@@ -438,11 +484,17 @@ class _AssemblyStore:
|
|
| 438 |
return token
|
| 439 |
|
| 440 |
def update(self, name, *args, **kwargs):
|
|
|
|
|
|
|
|
|
|
| 441 |
self.cacheable = False
|
| 442 |
self.docs = {key: value for key, value in self.docs.items() if key[0] != name}
|
| 443 |
return self._runtime.update(name, *args, **kwargs)
|
| 444 |
|
| 445 |
def put(self, name, *args, **kwargs):
|
|
|
|
|
|
|
|
|
|
| 446 |
self.cacheable = False
|
| 447 |
self.docs = {key: value for key, value in self.docs.items() if key[0] != name}
|
| 448 |
return self._runtime.put(name, *args, **kwargs)
|
|
@@ -461,26 +513,33 @@ def _wall_stamp(session, table_key):
|
|
| 461 |
|
| 462 |
|
| 463 |
def grid_assembly(session: Session, scope: str = "customer", storage_key: str = "",
|
| 464 |
-
consume_corrections: bool = False, *, build=None, pool_stamp=None
|
|
|
|
| 465 |
"""C2: one wall- and revision-scoped memo for customer, product and stored envelopes."""
|
| 466 |
global grid_assembly_shared
|
| 467 |
rt = session.runtime
|
|
|
|
| 468 |
if build is None:
|
| 469 |
-
build = lambda borrowed: _compute_grid_assembly(
|
|
|
|
| 470 |
if pool_stamp is None:
|
| 471 |
team_id, agent = _team_agent(session)
|
| 472 |
-
pool_stamp = lambda: _pool_stamp(rt, team_id, agent)
|
| 473 |
table_key = scope if scope.startswith("ut_") else (
|
| 474 |
"product_data" if scope == "product" else MODULE)
|
|
|
|
|
|
|
| 475 |
|
| 476 |
def base_key(revisions=()):
|
| 477 |
# _field_usage reads users.registry() from this global account store, including on pg.
|
| 478 |
-
uses_roster = scope != "product"
|
| 479 |
prefix = ("workspace_assembly", getattr(session, "tenant", None), scope,
|
| 480 |
getattr(session, "uname", None), getattr(session, "admin", False),
|
| 481 |
json.dumps(getattr(session, "user", {}), sort_keys=True,
|
| 482 |
separators=(",", ":"), default=str),
|
| 483 |
-
_wall_stamp(session, table_key) if memoable else None, pool_stamp()
|
|
|
|
|
|
|
| 484 |
if not memoable:
|
| 485 |
result = ((*prefix, json.dumps(None)), {})
|
| 486 |
return result
|
|
@@ -489,7 +548,8 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
|
|
| 489 |
for memo_key in list(rt.pool_cache):
|
| 490 |
if memo_key[:-2] == prefix:
|
| 491 |
names.update(name for name, _token in memo_key[-1])
|
| 492 |
-
tokens, users_stamp = _assembly_revisions(rt, names, uses_roster
|
|
|
|
| 493 |
result = ((*prefix, json.dumps(users_stamp, sort_keys=True, default=str)), tokens)
|
| 494 |
return result
|
| 495 |
|
|
@@ -505,7 +565,10 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
|
|
| 505 |
if not memoable:
|
| 506 |
# Partial sessions and revision-less readers keep their original build semantics,
|
| 507 |
# but concurrent callers can still borrow this flight's result.
|
| 508 |
-
|
|
|
|
|
|
|
|
|
|
| 509 |
return out
|
| 510 |
lent = assembly_rt
|
| 511 |
result = build(replace(session, runtime=lent))
|
|
@@ -520,11 +583,15 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
|
|
| 520 |
|
| 521 |
# Without a pool cache there is no runtime-scoped flight identity.
|
| 522 |
if not hasattr(rt, "pool_cache"):
|
| 523 |
-
|
|
|
|
|
|
|
|
|
|
| 524 |
return out
|
| 525 |
memoable = (is_dataclass(session)
|
| 526 |
and all(hasattr(session, name) for name in ("tenant", "uname", "admin", "user")))
|
| 527 |
-
assembly_rt = (rt if isinstance(rt, _AssemblyStore)
|
|
|
|
| 528 |
memoable = memoable and assembly_rt.cacheable
|
| 529 |
key, checked_tokens = base_key()
|
| 530 |
|
|
@@ -620,7 +687,7 @@ def grid_assembly(session: Session, scope: str = "customer", storage_key: str =
|
|
| 620 |
|
| 621 |
|
| 622 |
def _compute_grid_assembly(session: Session, scope: str = "customer", storage_key: str = "",
|
| 623 |
-
consume_corrections: bool = True):
|
| 624 |
"""ONE assembly of this session's grid state, shared by `/customers`, `/workspace` and the
|
| 625 |
events route (2026-07-31 — the standalone measure gap, owner item 1).
|
| 626 |
|
|
@@ -653,7 +720,7 @@ def _compute_grid_assembly(session: Session, scope: str = "customer", storage_ke
|
|
| 653 |
|
| 654 |
rt = session.runtime
|
| 655 |
team_id, agent = _team_agent(session)
|
| 656 |
-
rows_src = _pool_for(rt, team_id, agent)
|
| 657 |
# ⛔ THE ROW WALL, APPLIED BEFORE `pids` IS TAKEN. Everything downstream is bounded by that
|
| 658 |
# frozenset — `allowed_pids` for the workspace, cohort membership, measure resolution — so
|
| 659 |
# scoping here means a row this account may not see never enters ANY of them, rather than
|
|
@@ -676,8 +743,9 @@ def _compute_grid_assembly(session: Session, scope: str = "customer", storage_ke
|
|
| 676 |
# ⛔ THE SAME HANDLE GOES TO `allowed_pids` BELOW, AND THE PAIR IS NOT OPTIONAL. That is the
|
| 677 |
# WRITE wall to this one's READ wall; lending it here alone would make a user-generated rule
|
| 678 |
# narrow what an account SEES while leaving what it may PATCH untouched.
|
| 679 |
-
|
| 680 |
-
|
|
|
|
| 681 |
pids = frozenset(r["pid"] for r in rows_src if r.get("pid") is not None)
|
| 682 |
# ⭐ W38-T20 — THE COLUMN DEFINITIONS ARE READ **ONCE** PER ASSEMBLY AND THREADED, because
|
| 683 |
# `core.store.get` deep-copies whatever it hands back on every call. Three consumers want this
|
|
@@ -701,7 +769,7 @@ def _compute_grid_assembly(session: Session, scope: str = "customer", storage_ke
|
|
| 701 |
# number, so a per-user leftover under the same key is stale by construction. It is also what
|
| 702 |
# makes D-423 recoverable rather than permanent: a pre-fix per-user edit is shadowed, not
|
| 703 |
# promoted.
|
| 704 |
-
_shared = shared_cells(pids, st=rt)
|
| 705 |
if _shared:
|
| 706 |
_ov = dict(ws.get("overlays") or {})
|
| 707 |
for _pid, _cells in _shared.items():
|
|
@@ -839,7 +907,7 @@ def _compute_grid_assembly(session: Session, scope: str = "customer", storage_ke
|
|
| 839 |
|
| 840 |
today = time.strftime("%Y-%m-%d")
|
| 841 |
fields = aios_grid.project_date_recurrences(fields, today=today)
|
| 842 |
-
stamp = _pool_stamp(rt, team_id, agent)
|
| 843 |
# ⭐⭐ W38-T19 — THE METRICS CAPABILITY, AND THIS GRAIN NEEDS **THREE** GUARDS WHERE THE
|
| 844 |
# OTHER TWO NEED ONE. `routes_products` and `routes_tables` funnel their cells and their
|
| 845 |
# condition answers through helpers that short-circuit on an empty `offer`, so emptying the
|
|
@@ -853,10 +921,10 @@ def _compute_grid_assembly(session: Session, scope: str = "customer", storage_ke
|
|
| 853 |
measures = measure_resolve.offer(team_id, on_error=_measure_err) if may_metrics else []
|
| 854 |
measure_sets = measure_resolve.condition_sets(
|
| 855 |
[v.get("config") or {} for v in (views or [])], None, team_id, pids, today, stamp,
|
| 856 |
-
rt.mset_memo, on_error=_measure_err) if may_metrics else {}
|
| 857 |
# The derived channel: cohort membership cells + measure column values, ONE dict — the
|
| 858 |
# same read-only channel the embed host hands to rows_from_pool.
|
| 859 |
-
derived = aios_grid.cohort_cells(lists)
|
| 860 |
# ⭐ W33-T43 / owner item 12 ("One unique ID per database always"). The customer grid carried
|
| 861 |
# NO Odoo id column at all, while its retiring twin `ut_odoo_customers` carried `partner_id`
|
| 862 |
# as its join key — so the merge would have lost the one value every Odoo document joins on.
|
|
@@ -876,9 +944,11 @@ def _compute_grid_assembly(session: Session, scope: str = "customer", storage_ke
|
|
| 876 |
# grains already do under an empty offer. Deleting the column instead would be a second,
|
| 877 |
# louder behaviour for the same fact on one surface out of three, and it would destroy a
|
| 878 |
# definition the admin can restore with one tick.
|
|
|
|
| 879 |
for pid, cells in (measure_resolve.column_values(
|
| 880 |
-
|
| 881 |
-
on_error=_measure_err) if may_metrics
|
|
|
|
| 882 |
derived.setdefault(pid, {}).update(cells)
|
| 883 |
|
| 884 |
# Route stops and Zone membership are normalized system relations. They project into two
|
|
|
|
| 22 |
proof is single-process and would report green on exactly the thing that is still broken.
|
| 23 |
"""
|
| 24 |
import datetime as _dt
|
| 25 |
+
from copy import copy, deepcopy
|
| 26 |
from dataclasses import is_dataclass, replace
|
| 27 |
import hashlib
|
| 28 |
import json
|
|
|
|
| 70 |
return handle if isinstance(handle, store_pg.PgStore) else None
|
| 71 |
|
| 72 |
|
| 73 |
+
def _assembly_roster_stamp(tenant):
|
| 74 |
+
"""Only permission and visible identity changes invalidate workspace metadata."""
|
| 75 |
+
from core import users
|
| 76 |
+
from routes_admin import _tenant_of
|
| 77 |
+
roster = users.registry()
|
| 78 |
+
if not isinstance(roster, dict) or not roster:
|
| 79 |
+
# A failed roster read must never validate a previously permitted answer.
|
| 80 |
+
return time.time_ns()
|
| 81 |
+
keys = ("tenant", "name", "email", "avatar", "active", "role", "bus", "modules",
|
| 82 |
+
"agent", "perms", "perms_v", "platform_admin")
|
| 83 |
+
visible = {str(name): {key: record.get(key) for key in keys}
|
| 84 |
+
for name, record in roster.items()
|
| 85 |
+
if isinstance(record, dict) and _tenant_of(record) == tenant}
|
| 86 |
+
return hashlib.sha256(json.dumps(visible, sort_keys=True, separators=(",", ":"),
|
| 87 |
+
default=str).encode("utf-8")).hexdigest()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _assembly_revisions(runtime, names, uses_roster=False, roster_tenant=None, roster_memo=None):
|
| 91 |
"""Validate all tracked PostgreSQL documents in one round trip, with identical tokens."""
|
| 92 |
from core import store, store_pg
|
| 93 |
names = tuple(sorted(set(names)))
|
| 94 |
handle = _assembly_pg_store(runtime)
|
| 95 |
users_stamp = None
|
| 96 |
+
|
| 97 |
+
def roster_stamp(revision):
|
| 98 |
+
token = json.dumps(revision, sort_keys=True, default=str)
|
| 99 |
+
if roster_memo is None:
|
| 100 |
+
return _assembly_roster_stamp(roster_tenant)
|
| 101 |
+
if token not in roster_memo:
|
| 102 |
+
roster_memo[token] = _assembly_roster_stamp(roster_tenant)
|
| 103 |
+
return roster_memo[token]
|
| 104 |
+
|
| 105 |
if handle is None:
|
| 106 |
tokens = {name: _assembly_revision(runtime, name) for name in names}
|
| 107 |
if uses_roster:
|
| 108 |
+
users_stamp = roster_stamp(_assembly_revision(store, "users"))
|
| 109 |
return tokens, users_stamp
|
| 110 |
|
| 111 |
key = getattr(runtime, "store_key", str)
|
|
|
|
| 137 |
absent = {"rev": 0, "updated_at": None, "token": "pg:0"}
|
| 138 |
tokens = {name: dict(found.get(mapped, absent)) for name, mapped in keyed.items()}
|
| 139 |
if uses_roster:
|
| 140 |
+
users_stamp = roster_stamp(dict(found.get(roster_key, absent)) if same_roster
|
| 141 |
+
else _assembly_revision(store, "users"))
|
| 142 |
if isinstance(runtime, _AssemblyStore):
|
| 143 |
# The page may read these documents after its memo hit. Reuse this request's pre-read
|
| 144 |
# tokens without retaining any document bytes across requests.
|
|
|
|
| 295 |
"""
|
| 296 |
from core import field_permissions, shared_overlay
|
| 297 |
try:
|
| 298 |
+
document = shared_overlay.document(_shared_key(), st=st) if getattr(st, "schema_only", False) else None
|
| 299 |
field_permissions.migrate_legacy_fields(
|
| 300 |
+
_shared_key(), st=st, grant_topic="customer_data", shared_key=_shared_key(),
|
| 301 |
+
shared_document=document)
|
| 302 |
+
fields = shared_overlay.fields(_shared_key(), st=st, document=document)
|
| 303 |
# Normalized Routes use an invisible field-shaped bridge so the established Share dialog
|
| 304 |
# and grant registry can be reused. It is object metadata, never a customer column.
|
| 305 |
return {key: value for key, value in fields.items()
|
| 306 |
if not _is_route_share_bridge(value)}
|
| 307 |
+
except shared_overlay.SchemaUnavailable:
|
| 308 |
+
raise
|
| 309 |
except Exception: # noqa: BLE001
|
| 310 |
# Lenient like every other display read: an unreachable store degrades to "nothing is
|
| 311 |
# shared yet", never to a 500 on a grid that would otherwise render. The WALL does not
|
|
|
|
| 415 |
|
| 416 |
class _AssemblyStore:
|
| 417 |
"""One build's borrowed reads and their pre-read revisions, never a second cache."""
|
| 418 |
+
def __init__(self, runtime, *, schema_only=False):
|
| 419 |
self._runtime = runtime
|
| 420 |
+
self.schema_only = bool(schema_only)
|
| 421 |
self.docs, self.tokens = {}, {}
|
| 422 |
self._validated_tokens = {}
|
| 423 |
# A lent/test reader without its own coherent revision door can share a flight only.
|
|
|
|
| 439 |
except AttributeError:
|
| 440 |
self.cacheable = False
|
| 441 |
key = (name, shape)
|
| 442 |
+
if fresh or (not self.cacheable and not self.schema_only) or key not in self.docs:
|
| 443 |
self.docs[key] = read()
|
| 444 |
# TableStore readers can mutate nested projections; lend an independent read each time.
|
| 445 |
return deepcopy(self.docs[key])
|
| 446 |
|
| 447 |
def get(self, name, fresh=False):
|
| 448 |
+
if self.schema_only and fresh:
|
| 449 |
+
self.docs = {key: value for key, value in self.docs.items() if key[0] != name}
|
| 450 |
+
if self.schema_only and name.endswith("_table_workspace"):
|
| 451 |
+
return self._read(name, ("projection", ("overlays",)),
|
| 452 |
+
lambda: self._runtime.get_projection(name, drop=("overlays",)), fresh=fresh)
|
| 453 |
+
if self.schema_only and name.endswith("__shared"):
|
| 454 |
+
from core import shared_overlay
|
| 455 |
+
return shared_overlay.document(name[:-len("__shared")], st=self)
|
| 456 |
return self._read(name, "whole", lambda: (
|
| 457 |
self._runtime.get(name, fresh=True) if fresh else self._runtime.get(name)), fresh=fresh)
|
| 458 |
|
|
|
|
| 461 |
lambda: self._runtime.get_projection(name, drop=drop))
|
| 462 |
|
| 463 |
def get_entry(self, name, entry):
|
| 464 |
+
if self.schema_only:
|
| 465 |
+
backend = self._runtime._store() if callable(getattr(self._runtime, "_store", None)) else self._runtime
|
| 466 |
+
if not callable(getattr(backend, "get_entry", None)):
|
| 467 |
+
from core.shared_overlay import SchemaUnavailable
|
| 468 |
+
raise SchemaUnavailable("field definitions cannot be read without loading row cells")
|
| 469 |
return self._read(name, ("entry", str(entry)),
|
| 470 |
lambda: self._runtime.get_entry(name, entry))
|
| 471 |
|
| 472 |
def _read_strict(self, name):
|
| 473 |
+
if self.schema_only and name.endswith("_table_workspace"):
|
| 474 |
+
return self.get_projection(name, drop=("overlays",))
|
| 475 |
reader = getattr(self._runtime, "_read_strict", self._runtime.get)
|
| 476 |
return self._read(name, "strict", lambda: reader(name))
|
| 477 |
|
|
|
|
| 484 |
return token
|
| 485 |
|
| 486 |
def update(self, name, *args, **kwargs):
|
| 487 |
+
if self.schema_only:
|
| 488 |
+
from core.grid_events import StoreUnavailable
|
| 489 |
+
raise StoreUnavailable("field definitions need a full workspace refresh before they can be read")
|
| 490 |
self.cacheable = False
|
| 491 |
self.docs = {key: value for key, value in self.docs.items() if key[0] != name}
|
| 492 |
return self._runtime.update(name, *args, **kwargs)
|
| 493 |
|
| 494 |
def put(self, name, *args, **kwargs):
|
| 495 |
+
if self.schema_only:
|
| 496 |
+
from core.grid_events import StoreUnavailable
|
| 497 |
+
raise StoreUnavailable("field definitions need a full workspace refresh before they can be read")
|
| 498 |
self.cacheable = False
|
| 499 |
self.docs = {key: value for key, value in self.docs.items() if key[0] != name}
|
| 500 |
return self._runtime.put(name, *args, **kwargs)
|
|
|
|
| 513 |
|
| 514 |
|
| 515 |
def grid_assembly(session: Session, scope: str = "customer", storage_key: str = "",
|
| 516 |
+
consume_corrections: bool = False, *, build=None, pool_stamp=None,
|
| 517 |
+
with_rows: bool = True, needed=None):
|
| 518 |
"""C2: one wall- and revision-scoped memo for customer, product and stored envelopes."""
|
| 519 |
global grid_assembly_shared
|
| 520 |
rt = session.runtime
|
| 521 |
+
needed = None if needed is None else frozenset(str(key) for key in needed)
|
| 522 |
if build is None:
|
| 523 |
+
build = lambda borrowed: _compute_grid_assembly(
|
| 524 |
+
borrowed, scope, storage_key, False, with_rows=with_rows, needed=needed)
|
| 525 |
if pool_stamp is None:
|
| 526 |
team_id, agent = _team_agent(session)
|
| 527 |
+
pool_stamp = lambda: _pool_stamp(rt, team_id, agent) if with_rows else 0
|
| 528 |
table_key = scope if scope.startswith("ut_") else (
|
| 529 |
"product_data" if scope == "product" else MODULE)
|
| 530 |
+
# Pre/post-build validation shares one roster read only while its revision is unchanged.
|
| 531 |
+
roster_memo = {}
|
| 532 |
|
| 533 |
def base_key(revisions=()):
|
| 534 |
# _field_usage reads users.registry() from this global account store, including on pg.
|
| 535 |
+
uses_roster = scope != "product" and not getattr(session, "user", {}).get("qa_runner")
|
| 536 |
prefix = ("workspace_assembly", getattr(session, "tenant", None), scope,
|
| 537 |
getattr(session, "uname", None), getattr(session, "admin", False),
|
| 538 |
json.dumps(getattr(session, "user", {}), sort_keys=True,
|
| 539 |
separators=(",", ":"), default=str),
|
| 540 |
+
_wall_stamp(session, table_key) if memoable else None, pool_stamp(),
|
| 541 |
+
("full" if needed is None else ("columns", tuple(sorted(needed))))
|
| 542 |
+
if with_rows else "fields")
|
| 543 |
if not memoable:
|
| 544 |
result = ((*prefix, json.dumps(None)), {})
|
| 545 |
return result
|
|
|
|
| 548 |
for memo_key in list(rt.pool_cache):
|
| 549 |
if memo_key[:-2] == prefix:
|
| 550 |
names.update(name for name, _token in memo_key[-1])
|
| 551 |
+
tokens, users_stamp = _assembly_revisions(rt, names, uses_roster,
|
| 552 |
+
getattr(session, "tenant", None), roster_memo)
|
| 553 |
result = ((*prefix, json.dumps(users_stamp, sort_keys=True, default=str)), tokens)
|
| 554 |
return result
|
| 555 |
|
|
|
|
| 565 |
if not memoable:
|
| 566 |
# Partial sessions and revision-less readers keep their original build semantics,
|
| 567 |
# but concurrent callers can still borrow this flight's result.
|
| 568 |
+
borrowed = copy(session)
|
| 569 |
+
if not with_rows:
|
| 570 |
+
borrowed.runtime = _AssemblyStore(rt, schema_only=True)
|
| 571 |
+
out = (build(borrowed), (), False)
|
| 572 |
return out
|
| 573 |
lent = assembly_rt
|
| 574 |
result = build(replace(session, runtime=lent))
|
|
|
|
| 583 |
|
| 584 |
# Without a pool cache there is no runtime-scoped flight identity.
|
| 585 |
if not hasattr(rt, "pool_cache"):
|
| 586 |
+
borrowed = copy(session)
|
| 587 |
+
if not with_rows:
|
| 588 |
+
borrowed.runtime = _AssemblyStore(rt, schema_only=True)
|
| 589 |
+
out = own_copy(build(borrowed))
|
| 590 |
return out
|
| 591 |
memoable = (is_dataclass(session)
|
| 592 |
and all(hasattr(session, name) for name in ("tenant", "uname", "admin", "user")))
|
| 593 |
+
assembly_rt = (rt if isinstance(rt, _AssemblyStore) and rt.schema_only == (not with_rows)
|
| 594 |
+
else _AssemblyStore(rt, schema_only=not with_rows)) if memoable else None
|
| 595 |
memoable = memoable and assembly_rt.cacheable
|
| 596 |
key, checked_tokens = base_key()
|
| 597 |
|
|
|
|
| 687 |
|
| 688 |
|
| 689 |
def _compute_grid_assembly(session: Session, scope: str = "customer", storage_key: str = "",
|
| 690 |
+
consume_corrections: bool = True, *, with_rows: bool = True, needed=None):
|
| 691 |
"""ONE assembly of this session's grid state, shared by `/customers`, `/workspace` and the
|
| 692 |
events route (2026-07-31 — the standalone measure gap, owner item 1).
|
| 693 |
|
|
|
|
| 720 |
|
| 721 |
rt = session.runtime
|
| 722 |
team_id, agent = _team_agent(session)
|
| 723 |
+
rows_src = _pool_for(rt, team_id, agent) if with_rows else []
|
| 724 |
# ⛔ THE ROW WALL, APPLIED BEFORE `pids` IS TAKEN. Everything downstream is bounded by that
|
| 725 |
# frozenset — `allowed_pids` for the workspace, cohort membership, measure resolution — so
|
| 726 |
# scoping here means a row this account may not see never enters ANY of them, rather than
|
|
|
|
| 743 |
# ⛔ THE SAME HANDLE GOES TO `allowed_pids` BELOW, AND THE PAIR IS NOT OPTIONAL. That is the
|
| 744 |
# WRITE wall to this one's READ wall; lending it here alone would make a user-generated rule
|
| 745 |
# narrow what an account SEES while leaving what it may PATCH untouched.
|
| 746 |
+
if with_rows:
|
| 747 |
+
rows_src = perm_scope.apply_row_scope(rows_src, session.user, MODULE, aios_grid.FIELDS,
|
| 748 |
+
st=rt)
|
| 749 |
pids = frozenset(r["pid"] for r in rows_src if r.get("pid") is not None)
|
| 750 |
# ⭐ W38-T20 — THE COLUMN DEFINITIONS ARE READ **ONCE** PER ASSEMBLY AND THREADED, because
|
| 751 |
# `core.store.get` deep-copies whatever it hands back on every call. Three consumers want this
|
|
|
|
| 769 |
# number, so a per-user leftover under the same key is stale by construction. It is also what
|
| 770 |
# makes D-423 recoverable rather than permanent: a pre-fix per-user edit is shadowed, not
|
| 771 |
# promoted.
|
| 772 |
+
_shared = shared_cells(pids, st=rt) if with_rows else {}
|
| 773 |
if _shared:
|
| 774 |
_ov = dict(ws.get("overlays") or {})
|
| 775 |
for _pid, _cells in _shared.items():
|
|
|
|
| 907 |
|
| 908 |
today = time.strftime("%Y-%m-%d")
|
| 909 |
fields = aios_grid.project_date_recurrences(fields, today=today)
|
| 910 |
+
stamp = _pool_stamp(rt, team_id, agent) if with_rows else 0
|
| 911 |
# ⭐⭐ W38-T19 — THE METRICS CAPABILITY, AND THIS GRAIN NEEDS **THREE** GUARDS WHERE THE
|
| 912 |
# OTHER TWO NEED ONE. `routes_products` and `routes_tables` funnel their cells and their
|
| 913 |
# condition answers through helpers that short-circuit on an empty `offer`, so emptying the
|
|
|
|
| 921 |
measures = measure_resolve.offer(team_id, on_error=_measure_err) if may_metrics else []
|
| 922 |
measure_sets = measure_resolve.condition_sets(
|
| 923 |
[v.get("config") or {} for v in (views or [])], None, team_id, pids, today, stamp,
|
| 924 |
+
rt.mset_memo, on_error=_measure_err) if may_metrics and with_rows and needed is None else {}
|
| 925 |
# The derived channel: cohort membership cells + measure column values, ONE dict — the
|
| 926 |
# same read-only channel the embed host hands to rows_from_pool.
|
| 927 |
+
derived = aios_grid.cohort_cells(lists) if with_rows else {}
|
| 928 |
# ⭐ W33-T43 / owner item 12 ("One unique ID per database always"). The customer grid carried
|
| 929 |
# NO Odoo id column at all, while its retiring twin `ut_odoo_customers` carried `partner_id`
|
| 930 |
# as its join key — so the merge would have lost the one value every Odoo document joins on.
|
|
|
|
| 944 |
# grains already do under an empty offer. Deleting the column instead would be a second,
|
| 945 |
# louder behaviour for the same fact on one surface out of three, and it would destroy a
|
| 946 |
# definition the admin can restore with one tick.
|
| 947 |
+
materialized_fields = fields if needed is None else [f for f in fields if f.get("key") in needed]
|
| 948 |
for pid, cells in (measure_resolve.column_values(
|
| 949 |
+
materialized_fields, team_id, pids, today, stamp, rt.measure_memo,
|
| 950 |
+
on_error=_measure_err) if may_metrics and with_rows and
|
| 951 |
+
(needed is None or aios_grid.measure_fields_of(materialized_fields)) else {}).items():
|
| 952 |
derived.setdefault(pid, {}).update(cells)
|
| 953 |
|
| 954 |
# Route stops and Zone membership are normalized system relations. They project into two
|
api/routes_grid.py
CHANGED
|
@@ -321,7 +321,7 @@ def _map_setup(scope, fields, runtime):
|
|
| 321 |
|
| 322 |
@router.get("/workspace")
|
| 323 |
def workspace(scope: str = "customer",
|
| 324 |
-
session: Session = Depends(require_session)):
|
| 325 |
"""The durable table workspace for this session: views, fields, overlays, folders.
|
| 326 |
|
| 327 |
⛔ WAVE 21 (C4): the wall is TOPIC-SHAPED, so the DEPENDENCY is session-only and each scope
|
|
@@ -343,7 +343,7 @@ def workspace(scope: str = "customer",
|
|
| 343 |
wave-9 leak rule. Omitting it would hand a Fisch-scoped user a member list built by a
|
| 344 |
full-access user.
|
| 345 |
"""
|
| 346 |
-
from core import grid_events
|
| 347 |
from routes_customers import grid_assembly
|
| 348 |
|
| 349 |
scope = _scope_or_400(scope)
|
|
@@ -366,9 +366,13 @@ def workspace(scope: str = "customer",
|
|
| 366 |
# bought nothing and cost everything — it is why `?scope=ut_odoo_gl_lines` answered
|
| 367 |
# `409 window_required` six times out of six on the live deploy while the ROWS door for
|
| 368 |
# the same table served a page in ~150 ms, i.e. a grid that could not be opened at all.
|
| 369 |
-
g = ut_assembly(session, scope, storage_key=storage_key, with_rows=False
|
| 370 |
-
|
| 371 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 372 |
except grid_events.StoreUnavailable:
|
| 373 |
raise err(503, "store_unavailable", "the tenant store is unavailable")
|
| 374 |
workspace = g["workspace"]
|
|
@@ -399,7 +403,8 @@ def workspace(scope: str = "customer",
|
|
| 399 |
workspace["permissionUserOptions"] = []
|
| 400 |
workspace["userAvatars"] = {}
|
| 401 |
workspace["scopeKey"] = scope
|
| 402 |
-
workspace["auditTimestamps"] =
|
|
|
|
| 403 |
map_setup = _map_setup(scope, workspace["fields"], session.runtime)
|
| 404 |
if map_setup:
|
| 405 |
workspace["mapSetup"] = map_setup
|
|
@@ -409,6 +414,8 @@ def workspace(scope: str = "customer",
|
|
| 409 |
# `missing` on a shortened cohort). An unannounced empty scope is the silent limit R6
|
| 410 |
# forbids; this is the announcement, and W31-T22 is the ticket that renders it.
|
| 411 |
workspace["limits"] = g.get("limits") or []
|
|
|
|
|
|
|
| 412 |
return {"workspace": workspace}
|
| 413 |
|
| 414 |
# ── Wave 16 C-TOPIC: the PRODUCT surface has its own assembly (own pool, own field
|
|
@@ -424,9 +431,13 @@ def workspace(scope: str = "customer",
|
|
| 424 |
session.require(PRODUCT_MODULE)
|
| 425 |
storage_key = f"{session.tenant}:product-list:{session.uname}:all:all"
|
| 426 |
try:
|
| 427 |
-
g = product_assembly(session, scope=scope, storage_key=storage_key
|
| 428 |
-
|
| 429 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 430 |
except grid_events.StoreUnavailable:
|
| 431 |
raise err(503, "store_unavailable", "the tenant store is unavailable")
|
| 432 |
workspace = g["workspace"]
|
|
@@ -456,10 +467,13 @@ def workspace(scope: str = "customer",
|
|
| 456 |
workspace["permissionUserOptions"] = []
|
| 457 |
workspace["userAvatars"] = {}
|
| 458 |
workspace["scopeKey"] = scope
|
| 459 |
-
workspace["auditTimestamps"] =
|
|
|
|
| 460 |
map_setup = _map_setup(scope, workspace["fields"], session.runtime)
|
| 461 |
if map_setup:
|
| 462 |
workspace["mapSetup"] = map_setup
|
|
|
|
|
|
|
| 463 |
return {"workspace": workspace}
|
| 464 |
|
| 465 |
# The storage key mirrors the host's own convention byte-for-byte (app.py's `_table_grid`
|
|
@@ -483,9 +497,12 @@ def workspace(scope: str = "customer",
|
|
| 483 |
# never rendered, `cohortMode` never arrived, and the Cohort route silently drew the Customer
|
| 484 |
# surface. One projection for both servers is the fix that cannot drift.
|
| 485 |
try:
|
| 486 |
-
g = grid_assembly(session, scope=scope, storage_key=storage_key)
|
| 487 |
-
|
| 488 |
-
|
|
|
|
|
|
|
|
|
|
| 489 |
except grid_events.StoreUnavailable:
|
| 490 |
raise err(503, "store_unavailable", "the tenant store is unavailable")
|
| 491 |
workspace = g["workspace"]
|
|
@@ -546,8 +563,12 @@ def workspace(scope: str = "customer",
|
|
| 546 |
# ⚠ Deliberately NOT `hideViews`: `cohortMode` is what swaps the Views panel for the cohort
|
| 547 |
# list, and two switches for one behaviour would drift.
|
| 548 |
workspace["scopeKey"] = scope
|
| 549 |
-
|
| 550 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 551 |
map_setup = _map_setup(scope, workspace["fields"], session.runtime)
|
| 552 |
if map_setup:
|
| 553 |
workspace["mapSetup"] = map_setup
|
|
|
|
| 321 |
|
| 322 |
@router.get("/workspace")
|
| 323 |
def workspace(scope: str = "customer",
|
| 324 |
+
session: Session = Depends(require_session), fields_only: bool = False):
|
| 325 |
"""The durable table workspace for this session: views, fields, overlays, folders.
|
| 326 |
|
| 327 |
⛔ WAVE 21 (C4): the wall is TOPIC-SHAPED, so the DEPENDENCY is session-only and each scope
|
|
|
|
| 343 |
wave-9 leak rule. Omitting it would hand a Fisch-scoped user a member list built by a
|
| 344 |
full-access user.
|
| 345 |
"""
|
| 346 |
+
from core import grid_events, shared_overlay
|
| 347 |
from routes_customers import grid_assembly
|
| 348 |
|
| 349 |
scope = _scope_or_400(scope)
|
|
|
|
| 366 |
# bought nothing and cost everything — it is why `?scope=ut_odoo_gl_lines` answered
|
| 367 |
# `409 window_required` six times out of six on the live deploy while the ROWS door for
|
| 368 |
# the same table served a page in ~150 ms, i.e. a grid that could not be opened at all.
|
| 369 |
+
g = ut_assembly(session, scope, storage_key=storage_key, with_rows=False,
|
| 370 |
+
fields_only=fields_only)
|
| 371 |
+
if not fields_only:
|
| 372 |
+
grid_events.workspace_corrections(session.runtime, scope + '_table_workspace',
|
| 373 |
+
session.uname, g)
|
| 374 |
+
except shared_overlay.SchemaUnavailable as exc:
|
| 375 |
+
raise err(503, "schema_unavailable", str(exc))
|
| 376 |
except grid_events.StoreUnavailable:
|
| 377 |
raise err(503, "store_unavailable", "the tenant store is unavailable")
|
| 378 |
workspace = g["workspace"]
|
|
|
|
| 403 |
workspace["permissionUserOptions"] = []
|
| 404 |
workspace["userAvatars"] = {}
|
| 405 |
workspace["scopeKey"] = scope
|
| 406 |
+
workspace["auditTimestamps"] = ({} if fields_only else
|
| 407 |
+
_audit_timestamps(scope, g["pids"], set(), session.runtime))
|
| 408 |
map_setup = _map_setup(scope, workspace["fields"], session.runtime)
|
| 409 |
if map_setup:
|
| 410 |
workspace["mapSetup"] = map_setup
|
|
|
|
| 414 |
# `missing` on a shortened cohort). An unannounced empty scope is the silent limit R6
|
| 415 |
# forbids; this is the announcement, and W31-T22 is the ticket that renders it.
|
| 416 |
workspace["limits"] = g.get("limits") or []
|
| 417 |
+
if fields_only:
|
| 418 |
+
workspace["fieldsOnly"] = True
|
| 419 |
return {"workspace": workspace}
|
| 420 |
|
| 421 |
# ── Wave 16 C-TOPIC: the PRODUCT surface has its own assembly (own pool, own field
|
|
|
|
| 431 |
session.require(PRODUCT_MODULE)
|
| 432 |
storage_key = f"{session.tenant}:product-list:{session.uname}:all:all"
|
| 433 |
try:
|
| 434 |
+
g = product_assembly(session, scope=scope, storage_key=storage_key,
|
| 435 |
+
with_rows=not fields_only)
|
| 436 |
+
if not fields_only:
|
| 437 |
+
grid_events.workspace_corrections(session.runtime, 'product_table_workspace',
|
| 438 |
+
session.uname, g)
|
| 439 |
+
except shared_overlay.SchemaUnavailable as exc:
|
| 440 |
+
raise err(503, "schema_unavailable", str(exc))
|
| 441 |
except grid_events.StoreUnavailable:
|
| 442 |
raise err(503, "store_unavailable", "the tenant store is unavailable")
|
| 443 |
workspace = g["workspace"]
|
|
|
|
| 467 |
workspace["permissionUserOptions"] = []
|
| 468 |
workspace["userAvatars"] = {}
|
| 469 |
workspace["scopeKey"] = scope
|
| 470 |
+
workspace["auditTimestamps"] = ({} if fields_only else
|
| 471 |
+
_audit_timestamps(scope, g["pids"], set(), session.runtime))
|
| 472 |
map_setup = _map_setup(scope, workspace["fields"], session.runtime)
|
| 473 |
if map_setup:
|
| 474 |
workspace["mapSetup"] = map_setup
|
| 475 |
+
if fields_only:
|
| 476 |
+
workspace["fieldsOnly"] = True
|
| 477 |
return {"workspace": workspace}
|
| 478 |
|
| 479 |
# The storage key mirrors the host's own convention byte-for-byte (app.py's `_table_grid`
|
|
|
|
| 497 |
# never rendered, `cohortMode` never arrived, and the Cohort route silently drew the Customer
|
| 498 |
# surface. One projection for both servers is the fix that cannot drift.
|
| 499 |
try:
|
| 500 |
+
g = grid_assembly(session, scope=scope, storage_key=storage_key, with_rows=not fields_only)
|
| 501 |
+
if not fields_only:
|
| 502 |
+
grid_events.workspace_corrections(session.runtime, 'customer_table_workspace',
|
| 503 |
+
session.uname, g)
|
| 504 |
+
except shared_overlay.SchemaUnavailable as exc:
|
| 505 |
+
raise err(503, "schema_unavailable", str(exc))
|
| 506 |
except grid_events.StoreUnavailable:
|
| 507 |
raise err(503, "store_unavailable", "the tenant store is unavailable")
|
| 508 |
workspace = g["workspace"]
|
|
|
|
| 563 |
# ⚠ Deliberately NOT `hideViews`: `cohortMode` is what swaps the Views panel for the cohort
|
| 564 |
# list, and two switches for one behaviour would drift.
|
| 565 |
workspace["scopeKey"] = scope
|
| 566 |
+
if fields_only:
|
| 567 |
+
workspace["auditTimestamps"] = {}
|
| 568 |
+
workspace["fieldsOnly"] = True
|
| 569 |
+
else:
|
| 570 |
+
ctx = _ctx(session, g["fields"], g["pids"], scope_key=scope)
|
| 571 |
+
workspace["auditTimestamps"] = _audit_timestamps(scope, g["pids"], ctx.hidden_keys, session.runtime)
|
| 572 |
map_setup = _map_setup(scope, workspace["fields"], session.runtime)
|
| 573 |
if map_setup:
|
| 574 |
workspace["mapSetup"] = map_setup
|
api/routes_nav.py
CHANGED
|
@@ -562,10 +562,14 @@ def _odoo_connection_folders(runtime):
|
|
| 562 |
return {}, None
|
| 563 |
try:
|
| 564 |
import core.keychain as keychain
|
|
|
|
| 565 |
import odoo_relational as odoo_rel
|
|
|
|
|
|
|
|
|
|
| 566 |
connections = 0
|
| 567 |
labels = {}
|
| 568 |
-
for row in keychain.list_entries(
|
| 569 |
if str(row.get("type") or "") != "odoo":
|
| 570 |
continue
|
| 571 |
connections += 1
|
|
@@ -574,8 +578,8 @@ def _odoo_connection_folders(runtime):
|
|
| 574 |
if cid and label and label.lower() not in _RESERVED_GROUP_LABELS:
|
| 575 |
labels[cid] = label
|
| 576 |
if connections < 2:
|
| 577 |
-
return {}, odoo_rel.default_connection_id(
|
| 578 |
-
return labels, odoo_rel.default_connection_id(
|
| 579 |
except Exception: # noqa: BLE001
|
| 580 |
return {}, None
|
| 581 |
|
|
|
|
| 562 |
return {}, None
|
| 563 |
try:
|
| 564 |
import core.keychain as keychain
|
| 565 |
+
import core.user_tables as user_tables
|
| 566 |
import odoo_relational as odoo_rel
|
| 567 |
+
# Both existing metadata resolvers see this one request's captured document. The
|
| 568 |
+
# keychain bucket is explicitly supplied; it never joins the automatic lend list.
|
| 569 |
+
borrowed = user_tables.lend(runtime, **{keychain.KEY: runtime.get(keychain.KEY) or {}})
|
| 570 |
connections = 0
|
| 571 |
labels = {}
|
| 572 |
+
for row in keychain.list_entries(borrowed):
|
| 573 |
if str(row.get("type") or "") != "odoo":
|
| 574 |
continue
|
| 575 |
connections += 1
|
|
|
|
| 578 |
if cid and label and label.lower() not in _RESERVED_GROUP_LABELS:
|
| 579 |
labels[cid] = label
|
| 580 |
if connections < 2:
|
| 581 |
+
return {}, odoo_rel.default_connection_id(borrowed)
|
| 582 |
+
return labels, odoo_rel.default_connection_id(borrowed)
|
| 583 |
except Exception: # noqa: BLE001
|
| 584 |
return {}, None
|
| 585 |
|
api/routes_products.py
CHANGED
|
@@ -109,7 +109,7 @@ def _pool_for(rt, team_id):
|
|
| 109 |
return scope_cache.get(rt.pool_cache, key, _CACHE_TTL, build)
|
| 110 |
|
| 111 |
|
| 112 |
-
def scoped_pool(session: Session):
|
| 113 |
"""`(pids, team_id, rows_src, fields_base)` — THE PRODUCT WALL, on its own.
|
| 114 |
|
| 115 |
Extracted from `product_assembly` (wave 19, item 12) so a caller that needs only "which
|
|
@@ -124,7 +124,7 @@ def scoped_pool(session: Session):
|
|
| 124 |
|
| 125 |
team_id, _agent = perm_scope.derive_pool_scope(session.user, MODULE)
|
| 126 |
try:
|
| 127 |
-
rows_src = _pool_for(session.runtime, team_id)
|
| 128 |
except Exception as e:
|
| 129 |
raise err(503, "pool_unavailable",
|
| 130 |
f"the product catalogue could not be built; {str(e)[:160]}")
|
|
@@ -132,7 +132,8 @@ def scoped_pool(session: Session):
|
|
| 132 |
# the field wall runs so every reader receives the same metadata and the
|
| 133 |
# Leadership account owns the permission editor from the first request.
|
| 134 |
import modules.product_data as pd
|
| 135 |
-
|
|
|
|
| 136 |
fields_base = pd_fields(consolidated=team_id is None, st=session.runtime)
|
| 137 |
# The SAME wall the customer assembly applies, in the same order: rows first (before pids
|
| 138 |
# are taken, so an out-of-filter row never enters allowed_pids), then the field closure,
|
|
@@ -148,9 +149,10 @@ def scoped_pool(session: Session):
|
|
| 148 |
fields_base = list(fields_base) + [
|
| 149 |
field for field in enabled_raw if field.get("key") not in field_keys
|
| 150 |
]
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
|
|
|
| 154 |
pids = frozenset(r["pid"] for r in rows_src if r.get("pid") is not None)
|
| 155 |
return pids, team_id, rows_src, fields_base
|
| 156 |
|
|
@@ -397,17 +399,19 @@ def _project_enabled_raw_rows(rows, enabled, *, drop_source=False):
|
|
| 397 |
|
| 398 |
|
| 399 |
def product_assembly(session: Session, scope: str = "product", storage_key: str = "",
|
| 400 |
-
consume_corrections: bool = False):
|
| 401 |
from routes_customers import grid_assembly
|
| 402 |
from core import perm_scope
|
| 403 |
team_id, _agent = perm_scope.derive_pool_scope(session.user, MODULE)
|
| 404 |
return grid_assembly(session, scope, storage_key,
|
| 405 |
-
build=lambda borrowed: _compute_product_assembly(
|
| 406 |
-
|
|
|
|
|
|
|
| 407 |
|
| 408 |
|
| 409 |
def _compute_product_assembly(session: Session, scope: str = "product", storage_key: str = "",
|
| 410 |
-
consume_corrections: bool = False):
|
| 411 |
"""The product topic's mirror of `routes_customers.grid_assembly` — SAME g-dict keys, so
|
| 412 |
the /workspace and events routes consume either interchangeably.
|
| 413 |
|
|
@@ -437,7 +441,7 @@ def _compute_product_assembly(session: Session, scope: str = "product", storage_
|
|
| 437 |
import aios_grid
|
| 438 |
import core.perm_scope as perm_scope
|
| 439 |
import modules.product_data as pd
|
| 440 |
-
pids, team_id, rows_src, fields_base = scoped_pool(session)
|
| 441 |
shared_defs = pd.shared_fields(st=session.runtime)
|
| 442 |
|
| 443 |
ctx = grid_events.EventCtx(
|
|
@@ -457,7 +461,7 @@ def _compute_product_assembly(session: Session, scope: str = "product", storage_
|
|
| 457 |
# shared value can therefore never leak INTO the per-user bucket by way of this merge.
|
| 458 |
# ⚠ SHARED WINS per key — these are contract columns, so the tenant-wide value is the answer
|
| 459 |
# and any per-user leftover under the same key is stale by construction.
|
| 460 |
-
_shared = pd.shared_cells(pids, st=session.runtime)
|
| 461 |
if _shared:
|
| 462 |
_ov = dict(ws.get("overlays") or {})
|
| 463 |
for _pid, _cells in _shared.items():
|
|
@@ -513,15 +517,17 @@ def _compute_product_assembly(session: Session, scope: str = "product", storage_
|
|
| 513 |
|
| 514 |
today = time.strftime("%Y-%m-%d")
|
| 515 |
fields = aios_grid.project_date_recurrences(fields, today=today)
|
| 516 |
-
stamp = _measure_stamp(session.runtime, team_id)
|
| 517 |
measures = product_measures(session)
|
| 518 |
|
| 519 |
# R9: the Cohorts column's cells, built from THIS topic's lists. ⭐ W37-T10 — the measure
|
| 520 |
# half of this same read-only channel is no longer empty; the customer assembly merges its
|
| 521 |
# measure columns here for exactly the same reason and through the same door.
|
| 522 |
-
derived = aios_grid.cohort_cells(lists)
|
| 523 |
-
|
| 524 |
-
|
|
|
|
|
|
|
| 525 |
derived.setdefault(pid, {}).update(cells)
|
| 526 |
|
| 527 |
# ⛔ THE CONDITION CHANNEL SHIPS WITH THE OFFER, NOT AFTER IT. `routes_grid` derives
|
|
@@ -529,14 +535,16 @@ def _compute_product_assembly(session: Session, scope: str = "product", storage_
|
|
| 529 |
# filter builder offers measure conditions — and an id missing from `measureSets` renders as
|
| 530 |
# PENDING ("Calculating…") and matches nothing, permanently. Serving the offer without this
|
| 531 |
# would trade one honest absence for a spinner that never resolves.
|
| 532 |
-
measure_sets = _measure_condition_sets(views, measures, rows_src, team_id, today)
|
|
|
|
| 533 |
|
| 534 |
from core import user_tables as _zones
|
| 535 |
fields = _zones.with_zone_field("product_data", fields, st=session.runtime)
|
| 536 |
# Existing supplier-master defaults and imported overlay cells predate W43's write-time
|
| 537 |
# choice hydration. Build their effective, already-walled row values before returning the
|
| 538 |
# field contract so a populated select never opens as "no choices yet".
|
| 539 |
-
|
|
|
|
| 540 |
# ⭐⭐ D-590 (wave 46 hotfix) — **THE PER-TENANT SCHEMA OVERLAY, APPLIED TO THE GRID READ.**
|
| 541 |
# ⛔ THIS SURFACE IS THE ONE W46-T40 FAILED ON, and the staged spec named only the customer and
|
| 542 |
# user-table assemblies because lane E traced `routes_grid.py::workspace` alone. T40's evidence
|
|
|
|
| 109 |
return scope_cache.get(rt.pool_cache, key, _CACHE_TTL, build)
|
| 110 |
|
| 111 |
|
| 112 |
+
def scoped_pool(session: Session, *, with_rows: bool = True):
|
| 113 |
"""`(pids, team_id, rows_src, fields_base)` — THE PRODUCT WALL, on its own.
|
| 114 |
|
| 115 |
Extracted from `product_assembly` (wave 19, item 12) so a caller that needs only "which
|
|
|
|
| 124 |
|
| 125 |
team_id, _agent = perm_scope.derive_pool_scope(session.user, MODULE)
|
| 126 |
try:
|
| 127 |
+
rows_src = _pool_for(session.runtime, team_id) if with_rows else []
|
| 128 |
except Exception as e:
|
| 129 |
raise err(503, "pool_unavailable",
|
| 130 |
f"the product catalogue could not be built; {str(e)[:160]}")
|
|
|
|
| 132 |
# the field wall runs so every reader receives the same metadata and the
|
| 133 |
# Leadership account owns the permission editor from the first request.
|
| 134 |
import modules.product_data as pd
|
| 135 |
+
if with_rows:
|
| 136 |
+
pd.image_field_definition(st=session.runtime)
|
| 137 |
fields_base = pd_fields(consolidated=team_id is None, st=session.runtime)
|
| 138 |
# The SAME wall the customer assembly applies, in the same order: rows first (before pids
|
| 139 |
# are taken, so an out-of-filter row never enters allowed_pids), then the field closure,
|
|
|
|
| 149 |
fields_base = list(fields_base) + [
|
| 150 |
field for field in enabled_raw if field.get("key") not in field_keys
|
| 151 |
]
|
| 152 |
+
if with_rows:
|
| 153 |
+
rows_src = _project_enabled_raw_rows(rows_src, enabled_raw, drop_source=True)
|
| 154 |
+
rows_src = perm_scope.apply_row_scope(rows_src, session.user, MODULE, fields_base,
|
| 155 |
+
st=session.runtime)
|
| 156 |
pids = frozenset(r["pid"] for r in rows_src if r.get("pid") is not None)
|
| 157 |
return pids, team_id, rows_src, fields_base
|
| 158 |
|
|
|
|
| 399 |
|
| 400 |
|
| 401 |
def product_assembly(session: Session, scope: str = "product", storage_key: str = "",
|
| 402 |
+
consume_corrections: bool = False, *, with_rows: bool = True, needed=None):
|
| 403 |
from routes_customers import grid_assembly
|
| 404 |
from core import perm_scope
|
| 405 |
team_id, _agent = perm_scope.derive_pool_scope(session.user, MODULE)
|
| 406 |
return grid_assembly(session, scope, storage_key,
|
| 407 |
+
build=lambda borrowed: _compute_product_assembly(
|
| 408 |
+
borrowed, scope, storage_key, False, with_rows=with_rows, needed=needed),
|
| 409 |
+
pool_stamp=lambda: _measure_stamp(session.runtime, team_id) if with_rows else 0,
|
| 410 |
+
with_rows=with_rows, needed=needed)
|
| 411 |
|
| 412 |
|
| 413 |
def _compute_product_assembly(session: Session, scope: str = "product", storage_key: str = "",
|
| 414 |
+
consume_corrections: bool = False, *, with_rows: bool = True, needed=None):
|
| 415 |
"""The product topic's mirror of `routes_customers.grid_assembly` — SAME g-dict keys, so
|
| 416 |
the /workspace and events routes consume either interchangeably.
|
| 417 |
|
|
|
|
| 441 |
import aios_grid
|
| 442 |
import core.perm_scope as perm_scope
|
| 443 |
import modules.product_data as pd
|
| 444 |
+
pids, team_id, rows_src, fields_base = scoped_pool(session, with_rows=with_rows)
|
| 445 |
shared_defs = pd.shared_fields(st=session.runtime)
|
| 446 |
|
| 447 |
ctx = grid_events.EventCtx(
|
|
|
|
| 461 |
# shared value can therefore never leak INTO the per-user bucket by way of this merge.
|
| 462 |
# ⚠ SHARED WINS per key — these are contract columns, so the tenant-wide value is the answer
|
| 463 |
# and any per-user leftover under the same key is stale by construction.
|
| 464 |
+
_shared = pd.shared_cells(pids, st=session.runtime) if with_rows else {}
|
| 465 |
if _shared:
|
| 466 |
_ov = dict(ws.get("overlays") or {})
|
| 467 |
for _pid, _cells in _shared.items():
|
|
|
|
| 517 |
|
| 518 |
today = time.strftime("%Y-%m-%d")
|
| 519 |
fields = aios_grid.project_date_recurrences(fields, today=today)
|
| 520 |
+
stamp = _measure_stamp(session.runtime, team_id) if with_rows else 0
|
| 521 |
measures = product_measures(session)
|
| 522 |
|
| 523 |
# R9: the Cohorts column's cells, built from THIS topic's lists. ⭐ W37-T10 — the measure
|
| 524 |
# half of this same read-only channel is no longer empty; the customer assembly merges its
|
| 525 |
# measure columns here for exactly the same reason and through the same door.
|
| 526 |
+
derived = aios_grid.cohort_cells(lists) if with_rows else {}
|
| 527 |
+
materialized_fields = fields if needed is None else [f for f in fields if f.get("key") in needed]
|
| 528 |
+
for pid, cells in (_measure_cells(materialized_fields, rows_src, team_id, today, stamp,
|
| 529 |
+
session.runtime.measure_memo, measures)
|
| 530 |
+
if with_rows and (needed is None or aios_grid.measure_fields_of(materialized_fields)) else {}).items():
|
| 531 |
derived.setdefault(pid, {}).update(cells)
|
| 532 |
|
| 533 |
# ⛔ THE CONDITION CHANNEL SHIPS WITH THE OFFER, NOT AFTER IT. `routes_grid` derives
|
|
|
|
| 535 |
# filter builder offers measure conditions — and an id missing from `measureSets` renders as
|
| 536 |
# PENDING ("Calculating…") and matches nothing, permanently. Serving the offer without this
|
| 537 |
# would trade one honest absence for a spinner that never resolves.
|
| 538 |
+
measure_sets = (_measure_condition_sets(views, measures, rows_src, team_id, today)
|
| 539 |
+
if with_rows and needed is None else {})
|
| 540 |
|
| 541 |
from core import user_tables as _zones
|
| 542 |
fields = _zones.with_zone_field("product_data", fields, st=session.runtime)
|
| 543 |
# Existing supplier-master defaults and imported overlay cells predate W43's write-time
|
| 544 |
# choice hydration. Build their effective, already-walled row values before returning the
|
| 545 |
# field contract so a populated select never opens as "no choices yet".
|
| 546 |
+
if with_rows:
|
| 547 |
+
fields = _hydrate_effective_choice_options(fields, rows_src, ws.get("overlays"), derived)
|
| 548 |
# ⭐⭐ D-590 (wave 46 hotfix) — **THE PER-TENANT SCHEMA OVERLAY, APPLIED TO THE GRID READ.**
|
| 549 |
# ⛔ THIS SURFACE IS THE ONE W46-T40 FAILED ON, and the staged spec named only the customer and
|
| 550 |
# user-table assemblies because lane E traced `routes_grid.py::workspace` alone. T40's evidence
|
api/routes_sheet.py
CHANGED
|
@@ -326,7 +326,7 @@ def _amazon_stored_spec(cur, table_key):
|
|
| 326 |
return spec
|
| 327 |
|
| 328 |
|
| 329 |
-
def _registry_assembly(session: Session, table_key: str):
|
| 330 |
"""The `g` dict `/workspace` builds for one compiled registry grid, or a NAMED refusal.
|
| 331 |
|
| 332 |
⭐⭐ W53-T13 — THIS IS THE FIX, AND IT IS A SECOND CALLER OF AN ESTABLISHED PATH RATHER THAN A
|
|
@@ -366,22 +366,27 @@ def _registry_assembly(session: Session, table_key: str):
|
|
| 366 |
if memo is None:
|
| 367 |
memo = {}
|
| 368 |
session._sheet_assemblies = memo
|
| 369 |
-
if
|
| 370 |
-
|
|
|
|
|
|
|
|
|
|
| 371 |
try:
|
| 372 |
# W62 C2: a placed ut_* view needs its own field vocabulary, without fetching its rows.
|
| 373 |
if table_key.startswith("ut_"):
|
| 374 |
from routes_tables import ut_assembly
|
| 375 |
-
memo[
|
| 376 |
-
|
|
|
|
| 377 |
if table_key == "product_data":
|
| 378 |
from routes_products import product_assembly
|
| 379 |
-
memo[
|
| 380 |
-
|
| 381 |
-
return memo[
|
| 382 |
from routes_customers import grid_assembly
|
| 383 |
-
memo[
|
| 384 |
-
|
|
|
|
| 385 |
except perm_scope.Denied:
|
| 386 |
raise err(403, "database_unreadable", f"You cannot read {table_key}.")
|
| 387 |
except HTTPException:
|
|
@@ -458,7 +463,7 @@ def _legacy_linked_keys(database, entry):
|
|
| 458 |
def _related_condition_fields(session, database):
|
| 459 |
from core import perm_scope
|
| 460 |
_require_database(session, database)
|
| 461 |
-
fields = list(_registry_assembly(session, database).get("fields") or [])
|
| 462 |
hidden = perm_scope.hidden_keys(session.user, database, fields, st=session.runtime)
|
| 463 |
return [field for field in fields if field.get("key") not in hidden
|
| 464 |
and field.get("type") not in {"formula", "link", "lookup", "rollup", "metric", "measure"}
|
|
@@ -575,6 +580,15 @@ def distinct_values(database: str, field: str = Query(...),
|
|
| 575 |
@router.get("/sheets/filter-fields/{database}")
|
| 576 |
def linked_filter_fields(database: str, session: Session = Depends(require_session)):
|
| 577 |
"""Offer ordinary conditions grouped by their readable related database."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 578 |
from core import perm_scope, relations
|
| 579 |
database = _require_database(session, database)
|
| 580 |
_fields, defs, entries = _related_declarations(session, database)
|
|
@@ -655,9 +669,10 @@ def _registry_mirror(session: Session, cur, table_key: str, metric_window, neede
|
|
| 655 |
be a second answer to that question, from the one door that never asked it.
|
| 656 |
|
| 657 |
⭐⭐ W54-T36 — `needed` IS THE COLUMN SET THIS CELL CAN POSSIBLY READ, AND `None` IS EVERY
|
| 658 |
-
COLUMN.
|
| 659 |
-
|
| 660 |
-
so a refusal can name a column the
|
|
|
|
| 661 |
|
| 662 |
⛔⛔ IT IS INTERSECTED WITH THE ASSEMBLY'S OWN FIELDS AND MUST STAY THAT WAY. `cols` is what
|
| 663 |
`_resolve_binding` subtracts a row wall's columns from to decide whether the wall can be
|
|
@@ -670,11 +685,15 @@ def _registry_mirror(session: Session, cur, table_key: str, metric_window, neede
|
|
| 670 |
import routes_odoo_tables as rot
|
| 671 |
from modules import sheet as sheet_mod
|
| 672 |
|
| 673 |
-
g = _registry_assembly(session, table_key)
|
| 674 |
fields = list(g.get("fields") or [])
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 678 |
if table_key == "customer_data" and (needed is None or "agent_id" in needed):
|
| 679 |
from core import perm_scope
|
| 680 |
agent_field = {"key": "agent_id", "type": "int", "label": "Current agent ID"}
|
|
@@ -1816,14 +1835,17 @@ def _import_sentence(report):
|
|
| 1816 |
"""What a finished import SAYS, in digits (R16). No em dash and no en dash."""
|
| 1817 |
compared = int(report.get("compared") or 0)
|
| 1818 |
matched = int(report.get("matched") or 0)
|
| 1819 |
-
|
| 1820 |
-
|
|
|
|
|
|
|
| 1821 |
if compared:
|
| 1822 |
-
line += ("
|
| 1823 |
-
|
| 1824 |
if report.get("unsupported"):
|
| 1825 |
-
|
| 1826 |
-
|
|
|
|
| 1827 |
return line
|
| 1828 |
|
| 1829 |
|
|
@@ -2944,10 +2966,12 @@ def _sheet_request_scope(session):
|
|
| 2944 |
reads of the same document object (the Daily Sales repair projects in rounds and does not).
|
| 2945 |
"""
|
| 2946 |
previous = getattr(session, "_sheet_read_memo", None)
|
|
|
|
| 2947 |
memo = {"today": _sheet_today(session),
|
| 2948 |
"stats": {"engines": 0, "resolves": 0, "input_hits": 0}}
|
| 2949 |
try:
|
| 2950 |
session._sheet_read_memo = memo
|
|
|
|
| 2951 |
except Exception: # noqa: BLE001
|
| 2952 |
yield None
|
| 2953 |
return
|
|
@@ -2955,6 +2979,7 @@ def _sheet_request_scope(session):
|
|
| 2955 |
yield memo
|
| 2956 |
finally:
|
| 2957 |
session._sheet_read_memo = previous
|
|
|
|
| 2958 |
|
| 2959 |
|
| 2960 |
def _request_scoped(route):
|
|
@@ -3318,7 +3343,7 @@ def _read_binding_cell(session, ref, *, book=None, tab=None, today=None, seen=()
|
|
| 3318 |
cell = cells.get(key)
|
| 3319 |
if not any(fr.a1_key("A1", name).rpartition("!")[0] == key.rpartition("!")[0]
|
| 3320 |
for name in names):
|
| 3321 |
-
refuse("the
|
| 3322 |
if isinstance(cell, dict) and cell.get("state") in ("refused", "stale") \
|
| 3323 |
and cell.get("kind") != "formula" and cell.get("kind") != "bound":
|
| 3324 |
refuse((cell.get("refusal") or {}).get("message") or
|
|
|
|
| 326 |
return spec
|
| 327 |
|
| 328 |
|
| 329 |
+
def _registry_assembly(session: Session, table_key: str, *, with_rows: bool = True, needed=None):
|
| 330 |
"""The `g` dict `/workspace` builds for one compiled registry grid, or a NAMED refusal.
|
| 331 |
|
| 332 |
⭐⭐ W53-T13 — THIS IS THE FIX, AND IT IS A SECOND CALLER OF AN ESTABLISHED PATH RATHER THAN A
|
|
|
|
| 366 |
if memo is None:
|
| 367 |
memo = {}
|
| 368 |
session._sheet_assemblies = memo
|
| 369 |
+
needed = None if needed is None else frozenset(str(key) for key in needed)
|
| 370 |
+
shape = ("full" if needed is None else ("columns", tuple(sorted(needed)))) if with_rows else "fields"
|
| 371 |
+
slot = (table_key, shape)
|
| 372 |
+
if slot in memo:
|
| 373 |
+
return memo[slot]
|
| 374 |
try:
|
| 375 |
# W62 C2: a placed ut_* view needs its own field vocabulary, without fetching its rows.
|
| 376 |
if table_key.startswith("ut_"):
|
| 377 |
from routes_tables import ut_assembly
|
| 378 |
+
memo[slot] = ut_assembly(session, table_key, consume_corrections=False,
|
| 379 |
+
with_rows=False, fields_only=not with_rows, needed=needed)
|
| 380 |
+
return memo[slot]
|
| 381 |
if table_key == "product_data":
|
| 382 |
from routes_products import product_assembly
|
| 383 |
+
memo[slot] = product_assembly(session, scope="product",
|
| 384 |
+
consume_corrections=False, with_rows=with_rows, needed=needed)
|
| 385 |
+
return memo[slot]
|
| 386 |
from routes_customers import grid_assembly
|
| 387 |
+
memo[slot] = grid_assembly(session, scope="customer", consume_corrections=False,
|
| 388 |
+
with_rows=with_rows, needed=needed)
|
| 389 |
+
return memo[slot]
|
| 390 |
except perm_scope.Denied:
|
| 391 |
raise err(403, "database_unreadable", f"You cannot read {table_key}.")
|
| 392 |
except HTTPException:
|
|
|
|
| 463 |
def _related_condition_fields(session, database):
|
| 464 |
from core import perm_scope
|
| 465 |
_require_database(session, database)
|
| 466 |
+
fields = list(_registry_assembly(session, database, with_rows=False).get("fields") or [])
|
| 467 |
hidden = perm_scope.hidden_keys(session.user, database, fields, st=session.runtime)
|
| 468 |
return [field for field in fields if field.get("key") not in hidden
|
| 469 |
and field.get("type") not in {"formula", "link", "lookup", "rollup", "metric", "measure"}
|
|
|
|
| 580 |
@router.get("/sheets/filter-fields/{database}")
|
| 581 |
def linked_filter_fields(database: str, session: Session = Depends(require_session)):
|
| 582 |
"""Offer ordinary conditions grouped by their readable related database."""
|
| 583 |
+
from copy import copy
|
| 584 |
+
from routes_customers import _AssemblyStore
|
| 585 |
+
borrowed = copy(session)
|
| 586 |
+
borrowed.runtime = _AssemblyStore(session.runtime, schema_only=True)
|
| 587 |
+
with _sheet_request_scope(borrowed):
|
| 588 |
+
return _linked_filter_fields(database, borrowed)
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
def _linked_filter_fields(database, session):
|
| 592 |
from core import perm_scope, relations
|
| 593 |
database = _require_database(session, database)
|
| 594 |
_fields, defs, entries = _related_declarations(session, database)
|
|
|
|
| 669 |
be a second answer to that question, from the one door that never asked it.
|
| 670 |
|
| 671 |
⭐⭐ W54-T36 — `needed` IS THE COLUMN SET THIS CELL CAN POSSIBLY READ, AND `None` IS EVERY
|
| 672 |
+
COLUMN. The existing assembly keeps its full permitted definitions and row-wall inputs,
|
| 673 |
+
while unused metric cells and view-condition sets are not computed. Rows retain the same
|
| 674 |
+
authorized ids and `spec["fields"]` keeps the full list so a refusal can name a column the
|
| 675 |
+
mirror did not carry. The canonical selection belongs to the existing assembly identity.
|
| 676 |
|
| 677 |
⛔⛔ IT IS INTERSECTED WITH THE ASSEMBLY'S OWN FIELDS AND MUST STAY THAT WAY. `cols` is what
|
| 678 |
`_resolve_binding` subtracts a row wall's columns from to decide whether the wall can be
|
|
|
|
| 685 |
import routes_odoo_tables as rot
|
| 686 |
from modules import sheet as sheet_mod
|
| 687 |
|
| 688 |
+
g = _registry_assembly(session, table_key, needed=needed)
|
| 689 |
fields = list(g.get("fields") or [])
|
| 690 |
+
kept = (fields if needed is None else [f for f in fields if str(f.get("key") or "") in needed])
|
| 691 |
+
metric_input = g if needed is None else {**g, "fields": kept}
|
| 692 |
+
derived, bounded, limits = _metric_derived(session, table_key, metric_input, metric_window)
|
| 693 |
+
# Authorization has already scoped rows using the full wall vocabulary. Restrict only
|
| 694 |
+
# cell materialization; an empty selection is ids-only, not rows_from_pool's all-fields default.
|
| 695 |
+
rows = (aios_grid.rows_from_pool(g["rows_src"], kept, (g.get("ws") or {}).get("overlays"),
|
| 696 |
+
derived=derived) if kept else [{"pid": row["pid"]} for row in g["rows_src"]])
|
| 697 |
if table_key == "customer_data" and (needed is None or "agent_id" in needed):
|
| 698 |
from core import perm_scope
|
| 699 |
agent_field = {"key": "agent_id", "type": "int", "label": "Current agent ID"}
|
|
|
|
| 1835 |
"""What a finished import SAYS, in digits (R16). No em dash and no en dash."""
|
| 1836 |
compared = int(report.get("compared") or 0)
|
| 1837 |
matched = int(report.get("matched") or 0)
|
| 1838 |
+
cells = int(report.get("cells") or 0)
|
| 1839 |
+
formulas = int(report.get("formulas") or 0)
|
| 1840 |
+
line = (f"Imported {cells} cell{'' if cells == 1 else 's'} and "
|
| 1841 |
+
f"{formulas} formula{'' if formulas == 1 else 's'}.")
|
| 1842 |
if compared:
|
| 1843 |
+
line += (f" Matched {matched} of {compared} recalculated cell{'' if compared == 1 else 's'} against the "
|
| 1844 |
+
f"{'answer' if compared == 1 else 'answers'} the file had stored.")
|
| 1845 |
if report.get("unsupported"):
|
| 1846 |
+
kinds = len(report["unsupported"])
|
| 1847 |
+
line += (f" {kinds} kind{'' if kinds == 1 else 's'} of thing "
|
| 1848 |
+
"in that file could not be carried over.")
|
| 1849 |
return line
|
| 1850 |
|
| 1851 |
|
|
|
|
| 2966 |
reads of the same document object (the Daily Sales repair projects in rounds and does not).
|
| 2967 |
"""
|
| 2968 |
previous = getattr(session, "_sheet_read_memo", None)
|
| 2969 |
+
previous_assemblies = getattr(session, "_sheet_assemblies", None)
|
| 2970 |
memo = {"today": _sheet_today(session),
|
| 2971 |
"stats": {"engines": 0, "resolves": 0, "input_hits": 0}}
|
| 2972 |
try:
|
| 2973 |
session._sheet_read_memo = memo
|
| 2974 |
+
session._sheet_assemblies = {}
|
| 2975 |
except Exception: # noqa: BLE001
|
| 2976 |
yield None
|
| 2977 |
return
|
|
|
|
| 2979 |
yield memo
|
| 2980 |
finally:
|
| 2981 |
session._sheet_read_memo = previous
|
| 2982 |
+
session._sheet_assemblies = previous_assemblies
|
| 2983 |
|
| 2984 |
|
| 2985 |
def _request_scoped(route):
|
|
|
|
| 3343 |
cell = cells.get(key)
|
| 3344 |
if not any(fr.a1_key("A1", name).rpartition("!")[0] == key.rpartition("!")[0]
|
| 3345 |
for name in names):
|
| 3346 |
+
refuse("the referenced sheet is missing.")
|
| 3347 |
if isinstance(cell, dict) and cell.get("state") in ("refused", "stale") \
|
| 3348 |
and cell.get("kind") != "formula" and cell.get("kind") != "bound":
|
| 3349 |
refuse((cell.get("refusal") or {}).get("message") or
|
api/routes_tables.py
CHANGED
|
@@ -199,8 +199,11 @@ def _ut():
|
|
| 199 |
def _table_lend(runtime, table_key, defs_only=False):
|
| 200 |
"""Borrow one entry for the wall and page; old snapshot stores retain their lend."""
|
| 201 |
ut = _ut()
|
|
|
|
|
|
|
|
|
|
| 202 |
if _ut()._entry_reader(runtime) is None:
|
| 203 |
-
return ut.
|
| 204 |
try:
|
| 205 |
entry = ut.get_one(table_key, st=runtime)
|
| 206 |
except Exception as exc:
|
|
@@ -1348,17 +1351,21 @@ def _field_usage(session, table_key, fields, defn, ws_st, ws_key, st=None):
|
|
| 1348 |
|
| 1349 |
|
| 1350 |
def ut_assembly(session: Session, table_key: str, storage_key: str = "",
|
| 1351 |
-
consume_corrections: bool = False, with_rows: bool = True, st=None
|
|
|
|
| 1352 |
if not with_rows and st is None:
|
| 1353 |
from routes_customers import grid_assembly
|
| 1354 |
return grid_assembly(session, table_key, storage_key,
|
| 1355 |
-
build=lambda borrowed: _compute_ut_assembly(
|
| 1356 |
-
|
| 1357 |
-
|
|
|
|
|
|
|
| 1358 |
|
| 1359 |
|
| 1360 |
def _compute_ut_assembly(session: Session, table_key: str, storage_key: str = "",
|
| 1361 |
-
consume_corrections: bool = False, with_rows: bool = True, st=None
|
|
|
|
| 1362 |
"""The user-table mirror of `grid_assembly` / `product_assembly` — SAME g-dict keys, so
|
| 1363 |
`/workspace` and the events route consume any of the three interchangeably.
|
| 1364 |
|
|
@@ -1393,7 +1400,11 @@ def _compute_ut_assembly(session: Session, table_key: str, storage_key: str = ""
|
|
| 1393 |
# reading that bucket once per question asked of it.
|
| 1394 |
if st is None:
|
| 1395 |
st = _table_lend(session.runtime, table_key, defs_only=not with_rows)
|
| 1396 |
-
if
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1397 |
# ⭐ W33-T03 (D-214): `st` is a caller's LEND, threaded to the wall and nowhere else. Only
|
| 1398 |
# a READ route passes one — see `scoped_pool`'s own note and contract C5.
|
| 1399 |
pids, rows_src, fields_base, defn = scoped_pool(session, table_key, st=st)
|
|
@@ -1544,9 +1555,11 @@ def _compute_ut_assembly(session: Session, table_key: str, storage_key: str = ""
|
|
| 1544 |
# which is the honest answer for a hand-typed one rather than a descope.
|
| 1545 |
today = _recurrence_today
|
| 1546 |
measures = ut_measures(table_key, session)
|
| 1547 |
-
derived = aios_grid.cohort_cells(lists)
|
| 1548 |
-
|
| 1549 |
-
|
|
|
|
|
|
|
| 1550 |
derived.setdefault(_pid, {}).update(_cells)
|
| 1551 |
|
| 1552 |
# ⭐⭐ D-590 (wave 46 hotfix) — **THE PER-TENANT SCHEMA OVERLAY, APPLIED TO THE GRID READ.**
|
|
@@ -1583,7 +1596,8 @@ def _compute_ut_assembly(session: Session, table_key: str, storage_key: str = ""
|
|
| 1583 |
# here (`table_rows`) is layering strata in a fixed order.
|
| 1584 |
"shared_cells": shared_cells,
|
| 1585 |
"measures": measures,
|
| 1586 |
-
"measure_sets": _ut_measure_sets(table_key, views, measures, pids, today)
|
|
|
|
| 1587 |
"today": today,
|
| 1588 |
# ⚠ ALWAYS PRESENT, EMPTY WHEN THERE IS NOTHING TO SAY — a key a consumer has to test
|
| 1589 |
# for is a key a consumer forgets to test for, and this one carries a refusal.
|
|
|
|
| 199 |
def _table_lend(runtime, table_key, defs_only=False):
|
| 200 |
"""Borrow one entry for the wall and page; old snapshot stores retain their lend."""
|
| 201 |
ut = _ut()
|
| 202 |
+
if defs_only:
|
| 203 |
+
# Metadata must enter through the store projection, even on entry-capable stores.
|
| 204 |
+
return ut.lend_defs(runtime)
|
| 205 |
if _ut()._entry_reader(runtime) is None:
|
| 206 |
+
return ut.lend(runtime)
|
| 207 |
try:
|
| 208 |
entry = ut.get_one(table_key, st=runtime)
|
| 209 |
except Exception as exc:
|
|
|
|
| 1351 |
|
| 1352 |
|
| 1353 |
def ut_assembly(session: Session, table_key: str, storage_key: str = "",
|
| 1354 |
+
consume_corrections: bool = False, with_rows: bool = True, st=None,
|
| 1355 |
+
*, fields_only: bool = False, needed=None):
|
| 1356 |
if not with_rows and st is None:
|
| 1357 |
from routes_customers import grid_assembly
|
| 1358 |
return grid_assembly(session, table_key, storage_key,
|
| 1359 |
+
build=lambda borrowed: _compute_ut_assembly(
|
| 1360 |
+
borrowed, table_key, storage_key, False, False, fields_only=fields_only, needed=needed),
|
| 1361 |
+
pool_stamp=lambda: 0, with_rows=not fields_only, needed=needed)
|
| 1362 |
+
return _compute_ut_assembly(session, table_key, storage_key, False, with_rows, st,
|
| 1363 |
+
fields_only=fields_only, needed=needed)
|
| 1364 |
|
| 1365 |
|
| 1366 |
def _compute_ut_assembly(session: Session, table_key: str, storage_key: str = "",
|
| 1367 |
+
consume_corrections: bool = False, with_rows: bool = True, st=None,
|
| 1368 |
+
*, fields_only: bool = False, needed=None):
|
| 1369 |
"""The user-table mirror of `grid_assembly` / `product_assembly` — SAME g-dict keys, so
|
| 1370 |
`/workspace` and the events route consume any of the three interchangeably.
|
| 1371 |
|
|
|
|
| 1400 |
# reading that bucket once per question asked of it.
|
| 1401 |
if st is None:
|
| 1402 |
st = _table_lend(session.runtime, table_key, defs_only=not with_rows)
|
| 1403 |
+
if fields_only:
|
| 1404 |
+
defn = _defn_or_refuse(session, table_key, st=st, defs_only=True, scope_applied=True)
|
| 1405 |
+
fields_base = list(defn.get("fields") or [])
|
| 1406 |
+
pids, rows_src = frozenset(), []
|
| 1407 |
+
elif with_rows:
|
| 1408 |
# ⭐ W33-T03 (D-214): `st` is a caller's LEND, threaded to the wall and nowhere else. Only
|
| 1409 |
# a READ route passes one — see `scoped_pool`'s own note and contract C5.
|
| 1410 |
pids, rows_src, fields_base, defn = scoped_pool(session, table_key, st=st)
|
|
|
|
| 1555 |
# which is the honest answer for a hand-typed one rather than a descope.
|
| 1556 |
today = _recurrence_today
|
| 1557 |
measures = ut_measures(table_key, session)
|
| 1558 |
+
derived = aios_grid.cohort_cells(lists) if not fields_only else {}
|
| 1559 |
+
materialized_fields = fields if needed is None else [f for f in fields if f.get("key") in needed]
|
| 1560 |
+
for _pid, _cells in (_ut_measure_cells(table_key, materialized_fields, pids, today, measures,
|
| 1561 |
+
getattr(session.runtime, 'measure_memo', {}))
|
| 1562 |
+
if not fields_only and (needed is None or aios_grid.measure_fields_of(materialized_fields)) else {}).items():
|
| 1563 |
derived.setdefault(_pid, {}).update(_cells)
|
| 1564 |
|
| 1565 |
# ⭐⭐ D-590 (wave 46 hotfix) — **THE PER-TENANT SCHEMA OVERLAY, APPLIED TO THE GRID READ.**
|
|
|
|
| 1596 |
# here (`table_rows`) is layering strata in a fixed order.
|
| 1597 |
"shared_cells": shared_cells,
|
| 1598 |
"measures": measures,
|
| 1599 |
+
"measure_sets": (_ut_measure_sets(table_key, views, measures, pids, today)
|
| 1600 |
+
if not fields_only and needed is None else {}),
|
| 1601 |
"today": today,
|
| 1602 |
# ⚠ ALWAYS PRESENT, EMPTY WHEN THERE IS NOTHING TO SAY — a key a consumer has to test
|
| 1603 |
# for is a key a consumer forgets to test for, and this one carries a refusal.
|
platform/core/field_permissions.py
CHANGED
|
@@ -1157,7 +1157,8 @@ def reconcile_shared_permissions(shared_key, grant_topic, st=None, shared_docume
|
|
| 1157 |
# agree without turning ungoverned contract fields into read-only fields.
|
| 1158 |
updated[grant_mark] = True
|
| 1159 |
updated["permissions"] = derived
|
| 1160 |
-
|
|
|
|
| 1161 |
if isinstance(shared_document, dict):
|
| 1162 |
shared_document.setdefault("fields", {})[key] = updated
|
| 1163 |
rewritten += 1
|
|
@@ -1374,6 +1375,30 @@ def migrate_legacy_fields(table_key, st=None, known_users=None, grant_topic=None
|
|
| 1374 |
if not key or st is None:
|
| 1375 |
return {"promoted": 0, "normalized": 0, "reclassified": 0,
|
| 1376 |
"suppressed": 0, "purged": 0, "folded": 0}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1377 |
# ⭐⭐ W50-T23 — THE FOLD RUNS BEFORE THE RECONCILE, AND THE ORDER IS THE POINT. A definition
|
| 1378 |
# that arrives from the legacy bucket must be classified by the same pass that classifies
|
| 1379 |
# every other one; folding after the reconcile would leave the newcomer unreconciled until
|
|
|
|
| 1157 |
# agree without turning ungoverned contract fields into read-only fields.
|
| 1158 |
updated[grant_mark] = True
|
| 1159 |
updated["permissions"] = derived
|
| 1160 |
+
if not getattr(st, "schema_only", False):
|
| 1161 |
+
shared_overlay.put_field(bucket, key, updated, st=st)
|
| 1162 |
if isinstance(shared_document, dict):
|
| 1163 |
shared_document.setdefault("fields", {})[key] = updated
|
| 1164 |
rewritten += 1
|
|
|
|
| 1375 |
if not key or st is None:
|
| 1376 |
return {"promoted": 0, "normalized": 0, "reclassified": 0,
|
| 1377 |
"suppressed": 0, "purged": 0, "folded": 0}
|
| 1378 |
+
if getattr(st, "schema_only", False):
|
| 1379 |
+
# The same migration decisions and grant classifier, over detached definitions only.
|
| 1380 |
+
# A pending copy-before-remove operation belongs to the full read door.
|
| 1381 |
+
fold_legacy_shared_bucket(shared_key, st=st)
|
| 1382 |
+
document = (workspace_document if isinstance(workspace_document, dict)
|
| 1383 |
+
else st.get_projection(key, drop=("overlays",)))
|
| 1384 |
+
shared = (shared_document if isinstance(shared_document, dict)
|
| 1385 |
+
else shared_overlay.document(shared_key, st=st))
|
| 1386 |
+
tombstoned = _live_tombstones(document)
|
| 1387 |
+
for owner, workspace in (document or {}).items():
|
| 1388 |
+
if owner == WORKSPACE_SHARED_MEMBER or not isinstance(workspace, dict):
|
| 1389 |
+
continue
|
| 1390 |
+
for field_key, original in (workspace.get("fields") or {}).items():
|
| 1391 |
+
if (str(field_key) not in tombstoned and _field_is_migratable(original)
|
| 1392 |
+
and stored_permissions(original, fallback="collaborative",
|
| 1393 |
+
known_users=known_users)["edit"] != "personal"):
|
| 1394 |
+
raise shared_overlay.SchemaUnavailable(
|
| 1395 |
+
'field definitions need a full workspace refresh to finish migration')
|
| 1396 |
+
reclassified = reconcile_shared_permissions(
|
| 1397 |
+
shared_key, grant_key, st=st, shared_document=shared)
|
| 1398 |
+
for dead in tombstoned:
|
| 1399 |
+
(shared.get("fields") or {}).pop(dead, None)
|
| 1400 |
+
return {"promoted": 0, "normalized": 0, "reclassified": reclassified,
|
| 1401 |
+
"suppressed": 0, "purged": 0, "folded": 0}
|
| 1402 |
# ⭐⭐ W50-T23 — THE FOLD RUNS BEFORE THE RECONCILE, AND THE ORDER IS THE POINT. A definition
|
| 1403 |
# that arrives from the legacy bucket must be classified by the same pass that classifies
|
| 1404 |
# every other one; folding after the reconcile would leave the newcomer unreconciled until
|
platform/core/grid_events.py
CHANGED
|
@@ -1181,7 +1181,7 @@ def _refuse(ctx, code, message, key='', *, event='field_upsert'):
|
|
| 1181 |
#: the same 24-event window still overwrites it, because that branch assigns the slot directly.
|
| 1182 |
#: Widening `EventResult` to a message LIST is the real fix and it is not this ticket's file.
|
| 1183 |
def _folder_refuse(ctx, kind, code, message, key=''):
|
| 1184 |
-
"""Refuse
|
| 1185 |
try:
|
| 1186 |
out = getattr(ctx, 'out', None)
|
| 1187 |
if out is not None:
|
|
@@ -1489,6 +1489,12 @@ def handle_one(event, ctx):
|
|
| 1489 |
requested_name = name
|
| 1490 |
if not view_id or not name:
|
| 1491 |
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1492 |
if 'permissions' in raw:
|
| 1493 |
return _refuse(
|
| 1494 |
ctx, 'view_permissions_retired',
|
|
@@ -3350,8 +3356,12 @@ def handle_one(event, ctx):
|
|
| 3350 |
|
| 3351 |
if kind == 'overlay_patch':
|
| 3352 |
pid = event.get('pid')
|
| 3353 |
-
if not isinstance(pid, int) or pid
|
| 3354 |
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3355 |
_history_table = str(ctx.scope_key or 'customer')
|
| 3356 |
if _history_table.startswith('ut_') and ctx.table is not None:
|
| 3357 |
import core.user_tables as _ut_history
|
|
|
|
| 1181 |
#: the same 24-event window still overwrites it, because that branch assigns the slot directly.
|
| 1182 |
#: Widening `EventResult` to a message LIST is the real fix and it is not this ticket's file.
|
| 1183 |
def _folder_refuse(ctx, kind, code, message, key=''):
|
| 1184 |
+
"""Refuse one event out loud: the machine record AND the rendered sentence."""
|
| 1185 |
try:
|
| 1186 |
out = getattr(ctx, 'out', None)
|
| 1187 |
if out is not None:
|
|
|
|
| 1489 |
requested_name = name
|
| 1490 |
if not view_id or not name:
|
| 1491 |
return False
|
| 1492 |
+
display = raw['config'].get('display')
|
| 1493 |
+
if isinstance(display, dict) and display.get('mode') == 'timeseries':
|
| 1494 |
+
return _folder_refuse(
|
| 1495 |
+
ctx, kind, 'view_mode_retired',
|
| 1496 |
+
'Time-series Views are retired. Choose an available View display mode.',
|
| 1497 |
+
key=view_id)
|
| 1498 |
if 'permissions' in raw:
|
| 1499 |
return _refuse(
|
| 1500 |
ctx, 'view_permissions_retired',
|
|
|
|
| 3356 |
|
| 3357 |
if kind == 'overlay_patch':
|
| 3358 |
pid = event.get('pid')
|
| 3359 |
+
if not isinstance(pid, int) or isinstance(pid, bool):
|
| 3360 |
return False
|
| 3361 |
+
if pid not in allowed_pids:
|
| 3362 |
+
return _folder_refuse(
|
| 3363 |
+
ctx, kind, 'row_outside_audience',
|
| 3364 |
+
'This edit was not applied because the record is outside your permitted audience.')
|
| 3365 |
_history_table = str(ctx.scope_key or 'customer')
|
| 3366 |
if _history_table.startswith('ut_') and ctx.table is not None:
|
| 3367 |
import core.user_tables as _ut_history
|
platform/core/shared_overlay.py
CHANGED
|
@@ -64,6 +64,10 @@ BUCKET_SUFFIX = '__shared'
|
|
| 64 |
#: in the tenant, so an unbounded one is an unbounded cost for all of them.
|
| 65 |
MAX_VALUE_CHARS = 32_768
|
| 66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
# ══════════════════════════ W41-T04 / CONTRACT C3 — ONE COLUMN-CREATION DOOR ══════════════════
|
| 68 |
#
|
| 69 |
# ⭐⭐ WHAT THIS ALLOWLIST IS FOR, AND WHY IT IS *HERE* RATHER THAN AT EACH CALLER. Before it,
|
|
@@ -141,6 +145,15 @@ def _read(table_key, st=None):
|
|
| 141 |
"""The whole stratum, always in its full two-key shape. Lenient like every other display
|
| 142 |
read: an unreachable store degrades to "nothing shared yet", never to an exception on a page
|
| 143 |
that would otherwise render."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
try:
|
| 145 |
data = _st(st).get(bucket(table_key)) or {}
|
| 146 |
except Exception:
|
|
@@ -251,11 +264,15 @@ def fold_legacy_bucket(legacy_key, table_key, st=None):
|
|
| 251 |
if not _may_hold_anything(legacy, st=st):
|
| 252 |
return {'fields': 0, 'cells': 0}
|
| 253 |
src = _read(legacy, st=st)
|
| 254 |
-
if not src['fields'] and not src['cells']:
|
| 255 |
return {'fields': 0, 'cells': 0}
|
| 256 |
dst = _read(canon, st=st)
|
| 257 |
add_fields = {key: defn for key, defn in src['fields'].items()
|
| 258 |
if isinstance(defn, dict) and key not in dst['fields']}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
add_cells = {}
|
| 260 |
for pid, values in src['cells'].items():
|
| 261 |
if not isinstance(values, dict):
|
|
|
|
| 64 |
#: in the tenant, so an unbounded one is an unbounded cost for all of them.
|
| 65 |
MAX_VALUE_CHARS = 32_768
|
| 66 |
|
| 67 |
+
|
| 68 |
+
class SchemaUnavailable(RuntimeError):
|
| 69 |
+
"""Definitions cannot be answered without an unfinished full-workspace migration."""
|
| 70 |
+
|
| 71 |
# ══════════════════════════ W41-T04 / CONTRACT C3 — ONE COLUMN-CREATION DOOR ══════════════════
|
| 72 |
#
|
| 73 |
# ⭐⭐ WHAT THIS ALLOWLIST IS FOR, AND WHY IT IS *HERE* RATHER THAN AT EACH CALLER. Before it,
|
|
|
|
| 145 |
"""The whole stratum, always in its full two-key shape. Lenient like every other display
|
| 146 |
read: an unreachable store degrades to "nothing shared yet", never to an exception on a page
|
| 147 |
that would otherwise render."""
|
| 148 |
+
if getattr(_st(st), 'schema_only', False):
|
| 149 |
+
reader = getattr(_st(st), 'get_entry', None)
|
| 150 |
+
if not callable(reader):
|
| 151 |
+
raise SchemaUnavailable('field definitions cannot be read without loading row cells')
|
| 152 |
+
fields = reader(bucket(table_key), 'fields')
|
| 153 |
+
if fields is not None and not isinstance(fields, dict):
|
| 154 |
+
raise SchemaUnavailable('the stored field definitions are unavailable')
|
| 155 |
+
# Asking this metadata document for cells must remain a loud programming error.
|
| 156 |
+
return store._Projected({'fields': dict(fields or {})}, ('cells',))
|
| 157 |
try:
|
| 158 |
data = _st(st).get(bucket(table_key)) or {}
|
| 159 |
except Exception:
|
|
|
|
| 264 |
if not _may_hold_anything(legacy, st=st):
|
| 265 |
return {'fields': 0, 'cells': 0}
|
| 266 |
src = _read(legacy, st=st)
|
| 267 |
+
if not src['fields'] and (getattr(_st(st), 'schema_only', False) or not src['cells']):
|
| 268 |
return {'fields': 0, 'cells': 0}
|
| 269 |
dst = _read(canon, st=st)
|
| 270 |
add_fields = {key: defn for key, defn in src['fields'].items()
|
| 271 |
if isinstance(defn, dict) and key not in dst['fields']}
|
| 272 |
+
if getattr(_st(st), 'schema_only', False):
|
| 273 |
+
if add_fields:
|
| 274 |
+
raise SchemaUnavailable('field definitions need a full workspace refresh to finish migration')
|
| 275 |
+
return {'fields': 0, 'cells': 0}
|
| 276 |
add_cells = {}
|
| 277 |
for pid, values in src['cells'].items():
|
| 278 |
if not isinstance(values, dict):
|
platform/core/sheets.py
CHANGED
|
@@ -1839,7 +1839,7 @@ def put_workbook(st, workbook_id, raw, expect_rev=None, *, actor="", actor_name=
|
|
| 1839 |
if expect_rev is not None and int(expect_rev) < int(prior.get("structureRev") or 0):
|
| 1840 |
raise SheetStaleRefusal(
|
| 1841 |
"sheet_structure_stale",
|
| 1842 |
-
"Rows or columns changed since you opened this workbook. This save was not applied.
|
| 1843 |
rev_current=int(prior.get("rev") or 0))
|
| 1844 |
if expect_rev is not None and int(prior.get("rev") or 0) != int(expect_rev):
|
| 1845 |
raise SheetStaleRefusal(
|
|
@@ -2167,12 +2167,12 @@ def patch_cells(st, workbook_id, tab_ref, raw_cells, expect_rev=None, *, actor="
|
|
| 2167 |
if revision < int(prior.get("structureRev") or 0):
|
| 2168 |
raise SheetStaleRefusal(
|
| 2169 |
"sheet_structure_stale",
|
| 2170 |
-
"Rows or columns changed since you opened this workbook. This save was not applied.
|
| 2171 |
rev_current=current)
|
| 2172 |
if revision < int(tab.get("writesFrom") or 0):
|
| 2173 |
raise SheetStaleRefusal(
|
| 2174 |
"sheet_revision_stale",
|
| 2175 |
-
"This tab's retained change history was truncated after your revision.
|
| 2176 |
rev_current=current)
|
| 2177 |
for write in writes:
|
| 2178 |
if int(write["rev"]) > revision and write["by"] != actor:
|
|
|
|
| 1839 |
if expect_rev is not None and int(expect_rev) < int(prior.get("structureRev") or 0):
|
| 1840 |
raise SheetStaleRefusal(
|
| 1841 |
"sheet_structure_stale",
|
| 1842 |
+
"Rows or columns changed since you opened this workbook. This save was not applied. Try again using the refreshed workbook.",
|
| 1843 |
rev_current=int(prior.get("rev") or 0))
|
| 1844 |
if expect_rev is not None and int(prior.get("rev") or 0) != int(expect_rev):
|
| 1845 |
raise SheetStaleRefusal(
|
|
|
|
| 2167 |
if revision < int(prior.get("structureRev") or 0):
|
| 2168 |
raise SheetStaleRefusal(
|
| 2169 |
"sheet_structure_stale",
|
| 2170 |
+
"Rows or columns changed since you opened this workbook. This save was not applied. Try again using the refreshed workbook.",
|
| 2171 |
rev_current=current)
|
| 2172 |
if revision < int(tab.get("writesFrom") or 0):
|
| 2173 |
raise SheetStaleRefusal(
|
| 2174 |
"sheet_revision_stale",
|
| 2175 |
+
"This tab's retained change history was truncated after your revision. This save was not applied. Try again using the refreshed tab.",
|
| 2176 |
rev_current=current)
|
| 2177 |
for write in writes:
|
| 2178 |
if int(write["rev"]) > revision and write["by"] != actor:
|
platform/core/store.py
CHANGED
|
@@ -380,6 +380,34 @@ class Store:
|
|
| 380 |
self._base[name] = sha # D-305 — set with the cache, never apart from it
|
| 381 |
return _project(data, drop)
|
| 382 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 383 |
def _key_lock(self, name):
|
| 384 |
"""The write lock for ONE key (W31-T13). Created on demand; never removed."""
|
| 385 |
n = str(name)
|
|
@@ -1183,6 +1211,11 @@ def get_projection(name, drop=()):
|
|
| 1183 |
return _d().get_projection(name, drop=drop)
|
| 1184 |
|
| 1185 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1186 |
def revision(name):
|
| 1187 |
"""The bucket's change token — wave 29, C6. See `Store.revision` for why it copies nothing.
|
| 1188 |
|
|
|
|
| 380 |
self._base[name] = sha # D-305 — set with the cache, never apart from it
|
| 381 |
return _project(data, drop)
|
| 382 |
|
| 383 |
+
def get_entry(self, name, entry):
|
| 384 |
+
"""One detached dictionary entry, or None, with the existing document cache/lock.
|
| 385 |
+
|
| 386 |
+
Cold HF reads retain the whole downloaded document in the existing cache. Only the
|
| 387 |
+
selected entry is serialized; sibling rows/cells never enter the returned copy.
|
| 388 |
+
"""
|
| 389 |
+
def selected(data):
|
| 390 |
+
value = data.get(str(entry)) if isinstance(data, dict) else None
|
| 391 |
+
return json.loads(json.dumps(value)) if isinstance(value, dict) else None
|
| 392 |
+
|
| 393 |
+
with self._lock:
|
| 394 |
+
if name in self._cache:
|
| 395 |
+
return selected(self._cache[name])
|
| 396 |
+
try:
|
| 397 |
+
data, sha = self._download(name)
|
| 398 |
+
except Exception as exc:
|
| 399 |
+
try:
|
| 400 |
+
import harness.telemetry as telemetry
|
| 401 |
+
telemetry.error(f'store:get_entry:{name}', exc,
|
| 402 |
+
fallback='cached' if name in self._cache else 'empty')
|
| 403 |
+
except Exception:
|
| 404 |
+
pass
|
| 405 |
+
with self._lock:
|
| 406 |
+
return selected(self._cache.get(name))
|
| 407 |
+
with self._lock:
|
| 408 |
+
self._cache[name], self._base[name] = data, sha
|
| 409 |
+
return selected(data)
|
| 410 |
+
|
| 411 |
def _key_lock(self, name):
|
| 412 |
"""The write lock for ONE key (W31-T13). Created on demand; never removed."""
|
| 413 |
n = str(name)
|
|
|
|
| 1211 |
return _d().get_projection(name, drop=drop)
|
| 1212 |
|
| 1213 |
|
| 1214 |
+
def get_entry(name, entry):
|
| 1215 |
+
"""One dictionary entry through the default tenant's existing store handle."""
|
| 1216 |
+
return _d().get_entry(name, entry)
|
| 1217 |
+
|
| 1218 |
+
|
| 1219 |
def revision(name):
|
| 1220 |
"""The bucket's change token — wave 29, C6. See `Store.revision` for why it copies nothing.
|
| 1221 |
|
platform/core/store_backend.py
CHANGED
|
@@ -113,6 +113,11 @@ def get_projection(name_, drop=()):
|
|
| 113 |
return active().get_projection(name_, drop=drop)
|
| 114 |
|
| 115 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
def revision(name_):
|
| 117 |
"""The bucket's change token (wave 29, C6) — `{'rev', 'updated_at', 'token'}`.
|
| 118 |
|
|
|
|
| 113 |
return active().get_projection(name_, drop=drop)
|
| 114 |
|
| 115 |
|
| 116 |
+
def get_entry(name_, entry):
|
| 117 |
+
"""One dictionary entry through the existing active-backend selector."""
|
| 118 |
+
return active().get_entry(name_, entry)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
def revision(name_):
|
| 122 |
"""The bucket's change token (wave 29, C6) — `{'rev', 'updated_at', 'token'}`.
|
| 123 |
|
platform/core/store_pg.py
CHANGED
|
@@ -550,6 +550,11 @@ def _get_projections(names, drop=(), tenant_slug=None, timeout_s=None):
|
|
| 550 |
}
|
| 551 |
|
| 552 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 553 |
def _get_entry(name, entry, tenant_slug=None):
|
| 554 |
"""ONE top-level entry of document `name` (`value -> entry`), or None when either is absent.
|
| 555 |
|
|
|
|
| 550 |
}
|
| 551 |
|
| 552 |
|
| 553 |
+
def get_entry(name, entry, tenant_slug=None):
|
| 554 |
+
"""Dictionary entry parity with the HF store through the existing PG primitive."""
|
| 555 |
+
return _get_entry(name, entry, tenant_slug=tenant_slug)
|
| 556 |
+
|
| 557 |
+
|
| 558 |
def _get_entry(name, entry, tenant_slug=None):
|
| 559 |
"""ONE top-level entry of document `name` (`value -> entry`), or None when either is absent.
|
| 560 |
|
platform/core/table_store.py
CHANGED
|
@@ -774,7 +774,7 @@ class TableStore:
|
|
| 774 |
# then splice a bounded copy into that payload only. Keeping it out of `fields`
|
| 775 |
# prevents an old request id surviving forever and overriding a later rename.
|
| 776 |
corrections = {}
|
| 777 |
-
if consume_corrections and ws.get('fieldCorrections'):
|
| 778 |
def _take(current):
|
| 779 |
current_ws = current.get(username) or {}
|
| 780 |
pending = current_ws.get('fieldCorrections') or {}
|
|
@@ -824,7 +824,8 @@ class TableStore:
|
|
| 824 |
out = {
|
| 825 |
'views': dict(ws.get('views') or {}),
|
| 826 |
'fields': fields,
|
| 827 |
-
'overlays':
|
|
|
|
| 828 |
# wave-8 I11 (C4): folders over the saved views / cohorts sidebars. A FOURTH
|
| 829 |
# stratum rather than a key on each item — see aios_grid.clean_folders for why
|
| 830 |
# (a cohort lives in another store, and filing is an organising act, not part of
|
|
@@ -1402,6 +1403,9 @@ class TableStore:
|
|
| 1402 |
permission_plans = self._personal_permission_plans(source)
|
| 1403 |
if not plans and not permission_plans and not has_blank_legacy:
|
| 1404 |
return {'migrated': 0, 'status': 'clean'}
|
|
|
|
|
|
|
|
|
|
| 1405 |
|
| 1406 |
import core.shares as shares
|
| 1407 |
|
|
|
|
| 774 |
# then splice a bounded copy into that payload only. Keeping it out of `fields`
|
| 775 |
# prevents an old request id surviving forever and overriding a later rename.
|
| 776 |
corrections = {}
|
| 777 |
+
if consume_corrections and not getattr(self._st, 'schema_only', False) and ws.get('fieldCorrections'):
|
| 778 |
def _take(current):
|
| 779 |
current_ws = current.get(username) or {}
|
| 780 |
pending = current_ws.get('fieldCorrections') or {}
|
|
|
|
| 824 |
out = {
|
| 825 |
'views': dict(ws.get('views') or {}),
|
| 826 |
'fields': fields,
|
| 827 |
+
'overlays': ({} if getattr(self._st, 'schema_only', False)
|
| 828 |
+
else dict(ws.get('overlays') or {})),
|
| 829 |
# wave-8 I11 (C4): folders over the saved views / cohorts sidebars. A FOURTH
|
| 830 |
# stratum rather than a key on each item — see aios_grid.clean_folders for why
|
| 831 |
# (a cohort lives in another store, and filing is an organising act, not part of
|
|
|
|
| 1403 |
permission_plans = self._personal_permission_plans(source)
|
| 1404 |
if not plans and not permission_plans and not has_blank_legacy:
|
| 1405 |
return {'migrated': 0, 'status': 'clean'}
|
| 1406 |
+
if getattr(self._st, 'schema_only', False):
|
| 1407 |
+
from core.shared_overlay import SchemaUnavailable
|
| 1408 |
+
raise SchemaUnavailable('saved fields and views need a full workspace refresh to finish migration')
|
| 1409 |
|
| 1410 |
import core.shares as shares
|
| 1411 |
|
platform/core/user_tables.py
CHANGED
|
@@ -1585,9 +1585,17 @@ def all_defs(st=None):
|
|
| 1585 |
this function, so an empty answer here stops being a blank nav and becomes a 404 on every
|
| 1586 |
database in the tenant.
|
| 1587 |
"""
|
|
|
|
|
|
|
|
|
|
| 1588 |
try:
|
| 1589 |
-
return dict(
|
| 1590 |
except Exception:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1591 |
# ⚠ `AttributeError` (a store too old to project) is not special-cased any more — it was
|
| 1592 |
# only ever ONE of the ways this can fail, and singling it out is what made the other ways
|
| 1593 |
# silent. `all_tables` is correct for all of them.
|
|
@@ -4758,8 +4766,9 @@ def may_edit_database(table_key, viewer, is_admin=False, st=None):
|
|
| 4758 |
#: LAZILY (an admin, or a table's creator, is admitted before that leg runs and never pays for
|
| 4759 |
#: it) and memoised for the pass.
|
| 4760 |
#:
|
| 4761 |
-
#: ⚠ THE ALLOW-LIST
|
| 4762 |
-
#: to the real runtime uncached
|
|
|
|
| 4763 |
#: runtime through `__getattr__` — so this can serve a stale value for the two named keys and
|
| 4764 |
#: dynamically named `<key>__shared` overlay buckets, for
|
| 4765 |
#: exactly one pass, to code proven not to mutate them (`all_tables` shallow-copies the top level
|
|
@@ -4769,6 +4778,9 @@ def may_edit_database(table_key, viewer, is_admin=False, st=None):
|
|
| 4769 |
#: `fresh=True` and write verbs still reach the runtime, never the snapshot.
|
| 4770 |
_LENDABLE = (STORE_KEY, 'object_shares')
|
| 4771 |
|
|
|
|
|
|
|
|
|
|
| 4772 |
|
| 4773 |
class _Lent:
|
| 4774 |
"""A read-only `st` that serves already-read documents and passes everything else through."""
|
|
@@ -4777,7 +4789,8 @@ class _Lent:
|
|
| 4777 |
self._runtime, self._docs = runtime, dict(docs or {})
|
| 4778 |
|
| 4779 |
def get(self, name, fresh=False):
|
| 4780 |
-
if fresh or (name not in
|
|
|
|
| 4781 |
return self._runtime.get(name, fresh) if fresh else self._runtime.get(name)
|
| 4782 |
if name not in self._docs:
|
| 4783 |
self._docs[name] = self._runtime.get(name) # lazily, once, for this pass
|
|
@@ -4797,7 +4810,7 @@ class _Lent:
|
|
| 4797 |
A re-projection would cost a second copy to convert the first case and change nothing
|
| 4798 |
about the second.
|
| 4799 |
"""
|
| 4800 |
-
if name not in _LENDABLE and not str(name).endswith('__shared'):
|
| 4801 |
return self._runtime.get_projection(name, drop=drop)
|
| 4802 |
if name not in self._docs:
|
| 4803 |
self._docs[name] = self._runtime.get_projection(name, drop=drop)
|
|
@@ -4808,7 +4821,7 @@ class _Lent:
|
|
| 4808 |
|
| 4809 |
|
| 4810 |
def lend(st=None, **docs):
|
| 4811 |
-
"""Lend `_LENDABLE`
|
| 4812 |
|
| 4813 |
`lend(rt, user_tables=doc)` — keyword names are STORE KEYS. Call it once per read pass and
|
| 4814 |
hand the result to every predicate in that pass; see the note above for what makes it safe.
|
|
|
|
| 1585 |
this function, so an empty answer here stops being a blank nav and becomes a 404 on every
|
| 1586 |
database in the tenant.
|
| 1587 |
"""
|
| 1588 |
+
# Schema-only handles cannot use the historical whole-reader fallback described above:
|
| 1589 |
+
# their caller must distinguish an unavailable definition snapshot from an empty one.
|
| 1590 |
+
reader = _st(st)
|
| 1591 |
try:
|
| 1592 |
+
return dict(reader.get_projection(STORE_KEY, drop=DEF_ONLY_DROPS) or {})
|
| 1593 |
except Exception:
|
| 1594 |
+
# A schema-only request promises not to materialize rows, including on an outage.
|
| 1595 |
+
# Its existing route maps this failure to a named unavailable response. Ordinary
|
| 1596 |
+
# full readers retain the correct-but-slow fallback below.
|
| 1597 |
+
if getattr(reader, 'schema_only', False):
|
| 1598 |
+
raise
|
| 1599 |
# ⚠ `AttributeError` (a store too old to project) is not special-cased any more — it was
|
| 1600 |
# only ever ONE of the ways this can fail, and singling it out is what made the other ways
|
| 1601 |
# silent. `all_tables` is correct for all of them.
|
|
|
|
| 4766 |
#: LAZILY (an admin, or a table's creator, is admitted before that leg runs and never pays for
|
| 4767 |
#: it) and memoised for the pass.
|
| 4768 |
#:
|
| 4769 |
+
#: ⚠ THE ALLOW-LIST CONTROLS AUTOMATIC REUSE. Any other UNSUPPLIED key passes through
|
| 4770 |
+
#: to the real runtime uncached. Explicit snapshots are caller-captured read-only documents for
|
| 4771 |
+
#: this pass only; `fresh=True` always bypasses, and every WRITE verb reaches the
|
| 4772 |
#: runtime through `__getattr__` — so this can serve a stale value for the two named keys and
|
| 4773 |
#: dynamically named `<key>__shared` overlay buckets, for
|
| 4774 |
#: exactly one pass, to code proven not to mutate them (`all_tables` shallow-copies the top level
|
|
|
|
| 4778 |
#: `fresh=True` and write verbs still reach the runtime, never the snapshot.
|
| 4779 |
_LENDABLE = (STORE_KEY, 'object_shares')
|
| 4780 |
|
| 4781 |
+
# A caller may also supply a captured read-only document explicitly. That grants no automatic
|
| 4782 |
+
# reuse to its bucket: unsupplied keys outside the allow-list still read the real runtime.
|
| 4783 |
+
|
| 4784 |
|
| 4785 |
class _Lent:
|
| 4786 |
"""A read-only `st` that serves already-read documents and passes everything else through."""
|
|
|
|
| 4789 |
self._runtime, self._docs = runtime, dict(docs or {})
|
| 4790 |
|
| 4791 |
def get(self, name, fresh=False):
|
| 4792 |
+
if fresh or (name not in self._docs and name not in _LENDABLE
|
| 4793 |
+
and not str(name).endswith('__shared')):
|
| 4794 |
return self._runtime.get(name, fresh) if fresh else self._runtime.get(name)
|
| 4795 |
if name not in self._docs:
|
| 4796 |
self._docs[name] = self._runtime.get(name) # lazily, once, for this pass
|
|
|
|
| 4810 |
A re-projection would cost a second copy to convert the first case and change nothing
|
| 4811 |
about the second.
|
| 4812 |
"""
|
| 4813 |
+
if name not in self._docs and name not in _LENDABLE and not str(name).endswith('__shared'):
|
| 4814 |
return self._runtime.get_projection(name, drop=drop)
|
| 4815 |
if name not in self._docs:
|
| 4816 |
self._docs[name] = self._runtime.get_projection(name, drop=drop)
|
|
|
|
| 4821 |
|
| 4822 |
|
| 4823 |
def lend(st=None, **docs):
|
| 4824 |
+
"""Lend explicit snapshots plus `_LENDABLE` and `__shared` buckets; defer other keys to `st`.
|
| 4825 |
|
| 4826 |
`lend(rt, user_tables=doc)` — keyword names are STORE KEYS. Call it once per read pass and
|
| 4827 |
hand the result to every predicate in that pass; see the note above for what makes it safe.
|
platform/modules/product_data.py
CHANGED
|
@@ -188,6 +188,7 @@ def image_field_definition(st=None):
|
|
| 188 |
and deliberately claims the field for the Royal Imports Leadership
|
| 189 |
account, as the product owner requested.
|
| 190 |
"""
|
|
|
|
| 191 |
default = {
|
| 192 |
'key': IMAGE_FIELD_KEY,
|
| 193 |
'label': 'Image',
|
|
@@ -210,6 +211,8 @@ def image_field_definition(st=None):
|
|
| 210 |
# Old deployments may have a stored Image definition without the
|
| 211 |
# creator/custom markers. Repair the metadata without disturbing
|
| 212 |
# existing permissions, grants, or cells.
|
|
|
|
|
|
|
| 213 |
if merged != existing:
|
| 214 |
shared_overlay.put_field(TABLE_KEY, IMAGE_FIELD_KEY, merged, st=st)
|
| 215 |
try:
|
|
@@ -221,6 +224,10 @@ def image_field_definition(st=None):
|
|
| 221 |
pass
|
| 222 |
return merged
|
| 223 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
stored = shared_overlay.put_field(TABLE_KEY, IMAGE_FIELD_KEY, default, st=st)
|
| 225 |
try:
|
| 226 |
import core.shares as shares
|
|
@@ -330,9 +337,13 @@ def table_ops(st=None):
|
|
| 330 |
def shared_fields(st=None):
|
| 331 |
"""Return and lazily migrate tenant-wide product field definitions."""
|
| 332 |
from core import field_permissions
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 336 |
|
| 337 |
|
| 338 |
def shared_cells(pids, st=None):
|
|
|
|
| 188 |
and deliberately claims the field for the Royal Imports Leadership
|
| 189 |
account, as the product owner requested.
|
| 190 |
"""
|
| 191 |
+
schema_only = getattr(st, 'schema_only', False)
|
| 192 |
default = {
|
| 193 |
'key': IMAGE_FIELD_KEY,
|
| 194 |
'label': 'Image',
|
|
|
|
| 211 |
# Old deployments may have a stored Image definition without the
|
| 212 |
# creator/custom markers. Repair the metadata without disturbing
|
| 213 |
# existing permissions, grants, or cells.
|
| 214 |
+
if schema_only:
|
| 215 |
+
return merged
|
| 216 |
if merged != existing:
|
| 217 |
shared_overlay.put_field(TABLE_KEY, IMAGE_FIELD_KEY, merged, st=st)
|
| 218 |
try:
|
|
|
|
| 224 |
pass
|
| 225 |
return merged
|
| 226 |
|
| 227 |
+
# The built-in definition is deterministic. Schema discovery reads its detached
|
| 228 |
+
# metadata; seeding its stored definition and grants remains at the full read door.
|
| 229 |
+
if schema_only:
|
| 230 |
+
return dict(default)
|
| 231 |
stored = shared_overlay.put_field(TABLE_KEY, IMAGE_FIELD_KEY, default, st=st)
|
| 232 |
try:
|
| 233 |
import core.shares as shares
|
|
|
|
| 337 |
def shared_fields(st=None):
|
| 338 |
"""Return and lazily migrate tenant-wide product field definitions."""
|
| 339 |
from core import field_permissions
|
| 340 |
+
document = shared_overlay.document(TABLE_KEY, st=st) if getattr(st, 'schema_only', False) else None
|
| 341 |
+
field_permissions.migrate_legacy_fields(TABLE_KEY, st=st, grant_topic='product_data',
|
| 342 |
+
shared_document=document)
|
| 343 |
+
if not getattr(st, 'schema_only', False):
|
| 344 |
+
image_field_definition(st=st)
|
| 345 |
+
return shared_overlay.fields(TABLE_KEY, st=st if st is not None else TABLE_OPS.st,
|
| 346 |
+
document=document)
|
| 347 |
|
| 348 |
|
| 349 |
def shared_cells(pids, st=None):
|
web/public/AIOS_DEPLOY_RECEIPT
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
|
|
|
|
| 1 |
+
83231799356796f69f112cdd39ee74e390811d9df6ab22888104a5470c7e1c84
|
web/src/connectors/MonidRunDialog.tsx
CHANGED
|
@@ -141,7 +141,7 @@ type Phase =
|
|
| 141 |
| { kind: "refused"; message: string };
|
| 142 |
|
| 143 |
/**
|
| 144 |
-
* THE DIALOG. Portalled, focus-trapped, dismissed
|
| 145 |
* focus back to the control that opened it.
|
| 146 |
*/
|
| 147 |
export default function MonidRunDialog({
|
|
@@ -173,7 +173,7 @@ export default function MonidRunDialog({
|
|
| 173 |
useOverlayLayer({
|
| 174 |
panelRef,
|
| 175 |
onDismiss: onClose,
|
| 176 |
-
dismissOnOutside:
|
| 177 |
initialFocus: "[data-overlay-autofocus]",
|
| 178 |
// ⚠ EXPLICIT. The hook's own default is `false`.
|
| 179 |
trapFocus: true,
|
|
|
|
| 141 |
| { kind: "refused"; message: string };
|
| 142 |
|
| 143 |
/**
|
| 144 |
+
* THE DIALOG. Portalled, focus-trapped, dismissed deliberately or by Escape, and it hands
|
| 145 |
* focus back to the control that opened it.
|
| 146 |
*/
|
| 147 |
export default function MonidRunDialog({
|
|
|
|
| 173 |
useOverlayLayer({
|
| 174 |
panelRef,
|
| 175 |
onDismiss: onClose,
|
| 176 |
+
dismissOnOutside: false,
|
| 177 |
initialFocus: "[data-overlay-autofocus]",
|
| 178 |
// ⚠ EXPLICIT. The hook's own default is `false`.
|
| 179 |
trapFocus: true,
|
web/src/customer-grid/CustomerGrid.tsx
CHANGED
|
@@ -1773,6 +1773,8 @@ interface CustomerGridProps {
|
|
| 1773 |
/** Exact linked pids to page on the server. */
|
| 1774 |
embeddedRecordIds?: readonly number[];
|
| 1775 |
embeddedInitialPage?: RecordIdInitialPage;
|
|
|
|
|
|
|
| 1776 |
onEmbeddedTotalChange?: (total: number | null) => void;
|
| 1777 |
/** Selection mode used by an editable ordinary-Link modal. */
|
| 1778 |
embeddedSelectable?: boolean;
|
|
@@ -1869,6 +1871,7 @@ interface LinkGridModalProps {
|
|
| 1869 |
table: SurfaceScope;
|
| 1870 |
recordIds: readonly number[];
|
| 1871 |
initialPage?: RecordIdInitialPage;
|
|
|
|
| 1872 |
editable?: boolean;
|
| 1873 |
single?: boolean;
|
| 1874 |
excludeRecordId?: number;
|
|
@@ -1897,7 +1900,7 @@ interface LinkGridModalProps {
|
|
| 1897 |
// chrome slots and a `cellView` modifier while leaving existing callers and the focus trap intact.
|
| 1898 |
export function LinkGridModal({ label, table, recordIds, editable = false, single = false,
|
| 1899 |
excludeRecordId, cellView = false, cellFilter, cellFields, onCellFilterChange, onCellDisplayChange,
|
| 1900 |
-
headerActions, footer, initialPage,
|
| 1901 |
onOpenRecord, onSave, onClose }: LinkGridModalProps) {
|
| 1902 |
const panelRef = useRef<HTMLDivElement>(null);
|
| 1903 |
const [selectedIds, setSelectedIds] = useState<number[]>(() => [...recordIds]);
|
|
@@ -1906,7 +1909,7 @@ export function LinkGridModal({ label, table, recordIds, editable = false, singl
|
|
| 1906 |
const reportTotal = useCallback((total: number | null) => {
|
| 1907 |
setServerCount({ key: countKey, total });
|
| 1908 |
}, [countKey]);
|
| 1909 |
-
const recordCount = editable ? selectedIds.length
|
| 1910 |
: serverCount?.key === countKey ? serverCount.total : null;
|
| 1911 |
const changeSelectedIds = useCallback((ids: number[]) => {
|
| 1912 |
const next = single ? ids.slice(-1) : ids;
|
|
@@ -1917,7 +1920,7 @@ export function LinkGridModal({ label, table, recordIds, editable = false, singl
|
|
| 1917 |
useOverlayLayer({
|
| 1918 |
panelRef,
|
| 1919 |
onDismiss: onClose,
|
| 1920 |
-
dismissOnOutside:
|
| 1921 |
initialFocus: "[data-overlay-autofocus]",
|
| 1922 |
trapFocus: true,
|
| 1923 |
});
|
|
@@ -1966,6 +1969,7 @@ export function LinkGridModal({ label, table, recordIds, editable = false, singl
|
|
| 1966 |
onCellDisplayChange={onCellDisplayChange}
|
| 1967 |
embeddedRecordIds={editable ? undefined : recordIds}
|
| 1968 |
embeddedInitialPage={editable ? undefined : initialPage}
|
|
|
|
| 1969 |
onEmbeddedTotalChange={editable ? undefined : reportTotal}
|
| 1970 |
embeddedExcludeRecordId={editable ? excludeRecordId : undefined}
|
| 1971 |
embeddedSelectable={editable}
|
|
@@ -2098,9 +2102,9 @@ function CustomerGrid(props: CustomerGridProps = {}) {
|
|
| 2098 |
|
| 2099 |
/** An ID-backed grid supplies pages through the existing caller-owned payload seam. */
|
| 2100 |
function useRecordIdWindow(scope: SurfaceScope, ids: readonly number[] | undefined,
|
| 2101 |
-
related: RelatedPin | null, initialPage?: RecordIdInitialPage) {
|
| 2102 |
-
const key = JSON.stringify([scope, ids, related, initialPage]);
|
| 2103 |
-
const seed = ids !== undefined && !related && initialPage && initialPage.offset === 0
|
| 2104 |
? initialPage.payload : null;
|
| 2105 |
const currentKey = useRef(key);
|
| 2106 |
const sequence = useRef(0);
|
|
@@ -2114,7 +2118,7 @@ function useRecordIdWindow(scope: SurfaceScope, ids: readonly number[] | undefin
|
|
| 2114 |
key: string; payload: CustomersPayload | null; pending: boolean;
|
| 2115 |
} | null>(null);
|
| 2116 |
const requestWindow = useCallback((req: RowWindowRequest, fresh = false) => {
|
| 2117 |
-
if (ids === undefined) return;
|
| 2118 |
const seq = ++sequence.current;
|
| 2119 |
lastRequest.current = req;
|
| 2120 |
if (!fresh && seed && initialPage && req.offset === 0
|
|
@@ -2133,7 +2137,7 @@ function useRecordIdWindow(scope: SurfaceScope, ids: readonly number[] | undefin
|
|
| 2133 |
if (seq !== sequence.current || currentKey.current !== key) return;
|
| 2134 |
setPage({ key, payload, pending: false });
|
| 2135 |
});
|
| 2136 |
-
}, [scope, ids, related, key, seed, initialPage]);
|
| 2137 |
useEffect(() => {
|
| 2138 |
const refresh = () => { if (lastRequest.current) requestWindow(lastRequest.current, true); };
|
| 2139 |
// React can replay effect setup after cancelling its first request in StrictMode.
|
|
@@ -2145,8 +2149,8 @@ function useRecordIdWindow(scope: SurfaceScope, ids: readonly number[] | undefin
|
|
| 2145 |
};
|
| 2146 |
}, [requestWindow]);
|
| 2147 |
return {
|
| 2148 |
-
payload: page?.key === key ? page.payload : seed,
|
| 2149 |
-
pending: page?.key === key ? page.pending : !seed && ids !== undefined,
|
| 2150 |
requestWindow,
|
| 2151 |
};
|
| 2152 |
}
|
|
@@ -2169,6 +2173,7 @@ function CustomerGridSurface({
|
|
| 2169 |
embeddedPayload,
|
| 2170 |
embeddedRecordIds,
|
| 2171 |
embeddedInitialPage,
|
|
|
|
| 2172 |
onEmbeddedTotalChange,
|
| 2173 |
embeddedSelectable = false,
|
| 2174 |
embeddedSelectedIds = [],
|
|
@@ -2215,7 +2220,7 @@ function CustomerGridSurface({
|
|
| 2215 |
const embeddedIdsKey = recordIdsKey(embeddedPayload === undefined ? embeddedRecordIds : undefined);
|
| 2216 |
const embeddedIds = useMemo<readonly number[] | undefined>(
|
| 2217 |
() => embeddedIdsKey ? JSON.parse(embeddedIdsKey) as number[] : undefined, [embeddedIdsKey]);
|
| 2218 |
-
const idWindow = useRecordIdWindow(scope, embeddedIds, relatedPin, embeddedInitialPage);
|
| 2219 |
/**
|
| 2220 |
* ⭐⭐ W35-T23 (owner item 4 / R2) — **`previewReadOnly` IS GONE, AND THE SPLIT IS THE TICKET.**
|
| 2221 |
*
|
|
@@ -2249,6 +2254,7 @@ function CustomerGridSurface({
|
|
| 2249 |
payload,
|
| 2250 |
loading,
|
| 2251 |
windowPending: ordinaryWindowPending,
|
|
|
|
| 2252 |
overlayEdits,
|
| 2253 |
setOverlayEdits,
|
| 2254 |
patchOverlay,
|
|
@@ -9975,7 +9981,8 @@ function CustomerGridSurface({
|
|
| 9975 |
|
| 9976 |
// W45-T14 keeps the outer workspace and View rail mounted. Only the keyed right pane enters
|
| 9977 |
// loading, so a database switch cannot replace either navigation DOM subtree.
|
| 9978 |
-
const
|
|
|
|
| 9979 |
|
| 9980 |
const activeView = views.find((view) => view.id === activeViewId);
|
| 9981 |
const routeSourceView: RouteSourceView | null = activeView
|
|
@@ -10490,7 +10497,7 @@ function CustomerGridSurface({
|
|
| 10490 |
* autosave, the echo reconcile and `writeLocal` all key off it. A server-owned object
|
| 10491 |
* in that state means this browser starts writing a view it does not own.
|
| 10492 |
*/
|
| 10493 |
-
views={orderedRailViews}
|
| 10494 |
/* ⭐ W50-T11 / D-592 — the rail draws a skeleton while `/workspace` is in flight
|
| 10495 |
instead of asserting an empty list. `workspaceLoading` is the predicate this file
|
| 10496 |
already computes for the right pane, passed rather than re-derived in the rail. */
|
|
@@ -10800,9 +10807,17 @@ function CustomerGridSurface({
|
|
| 10800 |
cloned this `<main>` on every render without removing the last (21 copies measured,
|
| 10801 |
live). Both sides are prefixed so neither can be spelled by the other. */}
|
| 10802 |
<main className="cg-main" key={`cg-main:${scope}`}>
|
| 10803 |
-
{
|
| 10804 |
-
<div className="cg-
|
| 10805 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10806 |
</div>
|
| 10807 |
) : (
|
| 10808 |
<>
|
|
|
|
| 1773 |
/** Exact linked pids to page on the server. */
|
| 1774 |
embeddedRecordIds?: readonly number[];
|
| 1775 |
embeddedInitialPage?: RecordIdInitialPage;
|
| 1776 |
+
/** A fresh drill is resolving ids; withhold the previous id page during that request. */
|
| 1777 |
+
embeddedIdsPending?: boolean;
|
| 1778 |
onEmbeddedTotalChange?: (total: number | null) => void;
|
| 1779 |
/** Selection mode used by an editable ordinary-Link modal. */
|
| 1780 |
embeddedSelectable?: boolean;
|
|
|
|
| 1871 |
table: SurfaceScope;
|
| 1872 |
recordIds: readonly number[];
|
| 1873 |
initialPage?: RecordIdInitialPage;
|
| 1874 |
+
idsPending?: boolean;
|
| 1875 |
editable?: boolean;
|
| 1876 |
single?: boolean;
|
| 1877 |
excludeRecordId?: number;
|
|
|
|
| 1900 |
// chrome slots and a `cellView` modifier while leaving existing callers and the focus trap intact.
|
| 1901 |
export function LinkGridModal({ label, table, recordIds, editable = false, single = false,
|
| 1902 |
excludeRecordId, cellView = false, cellFilter, cellFields, onCellFilterChange, onCellDisplayChange,
|
| 1903 |
+
headerActions, footer, initialPage, idsPending = false,
|
| 1904 |
onOpenRecord, onSave, onClose }: LinkGridModalProps) {
|
| 1905 |
const panelRef = useRef<HTMLDivElement>(null);
|
| 1906 |
const [selectedIds, setSelectedIds] = useState<number[]>(() => [...recordIds]);
|
|
|
|
| 1909 |
const reportTotal = useCallback((total: number | null) => {
|
| 1910 |
setServerCount({ key: countKey, total });
|
| 1911 |
}, [countKey]);
|
| 1912 |
+
const recordCount = idsPending ? null : editable ? selectedIds.length
|
| 1913 |
: serverCount?.key === countKey ? serverCount.total : null;
|
| 1914 |
const changeSelectedIds = useCallback((ids: number[]) => {
|
| 1915 |
const next = single ? ids.slice(-1) : ids;
|
|
|
|
| 1920 |
useOverlayLayer({
|
| 1921 |
panelRef,
|
| 1922 |
onDismiss: onClose,
|
| 1923 |
+
dismissOnOutside: false,
|
| 1924 |
initialFocus: "[data-overlay-autofocus]",
|
| 1925 |
trapFocus: true,
|
| 1926 |
});
|
|
|
|
| 1969 |
onCellDisplayChange={onCellDisplayChange}
|
| 1970 |
embeddedRecordIds={editable ? undefined : recordIds}
|
| 1971 |
embeddedInitialPage={editable ? undefined : initialPage}
|
| 1972 |
+
embeddedIdsPending={!editable && idsPending}
|
| 1973 |
onEmbeddedTotalChange={editable ? undefined : reportTotal}
|
| 1974 |
embeddedExcludeRecordId={editable ? excludeRecordId : undefined}
|
| 1975 |
embeddedSelectable={editable}
|
|
|
|
| 2102 |
|
| 2103 |
/** An ID-backed grid supplies pages through the existing caller-owned payload seam. */
|
| 2104 |
function useRecordIdWindow(scope: SurfaceScope, ids: readonly number[] | undefined,
|
| 2105 |
+
related: RelatedPin | null, initialPage?: RecordIdInitialPage, idsPending = false) {
|
| 2106 |
+
const key = JSON.stringify([scope, ids, related, initialPage, idsPending]);
|
| 2107 |
+
const seed = !idsPending && ids !== undefined && !related && initialPage && initialPage.offset === 0
|
| 2108 |
? initialPage.payload : null;
|
| 2109 |
const currentKey = useRef(key);
|
| 2110 |
const sequence = useRef(0);
|
|
|
|
| 2118 |
key: string; payload: CustomersPayload | null; pending: boolean;
|
| 2119 |
} | null>(null);
|
| 2120 |
const requestWindow = useCallback((req: RowWindowRequest, fresh = false) => {
|
| 2121 |
+
if (idsPending || ids === undefined) return;
|
| 2122 |
const seq = ++sequence.current;
|
| 2123 |
lastRequest.current = req;
|
| 2124 |
if (!fresh && seed && initialPage && req.offset === 0
|
|
|
|
| 2137 |
if (seq !== sequence.current || currentKey.current !== key) return;
|
| 2138 |
setPage({ key, payload, pending: false });
|
| 2139 |
});
|
| 2140 |
+
}, [scope, ids, related, key, seed, initialPage, idsPending]);
|
| 2141 |
useEffect(() => {
|
| 2142 |
const refresh = () => { if (lastRequest.current) requestWindow(lastRequest.current, true); };
|
| 2143 |
// React can replay effect setup after cancelling its first request in StrictMode.
|
|
|
|
| 2149 |
};
|
| 2150 |
}, [requestWindow]);
|
| 2151 |
return {
|
| 2152 |
+
payload: idsPending ? null : page?.key === key ? page.payload : seed,
|
| 2153 |
+
pending: idsPending || (page?.key === key ? page.pending : !seed && ids !== undefined),
|
| 2154 |
requestWindow,
|
| 2155 |
};
|
| 2156 |
}
|
|
|
|
| 2173 |
embeddedPayload,
|
| 2174 |
embeddedRecordIds,
|
| 2175 |
embeddedInitialPage,
|
| 2176 |
+
embeddedIdsPending = false,
|
| 2177 |
onEmbeddedTotalChange,
|
| 2178 |
embeddedSelectable = false,
|
| 2179 |
embeddedSelectedIds = [],
|
|
|
|
| 2220 |
const embeddedIdsKey = recordIdsKey(embeddedPayload === undefined ? embeddedRecordIds : undefined);
|
| 2221 |
const embeddedIds = useMemo<readonly number[] | undefined>(
|
| 2222 |
() => embeddedIdsKey ? JSON.parse(embeddedIdsKey) as number[] : undefined, [embeddedIdsKey]);
|
| 2223 |
+
const idWindow = useRecordIdWindow(scope, embeddedIds, relatedPin, embeddedInitialPage, embeddedIdsPending);
|
| 2224 |
/**
|
| 2225 |
* ⭐⭐ W35-T23 (owner item 4 / R2) — **`previewReadOnly` IS GONE, AND THE SPLIT IS THE TICKET.**
|
| 2226 |
*
|
|
|
|
| 2254 |
payload,
|
| 2255 |
loading,
|
| 2256 |
windowPending: ordinaryWindowPending,
|
| 2257 |
+
workspacePending,
|
| 2258 |
overlayEdits,
|
| 2259 |
setOverlayEdits,
|
| 2260 |
patchOverlay,
|
|
|
|
| 9981 |
|
| 9982 |
// W45-T14 keeps the outer workspace and View rail mounted. Only the keyed right pane enters
|
| 9983 |
// loading, so a database switch cannot replace either navigation DOM subtree.
|
| 9984 |
+
const rowsLoading = loading || !workspaceReady;
|
| 9985 |
+
const workspaceLoading = rowsLoading || workspacePending;
|
| 9986 |
|
| 9987 |
const activeView = views.find((view) => view.id === activeViewId);
|
| 9988 |
const routeSourceView: RouteSourceView | null = activeView
|
|
|
|
| 10497 |
* autosave, the echo reconcile and `writeLocal` all key off it. A server-owned object
|
| 10498 |
* in that state means this browser starts writing a view it does not own.
|
| 10499 |
*/
|
| 10500 |
+
views={workspacePending ? [] : orderedRailViews}
|
| 10501 |
/* ⭐ W50-T11 / D-592 — the rail draws a skeleton while `/workspace` is in flight
|
| 10502 |
instead of asserting an empty list. `workspaceLoading` is the predicate this file
|
| 10503 |
already computes for the right pane, passed rather than re-derived in the rail. */
|
|
|
|
| 10807 |
cloned this `<main>` on every render without removing the last (21 copies measured,
|
| 10808 |
live). Both sides are prefixed so neither can be spelled by the other. */}
|
| 10809 |
<main className="cg-main" key={`cg-main:${scope}`}>
|
| 10810 |
+
{rowsLoading ? (
|
| 10811 |
+
<div className="cg-initial-skeleton" role="status" aria-label="Loading records" aria-busy="true"
|
| 10812 |
+
style={{ padding: "12px", width: "100%" }}>
|
| 10813 |
+
<div aria-hidden="true" style={{ display: "grid", gridTemplateColumns: "48px minmax(160px, 2fr) minmax(100px, 1fr) minmax(100px, 1fr)" }}>
|
| 10814 |
+
{Array.from({ length: 32 }, (_, index) => (
|
| 10815 |
+
<div key={index} style={{ height: "36px", padding: "12px", borderBottom: "1px solid var(--cg-line)" }}>
|
| 10816 |
+
<span style={{ display: "block", height: "10px", width: index % 4 === 0 ? "18px" : `${60 + (index % 3) * 12}%`,
|
| 10817 |
+
borderRadius: "var(--lp-r-sm)", background: "var(--lp-surface-2)" }} />
|
| 10818 |
+
</div>
|
| 10819 |
+
))}
|
| 10820 |
+
</div>
|
| 10821 |
</div>
|
| 10822 |
) : (
|
| 10823 |
<>
|
web/src/customer-grid/JsonViewer.tsx
CHANGED
|
@@ -663,7 +663,7 @@ export function CodeViewer({ label, value, language, onSave, onClose }: CodeView
|
|
| 663 |
useOverlayLayer({
|
| 664 |
panelRef,
|
| 665 |
onDismiss: onClose,
|
| 666 |
-
dismissOnOutside:
|
| 667 |
initialFocus: "[data-overlay-autofocus]",
|
| 668 |
trapFocus: true,
|
| 669 |
});
|
|
@@ -858,7 +858,7 @@ export default function JsonViewer({ label, value, onSave, onClose }: JsonViewer
|
|
| 858 |
useOverlayLayer({
|
| 859 |
panelRef,
|
| 860 |
onDismiss: onClose,
|
| 861 |
-
dismissOnOutside:
|
| 862 |
initialFocus: "[data-overlay-autofocus]",
|
| 863 |
trapFocus: true,
|
| 864 |
});
|
|
|
|
| 663 |
useOverlayLayer({
|
| 664 |
panelRef,
|
| 665 |
onDismiss: onClose,
|
| 666 |
+
dismissOnOutside: false,
|
| 667 |
initialFocus: "[data-overlay-autofocus]",
|
| 668 |
trapFocus: true,
|
| 669 |
});
|
|
|
|
| 858 |
useOverlayLayer({
|
| 859 |
panelRef,
|
| 860 |
onDismiss: onClose,
|
| 861 |
+
dismissOnOutside: false,
|
| 862 |
initialFocus: "[data-overlay-autofocus]",
|
| 863 |
trapFocus: true,
|
| 864 |
});
|
web/src/customer-grid/apiBridge.ts
CHANGED
|
@@ -230,8 +230,8 @@ const rowsCache = new Map<string, { at: number; payload: CustomersPayload }>();
|
|
| 230 |
* field, switch away, switch back, and be served the pre-write envelope — the write silently
|
| 231 |
* undone on screen, which is worse than the wait it replaced.
|
| 232 |
*/
|
| 233 |
-
const wsCache = new Map<string, { at: number; ws: GridWorkspace }>();
|
| 234 |
-
type WorkspaceRead = { ws: GridWorkspace | null; failure?: string };
|
| 235 |
// Pending reads belong to the same memo, not a second result cache. Uncached post-write
|
| 236 |
// reads replace the joinable flight; an older completion must not remove that newer one.
|
| 237 |
const wsFlights = new Map<string, Promise<WorkspaceRead>>();
|
|
@@ -1329,35 +1329,64 @@ export async function probeRelatedRead(
|
|
| 1329 |
* answer for `scope` when it is inside its freshness window, WITHOUT a request, else null. A
|
| 1330 |
* panel paints from it at once and still asks the server; the server's answer replaces it.
|
| 1331 |
*/
|
| 1332 |
-
export function peekWorkspace(scope: SurfaceScope): GridWorkspace | null {
|
| 1333 |
-
const
|
|
|
|
| 1334 |
return hit && Date.now() - hit.at < CUSTOMERS_FRESH_MS ? workspaceWithoutMetricCells(hit.ws) : null;
|
| 1335 |
}
|
| 1336 |
|
| 1337 |
export async function fetchWorkspace(
|
| 1338 |
scope: SurfaceScope = "customer",
|
| 1339 |
-
opts: { announceFailure?: boolean; allowCached?: boolean; refresh?: boolean } = {},
|
| 1340 |
): Promise<GridWorkspace | null> {
|
| 1341 |
const loud = opts.announceFailure === true;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1342 |
// ⭐ W31-T21 — OPT IN, NEVER BY DEFAULT. Only the first-paint read of a surface may be served
|
| 1343 |
// from the memo; the post-write `reread()` calls this with no options and therefore always goes
|
| 1344 |
// to the server, which is what keeps the memo from becoming a second source of truth.
|
| 1345 |
if (opts.allowCached === true) {
|
| 1346 |
-
const hit = wsCache.get(
|
| 1347 |
// A warm-open refresh bypasses only the completed memo, and still joins pending work.
|
| 1348 |
if (!opts.refresh && hit && Date.now() - hit.at < CUSTOMERS_FRESH_MS)
|
| 1349 |
return workspaceWithoutMetricCells(hit.ws);
|
| 1350 |
}
|
| 1351 |
-
let pending = opts.allowCached === true ? wsFlights.get(
|
| 1352 |
if (!pending) {
|
| 1353 |
-
|
| 1354 |
-
|
| 1355 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1356 |
void flight.then(() => {
|
| 1357 |
-
if (wsFlights.get(
|
| 1358 |
});
|
| 1359 |
}
|
| 1360 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1361 |
// Failure belongs to each caller: a loud joiner of a quiet request must still hear
|
| 1362 |
// the server's sentence. Parsing and the session check belong to the response once.
|
| 1363 |
if (loud && result.failure) signal(DATA_ERROR_EVENT, result.failure);
|
|
@@ -1365,16 +1394,23 @@ export async function fetchWorkspace(
|
|
| 1365 |
return good ? workspaceWithoutMetricCells(good) : null;
|
| 1366 |
}
|
| 1367 |
|
| 1368 |
-
async function readWorkspace(scope: SurfaceScope, epoch: number
|
|
|
|
| 1369 |
let res: Response;
|
| 1370 |
try {
|
| 1371 |
-
res = await fetch(`${API_V1}/workspace?scope=${encodeURIComponent(scope)}`,
|
| 1372 |
{ credentials: CREDENTIALS });
|
| 1373 |
} catch {
|
| 1374 |
return { ws: null, failure: "Cannot reach the server." };
|
| 1375 |
}
|
| 1376 |
if (handledSession(res) || epoch !== wsCacheEpoch) return { ws: null };
|
| 1377 |
if (!res.ok) {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1378 |
// 404 is the ONE status that means "this host does not serve a workspace",
|
| 1379 |
// which is the enhancement posture above and stays quiet. Everything else
|
| 1380 |
// is a server that had an answer and would not give it.
|
|
@@ -1387,21 +1423,28 @@ async function readWorkspace(scope: SurfaceScope, epoch: number): Promise<Worksp
|
|
| 1387 |
}
|
| 1388 |
const ws = (await readJson(res)) as { workspace?: GridWorkspace } | null;
|
| 1389 |
if (epoch !== wsCacheEpoch) return { ws: null };
|
| 1390 |
-
const w = ws?.workspace;
|
| 1391 |
// A 200 carrying no workspace is still an ABSENCE, not a refusal — an older
|
| 1392 |
// host, or a scope this one has nothing stored for. Unchanged, and quiet.
|
| 1393 |
-
const good = w && typeof w.storageKey === "string" && Array.isArray(w.views)
|
|
|
|
|
|
|
| 1394 |
// ⭐ W31-T21 — EVERY SUCCESSFUL READ REFRESHES THE MEMO, including the post-write `reread()`
|
| 1395 |
// that is not allowed to CONSUME it. That asymmetry is the whole safety argument: the write
|
| 1396 |
// path can never leave a stale envelope behind for the next switch to serve.
|
| 1397 |
// ⚠ A FAILURE LEAVES THE PREVIOUS ENTRY ALONE rather than poisoning it with `null` — the same
|
| 1398 |
// "absent stays absent, never blank a live panel" posture `reread()` already takes.
|
| 1399 |
-
if (good) {
|
| 1400 |
-
const
|
| 1401 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1402 |
// A refreshed metric definition or answer is read again through each grid's own pin.
|
| 1403 |
// The same rows door still supplies the ordinary record's global Details values.
|
| 1404 |
-
if (previous && JSON.stringify(metricWorkspaceCells(previous)) !== JSON.stringify(metricWorkspaceCells(good))) {
|
| 1405 |
rowsCache.clear();
|
| 1406 |
signal(ROWS_STALE_EVENT);
|
| 1407 |
}
|
|
|
|
| 230 |
* field, switch away, switch back, and be served the pre-write envelope — the write silently
|
| 231 |
* undone on screen, which is worse than the wait it replaced.
|
| 232 |
*/
|
| 233 |
+
const wsCache = new Map<string, { at: number; ws: GridWorkspace; current: boolean }>();
|
| 234 |
+
type WorkspaceRead = { ws: GridWorkspace | null; failure?: string; superseded?: boolean };
|
| 235 |
// Pending reads belong to the same memo, not a second result cache. Uncached post-write
|
| 236 |
// reads replace the joinable flight; an older completion must not remove that newer one.
|
| 237 |
const wsFlights = new Map<string, Promise<WorkspaceRead>>();
|
|
|
|
| 1329 |
* answer for `scope` when it is inside its freshness window, WITHOUT a request, else null. A
|
| 1330 |
* panel paints from it at once and still asks the server; the server's answer replaces it.
|
| 1331 |
*/
|
| 1332 |
+
export function peekWorkspace(scope: SurfaceScope, opts: { fieldsOnly?: boolean } = {}): GridWorkspace | null {
|
| 1333 |
+
const key = opts.fieldsOnly ? `${scope}:fields` : scope;
|
| 1334 |
+
const hit = wsCache.get(key);
|
| 1335 |
return hit && Date.now() - hit.at < CUSTOMERS_FRESH_MS ? workspaceWithoutMetricCells(hit.ws) : null;
|
| 1336 |
}
|
| 1337 |
|
| 1338 |
export async function fetchWorkspace(
|
| 1339 |
scope: SurfaceScope = "customer",
|
| 1340 |
+
opts: { announceFailure?: boolean; allowCached?: boolean; refresh?: boolean; fieldsOnly?: boolean } = {},
|
| 1341 |
): Promise<GridWorkspace | null> {
|
| 1342 |
const loud = opts.announceFailure === true;
|
| 1343 |
+
const fieldsOnly = opts.fieldsOnly === true;
|
| 1344 |
+
const key = fieldsOnly ? `${scope}:fields` : scope;
|
| 1345 |
+
const requestEpoch = wsCacheEpoch;
|
| 1346 |
+
const fullAtStart = wsCache.get(scope);
|
| 1347 |
// ⭐ W31-T21 — OPT IN, NEVER BY DEFAULT. Only the first-paint read of a surface may be served
|
| 1348 |
// from the memo; the post-write `reread()` calls this with no options and therefore always goes
|
| 1349 |
// to the server, which is what keeps the memo from becoming a second source of truth.
|
| 1350 |
if (opts.allowCached === true) {
|
| 1351 |
+
const hit = wsCache.get(key);
|
| 1352 |
// A warm-open refresh bypasses only the completed memo, and still joins pending work.
|
| 1353 |
if (!opts.refresh && hit && Date.now() - hit.at < CUSTOMERS_FRESH_MS)
|
| 1354 |
return workspaceWithoutMetricCells(hit.ws);
|
| 1355 |
}
|
| 1356 |
+
let pending = opts.allowCached === true ? wsFlights.get(key) : undefined;
|
| 1357 |
if (!pending) {
|
| 1358 |
+
// A fresh full question invalidates older schema offers through this same memo.
|
| 1359 |
+
if (!fieldsOnly) {
|
| 1360 |
+
wsCache.delete(`${scope}:fields`);
|
| 1361 |
+
wsFlights.delete(`${scope}:fields`);
|
| 1362 |
+
const previousFull = wsCache.get(scope);
|
| 1363 |
+
if (previousFull) previousFull.current = false;
|
| 1364 |
+
}
|
| 1365 |
+
const epoch = wsCacheEpoch;
|
| 1366 |
+
let flight: Promise<WorkspaceRead>;
|
| 1367 |
+
flight = readWorkspace(scope, epoch, fieldsOnly, () => wsFlights.get(key) === flight);
|
| 1368 |
+
pending = flight;
|
| 1369 |
+
wsFlights.set(key, pending);
|
| 1370 |
void flight.then(() => {
|
| 1371 |
+
if (wsFlights.get(key) === flight) wsFlights.delete(key);
|
| 1372 |
});
|
| 1373 |
}
|
| 1374 |
+
let result = await pending;
|
| 1375 |
+
if (fieldsOnly && result.superseded && requestEpoch === wsCacheEpoch) {
|
| 1376 |
+
// A Sheet full read may supersede the editor's schema read. Follow the current
|
| 1377 |
+
// existing flight, then use only an authoritative full memo published since this
|
| 1378 |
+
// question began. A failed full read cannot turn an older offer into a fresh one.
|
| 1379 |
+
let full = wsFlights.get(scope);
|
| 1380 |
+
while (full) {
|
| 1381 |
+
result = await full;
|
| 1382 |
+
if (requestEpoch !== wsCacheEpoch) return null;
|
| 1383 |
+
const next = wsFlights.get(scope);
|
| 1384 |
+
full = next !== full ? next : undefined;
|
| 1385 |
+
}
|
| 1386 |
+
const current = wsCache.get(scope);
|
| 1387 |
+
result = current && current.current && current !== fullAtStart && Date.now() - current.at < CUSTOMERS_FRESH_MS
|
| 1388 |
+
? { ws: workspaceWithoutMetricCells(current.ws) } : { ws: null, failure: result.failure };
|
| 1389 |
+
}
|
| 1390 |
// Failure belongs to each caller: a loud joiner of a quiet request must still hear
|
| 1391 |
// the server's sentence. Parsing and the session check belong to the response once.
|
| 1392 |
if (loud && result.failure) signal(DATA_ERROR_EVENT, result.failure);
|
|
|
|
| 1394 |
return good ? workspaceWithoutMetricCells(good) : null;
|
| 1395 |
}
|
| 1396 |
|
| 1397 |
+
async function readWorkspace(scope: SurfaceScope, epoch: number, fieldsOnly: boolean,
|
| 1398 |
+
isCurrent: () => boolean): Promise<WorkspaceRead> {
|
| 1399 |
let res: Response;
|
| 1400 |
try {
|
| 1401 |
+
res = await fetch(`${API_V1}/workspace?scope=${encodeURIComponent(scope)}${fieldsOnly ? "&fields_only=1" : ""}`,
|
| 1402 |
{ credentials: CREDENTIALS });
|
| 1403 |
} catch {
|
| 1404 |
return { ws: null, failure: "Cannot reach the server." };
|
| 1405 |
}
|
| 1406 |
if (handledSession(res) || epoch !== wsCacheEpoch) return { ws: null };
|
| 1407 |
if (!res.ok) {
|
| 1408 |
+
if (isCurrent() && (res.status === 403 || res.status === 404)) {
|
| 1409 |
+
wsCache.delete(scope);
|
| 1410 |
+
wsCache.delete(`${scope}:fields`);
|
| 1411 |
+
wsFlights.delete(scope);
|
| 1412 |
+
wsFlights.delete(`${scope}:fields`);
|
| 1413 |
+
}
|
| 1414 |
// 404 is the ONE status that means "this host does not serve a workspace",
|
| 1415 |
// which is the enhancement posture above and stays quiet. Everything else
|
| 1416 |
// is a server that had an answer and would not give it.
|
|
|
|
| 1423 |
}
|
| 1424 |
const ws = (await readJson(res)) as { workspace?: GridWorkspace } | null;
|
| 1425 |
if (epoch !== wsCacheEpoch) return { ws: null };
|
| 1426 |
+
const w = ws?.workspace as (GridWorkspace & { fieldsOnly?: boolean }) | undefined;
|
| 1427 |
// A 200 carrying no workspace is still an ABSENCE, not a refusal — an older
|
| 1428 |
// host, or a scope this one has nothing stored for. Unchanged, and quiet.
|
| 1429 |
+
const good = w && typeof w.storageKey === "string" && Array.isArray(w.views)
|
| 1430 |
+
&& (fieldsOnly ? w.fieldsOnly === true : w.fieldsOnly !== true) ? w : null;
|
| 1431 |
+
if (fieldsOnly && !isCurrent()) return { ws: null, superseded: true };
|
| 1432 |
// ⭐ W31-T21 — EVERY SUCCESSFUL READ REFRESHES THE MEMO, including the post-write `reread()`
|
| 1433 |
// that is not allowed to CONSUME it. That asymmetry is the whole safety argument: the write
|
| 1434 |
// path can never leave a stale envelope behind for the next switch to serve.
|
| 1435 |
// ⚠ A FAILURE LEAVES THE PREVIOUS ENTRY ALONE rather than poisoning it with `null` — the same
|
| 1436 |
// "absent stays absent, never blank a live panel" posture `reread()` already takes.
|
| 1437 |
+
if (good && isCurrent()) {
|
| 1438 |
+
const key = fieldsOnly ? `${scope}:fields` : scope;
|
| 1439 |
+
const previous = wsCache.get(key)?.ws;
|
| 1440 |
+
wsCache.set(key, { at: Date.now(), ws: good, current: true });
|
| 1441 |
+
if (!fieldsOnly) {
|
| 1442 |
+
wsCache.delete(`${scope}:fields`);
|
| 1443 |
+
wsFlights.delete(`${scope}:fields`);
|
| 1444 |
+
}
|
| 1445 |
// A refreshed metric definition or answer is read again through each grid's own pin.
|
| 1446 |
// The same rows door still supplies the ordinary record's global Details values.
|
| 1447 |
+
if (!fieldsOnly && previous && JSON.stringify(metricWorkspaceCells(previous)) !== JSON.stringify(metricWorkspaceCells(good))) {
|
| 1448 |
rowsCache.clear();
|
| 1449 |
signal(ROWS_STALE_EVENT);
|
| 1450 |
}
|
web/src/customer-grid/formulaEngine.ts
CHANGED
|
@@ -105,7 +105,7 @@ export type FormulaFn =
|
|
| 105 |
| "IF" | "AND" | "OR" | "NOT" | "IFERROR" | "ISBLANK" | "SWITCH"
|
| 106 |
| "CONCATENATE" | "LEFT" | "RIGHT" | "MID" | "LEN" | "TRIM"
|
| 107 |
| "UPPER" | "LOWER" | "PROPER" | "VALUE" | "TEXT"
|
| 108 |
-
| "SUBSTITUTE" | "FIND" | "REGEX_EXTRACT" | "REGEX_REPLACE"
|
| 109 |
| "TODAY" | "YEAR" | "MONTH" | "DAY" | "DAYS"
|
| 110 |
| "DATEADD" | "DATETIME_DIFF" | "DATETIME_FORMAT"
|
| 111 |
// ── wave 50, W50-T16: the Excel core ──────────────────────────────────────
|
|
@@ -284,6 +284,9 @@ const FN_ARITY: Record<FormulaFn, [number, number]> = {
|
|
| 284 |
SUBSTITUTE: [3, 4],
|
| 285 |
// FIND(stringToFind, whereToSearch, [startFromPosition]) — NEEDLE FIRST.
|
| 286 |
FIND: [2, 3],
|
|
|
|
|
|
|
|
|
|
| 287 |
REGEX_EXTRACT: [2, 2],
|
| 288 |
REGEX_REPLACE: [3, 3],
|
| 289 |
TODAY: [0, 0],
|
|
@@ -384,7 +387,7 @@ export const SHEET_ONLY_FNS: ReadonlySet<FormulaFn> = new Set<FormulaFn>([
|
|
| 384 |
"SUMIF", "SUMIFS", "COUNTIF", "COUNTIFS", "AVERAGEIF", "AVERAGEIFS", "MAXIFS", "MINIFS",
|
| 385 |
"SUMPRODUCT", "VLOOKUP", "HLOOKUP", "XLOOKUP", "INDEX", "MATCH", "ROWS", "COLUMNS",
|
| 386 |
"RANK", "PERCENTILE", "QUARTILE", "LARGE", "SMALL", "COUNTBLANK",
|
| 387 |
-
"ROW", "COLUMN",
|
| 388 |
]);
|
| 389 |
|
| 390 |
/**
|
|
@@ -395,7 +398,7 @@ export const SHEET_ONLY_FNS: ReadonlySet<FormulaFn> = new Set<FormulaFn>([
|
|
| 395 |
* to supply, and there is no range that would help. ROW and COLUMN want an address, so the
|
| 396 |
* sentence they produce says address.
|
| 397 |
*/
|
| 398 |
-
const ADDRESS_ONLY_FNS: ReadonlySet<FormulaFn> = new Set<FormulaFn>(["ROW", "COLUMN"]);
|
| 399 |
|
| 400 |
export type ParseResult =
|
| 401 |
| { ok: true; ast: FormulaAst; refs: string[] }
|
|
@@ -1400,6 +1403,25 @@ function evalNode(
|
|
| 1400 |
const at = hay.indexOf(needle, start - 1);
|
| 1401 |
return at < 0 ? 0 : at + 1;
|
| 1402 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1403 |
case "REGEX_EXTRACT": {
|
| 1404 |
// REGEX_EXTRACT(text, pattern) -> the FIRST WHOLE MATCH, blank when
|
| 1405 |
// the pattern does not match. (Airtable returns the whole match, not
|
|
@@ -1750,13 +1772,17 @@ function evalNode(
|
|
| 1750 |
// deliberately, which is Excel's rule for the operator, so EXACT is the only way to
|
| 1751 |
// ask the strict question and it must not be routed through the same helper.
|
| 1752 |
return asText(ev(n.args[0])) === asText(ev(n.args[1]));
|
| 1753 |
-
case "ISNUMBER":
|
| 1754 |
// ⚠ THE VALUE'S TYPE DECIDES, NOT A COERCION. ISNUMBER("12") is FALSE in Excel: the
|
| 1755 |
// cell holds text that looks like a number, and saying otherwise would make the
|
| 1756 |
// function useless for the one job it has, which is telling those two apart.
|
| 1757 |
-
|
| 1758 |
-
|
| 1759 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1760 |
}
|
| 1761 |
// The 24 range-and-address functions never arrive here: `badPattern` refuses them at
|
| 1762 |
// authoring time. If one somehow does, blank is the engine's one rule, never a throw.
|
|
|
|
| 105 |
| "IF" | "AND" | "OR" | "NOT" | "IFERROR" | "ISBLANK" | "SWITCH"
|
| 106 |
| "CONCATENATE" | "LEFT" | "RIGHT" | "MID" | "LEN" | "TRIM"
|
| 107 |
| "UPPER" | "LOWER" | "PROPER" | "VALUE" | "TEXT"
|
| 108 |
+
| "SUBSTITUTE" | "FIND" | "SEARCH" | "SEARCHB" | "ISFORMULA" | "REGEX_EXTRACT" | "REGEX_REPLACE"
|
| 109 |
| "TODAY" | "YEAR" | "MONTH" | "DAY" | "DAYS"
|
| 110 |
| "DATEADD" | "DATETIME_DIFF" | "DATETIME_FORMAT"
|
| 111 |
// ── wave 50, W50-T16: the Excel core ──────────────────────────────────────
|
|
|
|
| 284 |
SUBSTITUTE: [3, 4],
|
| 285 |
// FIND(stringToFind, whereToSearch, [startFromPosition]) — NEEDLE FIRST.
|
| 286 |
FIND: [2, 3],
|
| 287 |
+
SEARCH: [2, 3],
|
| 288 |
+
SEARCHB: [2, 3],
|
| 289 |
+
ISFORMULA: [1, 1],
|
| 290 |
REGEX_EXTRACT: [2, 2],
|
| 291 |
REGEX_REPLACE: [3, 3],
|
| 292 |
TODAY: [0, 0],
|
|
|
|
| 387 |
"SUMIF", "SUMIFS", "COUNTIF", "COUNTIFS", "AVERAGEIF", "AVERAGEIFS", "MAXIFS", "MINIFS",
|
| 388 |
"SUMPRODUCT", "VLOOKUP", "HLOOKUP", "XLOOKUP", "INDEX", "MATCH", "ROWS", "COLUMNS",
|
| 389 |
"RANK", "PERCENTILE", "QUARTILE", "LARGE", "SMALL", "COUNTBLANK",
|
| 390 |
+
"ROW", "COLUMN", "ISFORMULA",
|
| 391 |
]);
|
| 392 |
|
| 393 |
/**
|
|
|
|
| 398 |
* to supply, and there is no range that would help. ROW and COLUMN want an address, so the
|
| 399 |
* sentence they produce says address.
|
| 400 |
*/
|
| 401 |
+
const ADDRESS_ONLY_FNS: ReadonlySet<FormulaFn> = new Set<FormulaFn>(["ROW", "COLUMN", "ISFORMULA"]);
|
| 402 |
|
| 403 |
export type ParseResult =
|
| 404 |
| { ok: true; ast: FormulaAst; refs: string[] }
|
|
|
|
| 1403 |
const at = hay.indexOf(needle, start - 1);
|
| 1404 |
return at < 0 ? 0 : at + 1;
|
| 1405 |
}
|
| 1406 |
+
case "SEARCH": case "SEARCHB": {
|
| 1407 |
+
const within = Array.from(asText(ev(n.args[1])));
|
| 1408 |
+
const startValue = n.args.length > 2 ? strictNum(ev(n.args[2]), diag) : 1;
|
| 1409 |
+
const start = startValue === null ? 0 : Math.trunc(startValue);
|
| 1410 |
+
if (start < 1 || start > within.length + 1) { diag.push("bad_value"); return null; }
|
| 1411 |
+
const needle = Array.from(asText(ev(n.args[0])));
|
| 1412 |
+
let pattern = "";
|
| 1413 |
+
const literal = (ch: string) => ch.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
| 1414 |
+
for (let i = 0; i < needle.length; i++) {
|
| 1415 |
+
const ch = needle[i];
|
| 1416 |
+
if (ch === "~" && "?*~".includes(needle[i + 1] ?? "") && i + 1 < needle.length) {
|
| 1417 |
+
pattern += literal(needle[++i]);
|
| 1418 |
+
} else pattern += ch === "*" ? ".*?" : ch === "?" ? "." : literal(ch);
|
| 1419 |
+
}
|
| 1420 |
+
const subject = within.slice(start - 1).join("");
|
| 1421 |
+
const found = new RegExp(pattern, "isu").exec(subject);
|
| 1422 |
+
if (!found) { diag.push("bad_value"); return null; }
|
| 1423 |
+
return start + Array.from(subject.slice(0, found.index)).length;
|
| 1424 |
+
}
|
| 1425 |
case "REGEX_EXTRACT": {
|
| 1426 |
// REGEX_EXTRACT(text, pattern) -> the FIRST WHOLE MATCH, blank when
|
| 1427 |
// the pattern does not match. (Airtable returns the whole match, not
|
|
|
|
| 1772 |
// deliberately, which is Excel's rule for the operator, so EXACT is the only way to
|
| 1773 |
// ask the strict question and it must not be routed through the same helper.
|
| 1774 |
return asText(ev(n.args[0])) === asText(ev(n.args[1]));
|
| 1775 |
+
case "ISNUMBER": {
|
| 1776 |
// ⚠ THE VALUE'S TYPE DECIDES, NOT A COERCION. ISNUMBER("12") is FALSE in Excel: the
|
| 1777 |
// cell holds text that looks like a number, and saying otherwise would make the
|
| 1778 |
// function useless for the one job it has, which is telling those two apart.
|
| 1779 |
+
const local: string[] = [];
|
| 1780 |
+
return typeof evalNode(n.args[0], get, env, local) === "number" && local.length === 0;
|
| 1781 |
+
}
|
| 1782 |
+
case "ISTEXT": {
|
| 1783 |
+
const local: string[] = [];
|
| 1784 |
+
return typeof evalNode(n.args[0], get, env, local) === "string" && local.length === 0;
|
| 1785 |
+
}
|
| 1786 |
}
|
| 1787 |
// The 24 range-and-address functions never arrive here: `badPattern` refuses them at
|
| 1788 |
// authoring time. If one somehow does, blank is the engine's one rule, never a throw.
|
web/src/customer-grid/useCustomerData.ts
CHANGED
|
@@ -233,6 +233,7 @@ export interface CustomerData {
|
|
| 233 |
rawRows: Row[];
|
| 234 |
payload: CustomersPayload | null;
|
| 235 |
loading: boolean;
|
|
|
|
| 236 |
windowPending: boolean;
|
| 237 |
/** pid -> partial overlay of user-authored edits, layered OVER the fetched row. */
|
| 238 |
overlayEdits: OverlayEdits;
|
|
@@ -405,6 +406,7 @@ export function useCustomerData(
|
|
| 405 |
const workspaceOpen = useRef<{
|
| 406 |
cached: boolean; refresh: Promise<GridWorkspace | null> | null | false;
|
| 407 |
} | null>(null);
|
|
|
|
| 408 |
useEffect(() => {
|
| 409 |
if (suppliedPayload || STREAMLIT_COMPONENT) return; // the caller owns refresh
|
| 410 |
const onStale = () => setRowsBump((b) => b + 1);
|
|
@@ -550,6 +552,7 @@ export function useCustomerData(
|
|
| 550 |
};
|
| 551 |
}
|
| 552 |
const openWorkspace = workspaceOpen.current;
|
|
|
|
| 553 |
|
| 554 |
readThroughRef.current = false;
|
| 555 |
|
|
@@ -574,7 +577,10 @@ export function useCustomerData(
|
|
| 574 |
? fetchWorkspace(scope, { announceFailure: firstPaint, allowCached: true })
|
| 575 |
: Promise.resolve(null);
|
| 576 |
// Record an early answer without making the rows wait for a late one.
|
| 577 |
-
void wsPromise.then((ws) => {
|
|
|
|
|
|
|
|
|
|
| 578 |
// A pin selects the universal window reader before any status request. Unpinned
|
| 579 |
// grids retain their existing roster-based choice of window or whole-book reads.
|
| 580 |
const tableKey = topic.key;
|
|
@@ -864,6 +870,8 @@ export function useCustomerData(
|
|
| 864 |
rawRows: visibleData?.rows ?? [],
|
| 865 |
payload: visibleData,
|
| 866 |
loading: visibleData === null,
|
|
|
|
|
|
|
| 867 |
windowPending,
|
| 868 |
overlayEdits: suppliedPayload ? EMPTY_OVERLAY_EDITS : overlayEdits,
|
| 869 |
setOverlayEdits: suppliedPayload ? ignoreOverlayEdits : setOverlayEdits,
|
|
|
|
| 233 |
rawRows: Row[];
|
| 234 |
payload: CustomersPayload | null;
|
| 235 |
loading: boolean;
|
| 236 |
+
workspacePending: boolean;
|
| 237 |
windowPending: boolean;
|
| 238 |
/** pid -> partial overlay of user-authored edits, layered OVER the fetched row. */
|
| 239 |
overlayEdits: OverlayEdits;
|
|
|
|
| 406 |
const workspaceOpen = useRef<{
|
| 407 |
cached: boolean; refresh: Promise<GridWorkspace | null> | null | false;
|
| 408 |
} | null>(null);
|
| 409 |
+
const [workspaceRead, setWorkspaceRead] = useState({ scope, pending: includeWorkspace });
|
| 410 |
useEffect(() => {
|
| 411 |
if (suppliedPayload || STREAMLIT_COMPONENT) return; // the caller owns refresh
|
| 412 |
const onStale = () => setRowsBump((b) => b + 1);
|
|
|
|
| 552 |
};
|
| 553 |
}
|
| 554 |
const openWorkspace = workspaceOpen.current;
|
| 555 |
+
if (firstPaint) setWorkspaceRead({ scope, pending: includeWorkspace && !peekWorkspace(scope) });
|
| 556 |
|
| 557 |
readThroughRef.current = false;
|
| 558 |
|
|
|
|
| 577 |
? fetchWorkspace(scope, { announceFailure: firstPaint, allowCached: true })
|
| 578 |
: Promise.resolve(null);
|
| 579 |
// Record an early answer without making the rows wait for a late one.
|
| 580 |
+
void wsPromise.then((ws) => {
|
| 581 |
+
workspace = ws;
|
| 582 |
+
if (!cancelled) setWorkspaceRead({ scope, pending: false });
|
| 583 |
+
});
|
| 584 |
// A pin selects the universal window reader before any status request. Unpinned
|
| 585 |
// grids retain their existing roster-based choice of window or whole-book reads.
|
| 586 |
const tableKey = topic.key;
|
|
|
|
| 870 |
rawRows: visibleData?.rows ?? [],
|
| 871 |
payload: visibleData,
|
| 872 |
loading: visibleData === null,
|
| 873 |
+
workspacePending: includeWorkspace && !suppliedPayload
|
| 874 |
+
&& (workspaceRead.scope !== scope || workspaceRead.pending),
|
| 875 |
windowPending,
|
| 876 |
overlayEdits: suppliedPayload ? EMPTY_OVERLAY_EDITS : overlayEdits,
|
| 877 |
setOverlayEdits: suppliedPayload ? ignoreOverlayEdits : setOverlayEdits,
|
web/src/filter-kit/SheetFilterPopup.tsx
CHANGED
|
@@ -62,7 +62,7 @@ export interface SheetFilterPopupProps {
|
|
| 62 |
/** The cell this filter belongs to, e.g. `B4`. Named in the title so the dialog says which
|
| 63 |
* cell it is about, the way the binding panel behind it does. */
|
| 64 |
addr: string;
|
| 65 |
-
/** Escape,
|
| 66 |
* door: see the note about draft state at the top of this file. */
|
| 67 |
onClose: () => void;
|
| 68 |
fields: Field[];
|
|
@@ -193,7 +193,7 @@ export function SheetFilterDialog({
|
|
| 193 |
useOverlayLayer({
|
| 194 |
panelRef,
|
| 195 |
onDismiss: onClose,
|
| 196 |
-
dismissOnOutside:
|
| 197 |
initialFocus: "first",
|
| 198 |
restoreFocus: true,
|
| 199 |
trapFocus: true,
|
|
|
|
| 62 |
/** The cell this filter belongs to, e.g. `B4`. Named in the title so the dialog says which
|
| 63 |
* cell it is about, the way the binding panel behind it does. */
|
| 64 |
addr: string;
|
| 65 |
+
/** Escape, the close mark, or Done. There is no second, cancelling
|
| 66 |
* door: see the note about draft state at the top of this file. */
|
| 67 |
onClose: () => void;
|
| 68 |
fields: Field[];
|
|
|
|
| 193 |
useOverlayLayer({
|
| 194 |
panelRef,
|
| 195 |
onDismiss: onClose,
|
| 196 |
+
dismissOnOutside: false,
|
| 197 |
initialFocus: "first",
|
| 198 |
restoreFocus: true,
|
| 199 |
trapFocus: true,
|
web/src/inbox/InboxPage.tsx
CHANGED
|
@@ -47,6 +47,7 @@ import {
|
|
| 47 |
canOpen,
|
| 48 |
inboxSections,
|
| 49 |
previewOf,
|
|
|
|
| 50 |
senderOf,
|
| 51 |
subjectOf,
|
| 52 |
targetOf,
|
|
@@ -109,6 +110,14 @@ const CARD: React.CSSProperties = {
|
|
| 109 |
minHeight: 0,
|
| 110 |
};
|
| 111 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
export default function InboxPage({
|
| 113 |
onOpenTarget,
|
| 114 |
onInbox,
|
|
@@ -560,17 +569,7 @@ export function InboxSurface({
|
|
| 560 |
className="login-submit"
|
| 561 |
onClick={() => onOpen(selected)}
|
| 562 |
>
|
| 563 |
-
{
|
| 564 |
-
"open" generically — two kinds go two places.
|
| 565 |
-
⛔ WAVE 34 · R12 — THIS COMPARED A DISPLAY STRING, AND THAT IS WHY IT IS
|
| 566 |
-
WRITTEN THIS WAY NOW. It read `kindLabel(selected.kind) === "Automation"`:
|
| 567 |
-
a second copy of a caption, in a file the rename had no reason to open. The
|
| 568 |
-
moment `kindLabel` returned "Agents" the test went false in silence and
|
| 569 |
-
every automation notification offered to open a DATABASE. Compare the KIND,
|
| 570 |
-
which is a stored wire value nobody renames for a caption. */}
|
| 571 |
-
{selected.kind === NOTIF_KIND_AUTOMATION
|
| 572 |
-
? "Open the agent"
|
| 573 |
-
: "Open the database"}
|
| 574 |
</button>
|
| 575 |
) : (
|
| 576 |
/* ⛔ SAID ON THE ITEM, NOT ON THE CLICK. The pane raised this as a toast AFTER
|
|
|
|
| 47 |
canOpen,
|
| 48 |
inboxSections,
|
| 49 |
previewOf,
|
| 50 |
+
routeForTarget,
|
| 51 |
senderOf,
|
| 52 |
subjectOf,
|
| 53 |
targetOf,
|
|
|
|
| 110 |
minHeight: 0,
|
| 111 |
};
|
| 112 |
|
| 113 |
+
function actionLabelOf(notification: Notification): string {
|
| 114 |
+
const destination = routeForTarget(targetOf(notification));
|
| 115 |
+
if (destination?.surface === "automation") return "Open the agent";
|
| 116 |
+
if (destination?.surface === "database" && destination.key.startsWith("app?"))
|
| 117 |
+
return "Open the App";
|
| 118 |
+
return "Open the database";
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
export default function InboxPage({
|
| 122 |
onOpenTarget,
|
| 123 |
onInbox,
|
|
|
|
| 569 |
className="login-submit"
|
| 570 |
onClick={() => onOpen(selected)}
|
| 571 |
>
|
| 572 |
+
{actionLabelOf(selected)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 573 |
</button>
|
| 574 |
) : (
|
| 575 |
/* ⛔ SAID ON THE ITEM, NOT ON THE CLICK. The pane raised this as a toast AFTER
|
web/src/sheet/BindingEditor.tsx
CHANGED
|
@@ -537,7 +537,7 @@ function ColumnPickerDialog({
|
|
| 537 |
useOverlayLayer({
|
| 538 |
panelRef,
|
| 539 |
onDismiss: onClose,
|
| 540 |
-
dismissOnOutside:
|
| 541 |
initialFocus: "first",
|
| 542 |
restoreFocus: true,
|
| 543 |
trapFocus: true,
|
|
@@ -938,7 +938,7 @@ export default function BindingEditor({
|
|
| 938 |
// HOTFIX 2026-09-29: a scope this page read moments ago paints NOW from the memo, so a second
|
| 939 |
// Edit does not sit on a skeleton for a multi-second assembly. The server read below still
|
| 940 |
// runs and replaces these lists (and drops a view that no longer exists) when it answers.
|
| 941 |
-
const memo = peekWorkspace(scope);
|
| 942 |
if (memo) {
|
| 943 |
setFields((memo.fields ?? []) as Field[]);
|
| 944 |
setMeasures(memo.measures ?? []);
|
|
@@ -949,20 +949,16 @@ export default function BindingEditor({
|
|
| 949 |
}
|
| 950 |
(async () => {
|
| 951 |
// ONE door, and it is the one that knows what exists now.
|
| 952 |
-
const fresh = await fetchWorkspace(scope);
|
| 953 |
if (!live) return;
|
| 954 |
if (!fresh) {
|
| 955 |
-
//
|
| 956 |
-
|
| 957 |
-
|
| 958 |
-
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
|
| 962 |
-
setViews(viewList(ws.views));
|
| 963 |
-
setUserOptions(ws.userOptions ?? []);
|
| 964 |
-
setViewsLoaded(true);
|
| 965 |
-
}
|
| 966 |
// ⛔ W54-T33 — BUT THE PANEL REVEALS EITHER WAY. Nothing better is coming for this
|
| 967 |
// database, and a skeleton that outlives the request it was waiting on tells the reader
|
| 968 |
// the panel is broken rather than that the server would not answer.
|
|
@@ -1418,9 +1414,18 @@ export default function BindingEditor({
|
|
| 1418 |
const dataComplete = sourceComplete && (!chosenIsMetric || periodComplete);
|
| 1419 |
const copiedComplete = !savedDragDriverMissing;
|
| 1420 |
const relatedPending = relatedOffer.database !== database || !relatedOffer.loaded;
|
| 1421 |
-
const
|
| 1422 |
-
|
| 1423 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1424 |
&& (shape === "value" || activeSection === "place");
|
| 1425 |
|
| 1426 |
const sectionComplete = {
|
|
@@ -2193,6 +2198,9 @@ export default function BindingEditor({
|
|
| 2193 |
)}
|
| 2194 |
|
| 2195 |
{preview && <p className="sheet-preview">{`This cell would show ${preview}`}</p>}
|
|
|
|
|
|
|
|
|
|
| 2196 |
{notice && <p className="sheet-notice" role="alert">{notice}</p>}
|
| 2197 |
</>
|
| 2198 |
</div>
|
|
|
|
| 537 |
useOverlayLayer({
|
| 538 |
panelRef,
|
| 539 |
onDismiss: onClose,
|
| 540 |
+
dismissOnOutside: false,
|
| 541 |
initialFocus: "first",
|
| 542 |
restoreFocus: true,
|
| 543 |
trapFocus: true,
|
|
|
|
| 938 |
// HOTFIX 2026-09-29: a scope this page read moments ago paints NOW from the memo, so a second
|
| 939 |
// Edit does not sit on a skeleton for a multi-second assembly. The server read below still
|
| 940 |
// runs and replaces these lists (and drops a view that no longer exists) when it answers.
|
| 941 |
+
const memo = peekWorkspace(scope, { fieldsOnly: true });
|
| 942 |
if (memo) {
|
| 943 |
setFields((memo.fields ?? []) as Field[]);
|
| 944 |
setMeasures(memo.measures ?? []);
|
|
|
|
| 949 |
}
|
| 950 |
(async () => {
|
| 951 |
// ONE door, and it is the one that knows what exists now.
|
| 952 |
+
const fresh = await fetchWorkspace(scope, { fieldsOnly: true });
|
| 953 |
if (!live) return;
|
| 954 |
if (!fresh) {
|
| 955 |
+
// A failed fresh permission question cannot leave an earlier offer writable.
|
| 956 |
+
setFields([]);
|
| 957 |
+
setMeasures([]);
|
| 958 |
+
setViews([]);
|
| 959 |
+
setUserOptions([]);
|
| 960 |
+
setViewsLoaded(false);
|
| 961 |
+
setNotice("These fields could not be loaded. Close and reopen this panel to try again.");
|
|
|
|
|
|
|
|
|
|
|
|
|
| 962 |
// ⛔ W54-T33 — BUT THE PANEL REVEALS EITHER WAY. Nothing better is coming for this
|
| 963 |
// database, and a skeleton that outlives the request it was waiting on tells the reader
|
| 964 |
// the panel is broken rather than that the server would not answer.
|
|
|
|
| 1414 |
const dataComplete = sourceComplete && (!chosenIsMetric || periodComplete);
|
| 1415 |
const copiedComplete = !savedDragDriverMissing;
|
| 1416 |
const relatedPending = relatedOffer.database !== database || !relatedOffer.loaded;
|
| 1417 |
+
const relatedKeys = bindingFilterClauses(tree).flatMap((leaf) => [leaf.colId,
|
| 1418 |
+
...(leaf.rhs && "colId" in leaf.rhs ? [leaf.rhs.colId] : [])]).filter((key) =>
|
| 1419 |
+
key.startsWith("linked:") || key.startsWith("related:"));
|
| 1420 |
+
// The server validates this saved predicate again on Save. Pending discovery does not
|
| 1421 |
+
// require an unchanged predicate to be reconstructed from an offer it already names.
|
| 1422 |
+
const savedRelatedUnchanged = initial?.database === database && scopeKind === savedScope.kind
|
| 1423 |
+
&& JSON.stringify(tree) === JSON.stringify(savedScope.tree) && !relatedNotice;
|
| 1424 |
+
const aliasesPending = relatedKeys.length > 0 && relatedPending && !savedRelatedUnchanged;
|
| 1425 |
+
const relatedUnavailable = !relatedPending && relatedKeys.some((key) =>
|
| 1426 |
+
!relatedOffer.fields.some((offer) => offer.key === key));
|
| 1427 |
+
const ready = optionsResolved && viewsLoaded && !aliasesPending && !relatedUnavailable
|
| 1428 |
+
&& dataComplete && filterComplete && periodComplete && copiedComplete
|
| 1429 |
&& (shape === "value" || activeSection === "place");
|
| 1430 |
|
| 1431 |
const sectionComplete = {
|
|
|
|
| 2198 |
)}
|
| 2199 |
|
| 2200 |
{preview && <p className="sheet-preview">{`This cell would show ${preview}`}</p>}
|
| 2201 |
+
{relatedUnavailable && <p className="sheet-notice" role="status">
|
| 2202 |
+
Some related fields in this filter are unavailable. Review the filter before saving.
|
| 2203 |
+
</p>}
|
| 2204 |
{notice && <p className="sheet-notice" role="alert">{notice}</p>}
|
| 2205 |
</>
|
| 2206 |
</div>
|
web/src/sheet/DrillModal.tsx
CHANGED
|
@@ -496,6 +496,7 @@ function DrillModal(
|
|
| 496 |
useEffect(() => {
|
| 497 |
let live = true;
|
| 498 |
const seq = ++drillSeqRef.current;
|
|
|
|
| 499 |
(async () => {
|
| 500 |
const got = await drillCell(workbookId, addr, tab);
|
| 501 |
if (!live) return;
|
|
@@ -507,6 +508,7 @@ function DrillModal(
|
|
| 507 |
setError(got.message);
|
| 508 |
return;
|
| 509 |
}
|
|
|
|
| 510 |
setDrill(got.value);
|
| 511 |
})();
|
| 512 |
return () => {
|
|
@@ -551,7 +553,7 @@ function DrillModal(
|
|
| 551 |
setFields([]);
|
| 552 |
setWorkspace(null);
|
| 553 |
(async () => {
|
| 554 |
-
const ws = await fetchWorkspace(scope, { allowCached: true });
|
| 555 |
if (!live) return;
|
| 556 |
if (!ws?.fields) {
|
| 557 |
setRowsError("The fields for these records could not be loaded. Reopen View data to try again.");
|
|
@@ -585,14 +587,18 @@ function DrillModal(
|
|
| 585 |
const drillDraft = useCallback((tree: FilterTree) => {
|
| 586 |
setIdsPending(true);
|
| 587 |
if (draftTimerRef.current !== null) window.clearTimeout(draftTimerRef.current);
|
|
|
|
| 588 |
draftTimerRef.current = window.setTimeout(() => {
|
| 589 |
draftTimerRef.current = null;
|
| 590 |
-
const seq = ++drillSeqRef.current;
|
| 591 |
void drillCell(workbookId, addr, tab, { filter: tree }).then((got) => {
|
| 592 |
if (seq !== drillSeqRef.current) return;
|
| 593 |
-
// A refused draft releases the grid; the cell write and its re-drill still follow.
|
| 594 |
setIdsPending(false);
|
| 595 |
-
if (got.ok)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 596 |
});
|
| 597 |
}, 150);
|
| 598 |
}, [workbookId, addr, tab]);
|
|
@@ -700,8 +706,7 @@ function DrillModal(
|
|
| 700 |
return () => window.removeEventListener("keydown", onKey, true);
|
| 701 |
}, []);
|
| 702 |
|
| 703 |
-
//
|
| 704 |
-
// passes it harmlessly while the older LinkGridModal type and implementation are still here.
|
| 705 |
const initialPage = useMemo(() => {
|
| 706 |
if (!drill?.page) return undefined;
|
| 707 |
const payload: CustomersPayload = {
|
|
@@ -882,8 +887,6 @@ function DrillModal(
|
|
| 882 |
label={label}
|
| 883 |
table={scope}
|
| 884 |
recordIds={drill.record_ids}
|
| 885 |
-
// `idsPending` joins `initialPage` in the same way: lane F's LinkGridModal consumes it at
|
| 886 |
-
// the combine (COMBINE-AMEND in context/S68-T23.md) and ignores it until then.
|
| 887 |
{...{ initialPage, idsPending }}
|
| 888 |
editable={false}
|
| 889 |
cellView
|
|
|
|
| 496 |
useEffect(() => {
|
| 497 |
let live = true;
|
| 498 |
const seq = ++drillSeqRef.current;
|
| 499 |
+
setIdsPending(true);
|
| 500 |
(async () => {
|
| 501 |
const got = await drillCell(workbookId, addr, tab);
|
| 502 |
if (!live) return;
|
|
|
|
| 508 |
setError(got.message);
|
| 509 |
return;
|
| 510 |
}
|
| 511 |
+
setError("");
|
| 512 |
setDrill(got.value);
|
| 513 |
})();
|
| 514 |
return () => {
|
|
|
|
| 553 |
setFields([]);
|
| 554 |
setWorkspace(null);
|
| 555 |
(async () => {
|
| 556 |
+
const ws = await fetchWorkspace(scope, { allowCached: true, fieldsOnly: true });
|
| 557 |
if (!live) return;
|
| 558 |
if (!ws?.fields) {
|
| 559 |
setRowsError("The fields for these records could not be loaded. Reopen View data to try again.");
|
|
|
|
| 587 |
const drillDraft = useCallback((tree: FilterTree) => {
|
| 588 |
setIdsPending(true);
|
| 589 |
if (draftTimerRef.current !== null) window.clearTimeout(draftTimerRef.current);
|
| 590 |
+
const seq = ++drillSeqRef.current;
|
| 591 |
draftTimerRef.current = window.setTimeout(() => {
|
| 592 |
draftTimerRef.current = null;
|
|
|
|
| 593 |
void drillCell(workbookId, addr, tab, { filter: tree }).then((got) => {
|
| 594 |
if (seq !== drillSeqRef.current) return;
|
|
|
|
| 595 |
setIdsPending(false);
|
| 596 |
+
if (got.ok) {
|
| 597 |
+
setError("");
|
| 598 |
+
setDrill(got.value);
|
| 599 |
+
} else {
|
| 600 |
+
setError(got.message);
|
| 601 |
+
}
|
| 602 |
});
|
| 603 |
}, 150);
|
| 604 |
}, [workbookId, addr, tab]);
|
|
|
|
| 706 |
return () => window.removeEventListener("keydown", onKey, true);
|
| 707 |
}, []);
|
| 708 |
|
| 709 |
+
// The shared ID-window hook consumes the server page without a second row request.
|
|
|
|
| 710 |
const initialPage = useMemo(() => {
|
| 711 |
if (!drill?.page) return undefined;
|
| 712 |
const payload: CustomersPayload = {
|
|
|
|
| 887 |
label={label}
|
| 888 |
table={scope}
|
| 889 |
recordIds={drill.record_ids}
|
|
|
|
|
|
|
| 890 |
{...{ initialPage, idsPending }}
|
| 891 |
editable={false}
|
| 892 |
cellView
|
web/src/sheet/Ribbon.tsx
CHANGED
|
@@ -199,6 +199,8 @@ export interface RibbonProps {
|
|
| 199 |
style: CellStyle | null;
|
| 200 |
/** No selection, or a workbook that is saving: every control is inert but still readable. */
|
| 201 |
disabled?: boolean;
|
|
|
|
|
|
|
| 202 |
/** Whether the sheet currently freezes its leading column, so the Freeze item reads back. */
|
| 203 |
frozen?: boolean;
|
| 204 |
/** ⛔ NO FAKE AFFORDANCE. Import is offered only where the page actually has a door for it. */
|
|
@@ -286,6 +288,7 @@ const STRIP: readonly ControlKey[] = [
|
|
| 286 |
*/
|
| 287 |
export interface RibbonTabContext {
|
| 288 |
style: CellStyle | null;
|
|
|
|
| 289 |
frozen: boolean;
|
| 290 |
open: Popover;
|
| 291 |
anchorEl: HTMLElement | null;
|
|
@@ -411,6 +414,13 @@ function partitionRibbonGroups(node: ReactNode, visibleCount: number, folded: bo
|
|
| 411 |
/** Stateful child controls must be mounted by React, never called as groups(ctx) functions.
|
| 412 |
* The recording context returns no buttons, and open is empty, so no overlay or action mounts.
|
| 413 |
*/
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 414 |
function RibbonCommandProbe({ node, context, tab, group, disabled, runControl, publish }: {
|
| 415 |
node: React.ReactElement<{ ctx: RibbonTabContext }>;
|
| 416 |
context: RibbonTabContext;
|
|
@@ -425,7 +435,7 @@ function RibbonCommandProbe({ node, context, tab, group, disabled, runControl, p
|
|
| 425 |
...context, open: "", anchorEl: null,
|
| 426 |
control: (key, label, _body, _onClick, _pressed, _expanded, _kt, _opens, controlDisabled) => {
|
| 427 |
const command = { id: `${tab}:${key}`, key, label, location: group,
|
| 428 |
-
disabled: disabled || !!controlDisabled, run: () => runControl(tab, key) };
|
| 429 |
const at = records.findIndex(record => record.id === command.id);
|
| 430 |
if (at < 0) records.push(command);
|
| 431 |
else records[at] = command;
|
|
@@ -460,7 +470,8 @@ function recordRibbonCommands(
|
|
| 460 |
const record: Recorded = {
|
| 461 |
id: `${tab.id}:${key}`, key, label, location: tab.label, kind: "control",
|
| 462 |
opensGallery: opensGallery === "gallery",
|
| 463 |
-
disabled: disabled || !!controlDisabled || (tab.id === "insert" && !context.insert)
|
|
|
|
| 464 |
run: () => runControl(tab.id, key),
|
| 465 |
};
|
| 466 |
pending.push(record); records.push(record);
|
|
@@ -471,7 +482,8 @@ function recordRibbonCommands(
|
|
| 471 |
if (gallery) {
|
| 472 |
const record: Recorded = {
|
| 473 |
id: `${tab.id}:${gallery.key}:item:${label}`, key: gallery.key, label,
|
| 474 |
-
location: gallery.location, kind: "item", disabled: gallery.disabled
|
|
|
|
| 475 |
};
|
| 476 |
pending.push(record); records.push(record);
|
| 477 |
}
|
|
@@ -524,7 +536,7 @@ function recordRibbonCommands(
|
|
| 524 |
}
|
| 525 |
|
| 526 |
export default function Ribbon({
|
| 527 |
-
style, disabled = false, frozen = false, canImport = false, onApply, onAction, insert,
|
| 528 |
}: RibbonProps) {
|
| 529 |
const [focus, setFocus] = useState<ControlKey>(TABS[0].key);
|
| 530 |
const [open, setOpen] = useState<Popover>("");
|
|
@@ -715,16 +727,18 @@ export default function Ribbon({
|
|
| 715 |
}, [focus, focusControl, open, reachable]);
|
| 716 |
|
| 717 |
const apply = useCallback((patch: CellStylePatch) => {
|
|
|
|
| 718 |
setOpen("");
|
| 719 |
if (overflowOpen) closeOverflow();
|
| 720 |
onApply(patch);
|
| 721 |
-
}, [closeOverflow, onApply, overflowOpen]);
|
| 722 |
|
| 723 |
const act = useCallback((kind: RibbonActionKind, arg?: string | number) => {
|
|
|
|
| 724 |
setOpen("");
|
| 725 |
if (overflowOpen) closeOverflow();
|
| 726 |
onAction({ kind, arg });
|
| 727 |
-
}, [closeOverflow, onAction, overflowOpen]);
|
| 728 |
|
| 729 |
/**
|
| 730 |
* ⭐⭐ W53-T07 — CLOSING A MENU RETURNS FOCUS TO THE CONTROL THAT OWNS IT, and that is the
|
|
@@ -806,7 +820,7 @@ export default function Ribbon({
|
|
| 806 |
aria-expanded={expanded}
|
| 807 |
aria-haspopup={expanded === undefined ? undefined : popupRole}
|
| 808 |
tabIndex={focus === key ? 0 : -1}
|
| 809 |
-
|
| 810 |
onFocus={() => setFocus(key)}
|
| 811 |
// The grid keeps the keyboard: pressing a ribbon button must not blur the canvas, or glide
|
| 812 |
// drops its selection and the act lands on nothing. Same reason as `CellActionBar`.
|
|
@@ -826,7 +840,8 @@ export default function Ribbon({
|
|
| 826 |
let groupIndex = 0;
|
| 827 |
const group = (name: string, body: ReactNode, extra = "") => (
|
| 828 |
<div key={name} data-ribbon-group={groupIndex++} className={"sheet-ribbon-group" + extra} role="group" aria-label={name}>
|
| 829 |
-
<div className="sheet-ribbon-group-controls">{
|
|
|
|
| 830 |
<span className="sheet-ribbon-group-name">{name}</span>
|
| 831 |
</div>
|
| 832 |
);
|
|
@@ -870,7 +885,8 @@ export default function Ribbon({
|
|
| 870 |
role={role}
|
| 871 |
aria-checked={role === "menuitem" ? undefined : on}
|
| 872 |
className={"sheet-ribbon-item" + (on ? " is-on" : "")}
|
| 873 |
-
|
|
|
|
| 874 |
onMouseDown={(e) => e.preventDefault()}
|
| 875 |
onClick={onClick}
|
| 876 |
>
|
|
@@ -898,7 +914,7 @@ export default function Ribbon({
|
|
| 898 |
const pdf={...printSettings,from:pageFrom.trim()===""?undefined:Number(pageFrom),to:pageTo.trim()===""?undefined:Number(pageTo)};
|
| 899 |
if(format==="pdf") {
|
| 900 |
planSheetPdf(snapshot.book,pdf);
|
| 901 |
-
await exportContext.savePrintSettings(pdf);
|
| 902 |
snapshot.book={...snapshot.book,printSettings:pdf};
|
| 903 |
}
|
| 904 |
await runSheetExport(format,snapshot,{range:format==="csv"&&exportScope==="selection"&&selectionRange?selectionRange:undefined,pdf});
|
|
@@ -908,7 +924,7 @@ export default function Ribbon({
|
|
| 908 |
};
|
| 909 |
|
| 910 |
const tabContext: RibbonTabContext = {
|
| 911 |
-
style, frozen, open, anchorEl, onApply, apply, act,
|
| 912 |
fullscreen, toggleFullscreen,
|
| 913 |
newWindowBlocked, openNewWindow, openCellData,
|
| 914 |
openPop, closePop, control, group, word, large, stack, unavailable, item, insert,
|
|
|
|
| 199 |
style: CellStyle | null;
|
| 200 |
/** No selection, or a workbook that is saving: every control is inert but still readable. */
|
| 201 |
disabled?: boolean;
|
| 202 |
+
/** Viewers can navigate and export, while document commands remain disabled. */
|
| 203 |
+
readOnly?: boolean;
|
| 204 |
/** Whether the sheet currently freezes its leading column, so the Freeze item reads back. */
|
| 205 |
frozen?: boolean;
|
| 206 |
/** ⛔ NO FAKE AFFORDANCE. Import is offered only where the page actually has a door for it. */
|
|
|
|
| 288 |
*/
|
| 289 |
export interface RibbonTabContext {
|
| 290 |
style: CellStyle | null;
|
| 291 |
+
readOnly?: boolean;
|
| 292 |
frozen: boolean;
|
| 293 |
open: Popover;
|
| 294 |
anchorEl: HTMLElement | null;
|
|
|
|
| 414 |
/** Stateful child controls must be mounted by React, never called as groups(ctx) functions.
|
| 415 |
* The recording context returns no buttons, and open is empty, so no overlay or action mounts.
|
| 416 |
*/
|
| 417 |
+
export function ribbonCommandWrites(key: string, label?: string): boolean {
|
| 418 |
+
if (key === "findselect" && label !== undefined) return !/^(Find|Go To)/i.test(label);
|
| 419 |
+
return !key.startsWith("tab-") && !["copy", "findselect", "export", "fullscreen", "collapse",
|
| 420 |
+
"overflow", "cell-data", "data-queries-connections", "view-new-window", "view-fullscreen",
|
| 421 |
+
"view-go-to"].includes(key);
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
function RibbonCommandProbe({ node, context, tab, group, disabled, runControl, publish }: {
|
| 425 |
node: React.ReactElement<{ ctx: RibbonTabContext }>;
|
| 426 |
context: RibbonTabContext;
|
|
|
|
| 435 |
...context, open: "", anchorEl: null,
|
| 436 |
control: (key, label, _body, _onClick, _pressed, _expanded, _kt, _opens, controlDisabled) => {
|
| 437 |
const command = { id: `${tab}:${key}`, key, label, location: group,
|
| 438 |
+
disabled: disabled || !!controlDisabled || (!!context.readOnly && ribbonCommandWrites(key)), run: () => runControl(tab, key) };
|
| 439 |
const at = records.findIndex(record => record.id === command.id);
|
| 440 |
if (at < 0) records.push(command);
|
| 441 |
else records[at] = command;
|
|
|
|
| 470 |
const record: Recorded = {
|
| 471 |
id: `${tab.id}:${key}`, key, label, location: tab.label, kind: "control",
|
| 472 |
opensGallery: opensGallery === "gallery",
|
| 473 |
+
disabled: disabled || !!controlDisabled || (tab.id === "insert" && !context.insert)
|
| 474 |
+
|| (!!context.readOnly && ribbonCommandWrites(key)),
|
| 475 |
run: () => runControl(tab.id, key),
|
| 476 |
};
|
| 477 |
pending.push(record); records.push(record);
|
|
|
|
| 482 |
if (gallery) {
|
| 483 |
const record: Recorded = {
|
| 484 |
id: `${tab.id}:${gallery.key}:item:${label}`, key: gallery.key, label,
|
| 485 |
+
location: gallery.location, kind: "item", disabled: gallery.disabled
|
| 486 |
+
|| (!!context.readOnly && ribbonCommandWrites(gallery.key, label)), run: onClick,
|
| 487 |
};
|
| 488 |
pending.push(record); records.push(record);
|
| 489 |
}
|
|
|
|
| 536 |
}
|
| 537 |
|
| 538 |
export default function Ribbon({
|
| 539 |
+
style, disabled = false, readOnly = false, frozen = false, canImport = false, onApply, onAction, insert,
|
| 540 |
}: RibbonProps) {
|
| 541 |
const [focus, setFocus] = useState<ControlKey>(TABS[0].key);
|
| 542 |
const [open, setOpen] = useState<Popover>("");
|
|
|
|
| 727 |
}, [focus, focusControl, open, reachable]);
|
| 728 |
|
| 729 |
const apply = useCallback((patch: CellStylePatch) => {
|
| 730 |
+
if (readOnly) return;
|
| 731 |
setOpen("");
|
| 732 |
if (overflowOpen) closeOverflow();
|
| 733 |
onApply(patch);
|
| 734 |
+
}, [closeOverflow, onApply, overflowOpen, readOnly]);
|
| 735 |
|
| 736 |
const act = useCallback((kind: RibbonActionKind, arg?: string | number) => {
|
| 737 |
+
if (readOnly && !["copy", "find", "go-to"].includes(kind)) return;
|
| 738 |
setOpen("");
|
| 739 |
if (overflowOpen) closeOverflow();
|
| 740 |
onAction({ kind, arg });
|
| 741 |
+
}, [closeOverflow, onAction, overflowOpen, readOnly]);
|
| 742 |
|
| 743 |
/**
|
| 744 |
* ⭐⭐ W53-T07 — CLOSING A MENU RETURNS FOCUS TO THE CONTROL THAT OWNS IT, and that is the
|
|
|
|
| 820 |
aria-expanded={expanded}
|
| 821 |
aria-haspopup={expanded === undefined ? undefined : popupRole}
|
| 822 |
tabIndex={focus === key ? 0 : -1}
|
| 823 |
+
disabled={(key !== "overflow" && disabled) || controlDisabled || (readOnly && ribbonCommandWrites(key))}
|
| 824 |
onFocus={() => setFocus(key)}
|
| 825 |
// The grid keeps the keyboard: pressing a ribbon button must not blur the canvas, or glide
|
| 826 |
// drops its selection and the act lands on nothing. Same reason as `CellActionBar`.
|
|
|
|
| 840 |
let groupIndex = 0;
|
| 841 |
const group = (name: string, body: ReactNode, extra = "") => (
|
| 842 |
<div key={name} data-ribbon-group={groupIndex++} className={"sheet-ribbon-group" + extra} role="group" aria-label={name}>
|
| 843 |
+
<div className="sheet-ribbon-group-controls">{readOnly && name === "Font"
|
| 844 |
+
? <fieldset disabled style={{ display: "contents" }}>{body}</fieldset> : body}</div>
|
| 845 |
<span className="sheet-ribbon-group-name">{name}</span>
|
| 846 |
</div>
|
| 847 |
);
|
|
|
|
| 885 |
role={role}
|
| 886 |
aria-checked={role === "menuitem" ? undefined : on}
|
| 887 |
className={"sheet-ribbon-item" + (on ? " is-on" : "")}
|
| 888 |
+
data-kt={kt}
|
| 889 |
+
disabled={disabled || (readOnly && ribbonCommandWrites(open, label))}
|
| 890 |
onMouseDown={(e) => e.preventDefault()}
|
| 891 |
onClick={onClick}
|
| 892 |
>
|
|
|
|
| 914 |
const pdf={...printSettings,from:pageFrom.trim()===""?undefined:Number(pageFrom),to:pageTo.trim()===""?undefined:Number(pageTo)};
|
| 915 |
if(format==="pdf") {
|
| 916 |
planSheetPdf(snapshot.book,pdf);
|
| 917 |
+
if (!readOnly) await exportContext.savePrintSettings(pdf);
|
| 918 |
snapshot.book={...snapshot.book,printSettings:pdf};
|
| 919 |
}
|
| 920 |
await runSheetExport(format,snapshot,{range:format==="csv"&&exportScope==="selection"&&selectionRange?selectionRange:undefined,pdf});
|
|
|
|
| 924 |
};
|
| 925 |
|
| 926 |
const tabContext: RibbonTabContext = {
|
| 927 |
+
style, frozen, open, anchorEl, readOnly, onApply: patch => { if (!readOnly) onApply(patch); }, apply, act,
|
| 928 |
fullscreen, toggleFullscreen,
|
| 929 |
newWindowBlocked, openNewWindow, openCellData,
|
| 930 |
openPop, closePop, control, group, word, large, stack, unavailable, item, insert,
|
web/src/sheet/SheetGrid.tsx
CHANGED
|
@@ -768,7 +768,7 @@ export interface SheetGridProps {
|
|
| 768 |
*/
|
| 769 |
onCommit: (edits: Record<string, Cell | null>, move?: MovedBlock) => void;
|
| 770 |
/** The one cell selected when this workbook and tab are adopted. */
|
| 771 |
-
openAt: { workbookId: string; tabId: string; addr: string };
|
| 772 |
onUndo: () => void;
|
| 773 |
onRedo: () => void;
|
| 774 |
onNotice: (message: string) => void;
|
|
@@ -1432,9 +1432,8 @@ export default function SheetGrid({
|
|
| 1432 |
}>());
|
| 1433 |
const borderRowLayout = useRef<{ offsets: number[]; heightAt: (index: number) => number } | null>(null);
|
| 1434 |
const spillPaintFrame = useRef<number | null>(null);
|
| 1435 |
-
//
|
| 1436 |
-
//
|
| 1437 |
-
spillPaintQueue.current.clear();
|
| 1438 |
const queueSpillPaint = useCallback((key: string, paint: () => void, border = false) => {
|
| 1439 |
(border ? borderPaintQueue : spillPaintQueue).current.set(key, paint);
|
| 1440 |
if (spillPaintFrame.current !== null) return;
|
|
@@ -1880,6 +1879,14 @@ export default function SheetGrid({
|
|
| 1880 |
borderPaintQueue.current.clear();
|
| 1881 |
borderPaintViewports.current = new WeakMap();
|
| 1882 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1883 |
/** Imported merged ranges reserve their cells even though the client does not merge-paint them. */
|
| 1884 |
const mergedSpillRanges = useMemo(() => {
|
| 1885 |
const raw = tab.excel?.mergedCells;
|
|
@@ -2022,15 +2029,15 @@ export default function SheetGrid({
|
|
| 2022 |
// cell's editor: `onCellActivated` opens it for an EXISTING formula, and `onKeyDown`'s
|
| 2023 |
// typed-character branch opens it the moment a fresh "=" starts one. glide's own overlay
|
| 2024 |
// would otherwise sit on top of the dropdown/ScreenTip a person may be typing INTO.
|
| 2025 |
-
allowOverlay: !viewChromeRefusal(cell) && cell?.kind !== "bound"
|
| 2026 |
&& cell?.kind !== "formula" && !validationOf(cell),
|
| 2027 |
-
readonly: !!viewChromeRefusal(cell) || cell?.kind === "bound" || validationOf(cell) !== null,
|
| 2028 |
};
|
| 2029 |
},
|
| 2030 |
// `cells` is the whole dependency: a new workbook object gives a new `cells`, which is what
|
| 2031 |
// makes glide repaint. Narrowing this to `tab.id` is the stale-closure bug.
|
| 2032 |
// Filter toggles must also invalidate Glide's cell paint, even before rows are hidden.
|
| 2033 |
-
[addrAt, cells, sheetFilter],
|
| 2034 |
);
|
| 2035 |
|
| 2036 |
/**
|
|
@@ -2052,6 +2059,33 @@ export default function SheetGrid({
|
|
| 2052 |
[fromBand, getCellContent, bandRepaint],
|
| 2053 |
);
|
| 2054 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2055 |
const selected = useMemo(() => {
|
| 2056 |
const cur = selection?.current?.cell;
|
| 2057 |
if (!cur) return null;
|
|
@@ -2159,6 +2193,9 @@ export default function SheetGrid({
|
|
| 2159 |
};
|
| 2160 |
selectionRef.current = accepted;
|
| 2161 |
setSelection(accepted);
|
|
|
|
|
|
|
|
|
|
| 2162 |
// ⭐⭐ W54-T28 / R9(iv): "the run resets when the selection is moved by anything other than
|
| 2163 |
// Tab", said in the one place every move arrives at. The commit arm raises the flag for its
|
| 2164 |
// own move and this consumes it, so a Tab keeps the run and everything else ends it.
|
|
@@ -2475,6 +2512,7 @@ export default function SheetGrid({
|
|
| 2475 |
|
| 2476 |
const commitWithRecalc = useCallback((edits: Record<string, Cell | null>, move?: MovedBlock,
|
| 2477 |
landed?: SheetTab) => {
|
|
|
|
| 2478 |
const entries = Object.entries(edits);
|
| 2479 |
const reserved = entries.some(([addr, value]) => value && isViewReserved(addr));
|
| 2480 |
if (reserved) { onNotice("Resize or remove this view before editing its reserved cells."); return; }
|
|
@@ -2509,7 +2547,7 @@ export default function SheetGrid({
|
|
| 2509 |
onCommit(calculated, move && Object.keys(document).length > 0
|
| 2510 |
? { ...move, pasteTab: document } : move);
|
| 2511 |
}
|
| 2512 |
-
}, [commitViewRecord, isViewReserved, onCommit, onNotice, onTabView, tab, workbook]);
|
| 2513 |
|
| 2514 |
/** ONE typed commit. `commitTyped` picks literal or formula and drops a binding on its own. */
|
| 2515 |
const onCellEdited = useCallback((item: Item, value: EditableGridCell) => {
|
|
@@ -2571,6 +2609,7 @@ export default function SheetGrid({
|
|
| 2571 |
const openFormulaEditor = useCallback((
|
| 2572 |
addr: string, draft: string, caret: number, viewCell: readonly [number, number], inBand: boolean,
|
| 2573 |
) => {
|
|
|
|
| 2574 |
const anchor = splitAddress(addr);
|
| 2575 |
if (!anchor) return;
|
| 2576 |
// A formula edit is the ONE editor at a time this component ever shows, same as every other
|
|
@@ -2582,7 +2621,7 @@ export default function SheetGrid({
|
|
| 2582 |
addr, inBand, viewCell, draft, caret, dropdownIndex: 0, dismissed: false, mode: "enter", caretOnly: false,
|
| 2583 |
anchor, insertStart: null, pointCell: null, pointBand: null, rangeAnchor: null,
|
| 2584 |
});
|
| 2585 |
-
}, []);
|
| 2586 |
|
| 2587 |
/**
|
| 2588 |
* ⭐⭐ W54-T21 / INSTRUCTION 18 — ESCAPE CANCELS THE EDIT AND THE CELL GOES BACK TO WHAT IT HELD.
|
|
@@ -3617,6 +3656,7 @@ export default function SheetGrid({
|
|
| 3617 |
* ⚠ R10 IS UNTOUCHED: a format presents the stored value and never recomputes it.
|
| 3618 |
*/
|
| 3619 |
const applyStyle = useCallback((patch: CellStylePatch) => {
|
|
|
|
| 3620 |
const addrs = selectedAddrs();
|
| 3621 |
if (addrs.length === 0) {
|
| 3622 |
onNotice("Select a cell first, then choose a format for it.");
|
|
@@ -3625,7 +3665,7 @@ export default function SheetGrid({
|
|
| 3625 |
const out = styleCells(tab, addrs, patch);
|
| 3626 |
if (Object.keys(out.edits).length === 0) return;
|
| 3627 |
onCommit(out.edits);
|
| 3628 |
-
}, [onCommit, onNotice, selectedAddrs, tab]);
|
| 3629 |
|
| 3630 |
/**
|
| 3631 |
* ⭐⭐ S67-T11 (QI16, J16, C2) — EXCEL'S DRAW BORDER PENS. Lane B's Borders menu raises
|
|
@@ -4068,11 +4108,9 @@ export default function SheetGrid({
|
|
| 4068 |
* from pulling the reader back after they have already moved.
|
| 4069 |
*/
|
| 4070 |
useEffect(() => {
|
| 4071 |
-
const key = `${workbook.id}:${tab.id}`;
|
| 4072 |
if (openAt.workbookId !== workbook.id || openAt.tabId !== tab.id
|
| 4073 |
|| openedSelectionRef.current === key) return;
|
| 4074 |
-
openedSelectionRef.current = key;
|
| 4075 |
-
|
| 4076 |
const requested = splitAddress(openAt.addr) ?? { col: 1, row: 1 };
|
| 4077 |
let col = viewIndexOf(visCols, requested.col - 1);
|
| 4078 |
let row = viewRowOf(requested.row - 1);
|
|
@@ -4080,8 +4118,21 @@ export default function SheetGrid({
|
|
| 4080 |
col = viewIndexOf(visCols, 0);
|
| 4081 |
row = viewRowOf(0);
|
| 4082 |
}
|
| 4083 |
-
|
| 4084 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4085 |
|
| 4086 |
/**
|
| 4087 |
* W55-T05 / R4: KeyTips consumes its capture-phase key while focus is on the ribbon, then
|
|
@@ -4553,8 +4604,9 @@ export default function SheetGrid({
|
|
| 4553 |
* through the same builder.
|
| 4554 |
*/
|
| 4555 |
const copySelection = useCallback((cut: boolean) => {
|
|
|
|
| 4556 |
runCopySelection(cut, viewRange, heldFor, copiedRef, setCopyMarquee, clearSelection, onNotice);
|
| 4557 |
-
}, [clearSelection, heldFor, onNotice, viewRange]);
|
| 4558 |
|
| 4559 |
/**
|
| 4560 |
* PASTE. Native paste supplies its event payload; the ribbon reads the browser clipboard.
|
|
@@ -5262,6 +5314,8 @@ export default function SheetGrid({
|
|
| 5262 |
// W51-T18 turned the other one into a door.
|
| 5263 |
// ═══════════════════════════════════════════════════════════════════════════════════════════
|
| 5264 |
const onRibbonAction = useCallback((action: RibbonAction) => {
|
|
|
|
|
|
|
| 5265 |
if (action.kind === "paste" && action.arg === "special") { openPasteSpecial(); return; }
|
| 5266 |
if (action.kind === "paste" && (action.arg === "transpose" || action.arg === "link")) {
|
| 5267 |
pasteFromClipboard(MENU_PASTE_OPTIONS[action.arg === "transpose" ? "paste-transpose" : "paste-link"]);
|
|
@@ -5411,7 +5465,7 @@ export default function SheetGrid({
|
|
| 5411 |
clearSelectionWith, copyChartImageToClipboard, copySelection,
|
| 5412 |
fillSelection, frozenCols, frozenRows, hideBand, onGrow, onNotice, onOpenImport, onRefresh,
|
| 5413 |
openPasteSpecial, pasteFromClipboard, rowHeight, rules, saveRules, selectedAddrs, selectedChartId, selectionRange, stepIndent,
|
| 5414 |
-
structure, tab, toggleFormatPainter, unhideAll]);
|
| 5415 |
|
| 5416 |
// ═══════════════════════════════════════════════════════════════════════════════════════════
|
| 5417 |
// ⭐⭐ W54-T19 (INSTRUCTION 13) — THE HALF OF THE DEFECT THAT NEVER REACHES glide AT ALL.
|
|
@@ -5520,6 +5574,14 @@ export default function SheetGrid({
|
|
| 5520 |
|
| 5521 |
const onKeyDown = useCallback(
|
| 5522 |
(event: GridKeyEventArgs) => {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5523 |
// glide invokes this before applying its own key-driven selection. Keep that callback tied
|
| 5524 |
// to the reader's key for this event only; a later data-identity reconciliation has no key.
|
| 5525 |
keyboardSelectingRef.current = true;
|
|
@@ -5943,7 +6005,7 @@ export default function SheetGrid({
|
|
| 5943 |
onSaveNow, onUndo, openFormulaEditor, openSheetFilter, options,
|
| 5944 |
openNumberFormat, openPasteSpecial, pasteShortcutContext, realCol, realRow, selectDocumentAxis, selectDocumentRegion, selection,
|
| 5945 |
structureForSelection, switchTab, tab,
|
| 5946 |
-
|
| 5947 |
);
|
| 5948 |
|
| 5949 |
// ══════════════════════════════════════════════════════════════════════════════════════════
|
|
@@ -6409,29 +6471,8 @@ export default function SheetGrid({
|
|
| 6409 |
}, true);
|
| 6410 |
}
|
| 6411 |
|
| 6412 |
-
//
|
| 6413 |
-
//
|
| 6414 |
-
//
|
| 6415 |
-
// `drawSparkline` is handed the cell, so this is the first statement that can possibly call
|
| 6416 |
-
// it: `cell` has to be read first. It answers `false` today and NOTHING changes; when lane B
|
| 6417 |
-
// fills it in, a `true` means that cell's whole paint belonged to the sparkline.
|
| 6418 |
-
//
|
| 6419 |
-
// ⛔ THE TRUE BRANCH IS A BARE `return;`, AND THAT IS DELIBERATE TWICE OVER. glide 6.0.3
|
| 6420 |
-
// ignores a `DrawCellCallback`'s return (see D-642 above), so `return;` is the only way to
|
| 6421 |
-
// say "done"; and the gates COUNT the other calls rather than merely looking for them --
|
| 6422 |
-
// `verify_api.py` pins the default renderer at EXACTLY two call sites and `verify_grid_ux.py`
|
| 6423 |
-
// pins the marquee closure at exactly three, on the RAW file, so adding either call here
|
| 6424 |
-
// would red a leg belonging to a different ticket for a line that changed no pixel. ⚠ That
|
| 6425 |
-
// also means naming those calls in prose HERE, with their parentheses and semicolon, moves a
|
| 6426 |
-
// count: this note says them in words on purpose.
|
| 6427 |
-
//
|
| 6428 |
-
// ⚠ LANE B: THIS RETURNS BEFORE `ruleStyleAt` AND BEFORE ALL FOUR OVERLAY CLOSURES
|
| 6429 |
-
// (`paintRefBorder`, `paintMarquee`, `paintShimmer`, `paintMark`). A sparkline cell therefore
|
| 6430 |
-
// wears NO conditional-format rule, NO copy marquee, NO reference border and NO corner mark
|
| 6431 |
-
// unless you decide it should and call them. That decision is yours; the seam does not make
|
| 6432 |
-
// it for you.
|
| 6433 |
-
// ═══════════════════════════════════════════════════════════════════════════════
|
| 6434 |
-
if (cell && drawSparkline(ctx, rect, cell, cells)) { paintFilterButton(); return; }
|
| 6435 |
|
| 6436 |
// ═══════════════════════════════════════════════════════════════════════════════
|
| 6437 |
// ⭐⭐ W51-T18 — THE RULE IS ASKED BEFORE THE EARLY RETURN, AND THAT IS THE HALF
|
|
@@ -6744,6 +6785,7 @@ export default function SheetGrid({
|
|
| 6744 |
// Give even an unstyled refusal the shared text routine and the cell's own spacing.
|
| 6745 |
const style = bindingRefusal(cell) ? { ...baseStyle, color: "--lp-red-deep" } : baseStyle;
|
| 6746 |
if ((!stylePaints(style) && !ruleStyle) || !style) {
|
|
|
|
| 6747 |
// ⭐ `drawContent()` IS the default renderer, and it must run BEFORE the mark so
|
| 6748 |
// the mark sits on top of the value rather than under it.
|
| 6749 |
if (!paintTextSpill()) drawContent();
|
|
@@ -6789,6 +6831,8 @@ export default function SheetGrid({
|
|
| 6789 |
// be covered only inside the text band; unrelated segments and every outer edge survive.
|
| 6790 |
paintCellBorders(ctx, rect, style.border);
|
| 6791 |
|
|
|
|
|
|
|
| 6792 |
// 3. THE TEXT. Spill owns its expanded, separator-reaching clip; an ordinary run retains the
|
| 6793 |
// old inset clip. Clipping before asking the spill would also clip away its line mask.
|
| 6794 |
if (!paintTextSpill()) {
|
|
@@ -6956,7 +7000,8 @@ export default function SheetGrid({
|
|
| 6956 |
if (!selectionProjectsHeader(selection, "row", row, headerProjectionBounds)) return [];
|
| 6957 |
const grid = row < 0 ? bandGridRef.current : gridRef.current;
|
| 6958 |
const bounds = grid?.getBounds(-1, row < 0 ? row + bandRows : row);
|
| 6959 |
-
if (!bounds || bounds.
|
|
|
|
| 6960 |
return [{ row, label: realRow(row) + 1, left: bounds.x - origin.x,
|
| 6961 |
top: bounds.y - origin.y, width: bounds.width, height: bounds.height }];
|
| 6962 |
});
|
|
@@ -7057,6 +7102,7 @@ export default function SheetGrid({
|
|
| 7057 |
<Ribbon
|
| 7058 |
style={selected?.cell?.style ?? null}
|
| 7059 |
disabled={busy}
|
|
|
|
| 7060 |
// ⭐ W51-T34: the readback covers BOTH axes now, because the item it reads back to
|
| 7061 |
// opens the panes panel rather than toggling one column.
|
| 7062 |
frozen={frozenCols > 0 || bandRows > 0}
|
|
@@ -7092,6 +7138,7 @@ export default function SheetGrid({
|
|
| 7092 |
const typing = target instanceof Element
|
| 7093 |
&& !!target.closest('input, textarea, [contenteditable="true"]');
|
| 7094 |
if (matchShortcutInGrid(event, pasteShortcutContext(target)) === "paste-special") {
|
|
|
|
| 7095 |
event.preventDefault();
|
| 7096 |
event.stopPropagation();
|
| 7097 |
openPasteSpecial();
|
|
@@ -7102,6 +7149,7 @@ export default function SheetGrid({
|
|
| 7102 |
&& (event.key === "ArrowRight" || event.key === "ArrowLeft")) {
|
| 7103 |
event.preventDefault();
|
| 7104 |
event.stopPropagation();
|
|
|
|
| 7105 |
if (event.key === "ArrowRight") groupRows();
|
| 7106 |
else ungroupRows();
|
| 7107 |
return;
|
|
@@ -7115,6 +7163,7 @@ export default function SheetGrid({
|
|
| 7115 |
&& (copyKey === "c" || copyKey === "x") && !!held?.current) {
|
| 7116 |
event.preventDefault();
|
| 7117 |
event.stopPropagation();
|
|
|
|
| 7118 |
copySelection(copyKey === "x");
|
| 7119 |
return;
|
| 7120 |
}
|
|
@@ -7314,6 +7363,7 @@ export default function SheetGrid({
|
|
| 7314 |
onKeyDown={onKeyDown}
|
| 7315 |
onPaste={(target, values) => onPaste(fromBand(target), values)}
|
| 7316 |
onCellActivated={(item: Item) => {
|
|
|
|
| 7317 |
const shifted = fromBand(item);
|
| 7318 |
const addr = addrAt(shifted[0], shifted[1]);
|
| 7319 |
const cell = cellAt(tab, addr);
|
|
@@ -7466,6 +7516,7 @@ export default function SheetGrid({
|
|
| 7466 |
// either any more (`getCellContent` above), so activating it opens THIS component's own
|
| 7467 |
// floating editor instead -- same door, same gesture, a different cell kind.
|
| 7468 |
onCellActivated={(item: Item) => {
|
|
|
|
| 7469 |
const addr = addrAt(item[0], item[1]);
|
| 7470 |
const cell = cellAt(tab, addr);
|
| 7471 |
const chrome = viewChromeRefusal(cell);
|
|
@@ -8262,7 +8313,7 @@ export default function SheetGrid({
|
|
| 8262 |
// ⭐ R5 (W52-T09): `editIntent`'s "edit" vs. "convert" distinction is retired, and this
|
| 8263 |
// was always `true` regardless of it - the Edit button opens the binding panel for
|
| 8264 |
// every kind of cell, bound or not.
|
| 8265 |
-
canEdit
|
| 8266 |
busy={busy}
|
| 8267 |
onEdit={() => onEdit(selected.addr, selected.cell)}
|
| 8268 |
onViewRows={() => onViewRows(selected.addr, selected.cell)}
|
|
|
|
| 768 |
*/
|
| 769 |
onCommit: (edits: Record<string, Cell | null>, move?: MovedBlock) => void;
|
| 770 |
/** The one cell selected when this workbook and tab are adopted. */
|
| 771 |
+
openAt: { workbookId: string; tabId: string; addr: string; request?: number };
|
| 772 |
onUndo: () => void;
|
| 773 |
onRedo: () => void;
|
| 774 |
onNotice: (message: string) => void;
|
|
|
|
| 1432 |
}>());
|
| 1433 |
const borderRowLayout = useRef<{ offsets: number[]; heightAt: (index: number) => number } | null>(null);
|
| 1434 |
const spillPaintFrame = useRef<number | null>(null);
|
| 1435 |
+
// Selection renders can precede the deferred text frame while Glide only blits its cells.
|
| 1436 |
+
// Document/geometry changes invalidate queued text below; selection alone keeps that run.
|
|
|
|
| 1437 |
const queueSpillPaint = useCallback((key: string, paint: () => void, border = false) => {
|
| 1438 |
(border ? borderPaintQueue : spillPaintQueue).current.set(key, paint);
|
| 1439 |
if (spillPaintFrame.current !== null) return;
|
|
|
|
| 1879 |
borderPaintQueue.current.clear();
|
| 1880 |
borderPaintViewports.current = new WeakMap();
|
| 1881 |
}
|
| 1882 |
+
const spillPaintRules = onRules ? tab.rules : localRules;
|
| 1883 |
+
const spillPaintDocument = useMemo(() => ({}),
|
| 1884 |
+
[borderPaintDocument, tab, workbook.sheets, spillPaintRules, sheetFilter]);
|
| 1885 |
+
const spillPaintDocumentRef = useRef(spillPaintDocument);
|
| 1886 |
+
if (spillPaintDocumentRef.current !== spillPaintDocument) {
|
| 1887 |
+
spillPaintDocumentRef.current = spillPaintDocument;
|
| 1888 |
+
spillPaintQueue.current.clear();
|
| 1889 |
+
}
|
| 1890 |
/** Imported merged ranges reserve their cells even though the client does not merge-paint them. */
|
| 1891 |
const mergedSpillRanges = useMemo(() => {
|
| 1892 |
const raw = tab.excel?.mergedCells;
|
|
|
|
| 2029 |
// cell's editor: `onCellActivated` opens it for an EXISTING formula, and `onKeyDown`'s
|
| 2030 |
// typed-character branch opens it the moment a fresh "=" starts one. glide's own overlay
|
| 2031 |
// would otherwise sit on top of the dropdown/ScreenTip a person may be typing INTO.
|
| 2032 |
+
allowOverlay: !readOnly && !viewChromeRefusal(cell) && cell?.kind !== "bound"
|
| 2033 |
&& cell?.kind !== "formula" && !validationOf(cell),
|
| 2034 |
+
readonly: readOnly || !!viewChromeRefusal(cell) || cell?.kind === "bound" || validationOf(cell) !== null,
|
| 2035 |
};
|
| 2036 |
},
|
| 2037 |
// `cells` is the whole dependency: a new workbook object gives a new `cells`, which is what
|
| 2038 |
// makes glide repaint. Narrowing this to `tab.id` is the stale-closure bug.
|
| 2039 |
// Filter toggles must also invalidate Glide's cell paint, even before rows are hidden.
|
| 2040 |
+
[addrAt, cells, sheetFilter, readOnly],
|
| 2041 |
);
|
| 2042 |
|
| 2043 |
/**
|
|
|
|
| 2059 |
[fromBand, getCellContent, bandRepaint],
|
| 2060 |
);
|
| 2061 |
|
| 2062 |
+
const hasCellAnchor = anchor !== null;
|
| 2063 |
+
useEffect(() => {
|
| 2064 |
+
if (!hasCellAnchor || !wrapRef.current) return;
|
| 2065 |
+
let frame = 0;
|
| 2066 |
+
const project = () => {
|
| 2067 |
+
cancelAnimationFrame(frame);
|
| 2068 |
+
frame = requestAnimationFrame(() => {
|
| 2069 |
+
frame = requestAnimationFrame(() => {
|
| 2070 |
+
const item = selectionRef.current?.current?.cell;
|
| 2071 |
+
if (!item) return;
|
| 2072 |
+
const bounds = item[1] < 0
|
| 2073 |
+
? bandGridRef.current?.getBounds(item[0], item[1] + bandRows)
|
| 2074 |
+
: gridRef.current?.getBounds(item[0], item[1]);
|
| 2075 |
+
if (!bounds || ![bounds.x, bounds.y, bounds.width, bounds.height].every(Number.isFinite)) return;
|
| 2076 |
+
setAnchor(prior => !prior || (prior.x === bounds.x && prior.y === bounds.y
|
| 2077 |
+
&& prior.width === bounds.width && prior.height === bounds.height) ? prior : bounds);
|
| 2078 |
+
});
|
| 2079 |
+
});
|
| 2080 |
+
};
|
| 2081 |
+
// A cell click can collapse the navigation rail after Glide emitted its old viewport rect.
|
| 2082 |
+
// Reproject the selected cell when that layout settles, including the frozen grid.
|
| 2083 |
+
const observer = new ResizeObserver(project);
|
| 2084 |
+
observer.observe(wrapRef.current);
|
| 2085 |
+
project();
|
| 2086 |
+
return () => { observer.disconnect(); cancelAnimationFrame(frame); };
|
| 2087 |
+
}, [hasCellAnchor, bandRows, zoom]);
|
| 2088 |
+
|
| 2089 |
const selected = useMemo(() => {
|
| 2090 |
const cur = selection?.current?.cell;
|
| 2091 |
if (!cur) return null;
|
|
|
|
| 2193 |
};
|
| 2194 |
selectionRef.current = accepted;
|
| 2195 |
setSelection(accepted);
|
| 2196 |
+
// An explicit opening/name-box move also owns the next gesture-less reconciliation.
|
| 2197 |
+
// The first real click or key still wins and consumes this same one-shot handoff.
|
| 2198 |
+
if (selectionIntent === "app") replacementSelectionRef.current = accepted;
|
| 2199 |
// ⭐⭐ W54-T28 / R9(iv): "the run resets when the selection is moved by anything other than
|
| 2200 |
// Tab", said in the one place every move arrives at. The commit arm raises the flag for its
|
| 2201 |
// own move and this consumes it, so a Tab keeps the run and everything else ends it.
|
|
|
|
| 2512 |
|
| 2513 |
const commitWithRecalc = useCallback((edits: Record<string, Cell | null>, move?: MovedBlock,
|
| 2514 |
landed?: SheetTab) => {
|
| 2515 |
+
if (readOnly) return;
|
| 2516 |
const entries = Object.entries(edits);
|
| 2517 |
const reserved = entries.some(([addr, value]) => value && isViewReserved(addr));
|
| 2518 |
if (reserved) { onNotice("Resize or remove this view before editing its reserved cells."); return; }
|
|
|
|
| 2547 |
onCommit(calculated, move && Object.keys(document).length > 0
|
| 2548 |
? { ...move, pasteTab: document } : move);
|
| 2549 |
}
|
| 2550 |
+
}, [commitViewRecord, isViewReserved, onCommit, onNotice, onTabView, tab, workbook, readOnly]);
|
| 2551 |
|
| 2552 |
/** ONE typed commit. `commitTyped` picks literal or formula and drops a binding on its own. */
|
| 2553 |
const onCellEdited = useCallback((item: Item, value: EditableGridCell) => {
|
|
|
|
| 2609 |
const openFormulaEditor = useCallback((
|
| 2610 |
addr: string, draft: string, caret: number, viewCell: readonly [number, number], inBand: boolean,
|
| 2611 |
) => {
|
| 2612 |
+
if (readOnly) return;
|
| 2613 |
const anchor = splitAddress(addr);
|
| 2614 |
if (!anchor) return;
|
| 2615 |
// A formula edit is the ONE editor at a time this component ever shows, same as every other
|
|
|
|
| 2621 |
addr, inBand, viewCell, draft, caret, dropdownIndex: 0, dismissed: false, mode: "enter", caretOnly: false,
|
| 2622 |
anchor, insertStart: null, pointCell: null, pointBand: null, rangeAnchor: null,
|
| 2623 |
});
|
| 2624 |
+
}, [readOnly]);
|
| 2625 |
|
| 2626 |
/**
|
| 2627 |
* ⭐⭐ W54-T21 / INSTRUCTION 18 — ESCAPE CANCELS THE EDIT AND THE CELL GOES BACK TO WHAT IT HELD.
|
|
|
|
| 3656 |
* ⚠ R10 IS UNTOUCHED: a format presents the stored value and never recomputes it.
|
| 3657 |
*/
|
| 3658 |
const applyStyle = useCallback((patch: CellStylePatch) => {
|
| 3659 |
+
if (readOnly) return;
|
| 3660 |
const addrs = selectedAddrs();
|
| 3661 |
if (addrs.length === 0) {
|
| 3662 |
onNotice("Select a cell first, then choose a format for it.");
|
|
|
|
| 3665 |
const out = styleCells(tab, addrs, patch);
|
| 3666 |
if (Object.keys(out.edits).length === 0) return;
|
| 3667 |
onCommit(out.edits);
|
| 3668 |
+
}, [onCommit, onNotice, selectedAddrs, tab, readOnly]);
|
| 3669 |
|
| 3670 |
/**
|
| 3671 |
* ⭐⭐ S67-T11 (QI16, J16, C2) — EXCEL'S DRAW BORDER PENS. Lane B's Borders menu raises
|
|
|
|
| 4108 |
* from pulling the reader back after they have already moved.
|
| 4109 |
*/
|
| 4110 |
useEffect(() => {
|
| 4111 |
+
const key = `${workbook.id}:${tab.id}:${openAt.addr}:${openAt.request ?? 0}`;
|
| 4112 |
if (openAt.workbookId !== workbook.id || openAt.tabId !== tab.id
|
| 4113 |
|| openedSelectionRef.current === key) return;
|
|
|
|
|
|
|
| 4114 |
const requested = splitAddress(openAt.addr) ?? { col: 1, row: 1 };
|
| 4115 |
let col = viewIndexOf(visCols, requested.col - 1);
|
| 4116 |
let row = viewRowOf(requested.row - 1);
|
|
|
|
| 4118 |
col = viewIndexOf(visCols, 0);
|
| 4119 |
row = viewRowOf(0);
|
| 4120 |
}
|
| 4121 |
+
// Glide's first viewport measurement follows mount. Reveal after that measurement so a
|
| 4122 |
+
// deep link and a repeated name-box request use the same settled geometry.
|
| 4123 |
+
let revealFrame: number | null = null;
|
| 4124 |
+
const frame = window.requestAnimationFrame(() => {
|
| 4125 |
+
revealFrame = window.requestAnimationFrame(() => {
|
| 4126 |
+
openedSelectionRef.current = key;
|
| 4127 |
+
applySelection({ col0: col, row0: row, col1: col, row1: row }, [col, row], true, false);
|
| 4128 |
+
});
|
| 4129 |
+
});
|
| 4130 |
+
return () => {
|
| 4131 |
+
window.cancelAnimationFrame(frame);
|
| 4132 |
+
if (revealFrame !== null) window.cancelAnimationFrame(revealFrame);
|
| 4133 |
+
};
|
| 4134 |
+
}, [applySelection, openAt.workbookId, openAt.tabId, openAt.addr, openAt.request,
|
| 4135 |
+
realCol, realRow, tab.id, viewRowOf, visCols, workbook.id]);
|
| 4136 |
|
| 4137 |
/**
|
| 4138 |
* W55-T05 / R4: KeyTips consumes its capture-phase key while focus is on the ribbon, then
|
|
|
|
| 4604 |
* through the same builder.
|
| 4605 |
*/
|
| 4606 |
const copySelection = useCallback((cut: boolean) => {
|
| 4607 |
+
if (readOnly && cut) return;
|
| 4608 |
runCopySelection(cut, viewRange, heldFor, copiedRef, setCopyMarquee, clearSelection, onNotice);
|
| 4609 |
+
}, [clearSelection, heldFor, onNotice, viewRange, readOnly]);
|
| 4610 |
|
| 4611 |
/**
|
| 4612 |
* PASTE. Native paste supplies its event payload; the ribbon reads the browser clipboard.
|
|
|
|
| 5314 |
// W51-T18 turned the other one into a door.
|
| 5315 |
// ═══════════════════════════════════════════════════════════════════════════════════════════
|
| 5316 |
const onRibbonAction = useCallback((action: RibbonAction) => {
|
| 5317 |
+
if (readOnly && (!["copy", "find", "go-to"].includes(action.kind)
|
| 5318 |
+
|| (action.kind === "find" && action.arg === "replace"))) return;
|
| 5319 |
if (action.kind === "paste" && action.arg === "special") { openPasteSpecial(); return; }
|
| 5320 |
if (action.kind === "paste" && (action.arg === "transpose" || action.arg === "link")) {
|
| 5321 |
pasteFromClipboard(MENU_PASTE_OPTIONS[action.arg === "transpose" ? "paste-transpose" : "paste-link"]);
|
|
|
|
| 5465 |
clearSelectionWith, copyChartImageToClipboard, copySelection,
|
| 5466 |
fillSelection, frozenCols, frozenRows, hideBand, onGrow, onNotice, onOpenImport, onRefresh,
|
| 5467 |
openPasteSpecial, pasteFromClipboard, rowHeight, rules, saveRules, selectedAddrs, selectedChartId, selectionRange, stepIndent,
|
| 5468 |
+
structure, tab, toggleFormatPainter, unhideAll, readOnly]);
|
| 5469 |
|
| 5470 |
// ═══════════════════════════════════════════════════════════════════════════════════════════
|
| 5471 |
// ⭐⭐ W54-T19 (INSTRUCTION 13) — THE HALF OF THE DEFECT THAT NEVER REACHES glide AT ALL.
|
|
|
|
| 5574 |
|
| 5575 |
const onKeyDown = useCallback(
|
| 5576 |
(event: GridKeyEventArgs) => {
|
| 5577 |
+
const viewerHit = readOnly ? matchShortcut(event) : null;
|
| 5578 |
+
if (readOnly && ((viewerHit !== null && !["jump-edge", "extend-edge", "extend-cell",
|
| 5579 |
+
"go-home", "go-end", "page-up", "page-down", "prev-sheet", "next-sheet", "select-all",
|
| 5580 |
+
"select-column", "select-row", "select-region", "find", "show-shortcuts"].includes(viewerHit))
|
| 5581 |
+
|| (!event.ctrlKey && !event.metaKey && !event.altKey && (event.key.length === 1 || event.key === "F2")))) {
|
| 5582 |
+
event.cancel(); event.preventDefault(); event.stopPropagation();
|
| 5583 |
+
return;
|
| 5584 |
+
}
|
| 5585 |
// glide invokes this before applying its own key-driven selection. Keep that callback tied
|
| 5586 |
// to the reader's key for this event only; a later data-identity reconciliation has no key.
|
| 5587 |
keyboardSelectingRef.current = true;
|
|
|
|
| 6005 |
onSaveNow, onUndo, openFormulaEditor, openSheetFilter, options,
|
| 6006 |
openNumberFormat, openPasteSpecial, pasteShortcutContext, realCol, realRow, selectDocumentAxis, selectDocumentRegion, selection,
|
| 6007 |
structureForSelection, switchTab, tab,
|
| 6008 |
+
viewRange, viewRowOf, viewShadows, visCols, visRows, readOnly],
|
| 6009 |
);
|
| 6010 |
|
| 6011 |
// ══════════════════════════════════════════════════════════════════════════════════════════
|
|
|
|
| 6471 |
}, true);
|
| 6472 |
}
|
| 6473 |
|
| 6474 |
+
// Sparkline marks are painted in each value branch below, after the resolved fill and
|
| 6475 |
+
// borders. Text and selection overlays still finish the cell, including no-text plots.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6476 |
|
| 6477 |
// ═══════════════════════════════════════════════════════════════════════════════
|
| 6478 |
// ⭐⭐ W51-T18 — THE RULE IS ASKED BEFORE THE EARLY RETURN, AND THAT IS THE HALF
|
|
|
|
| 6785 |
// Give even an unstyled refusal the shared text routine and the cell's own spacing.
|
| 6786 |
const style = bindingRefusal(cell) ? { ...baseStyle, color: "--lp-red-deep" } : baseStyle;
|
| 6787 |
if ((!stylePaints(style) && !ruleStyle) || !style) {
|
| 6788 |
+
if (cell) drawSparkline(ctx, rect, cell, cells, zoom);
|
| 6789 |
// ⭐ `drawContent()` IS the default renderer, and it must run BEFORE the mark so
|
| 6790 |
// the mark sits on top of the value rather than under it.
|
| 6791 |
if (!paintTextSpill()) drawContent();
|
|
|
|
| 6831 |
// be covered only inside the text band; unrelated segments and every outer edge survive.
|
| 6832 |
paintCellBorders(ctx, rect, style.border);
|
| 6833 |
|
| 6834 |
+
if (cell) drawSparkline(ctx, rect, cell, cells, zoom);
|
| 6835 |
+
|
| 6836 |
// 3. THE TEXT. Spill owns its expanded, separator-reaching clip; an ordinary run retains the
|
| 6837 |
// old inset clip. Clipping before asking the spill would also clip away its line mask.
|
| 6838 |
if (!paintTextSpill()) {
|
|
|
|
| 7000 |
if (!selectionProjectsHeader(selection, "row", row, headerProjectionBounds)) return [];
|
| 7001 |
const grid = row < 0 ? bandGridRef.current : gridRef.current;
|
| 7002 |
const bounds = grid?.getBounds(-1, row < 0 ? row + bandRows : row);
|
| 7003 |
+
if (!bounds || ![bounds.x, bounds.y, bounds.width, bounds.height].every(Number.isFinite)
|
| 7004 |
+
|| bounds.y + bounds.height <= origin.y || bounds.y >= origin.bottom) return [];
|
| 7005 |
return [{ row, label: realRow(row) + 1, left: bounds.x - origin.x,
|
| 7006 |
top: bounds.y - origin.y, width: bounds.width, height: bounds.height }];
|
| 7007 |
});
|
|
|
|
| 7102 |
<Ribbon
|
| 7103 |
style={selected?.cell?.style ?? null}
|
| 7104 |
disabled={busy}
|
| 7105 |
+
readOnly={readOnly}
|
| 7106 |
// ⭐ W51-T34: the readback covers BOTH axes now, because the item it reads back to
|
| 7107 |
// opens the panes panel rather than toggling one column.
|
| 7108 |
frozen={frozenCols > 0 || bandRows > 0}
|
|
|
|
| 7138 |
const typing = target instanceof Element
|
| 7139 |
&& !!target.closest('input, textarea, [contenteditable="true"]');
|
| 7140 |
if (matchShortcutInGrid(event, pasteShortcutContext(target)) === "paste-special") {
|
| 7141 |
+
if (readOnly) { event.preventDefault(); event.stopPropagation(); return; }
|
| 7142 |
event.preventDefault();
|
| 7143 |
event.stopPropagation();
|
| 7144 |
openPasteSpecial();
|
|
|
|
| 7149 |
&& (event.key === "ArrowRight" || event.key === "ArrowLeft")) {
|
| 7150 |
event.preventDefault();
|
| 7151 |
event.stopPropagation();
|
| 7152 |
+
if (readOnly) return;
|
| 7153 |
if (event.key === "ArrowRight") groupRows();
|
| 7154 |
else ungroupRows();
|
| 7155 |
return;
|
|
|
|
| 7163 |
&& (copyKey === "c" || copyKey === "x") && !!held?.current) {
|
| 7164 |
event.preventDefault();
|
| 7165 |
event.stopPropagation();
|
| 7166 |
+
if (readOnly && copyKey === "x") return;
|
| 7167 |
copySelection(copyKey === "x");
|
| 7168 |
return;
|
| 7169 |
}
|
|
|
|
| 7363 |
onKeyDown={onKeyDown}
|
| 7364 |
onPaste={(target, values) => onPaste(fromBand(target), values)}
|
| 7365 |
onCellActivated={(item: Item) => {
|
| 7366 |
+
if (readOnly) return;
|
| 7367 |
const shifted = fromBand(item);
|
| 7368 |
const addr = addrAt(shifted[0], shifted[1]);
|
| 7369 |
const cell = cellAt(tab, addr);
|
|
|
|
| 7516 |
// either any more (`getCellContent` above), so activating it opens THIS component's own
|
| 7517 |
// floating editor instead -- same door, same gesture, a different cell kind.
|
| 7518 |
onCellActivated={(item: Item) => {
|
| 7519 |
+
if (readOnly) return;
|
| 7520 |
const addr = addrAt(item[0], item[1]);
|
| 7521 |
const cell = cellAt(tab, addr);
|
| 7522 |
const chrome = viewChromeRefusal(cell);
|
|
|
|
| 8313 |
// ⭐ R5 (W52-T09): `editIntent`'s "edit" vs. "convert" distinction is retired, and this
|
| 8314 |
// was always `true` regardless of it - the Edit button opens the binding panel for
|
| 8315 |
// every kind of cell, bound or not.
|
| 8316 |
+
canEdit={!readOnly}
|
| 8317 |
busy={busy}
|
| 8318 |
onEdit={() => onEdit(selected.addr, selected.cell)}
|
| 8319 |
onViewRows={() => onViewRows(selected.addr, selected.cell)}
|
web/src/sheet/SheetPage.tsx
CHANGED
|
@@ -390,6 +390,7 @@ export default function SheetPage() {
|
|
| 390 |
const [lastWorkbookId] = useState<string>(() => readLastWorkbook());
|
| 391 |
const [sheetHash, setSheetHash] = useState(() => window.location.hash);
|
| 392 |
const [addressSelectionKey, setAddressSelectionKey] = useState(0);
|
|
|
|
| 393 |
const [tabId, setTabId] = useState<string>("");
|
| 394 |
const [unreadableAddressTab, setUnreadableAddressTab] = useState("");
|
| 395 |
const [pendingTab, setPendingTab] = useState<{
|
|
@@ -2018,6 +2019,7 @@ export default function SheetPage() {
|
|
| 2018 |
// ── the tab bar (wave-49 R7) ───────────────────────────────────────────────────────────────
|
| 2019 |
|
| 2020 |
const onAddTab = useCallback(() => {
|
|
|
|
| 2021 |
const base = bookRef.current;
|
| 2022 |
if (!base) return;
|
| 2023 |
const made = addTab(base);
|
|
@@ -2026,16 +2028,18 @@ export default function SheetPage() {
|
|
| 2026 |
// and must never be fetched: a lazy read of it would 404 or answer an empty tab.
|
| 2027 |
tabLoadedRef.current.add(tabKeyOf(base.id, made.id));
|
| 2028 |
setTabId(made.id);
|
| 2029 |
-
}, [commitSheets]);
|
| 2030 |
|
| 2031 |
const onMoveTab = useCallback((id: string, step: number) => {
|
|
|
|
| 2032 |
const base = bookRef.current;
|
| 2033 |
setTabMenu(null);
|
| 2034 |
if (base) commitSheets(moveTab(base, id, step));
|
| 2035 |
-
}, [commitSheets]);
|
| 2036 |
|
| 2037 |
/** Capture the whole tab, preserving the exact point inside it that the pointer grabbed. */
|
| 2038 |
const startTabDrag = useCallback((id: string, event: ReactPointerEvent<HTMLButtonElement>) => {
|
|
|
|
| 2039 |
if (event.button !== 0 || !bookRef.current || tabDragRef.current) return;
|
| 2040 |
const element = event.currentTarget;
|
| 2041 |
const rect = element.getBoundingClientRect();
|
|
@@ -2056,7 +2060,7 @@ export default function SheetPage() {
|
|
| 2056 |
targetIndex: startIndex,
|
| 2057 |
moved: false,
|
| 2058 |
};
|
| 2059 |
-
}, []);
|
| 2060 |
|
| 2061 |
/**
|
| 2062 |
* Gesture frames write only a transform and a target index. React state would re-layout the
|
|
@@ -2130,6 +2134,7 @@ export default function SheetPage() {
|
|
| 2130 |
}, [commitSheets]);
|
| 2131 |
|
| 2132 |
const onRenameTab = useCallback(() => {
|
|
|
|
| 2133 |
const pending = tabRename;
|
| 2134 |
const base = bookRef.current;
|
| 2135 |
if (!pending || !base) return;
|
|
@@ -2140,9 +2145,10 @@ export default function SheetPage() {
|
|
| 2140 |
}
|
| 2141 |
setTabRename(null);
|
| 2142 |
commitSheets(renameTab(base, pending.id, pending.name));
|
| 2143 |
-
}, [commitSheets, tabRename]);
|
| 2144 |
|
| 2145 |
const onRemoveTab = useCallback((id: string) => {
|
|
|
|
| 2146 |
const base = bookRef.current;
|
| 2147 |
setTabMenu(null);
|
| 2148 |
if (!base) return;
|
|
@@ -2159,7 +2165,7 @@ export default function SheetPage() {
|
|
| 2159 |
}
|
| 2160 |
commitSheets(removeTab(base, id));
|
| 2161 |
if (tabIdRef.current === id) setTabId(base.sheets.find((t) => t.id !== id)?.id ?? "");
|
| 2162 |
-
}, [commitSheets]);
|
| 2163 |
|
| 2164 |
const confirmRemoveTab = useCallback(() => {
|
| 2165 |
const pending = tabDelete;
|
|
@@ -3187,7 +3193,7 @@ export default function SheetPage() {
|
|
| 3187 |
onViewRows={onViewRows}
|
| 3188 |
onRefresh={onRefresh}
|
| 3189 |
onCommit={commitCells}
|
| 3190 |
-
openAt={openAtRef.current}
|
| 3191 |
onEvaluateBindings={onEvaluateBindings}
|
| 3192 |
onUndo={onUndo}
|
| 3193 |
onRedo={onRedo}
|
|
@@ -3217,7 +3223,7 @@ export default function SheetPage() {
|
|
| 3217 |
// S67-T03 / C1: the in-cell draft channel. After `onCommit` for the same W50-T17 reason.
|
| 3218 |
onDraftChange={setCellDraft}
|
| 3219 |
// S67-T07: a viewer's cell menu shows its edit items disabled, not hidden.
|
| 3220 |
-
readOnly={
|
| 3221 |
onHideBands={onHideBands}
|
| 3222 |
onRowGroups={canEditOutline ? onRowGroups : undefined}
|
| 3223 |
// ⭐⭐ W51-T08 / CONTRACT C1 — THE FOUR SEAM PROPS THE RIBBON IS FED THROUGH.
|
|
@@ -3233,8 +3239,12 @@ export default function SheetPage() {
|
|
| 3233 |
formulaBar={<FormulaBar
|
| 3234 |
addr={barAddr}
|
| 3235 |
cell={cellAt(tab, barAddr)}
|
| 3236 |
-
disabled={busy}
|
| 3237 |
-
onAddrChange={
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3238 |
onCommit={commitCells}
|
| 3239 |
draft={cellDraft}
|
| 3240 |
/>}
|
|
@@ -3295,7 +3305,7 @@ export default function SheetPage() {
|
|
| 3295 |
}
|
| 3296 |
openTab(t.id);
|
| 3297 |
}}
|
| 3298 |
-
onDoubleClick={() => setTabRename({ id: t.id, name: t.name })}
|
| 3299 |
onPointerDown={(event) => startTabDrag(t.id, event)}
|
| 3300 |
onPointerMove={moveTabDrag}
|
| 3301 |
onPointerUp={(event) => finishTabDrag(event, true)}
|
|
@@ -3308,6 +3318,7 @@ export default function SheetPage() {
|
|
| 3308 |
e.preventDefault();
|
| 3309 |
const el = e.currentTarget;
|
| 3310 |
openTab(t.id);
|
|
|
|
| 3311 |
setTabMenu({ id: t.id, el });
|
| 3312 |
}}
|
| 3313 |
title="Click to open. Drag to reorder. Double click to rename. Right click for more."
|
|
@@ -3319,6 +3330,7 @@ export default function SheetPage() {
|
|
| 3319 |
<button
|
| 3320 |
type="button"
|
| 3321 |
className="sheet-ribbon-btn sheet-tab-add"
|
|
|
|
| 3322 |
onClick={onAddTab}
|
| 3323 |
title="Add a sheet to this workbook"
|
| 3324 |
>
|
|
|
|
| 390 |
const [lastWorkbookId] = useState<string>(() => readLastWorkbook());
|
| 391 |
const [sheetHash, setSheetHash] = useState(() => window.location.hash);
|
| 392 |
const [addressSelectionKey, setAddressSelectionKey] = useState(0);
|
| 393 |
+
const [cellAddressRequest, setCellAddressRequest] = useState(0);
|
| 394 |
const [tabId, setTabId] = useState<string>("");
|
| 395 |
const [unreadableAddressTab, setUnreadableAddressTab] = useState("");
|
| 396 |
const [pendingTab, setPendingTab] = useState<{
|
|
|
|
| 2019 |
// ── the tab bar (wave-49 R7) ───────────────────────────────────────────────────────────────
|
| 2020 |
|
| 2021 |
const onAddTab = useCallback(() => {
|
| 2022 |
+
if (!canEditOutline) return;
|
| 2023 |
const base = bookRef.current;
|
| 2024 |
if (!base) return;
|
| 2025 |
const made = addTab(base);
|
|
|
|
| 2028 |
// and must never be fetched: a lazy read of it would 404 or answer an empty tab.
|
| 2029 |
tabLoadedRef.current.add(tabKeyOf(base.id, made.id));
|
| 2030 |
setTabId(made.id);
|
| 2031 |
+
}, [commitSheets, canEditOutline]);
|
| 2032 |
|
| 2033 |
const onMoveTab = useCallback((id: string, step: number) => {
|
| 2034 |
+
if (!canEditOutline) return;
|
| 2035 |
const base = bookRef.current;
|
| 2036 |
setTabMenu(null);
|
| 2037 |
if (base) commitSheets(moveTab(base, id, step));
|
| 2038 |
+
}, [commitSheets, canEditOutline]);
|
| 2039 |
|
| 2040 |
/** Capture the whole tab, preserving the exact point inside it that the pointer grabbed. */
|
| 2041 |
const startTabDrag = useCallback((id: string, event: ReactPointerEvent<HTMLButtonElement>) => {
|
| 2042 |
+
if (!canEditOutline) return;
|
| 2043 |
if (event.button !== 0 || !bookRef.current || tabDragRef.current) return;
|
| 2044 |
const element = event.currentTarget;
|
| 2045 |
const rect = element.getBoundingClientRect();
|
|
|
|
| 2060 |
targetIndex: startIndex,
|
| 2061 |
moved: false,
|
| 2062 |
};
|
| 2063 |
+
}, [canEditOutline]);
|
| 2064 |
|
| 2065 |
/**
|
| 2066 |
* Gesture frames write only a transform and a target index. React state would re-layout the
|
|
|
|
| 2134 |
}, [commitSheets]);
|
| 2135 |
|
| 2136 |
const onRenameTab = useCallback(() => {
|
| 2137 |
+
if (!canEditOutline) return;
|
| 2138 |
const pending = tabRename;
|
| 2139 |
const base = bookRef.current;
|
| 2140 |
if (!pending || !base) return;
|
|
|
|
| 2145 |
}
|
| 2146 |
setTabRename(null);
|
| 2147 |
commitSheets(renameTab(base, pending.id, pending.name));
|
| 2148 |
+
}, [commitSheets, tabRename, canEditOutline]);
|
| 2149 |
|
| 2150 |
const onRemoveTab = useCallback((id: string) => {
|
| 2151 |
+
if (!canEditOutline) return;
|
| 2152 |
const base = bookRef.current;
|
| 2153 |
setTabMenu(null);
|
| 2154 |
if (!base) return;
|
|
|
|
| 2165 |
}
|
| 2166 |
commitSheets(removeTab(base, id));
|
| 2167 |
if (tabIdRef.current === id) setTabId(base.sheets.find((t) => t.id !== id)?.id ?? "");
|
| 2168 |
+
}, [commitSheets, canEditOutline]);
|
| 2169 |
|
| 2170 |
const confirmRemoveTab = useCallback(() => {
|
| 2171 |
const pending = tabDelete;
|
|
|
|
| 3193 |
onViewRows={onViewRows}
|
| 3194 |
onRefresh={onRefresh}
|
| 3195 |
onCommit={commitCells}
|
| 3196 |
+
openAt={{ ...openAtRef.current, request: cellAddressRequest }}
|
| 3197 |
onEvaluateBindings={onEvaluateBindings}
|
| 3198 |
onUndo={onUndo}
|
| 3199 |
onRedo={onRedo}
|
|
|
|
| 3223 |
// S67-T03 / C1: the in-cell draft channel. After `onCommit` for the same W50-T17 reason.
|
| 3224 |
onDraftChange={setCellDraft}
|
| 3225 |
// S67-T07: a viewer's cell menu shows its edit items disabled, not hidden.
|
| 3226 |
+
readOnly={!canEditOutline}
|
| 3227 |
onHideBands={onHideBands}
|
| 3228 |
onRowGroups={canEditOutline ? onRowGroups : undefined}
|
| 3229 |
// ⭐⭐ W51-T08 / CONTRACT C1 — THE FOUR SEAM PROPS THE RIBBON IS FED THROUGH.
|
|
|
|
| 3239 |
formulaBar={<FormulaBar
|
| 3240 |
addr={barAddr}
|
| 3241 |
cell={cellAt(tab, barAddr)}
|
| 3242 |
+
disabled={busy || !canEditOutline}
|
| 3243 |
+
onAddrChange={(addr) => {
|
| 3244 |
+
openAtRef.current = { workbookId: book.id, tabId: tab.id, addr };
|
| 3245 |
+
setBarAddr(addr);
|
| 3246 |
+
setCellAddressRequest((request) => request + 1);
|
| 3247 |
+
}}
|
| 3248 |
onCommit={commitCells}
|
| 3249 |
draft={cellDraft}
|
| 3250 |
/>}
|
|
|
|
| 3305 |
}
|
| 3306 |
openTab(t.id);
|
| 3307 |
}}
|
| 3308 |
+
onDoubleClick={() => { if (canEditOutline) setTabRename({ id: t.id, name: t.name }); }}
|
| 3309 |
onPointerDown={(event) => startTabDrag(t.id, event)}
|
| 3310 |
onPointerMove={moveTabDrag}
|
| 3311 |
onPointerUp={(event) => finishTabDrag(event, true)}
|
|
|
|
| 3318 |
e.preventDefault();
|
| 3319 |
const el = e.currentTarget;
|
| 3320 |
openTab(t.id);
|
| 3321 |
+
if (!canEditOutline) return;
|
| 3322 |
setTabMenu({ id: t.id, el });
|
| 3323 |
}}
|
| 3324 |
title="Click to open. Drag to reorder. Double click to rename. Right click for more."
|
|
|
|
| 3330 |
<button
|
| 3331 |
type="button"
|
| 3332 |
className="sheet-ribbon-btn sheet-tab-add"
|
| 3333 |
+
disabled={!canEditOutline}
|
| 3334 |
onClick={onAddTab}
|
| 3335 |
title="Add a sheet to this workbook"
|
| 3336 |
>
|
web/src/sheet/formulaEval.ts
CHANGED
|
@@ -2803,7 +2803,7 @@ const cyclicComponents = (nodes: Set<string>, reads: Map<string, Set<string>>):
|
|
| 2803 |
}
|
| 2804 |
return result;
|
| 2805 |
};
|
| 2806 |
-
const sameFormat = (a: unknown, b: unknown): boolean => {
|
| 2807 |
const stable = (v: unknown): string => v && typeof v === "object" && !Array.isArray(v)
|
| 2808 |
? JSON.stringify(Object.keys(v).sort().map((k) => [k, stable((v as Record<string, unknown>)[k])])) : JSON.stringify(v);
|
| 2809 |
return stable(a) === stable(b);
|
|
|
|
| 2803 |
}
|
| 2804 |
return result;
|
| 2805 |
};
|
| 2806 |
+
export const sameFormat = (a: unknown, b: unknown): boolean => {
|
| 2807 |
const stable = (v: unknown): string => v && typeof v === "object" && !Array.isArray(v)
|
| 2808 |
? JSON.stringify(Object.keys(v).sort().map((k) => [k, stable((v as Record<string, unknown>)[k])])) : JSON.stringify(v);
|
| 2809 |
return stable(a) === stable(b);
|
web/src/sheet/sheetState.ts
CHANGED
|
@@ -42,7 +42,7 @@ import type { SavedViewShadow } from "./bindingRefs";
|
|
| 42 |
// one door that turns this file's `Cell` into that shape, so the evaluator itself never has to.
|
| 43 |
import {
|
| 44 |
compileSheetFormula, CYCLE_REFUSAL, ERROR_REF, evaluateCompiledSheetFormula, evaluateFormula,
|
| 45 |
-
formulaReferenceKey, WorkbookCalculation as FormulaCalculation, workbookFormulaGetter,
|
| 46 |
} from "./formulaEval";
|
| 47 |
import type { CellValue, QualifiedFormula, SpillChildMarker, FormulaErrorCode } from "./formulaEval";
|
| 48 |
import { copyCell, replaceCellStyle } from "./cellStyleOps";
|
|
@@ -266,7 +266,8 @@ export const cellToValue = (cell: Cell | null | undefined): CellValue => {
|
|
| 266 |
if (cell.value == null) {
|
| 267 |
// ⛔ A BLANK LITERAL IS EMPTY; A BOUND OR FORMULA CELL WITH NOTHING COMPUTED IS PENDING. The
|
| 268 |
// difference is a confident zero versus an honest "not yet", and it is the whole of the trap.
|
| 269 |
-
return cell.kind === "literal"
|
|
|
|
| 270 |
}
|
| 271 |
const pending = cell.kind !== "literal" && cell.state === "stale";
|
| 272 |
if (typeof cell.value === "boolean") return { kind: "boolean", value: cell.value, pending, ...metadata };
|
|
@@ -377,11 +378,12 @@ export const setFormula = (
|
|
| 377 |
delete rest.spill;
|
| 378 |
delete rest.spillParent;
|
| 379 |
delete rest.error;
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
delete rest.
|
| 384 |
}
|
|
|
|
| 385 |
delete rest.binding;
|
| 386 |
delete rest.source;
|
| 387 |
delete rest.refusal;
|
|
|
|
| 42 |
// one door that turns this file's `Cell` into that shape, so the evaluator itself never has to.
|
| 43 |
import {
|
| 44 |
compileSheetFormula, CYCLE_REFUSAL, ERROR_REF, evaluateCompiledSheetFormula, evaluateFormula,
|
| 45 |
+
formulaReferenceKey, sameFormat, WorkbookCalculation as FormulaCalculation, workbookFormulaGetter,
|
| 46 |
} from "./formulaEval";
|
| 47 |
import type { CellValue, QualifiedFormula, SpillChildMarker, FormulaErrorCode } from "./formulaEval";
|
| 48 |
import { copyCell, replaceCellStyle } from "./cellStyleOps";
|
|
|
|
| 266 |
if (cell.value == null) {
|
| 267 |
// ⛔ A BLANK LITERAL IS EMPTY; A BOUND OR FORMULA CELL WITH NOTHING COMPUTED IS PENDING. The
|
| 268 |
// difference is a confident zero versus an honest "not yet", and it is the whole of the trap.
|
| 269 |
+
return cell.kind === "literal" || cell.state === "fresh"
|
| 270 |
+
? { kind: "empty", ...metadata } : { kind: "pending", ...metadata };
|
| 271 |
}
|
| 272 |
const pending = cell.kind !== "literal" && cell.state === "stale";
|
| 273 |
if (typeof cell.value === "boolean") return { kind: "boolean", value: cell.value, pending, ...metadata };
|
|
|
|
| 378 |
delete rest.spill;
|
| 379 |
delete rest.spillParent;
|
| 380 |
delete rest.error;
|
| 381 |
+
const inferred = rest.formulaMeta?.inferredFormat as { version?: number; format?: unknown } | undefined;
|
| 382 |
+
if (inferred?.version === 1 && sameFormat(inferred.format, rest.style?.format)) {
|
| 383 |
+
rest.style = { ...rest.style };
|
| 384 |
+
delete rest.style.format;
|
| 385 |
}
|
| 386 |
+
delete rest.formulaMeta;
|
| 387 |
delete rest.binding;
|
| 388 |
delete rest.source;
|
| 389 |
delete rest.refusal;
|
web/src/sheet/sparkline.ts
CHANGED
|
@@ -1,37 +1,14 @@
|
|
| 1 |
// ---------------------------------------------------------------------------------------------
|
| 2 |
-
// sheet/sparkline.ts —
|
| 3 |
-
//
|
| 4 |
-
//
|
| 5 |
-
//
|
| 6 |
-
//
|
| 7 |
-
// READS A RANGE and a paint callback is only ever handed its own cell.
|
| 8 |
-
//
|
| 9 |
-
// ⛔ THE PARAMETER NAMES CARRY A LEADING UNDERSCORE ONLY WHILE THEY ARE UNREAD.
|
| 10 |
-
// `tsconfig.app.json` sets `noUnusedParameters: true`, so a parameter a body never touches must
|
| 11 |
-
// wear one or the file does not compile. All four are read now, so none of them wears one; the
|
| 12 |
-
// note stays because the next parameter added here inherits the rule.
|
| 13 |
-
//
|
| 14 |
-
// ⛔⛔ TWO ANSWERS, AND THE CELL'S OWN TEXT IS WHAT PICKS BETWEEN THEM. The seam reads a `true` as
|
| 15 |
-
// "this cell's WHOLE paint belonged to the sparkline" and returns before the default renderer:
|
| 16 |
-
// • a cell with NO text of its own — the ordinary case, `kind: "empty"` carrying only the spec —
|
| 17 |
-
// is drawn in full and answers `true`;
|
| 18 |
-
// • a cell that ALSO holds text draws the sparkline as an UNDERLAY, quietened, and answers
|
| 19 |
-
// `false`, so `paintCell` goes on to lay that cell's value over the top of it. Owning the
|
| 20 |
-
// paint there would mean re-implementing the styled text renderer, alignment, wrap, number
|
| 21 |
-
// format and all, in a file whose job is to draw three marks.
|
| 22 |
-
// ⚠ Driven in a browser rather than reasoned about: glide 6.0.3 fills a cell's background BEFORE
|
| 23 |
-
// `drawCell`, and `drawContent()` paints the value alone, so an underlay survives into the frame.
|
| 24 |
-
// The one case it does not survive is a cell carrying an explicit `style.fill`, which `paintCell`
|
| 25 |
-
// lays down itself after this function has returned — see the handoff's PENDING row.
|
| 26 |
-
//
|
| 27 |
-
// ⚠ A `true` ALSO SKIPS `ruleStyleAt` AND ALL FOUR OVERLAY CLOSURES (reference border, copy
|
| 28 |
-
// marquee, shimmer, corner mark), which the seam's own comment warns about. That is accepted for
|
| 29 |
-
// the no-text case: those four all describe a cell's VALUE, and a cell drawn by this function has
|
| 30 |
-
// none. The moment a cell has both, the `false` branch hands every one of them back.
|
| 31 |
// ---------------------------------------------------------------------------------------------
|
| 32 |
|
| 33 |
import { tokenColour } from "./cellBorders";
|
| 34 |
import { addressOf } from "./sheetState";
|
|
|
|
| 35 |
import type { Cell, CellMap } from "./types";
|
| 36 |
|
| 37 |
interface Rect {
|
|
@@ -75,9 +52,8 @@ const valuesIn = (
|
|
| 75 |
const out: (number | null)[] = [];
|
| 76 |
for (let r = r0; r <= r1; r += 1) {
|
| 77 |
for (let c = c0; c <= c1; c += 1) {
|
| 78 |
-
const
|
| 79 |
-
|
| 80 |
-
out.push(Number.isFinite(n) ? n : null);
|
| 81 |
}
|
| 82 |
}
|
| 83 |
return out;
|
|
@@ -91,7 +67,7 @@ const centreX = (box: Rect, i: number, n: number): number =>
|
|
| 91 |
* A POLYLINE, BROKEN AT EVERY GAP. Scaled to the readings that are present, so a flat run still
|
| 92 |
* reads as flat rather than being stretched into noise: an empty span is drawn on the middle line.
|
| 93 |
*/
|
| 94 |
-
const drawLine = (ctx: CanvasRenderingContext2D, box: Rect, values: (number | null)[]): void => {
|
| 95 |
const present = values.filter((v): v is number => v !== null);
|
| 96 |
if (!present.length) return;
|
| 97 |
const lo = Math.min(...present);
|
|
@@ -102,7 +78,7 @@ const drawLine = (ctx: CanvasRenderingContext2D, box: Rect, values: (number | nu
|
|
| 102 |
|
| 103 |
ctx.save();
|
| 104 |
ctx.strokeStyle = tokenColour("--lp-blue-deep", "#768fb6");
|
| 105 |
-
ctx.lineWidth = 1.25;
|
| 106 |
ctx.lineJoin = "round";
|
| 107 |
ctx.lineCap = "round";
|
| 108 |
ctx.beginPath();
|
|
@@ -125,7 +101,7 @@ const drawLine = (ctx: CanvasRenderingContext2D, box: Rect, values: (number | nu
|
|
| 125 |
const i = values.findIndex((v) => v !== null);
|
| 126 |
ctx.fillStyle = tokenColour("--lp-blue-deep", "#768fb6");
|
| 127 |
ctx.beginPath();
|
| 128 |
-
ctx.arc(centreX(box, i, values.length), yOf(present[0]), 1.4, 0, Math.PI * 2);
|
| 129 |
ctx.fill();
|
| 130 |
}
|
| 131 |
ctx.restore();
|
|
@@ -139,7 +115,7 @@ const drawLine = (ctx: CanvasRenderingContext2D, box: Rect, values: (number | nu
|
|
| 139 |
* zero gets the line drawn where zero actually falls. A bar chart whose axis starts at the
|
| 140 |
* smallest reading is the classic lie, and it is one line of arithmetic to avoid.
|
| 141 |
*/
|
| 142 |
-
const drawColumn = (ctx: CanvasRenderingContext2D, box: Rect, values: (number | null)[]): void => {
|
| 143 |
const present = values.filter((v): v is number => v !== null);
|
| 144 |
if (!present.length) return;
|
| 145 |
const lo = Math.min(0, ...present);
|
|
@@ -149,7 +125,7 @@ const drawColumn = (ctx: CanvasRenderingContext2D, box: Rect, values: (number |
|
|
| 149 |
const zero = yOf(0);
|
| 150 |
|
| 151 |
const slot = box.width / values.length;
|
| 152 |
-
const barW = Math.max(
|
| 153 |
const up = tokenColour("--lp-blue-solid", "#5b8fd9");
|
| 154 |
const down = tokenColour("--lp-red-deep", "#a3453c");
|
| 155 |
|
|
@@ -159,7 +135,7 @@ const drawColumn = (ctx: CanvasRenderingContext2D, box: Rect, values: (number |
|
|
| 159 |
const x = box.x + slot * i + (slot - barW) / 2;
|
| 160 |
const y = yOf(v);
|
| 161 |
const top = Math.min(y, zero);
|
| 162 |
-
const height = Math.max(
|
| 163 |
ctx.fillStyle = v < 0 ? down : up;
|
| 164 |
ctx.fillRect(x, top, barW, height);
|
| 165 |
});
|
|
@@ -167,10 +143,10 @@ const drawColumn = (ctx: CanvasRenderingContext2D, box: Rect, values: (number |
|
|
| 167 |
// The baseline only earns its pixel when readings actually sit on both sides of it.
|
| 168 |
if (lo < 0 && hi > 0) {
|
| 169 |
ctx.strokeStyle = tokenColour("--lp-line", "#e6e9ef");
|
| 170 |
-
ctx.lineWidth =
|
| 171 |
ctx.beginPath();
|
| 172 |
-
ctx.moveTo(box.x,
|
| 173 |
-
ctx.lineTo(box.x + box.width,
|
| 174 |
ctx.stroke();
|
| 175 |
}
|
| 176 |
ctx.restore();
|
|
@@ -183,20 +159,20 @@ const drawColumn = (ctx: CanvasRenderingContext2D, box: Rect, values: (number |
|
|
| 183 |
* make this a second, quieter column chart and delete the only kind that answers "how often".
|
| 184 |
* Zero is neither, and so is a gap: both draw nothing.
|
| 185 |
*/
|
| 186 |
-
const drawWinLoss = (ctx: CanvasRenderingContext2D, box: Rect, values: (number | null)[]): void => {
|
| 187 |
const mid = box.y + box.height / 2;
|
| 188 |
-
const markH = Math.max(2, box.height * 0.34);
|
| 189 |
const slot = box.width / values.length;
|
| 190 |
-
const barW = Math.max(
|
| 191 |
const up = tokenColour("--lp-blue-deep", "#768fb6");
|
| 192 |
const down = tokenColour("--lp-red-deep", "#a3453c");
|
| 193 |
|
| 194 |
ctx.save();
|
| 195 |
ctx.strokeStyle = tokenColour("--lp-line", "#e6e9ef");
|
| 196 |
-
ctx.lineWidth =
|
| 197 |
ctx.beginPath();
|
| 198 |
-
ctx.moveTo(box.x,
|
| 199 |
-
ctx.lineTo(box.x + box.width,
|
| 200 |
ctx.stroke();
|
| 201 |
|
| 202 |
values.forEach((v, i) => {
|
|
@@ -211,26 +187,26 @@ const drawWinLoss = (ctx: CanvasRenderingContext2D, box: Rect, values: (number |
|
|
| 211 |
/**
|
| 212 |
* Draw an in-cell sparkline over the range its spec names.
|
| 213 |
*
|
| 214 |
-
* @returns
|
| 215 |
-
*
|
| 216 |
-
* underlay and the cell's own text still has to land on top of it".
|
| 217 |
*/
|
| 218 |
export function drawSparkline(
|
| 219 |
ctx: CanvasRenderingContext2D,
|
| 220 |
rect: Rect,
|
| 221 |
cell: Cell,
|
| 222 |
cells: CellMap,
|
|
|
|
| 223 |
): boolean {
|
| 224 |
const spec = cell.sparkline;
|
| 225 |
-
if (!spec) return false;
|
| 226 |
|
| 227 |
const box: Rect = {
|
| 228 |
-
x: rect.x + INSET,
|
| 229 |
-
y: rect.y + INSET,
|
| 230 |
-
width: rect.width - INSET * 2,
|
| 231 |
-
height: rect.height - INSET * 2,
|
| 232 |
};
|
| 233 |
-
if (box.width < MIN_SIDE || box.height < MIN_SIDE) return false;
|
| 234 |
|
| 235 |
const values = valuesIn(cells, spec.range);
|
| 236 |
if (!values.length) return false;
|
|
@@ -241,14 +217,14 @@ export function drawSparkline(
|
|
| 241 |
// The mark is clipped to its own cell for the same reason the text is: a wide range drawn in a
|
| 242 |
// narrow column must stop at the column edge rather than reach into its neighbour.
|
| 243 |
ctx.beginPath();
|
| 244 |
-
ctx.rect(rect.x +
|
| 245 |
ctx.clip();
|
| 246 |
// ⭐ QUIETER UNDER TEXT, FULL STRENGTH ALONE. The underlay has to stay a background: at full
|
| 247 |
// opacity a column chart competes with the digits sitting on it and neither one wins.
|
| 248 |
if (hasText) ctx.globalAlpha = 0.45;
|
| 249 |
-
if (spec.kind === "line") drawLine(ctx, box, values);
|
| 250 |
-
else if (spec.kind === "column") drawColumn(ctx, box, values);
|
| 251 |
-
else drawWinLoss(ctx, box, values);
|
| 252 |
ctx.globalAlpha = 1;
|
| 253 |
ctx.restore();
|
| 254 |
|
|
|
|
| 1 |
// ---------------------------------------------------------------------------------------------
|
| 2 |
+
// sheet/sparkline.ts — an in-cell picture of a range.
|
| 3 |
+
// SheetGrid paints the resolved background first, these marks next, and the value and selection
|
| 4 |
+
// overlays last. A sparkline never takes over the cell's conditional rules, text or overlays.
|
| 5 |
+
// Source readings use the underlying numeric value; presentation such as `(370)` cannot change
|
| 6 |
+
// the sign. Gaps remain gaps. Geometry scales with the grid zoom, including its minimum size.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
// ---------------------------------------------------------------------------------------------
|
| 8 |
|
| 9 |
import { tokenColour } from "./cellBorders";
|
| 10 |
import { addressOf } from "./sheetState";
|
| 11 |
+
import { asNumber } from "./types";
|
| 12 |
import type { Cell, CellMap } from "./types";
|
| 13 |
|
| 14 |
interface Rect {
|
|
|
|
| 52 |
const out: (number | null)[] = [];
|
| 53 |
for (let r = r0; r <= r1; r += 1) {
|
| 54 |
for (let c = c0; c <= c1; c += 1) {
|
| 55 |
+
const cell = cells[addressOf(c, r)];
|
| 56 |
+
out.push(cell?.state === "refused" ? null : asNumber(cell?.value));
|
|
|
|
| 57 |
}
|
| 58 |
}
|
| 59 |
return out;
|
|
|
|
| 67 |
* A POLYLINE, BROKEN AT EVERY GAP. Scaled to the readings that are present, so a flat run still
|
| 68 |
* reads as flat rather than being stretched into noise: an empty span is drawn on the middle line.
|
| 69 |
*/
|
| 70 |
+
const drawLine = (ctx: CanvasRenderingContext2D, box: Rect, values: (number | null)[], zoom: number): void => {
|
| 71 |
const present = values.filter((v): v is number => v !== null);
|
| 72 |
if (!present.length) return;
|
| 73 |
const lo = Math.min(...present);
|
|
|
|
| 78 |
|
| 79 |
ctx.save();
|
| 80 |
ctx.strokeStyle = tokenColour("--lp-blue-deep", "#768fb6");
|
| 81 |
+
ctx.lineWidth = Math.max(0.5, 1.25 * zoom);
|
| 82 |
ctx.lineJoin = "round";
|
| 83 |
ctx.lineCap = "round";
|
| 84 |
ctx.beginPath();
|
|
|
|
| 101 |
const i = values.findIndex((v) => v !== null);
|
| 102 |
ctx.fillStyle = tokenColour("--lp-blue-deep", "#768fb6");
|
| 103 |
ctx.beginPath();
|
| 104 |
+
ctx.arc(centreX(box, i, values.length), yOf(present[0]), 1.4 * zoom, 0, Math.PI * 2);
|
| 105 |
ctx.fill();
|
| 106 |
}
|
| 107 |
ctx.restore();
|
|
|
|
| 115 |
* zero gets the line drawn where zero actually falls. A bar chart whose axis starts at the
|
| 116 |
* smallest reading is the classic lie, and it is one line of arithmetic to avoid.
|
| 117 |
*/
|
| 118 |
+
const drawColumn = (ctx: CanvasRenderingContext2D, box: Rect, values: (number | null)[], zoom: number): void => {
|
| 119 |
const present = values.filter((v): v is number => v !== null);
|
| 120 |
if (!present.length) return;
|
| 121 |
const lo = Math.min(0, ...present);
|
|
|
|
| 125 |
const zero = yOf(0);
|
| 126 |
|
| 127 |
const slot = box.width / values.length;
|
| 128 |
+
const barW = Math.max(zoom, Math.min(slot - zoom, slot * 0.72));
|
| 129 |
const up = tokenColour("--lp-blue-solid", "#5b8fd9");
|
| 130 |
const down = tokenColour("--lp-red-deep", "#a3453c");
|
| 131 |
|
|
|
|
| 135 |
const x = box.x + slot * i + (slot - barW) / 2;
|
| 136 |
const y = yOf(v);
|
| 137 |
const top = Math.min(y, zero);
|
| 138 |
+
const height = Math.max(zoom, Math.abs(zero - y));
|
| 139 |
ctx.fillStyle = v < 0 ? down : up;
|
| 140 |
ctx.fillRect(x, top, barW, height);
|
| 141 |
});
|
|
|
|
| 143 |
// The baseline only earns its pixel when readings actually sit on both sides of it.
|
| 144 |
if (lo < 0 && hi > 0) {
|
| 145 |
ctx.strokeStyle = tokenColour("--lp-line", "#e6e9ef");
|
| 146 |
+
ctx.lineWidth = Math.max(0.5, zoom);
|
| 147 |
ctx.beginPath();
|
| 148 |
+
ctx.moveTo(box.x, zero);
|
| 149 |
+
ctx.lineTo(box.x + box.width, zero);
|
| 150 |
ctx.stroke();
|
| 151 |
}
|
| 152 |
ctx.restore();
|
|
|
|
| 159 |
* make this a second, quieter column chart and delete the only kind that answers "how often".
|
| 160 |
* Zero is neither, and so is a gap: both draw nothing.
|
| 161 |
*/
|
| 162 |
+
const drawWinLoss = (ctx: CanvasRenderingContext2D, box: Rect, values: (number | null)[], zoom: number): void => {
|
| 163 |
const mid = box.y + box.height / 2;
|
| 164 |
+
const markH = Math.max(2 * zoom, box.height * 0.34);
|
| 165 |
const slot = box.width / values.length;
|
| 166 |
+
const barW = Math.max(zoom, Math.min(slot - zoom, slot * 0.72));
|
| 167 |
const up = tokenColour("--lp-blue-deep", "#768fb6");
|
| 168 |
const down = tokenColour("--lp-red-deep", "#a3453c");
|
| 169 |
|
| 170 |
ctx.save();
|
| 171 |
ctx.strokeStyle = tokenColour("--lp-line", "#e6e9ef");
|
| 172 |
+
ctx.lineWidth = Math.max(0.5, zoom);
|
| 173 |
ctx.beginPath();
|
| 174 |
+
ctx.moveTo(box.x, mid);
|
| 175 |
+
ctx.lineTo(box.x + box.width, mid);
|
| 176 |
ctx.stroke();
|
| 177 |
|
| 178 |
values.forEach((v, i) => {
|
|
|
|
| 187 |
/**
|
| 188 |
* Draw an in-cell sparkline over the range its spec names.
|
| 189 |
*
|
| 190 |
+
* @returns whether the mark has no value text above it. Callers always finish painting the cell;
|
| 191 |
+
* this compatibility result does not transfer ownership of the paint pass.
|
|
|
|
| 192 |
*/
|
| 193 |
export function drawSparkline(
|
| 194 |
ctx: CanvasRenderingContext2D,
|
| 195 |
rect: Rect,
|
| 196 |
cell: Cell,
|
| 197 |
cells: CellMap,
|
| 198 |
+
zoom = 1,
|
| 199 |
): boolean {
|
| 200 |
const spec = cell.sparkline;
|
| 201 |
+
if (!spec || !Number.isFinite(zoom) || zoom <= 0) return false;
|
| 202 |
|
| 203 |
const box: Rect = {
|
| 204 |
+
x: rect.x + INSET * zoom,
|
| 205 |
+
y: rect.y + INSET * zoom,
|
| 206 |
+
width: rect.width - INSET * zoom * 2,
|
| 207 |
+
height: rect.height - INSET * zoom * 2,
|
| 208 |
};
|
| 209 |
+
if (box.width < MIN_SIDE * zoom || box.height < MIN_SIDE * zoom) return false;
|
| 210 |
|
| 211 |
const values = valuesIn(cells, spec.range);
|
| 212 |
if (!values.length) return false;
|
|
|
|
| 217 |
// The mark is clipped to its own cell for the same reason the text is: a wide range drawn in a
|
| 218 |
// narrow column must stop at the column edge rather than reach into its neighbour.
|
| 219 |
ctx.beginPath();
|
| 220 |
+
ctx.rect(rect.x + zoom, rect.y + zoom, rect.width - 2 * zoom, rect.height - 2 * zoom);
|
| 221 |
ctx.clip();
|
| 222 |
// ⭐ QUIETER UNDER TEXT, FULL STRENGTH ALONE. The underlay has to stay a background: at full
|
| 223 |
// opacity a column chart competes with the digits sitting on it and neither one wins.
|
| 224 |
if (hasText) ctx.globalAlpha = 0.45;
|
| 225 |
+
if (spec.kind === "line") drawLine(ctx, box, values, zoom);
|
| 226 |
+
else if (spec.kind === "column") drawColumn(ctx, box, values, zoom);
|
| 227 |
+
else drawWinLoss(ctx, box, values, zoom);
|
| 228 |
ctx.globalAlpha = 1;
|
| 229 |
ctx.restore();
|
| 230 |
|
web/src/sheet/types.ts
CHANGED
|
@@ -176,6 +176,8 @@ export interface BindingFilterClause {
|
|
| 176 |
value: string;
|
| 177 |
/** Set operands stay separate, including singleton Step drivers. */
|
| 178 |
values?: string[];
|
|
|
|
|
|
|
| 179 |
/** True when the clause holds a SET rather than one value (the `values` operand). */
|
| 180 |
multiValued: boolean;
|
| 181 |
/** True on a MEASURE condition (a leaf carrying a window), which is not a column clause. */
|
|
@@ -207,11 +209,13 @@ export const bindingFilterClauses = (tree: unknown): BindingFilterClause[] => {
|
|
| 207 |
// ⚠ First occurrence wins because drag selects a DRIVER COLUMN and rewrites every clause
|
| 208 |
// on that column; a second entry would offer the same drag twice.
|
| 209 |
seen.add(colId);
|
|
|
|
| 210 |
clauses.push({
|
| 211 |
colId,
|
| 212 |
op: typeof node.op === "string" ? node.op : "",
|
| 213 |
value: typeof node.value === "string" ? node.value : "",
|
| 214 |
...(Array.isArray(node.values) ? { values: node.values.map(String) } : {}),
|
|
|
|
| 215 |
// ⛔ A non-empty `values` operand is a SET, while `window` marks a MEASURE condition;
|
| 216 |
// preserving both facts lets the panel explain why neither is one ordered option.
|
| 217 |
multiValued: Array.isArray(node.values) && node.values.length > 0,
|
|
|
|
| 176 |
value: string;
|
| 177 |
/** Set operands stay separate, including singleton Step drivers. */
|
| 178 |
values?: string[];
|
| 179 |
+
/** Preserve a compared field for related-offer readiness. */
|
| 180 |
+
rhs?: { colId: string };
|
| 181 |
/** True when the clause holds a SET rather than one value (the `values` operand). */
|
| 182 |
multiValued: boolean;
|
| 183 |
/** True on a MEASURE condition (a leaf carrying a window), which is not a column clause. */
|
|
|
|
| 209 |
// ⚠ First occurrence wins because drag selects a DRIVER COLUMN and rewrites every clause
|
| 210 |
// on that column; a second entry would offer the same drag twice.
|
| 211 |
seen.add(colId);
|
| 212 |
+
const rhs = asRecord(node.rhs);
|
| 213 |
clauses.push({
|
| 214 |
colId,
|
| 215 |
op: typeof node.op === "string" ? node.op : "",
|
| 216 |
value: typeof node.value === "string" ? node.value : "",
|
| 217 |
...(Array.isArray(node.values) ? { values: node.values.map(String) } : {}),
|
| 218 |
+
...(rhs && typeof rhs.colId === "string" ? { rhs: { colId: rhs.colId } } : {}),
|
| 219 |
// ⛔ A non-empty `values` operand is a SET, while `window` marks a MEASURE condition;
|
| 220 |
// preserving both facts lets the panel explain why neither is one ordered option.
|
| 221 |
multiValued: Array.isArray(node.values) && node.values.length > 0,
|
web/src/ui/useEscapeClose.ts
CHANGED
|
@@ -48,6 +48,7 @@ export interface EscapeEntry {
|
|
| 48 |
export interface FocusedShape {
|
| 49 |
tagName: string;
|
| 50 |
isContentEditable: boolean;
|
|
|
|
| 51 |
/** Is this element inside the topmost overlay's own container? */
|
| 52 |
insideTop: boolean;
|
| 53 |
}
|
|
@@ -76,11 +77,13 @@ export function escapeTargets(entries: readonly EscapeEntry[]): EscapeEntry[] {
|
|
| 76 |
|
| 77 |
/** Is the focused element a live text edit? */
|
| 78 |
export function isEditingElement(
|
| 79 |
-
focused: { tagName: string; isContentEditable: boolean } | null
|
| 80 |
): boolean {
|
| 81 |
if (!focused) return false;
|
| 82 |
if (focused.isContentEditable) return true;
|
| 83 |
const tag = focused.tagName.toUpperCase();
|
|
|
|
|
|
|
| 84 |
return tag === "INPUT" || tag === "TEXTAREA";
|
| 85 |
}
|
| 86 |
|
|
@@ -138,6 +141,7 @@ function onDocumentKeyDown(event: KeyboardEvent): void {
|
|
| 138 |
const focused: FocusedShape | null = active
|
| 139 |
? {
|
| 140 |
tagName: active.tagName,
|
|
|
|
| 141 |
isContentEditable: active.isContentEditable,
|
| 142 |
insideTop: node ? node.contains(active) : true,
|
| 143 |
}
|
|
|
|
| 48 |
export interface FocusedShape {
|
| 49 |
tagName: string;
|
| 50 |
isContentEditable: boolean;
|
| 51 |
+
type?: string;
|
| 52 |
/** Is this element inside the topmost overlay's own container? */
|
| 53 |
insideTop: boolean;
|
| 54 |
}
|
|
|
|
| 77 |
|
| 78 |
/** Is the focused element a live text edit? */
|
| 79 |
export function isEditingElement(
|
| 80 |
+
focused: { tagName: string; isContentEditable: boolean; type?: string } | null
|
| 81 |
): boolean {
|
| 82 |
if (!focused) return false;
|
| 83 |
if (focused.isContentEditable) return true;
|
| 84 |
const tag = focused.tagName.toUpperCase();
|
| 85 |
+
if (tag === "INPUT" && ["checkbox", "radio", "button", "submit", "reset", "file", "range",
|
| 86 |
+
"color", "hidden", "image"].includes((focused.type ?? "text").toLowerCase())) return false;
|
| 87 |
return tag === "INPUT" || tag === "TEXTAREA";
|
| 88 |
}
|
| 89 |
|
|
|
|
| 141 |
const focused: FocusedShape | null = active
|
| 142 |
? {
|
| 143 |
tagName: active.tagName,
|
| 144 |
+
type: active instanceof HTMLInputElement ? active.type : undefined,
|
| 145 |
isContentEditable: active.isContentEditable,
|
| 146 |
insideTop: node ? node.contains(active) : true,
|
| 147 |
}
|