@aglyn/tenant-feature-instance 1.20.2 → 1.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/lib/hooks/firebase/firebase-services.js +4 -0
- package/src/lib/hooks/firebase/firebase-services.js.map +1 -1
- package/src/lib/hooks/firebase/firestore-multitab-wedge.d.ts +19 -1
- package/src/lib/hooks/firebase/firestore-multitab-wedge.js +24 -11
- package/src/lib/hooks/firebase/firestore-multitab-wedge.js.map +1 -1
- package/src/lib/hooks/firebase/firestore-page-wedge-check.d.ts +94 -0
- package/src/lib/hooks/firebase/firestore-page-wedge-check.js +136 -0
- package/src/lib/hooks/firebase/firestore-page-wedge-check.js.map +1 -0
- package/src/lib/hooks/firebase/firestore-stall-recovery.d.ts +6 -0
- package/src/lib/hooks/firebase/firestore-stall-recovery.js +7 -0
- package/src/lib/hooks/firebase/firestore-stall-recovery.js.map +1 -1
- package/src/lib/hooks/use-seed-draft.d.ts +50 -0
- package/src/lib/hooks/use-seed-draft.js +135 -0
- package/src/lib/hooks/use-seed-draft.js.map +1 -0
- package/src/lib/hooks/use-seed-edits.d.ts +84 -0
- package/src/lib/hooks/use-seed-edits.js +188 -0
- package/src/lib/hooks/use-seed-edits.js.map +1 -0
- package/src/lib/tenant.d.ts +1 -0
- package/src/lib/tenant.js +1 -0
- package/src/lib/tenant.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firestore-stall-recovery.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n disableNetwork,\n enableNetwork,\n type Firestore,\n} from 'firebase/firestore'\n\nimport {\n browserLeaseCheckFor,\n browserWedgeEscalationFor,\n type LeaseCheck,\n} from './firestore-multitab-wedge'\n\n/**\n * RECOVERING A FIRESTORE CLIENT THAT HAS STOPPED SYNCING (AGL-3373).\n *\n * ## The wedge\n *\n * The console runs the persistent cache with `persistentMultipleTabManager`\n * (`firestore-cache.ts`). Only the PRIMARY tab talks to the backend; every\n * other tab reads the shared IndexedDB cache and takes its online state from\n * a `localStorage` record the primary writes. A secondary that believes the\n * client is online answers a `getDocs` only once the primary has synced the\n * query, and raises no first snapshot for a listener whose cache is empty.\n *\n * When the primary dies without handing over — a crashed, discarded or\n * frozen tab — its \"Online\" record outlives it, and until some tab runs the\n * lease election and wins, nothing syncs. The election runs on a 4-second\n * timer inside each tab, which the browser throttles to about once a minute\n * in a hidden tab. On 2026-09-28 no live tab synced for about ten minutes:\n * the notifications page never left its loading state and a staff page sat\n * on its splash until a fresh tab (which wins the election on start) was\n * opened.\n *\n * ## The recovery, and why it is this one\n *\n * `disableNetwork` then `enableNetwork`, from the tab that noticed. Both are\n * public API, and in the multi-tab client each one calls\n * `setNetworkEnabled`, which schedules the lease election for IMMEDIATE\n * execution instead of the next (possibly throttled) timer tick. A visible\n * tab that finds the lease lapsed takes it, starts its own streams and\n * writes its own online state, which replaces the dead tab's. A tab that was\n * already primary with a silently dead stream gets fresh streams.\n *\n * Nothing is lost. Writes made meanwhile sit in the mutation queue (in\n * IndexedDB, under the persistent cache) and are sent when the network comes\n * back; the SDK's own contract for `disableNetwork` is that writes queue.\n *\n * The rejected alternatives:\n *\n * - **Clearing the persistence cache** (`terminate` + `clearIndexedDbPersistence`).\n * It deletes the mutation queue, so pending writes are lost, and\n * `waitForPendingWrites` cannot drain them first because draining is the\n * very thing that is stuck. It also refuses to run while any other tab\n * holds the database, which in a multi-tab wedge is always. And\n * `terminate` invalidates the one `Firestore` instance every hook in the\n * console holds.\n * - **Pruning the dead tab's online-state record at startup**, beside the\n * AGL-2845 prune. The SDK already ignores an online-state record at\n * startup unless its writer is an active, non-zombie client\n * (`WebStorageSharedClientState.handleOnlineStateEvent`), and a freshly\n * started tab wins the election anyway — which is why a fresh tab fixed\n * the incident. The tabs that stayed stuck were the ones ALREADY running,\n * which a startup prune never reaches.\n * - **`persistentSingleTabManager`.** It removes cross-tab dependency, but\n * every tab after the first falls back to a memory cache, so writes made\n * offline in those tabs are lost when they close. And a tab still on the\n * multi-tab build that meets a single-tab lease holder fails its queue\n * with `failed-precondition` until reloaded, so the rollout itself would\n * wedge the tabs left open across it.\n *\n * ## Guards\n *\n * - **Online only.** A browser that reports no network is correctly offline,\n * and the cache answering is the cache doing its job.\n * - **Visible only.** A hidden tab's timers are throttled and its reader is\n * not waiting; if it is stalled, it recovers the moment it is looked at.\n * - **Once per {@link STALL_RECOVERY_COOLDOWN_MS} per client.** Every list on\n * a page stalls together, and one cycle serves them all. A concurrent\n * request shares the cycle already running.\n * - **A client the server is answering is not stalled (AGL-4120).** See below.\n * - **Nor is one waiting on the shared cache, or served by a live lease\n * holder (AGL-4135).** See below.\n * - **The network is always re-enabled**, including when disabling fails.\n * - **Each step is bounded by {@link NETWORK_STEP_TIMEOUT_MS}.** Both calls are\n * queued on the client's AsyncQueue, and when another tab has locked the\n * shared IndexedDB they queue behind an operation that never finishes\n * (AGL-3428). Unbounded, the first such cycle never settled, and every\n * later recovery request shared it forever.\n *\n * ## The cycle is not free, so it needs a silent client (AGL-4120)\n *\n * A stall watch knows one thing: ITS listener has not been confirmed. That used\n * to be enough to cycle, so one slow listener among thirty-five took the whole\n * client off the network, and the cycle did real damage to one that was working.\n * `disableNetwork` makes a primary ineligible for its own lease\n * (`canActAsPrimary`), so it hands the lease over, to a hidden tab if one is\n * waiting: captured in production as `NET-OFF, LEASE-RELEASE, NET-ON`. And while\n * the network is off, every view in a primary goes Offline, so every listener the\n * server had already confirmed reads `fromCache` again until it is confirmed a\n * second time. A contact page read server-confirmed at 9 s and unconfirmed from\n * 14 s to past a minute, on a page nobody touched, refusing every save on it. A\n * slow page was turned into a broken one by the code meant to rescue it.\n *\n * So every server-confirmed snapshot stamps the client\n * ({@link noteFirestoreServerAnswer}), and a recovery within\n * {@link FIRESTORE_STALL_MS} of one answers `'answering'` and does nothing. A\n * client that is working through a page is left to finish. One that has really\n * gone silent stops stamping, and the next watch to fire gets its cycle.\n *\n * ## A client that is waiting is not silent either (AGL-4135)\n *\n * A client can go 8 s without an answer while nothing is wrong with it. Every\n * console tab shares one IndexedDB cache, and every SDK transaction locks every\n * store. A tab that is starved (busy, slow, throttled in the background) keeps\n * each transaction open until its event loop comes back between requests, for\n * seconds at a time. A healthy tab's client waits behind that lock and cannot\n * apply what the server sends, so it raises no confirmed snapshot. Measured in\n * production (v1.5.0, two tabs): the tab holding the lease was blocked for\n * about 12 s, and when its queue drained the cycle it had asked for ran, broadcast\n * `Offline` and put every confirmed view in both tabs back on the cache, the\n * record being saved included. The cycle cannot shorten another tab's\n * transaction, because both of its calls queue behind it.\n *\n * And a client in a tab that does not hold the lease is served by the tab that\n * does. Cycling it cannot reach the holder's stream. It only marks this tab\n * `networkEnabled: false` and reruns an election the live holder wins\n * (`networkEnabled: false` at 5.7 s in the AGL-4132 run).\n *\n * So before a cycle, the client reads the lease ({@link StallRecoveryDeps.checkLease}):\n *\n * - **the read waits** (`waiting`): a transaction holds the store. No cycle.\n * The wedge check below runs in its place, since a store that stays locked is\n * the AGL-3428 wedge whether or not a cycle ran first.\n * - **another tab holds a live lease** (`served`): no cycle. The holder is\n * slow, and nothing this tab does makes it faster.\n * - **anything else** (`silent`): this tab holds the lease and its stream has\n * gone quiet, or the lease has lapsed or is vacant and an election is due.\n * That is what the cycle is for, and it runs.\n *\n * The read takes up to a second (`LEASE_PROMPT_READ_MS`), so the client is\n * asked again afterwards whether the server has answered meanwhile.\n *\n * ## When the cycle is not enough (AGL-3428)\n *\n * A tab frozen partway through an IndexedDB transaction holds every store the\n * SDK uses, and the election the cycle forces cannot run. For a client on the\n * durable multi-tab cache the cycle is followed by the lease check in\n * `firestore-multitab-wedge.ts`, which moves the tab to a memory cache when\n * the lease shows the wedge. A client found `waiting` gets that check without\n * the cycle.\n */\n\n/**\n * How long a server read or a listener's first server-confirmed snapshot may\n * take before the client is treated as stalled. A healthy console answers\n * in well under two seconds; this leaves room for a slow network without\n * leaving a reader on a spinner for long.\n */\nexport const FIRESTORE_STALL_MS = 8_000\n\n/** The least time between two recoveries of the same client. */\nexport const STALL_RECOVERY_COOLDOWN_MS = 30_000\n\n/**\n * The longest the wait between two cycles grows to, on a client that cycling is\n * not bringing back. Doubling, so that a connection too slow to answer inside\n * one cooldown is not restarted before it can.\n */\nexport const STALL_RECOVERY_MAX_COOLDOWN_MS = 5 * 60_000\n\n/**\n * The longest `disableNetwork` or `enableNetwork` may take. Both finish in\n * milliseconds on a client whose queue is moving.\n */\nexport const NETWORK_STEP_TIMEOUT_MS = 5_000\n\n/** What a recovery request did. */\nexport type StallRecoveryOutcome =\n /** The browser reports no network: the cache is the right answer. */\n | 'offline'\n /** The tab is hidden: nobody is waiting on it. */\n | 'hidden'\n /** A recovery ran moments ago; this request rode on it. */\n | 'cooling'\n /** The server answered this client moments ago: it is busy, not stalled. */\n | 'answering'\n /** A transaction holds the shared cache, and this client is queued behind it (AGL-4135). */\n | 'waiting'\n /** Another tab holds a live lease and serves this client (AGL-4135). */\n | 'served'\n /** The network was cycled. */\n | 'recovered'\n /** The cycle threw or timed out; the network was still re-enabled if at all possible. */\n | 'failed'\n /** The multi-tab cache was wedged and this tab is moving to the memory cache. */\n | 'fell-back'\n\nexport interface StallRecoveryDeps {\n /** Take the client off the network. */\n disable: () => Promise<void>\n /** Put it back. */\n enable: () => Promise<void>\n /** `navigator.onLine`, or `true` where there is no navigator. */\n isOnline?: () => boolean\n /** Whether the document is visible, or `true` where there is none. */\n isVisible?: () => boolean\n now?: () => number\n /**\n * When the server last confirmed anything for this client, or `undefined`\n * if it has not. Without one, every stall is taken at its word.\n */\n lastServerAnswerAt?: () => number | undefined\n /** How recent an answer proves the client is alive. */\n answeringWindowMs?: number\n cooldownMs?: number\n /** The bound on each of `disable` and `enable`. */\n stepTimeoutMs?: number\n /**\n * Reads the shared cache's lease before a cycle (AGL-4135). Only a multi-tab\n * client has one; without it, every stall that passes the other guards is\n * cycled.\n */\n checkLease?: () => Promise<LeaseCheck>\n /**\n * The wedge check. Runs after every cycle, and in place of one for a client\n * found `waiting`. Resolves `true` when it has moved the tab off the shared\n * cache. Only a multi-tab client has one.\n */\n escalate?: () => Promise<boolean>\n}\n\nexport interface StallRecovery {\n recover: () => Promise<StallRecoveryOutcome>\n}\n\nconst browserOnline = () =>\n typeof navigator === 'undefined' || navigator.onLine !== false\n\nconst documentVisible = () =>\n typeof document === 'undefined' || document.visibilityState !== 'hidden'\n\n/** The recovery for one client, with its guards. Pure over `deps`. */\nexport function createStallRecovery(deps: StallRecoveryDeps): StallRecovery {\n const {\n disable,\n enable,\n isOnline = browserOnline,\n isVisible = documentVisible,\n now = Date.now,\n lastServerAnswerAt,\n answeringWindowMs = FIRESTORE_STALL_MS,\n cooldownMs = STALL_RECOVERY_COOLDOWN_MS,\n stepTimeoutMs = NETWORK_STEP_TIMEOUT_MS,\n checkLease,\n escalate,\n } = deps\n let lastStartedAt: number | undefined\n /** Cycles in a row that the server has not answered since. */\n let quietCycles = 0\n /** When a client found waiting last had the wedge check (AGL-4135). */\n let lastWaitCheckedAt: number | undefined\n let running: Promise<StallRecoveryOutcome> | undefined\n\n /** Whether `step` settled successfully within `stepTimeoutMs`. */\n const bounded = (step: () => Promise<void>): Promise<boolean> =>\n new Promise((resolve) => {\n const timer = setTimeout(() => resolve(false), stepTimeoutMs)\n const done = (ok: boolean) => {\n clearTimeout(timer)\n resolve(ok)\n }\n try {\n step().then(\n () => done(true),\n () => done(false),\n )\n } catch {\n done(false)\n }\n })\n\n /** Whether the escalation moved the tab off the shared cache. Best effort. */\n const escalated = async (): Promise<boolean> => {\n if (!escalate) return false\n try {\n return await escalate()\n } catch {\n return false\n }\n }\n\n const cycle = async (): Promise<StallRecoveryOutcome> => {\n let outcome: StallRecoveryOutcome = 'recovered'\n if (!(await bounded(disable))) outcome = 'failed'\n if (!(await bounded(enable))) outcome = 'failed'\n // The escalation is best effort; the cycle's own outcome stands.\n return (await escalated()) ? 'fell-back' : outcome\n }\n\n const answeredWithin = (at: number): boolean => {\n const answeredAt = lastServerAnswerAt?.()\n return answeredAt !== undefined && at - answeredAt < answeringWindowMs\n }\n\n /** Past the guards: reads the lease, then cycles only a client nothing explains. */\n const attempt = async (): Promise<StallRecoveryOutcome> => {\n let lease: LeaseCheck = { state: 'silent' }\n if (checkLease) {\n try {\n lease = await checkLease()\n } catch {\n // Unread, the stall is taken at its word, as it always was.\n }\n }\n if (lease.state === 'served') return 'served'\n if (lease.state === 'waiting') {\n // As often as a cycle would have run it, and no more: every check is\n // one more chance for a long wait to read as a wedge.\n const checkedAt = now()\n if (\n lastWaitCheckedAt !== undefined &&\n checkedAt - lastWaitCheckedAt < cooldownMs\n ) {\n return 'waiting'\n }\n lastWaitCheckedAt = checkedAt\n return (await escalated()) ? 'fell-back' : 'waiting'\n }\n // The read took time, and a client that was waiting may have answered.\n const at = now()\n if (answeredWithin(at)) return 'answering'\n if (lastStartedAt !== undefined) {\n const answeredAt = lastServerAnswerAt?.()\n const answeredSince =\n answeredAt !== undefined && answeredAt >= lastStartedAt\n quietCycles = answeredSince ? 0 : quietCycles + 1\n }\n lastStartedAt = at\n return cycle()\n }\n\n return {\n recover: () => {\n if (running) return running\n if (!isOnline()) return Promise.resolve('offline')\n if (!isVisible()) return Promise.resolve('hidden')\n const at = now()\n if (answeredWithin(at)) return Promise.resolve('answering')\n if (lastStartedAt !== undefined) {\n const cooldown = Math.min(\n cooldownMs * 2 ** quietCycles,\n STALL_RECOVERY_MAX_COOLDOWN_MS,\n )\n if (at - lastStartedAt < cooldown) return Promise.resolve('cooling')\n }\n running = attempt().finally(() => {\n running = undefined\n })\n return running\n },\n }\n}\n\nconst recoveries = new WeakMap<Firestore, StallRecovery>()\n\n/** When the server last confirmed a snapshot for each client. */\nconst serverAnswers = new WeakMap<Firestore, number>()\n\n/**\n * Records that the server just confirmed something for `firestore`: the\n * evidence a stall watch does not have that this client is alive. Every listener\n * that arms a watch calls this on a server-confirmed snapshot.\n */\nexport function noteFirestoreServerAnswer(\n firestore: Firestore | null | undefined,\n): void {\n if (firestore && typeof firestore === 'object') {\n serverAnswers.set(firestore, Date.now())\n }\n}\n\n/**\n * Whether the server has confirmed anything for `firestore` in this tab: the\n * boot check's line between a tab still booting and one in use (AGL-4201).\n */\nexport function firestoreHasServerAnswered(\n firestore: Firestore | null | undefined,\n): boolean {\n return Boolean(\n firestore && typeof firestore === 'object' && serverAnswers.has(firestore),\n )\n}\n\n/**\n * Recovers `firestore` if it has stalled. Safe to call from every reader\n * that notices: the guards above collapse the calls into at most one network\n * cycle per cooldown. Never rejects.\n */\nexport function recoverStalledFirestore(\n firestore: Firestore | null | undefined,\n): Promise<StallRecoveryOutcome> {\n if (!firestore || typeof firestore !== 'object') {\n return Promise.resolve('failed')\n }\n let recovery = recoveries.get(firestore)\n if (!recovery) {\n recovery = createStallRecovery({\n disable: () => disableNetwork(firestore),\n enable: () => enableNetwork(firestore),\n lastServerAnswerAt: () => serverAnswers.get(firestore),\n checkLease: browserLeaseCheckFor(firestore),\n escalate: browserWedgeEscalationFor(firestore),\n })\n recoveries.set(firestore, recovery)\n }\n return recovery.recover().catch(() => 'failed' as const)\n}\n\n/**\n * Arms a stall timer for one read or listen. Until `disarm` is called, `onStall`\n * runs (by default, {@link recoverStalledFirestore}) every `stallMs`. A tab that\n * is hidden when the timer fires waits until it is shown, since that is when a\n * reader is waiting again.\n *\n * It keeps firing because one call can do nothing: the request may land inside\n * a cooldown, or on a client that is still answering. A watch that spent itself\n * there left its listener unconfirmed for life (AGL-4120), which is how a tab's\n * first page worked and a later page's saves were refused. The calls cost nothing\n * until one of them finds a client that really needs a cycle.\n *\n * Returns `disarm`, which is idempotent.\n */\nexport function armFirestoreStallWatch(\n firestore: Firestore | null | undefined,\n options: { stallMs?: number; onStall?: () => void } = {},\n): () => void {\n const { stallMs = FIRESTORE_STALL_MS } = options\n const onStall =\n options.onStall ?? (() => void recoverStalledFirestore(firestore))\n let done = false\n let timer: ReturnType<typeof setTimeout> | undefined\n let onVisible: (() => void) | undefined\n const fire = () => {\n if (done) return\n if (!documentVisible() && typeof document !== 'undefined') {\n onVisible = () => {\n if (!documentVisible()) return\n document.removeEventListener('visibilitychange', onVisible!)\n onVisible = undefined\n fire()\n }\n document.addEventListener('visibilitychange', onVisible)\n return\n }\n onStall()\n timer = setTimeout(fire, stallMs)\n }\n timer = setTimeout(fire, stallMs)\n return () => {\n if (done) return\n done = true\n clearTimeout(timer)\n if (onVisible && typeof document !== 'undefined') {\n document.removeEventListener('visibilitychange', onVisible)\n }\n }\n}\n"],"names":["disableNetwork","enableNetwork","browserLeaseCheckFor","browserWedgeEscalationFor","FIRESTORE_STALL_MS","STALL_RECOVERY_COOLDOWN_MS","STALL_RECOVERY_MAX_COOLDOWN_MS","NETWORK_STEP_TIMEOUT_MS","browserOnline","navigator","onLine","documentVisible","document","visibilityState","createStallRecovery","deps","disable","enable","isOnline","isVisible","now","Date","lastServerAnswerAt","answeringWindowMs","cooldownMs","stepTimeoutMs","checkLease","escalate","lastStartedAt","quietCycles","lastWaitCheckedAt","running","bounded","step","Promise","resolve","timer","setTimeout","done","ok","clearTimeout","then","escalated","cycle","outcome","answeredWithin","at","answeredAt","undefined","attempt","lease","state","checkedAt","answeredSince","recover","cooldown","Math","min","finally","recoveries","WeakMap","serverAnswers","noteFirestoreServerAnswer","firestore","set","firestoreHasServerAnswered","Boolean","has","recoverStalledFirestore","recovery","get","catch","armFirestoreStallWatch","options","stallMs","onStall","onVisible","fire","removeEventListener","addEventListener"],"mappings":"AAAA;;;;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A,OAAOA,SAASf,OAAO,GAAGiB,KAAK,CAAC,IAAM;AACxC;AAEA;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,uBACdT,SAAuC,EACvCU,UAAsD,CAAC,CAAC;QAItDA;IAFF,MAAM,EAAEC,UAAUtE,kBAAkB,EAAE,GAAGqE;IACzC,MAAME,WACJF,mBAAAA,QAAQE,OAAO,YAAfF,mBAAoB,IAAM,KAAKL,wBAAwBL;IACzD,IAAIzB,OAAO;IACX,IAAIF;IACJ,IAAIwC;IACJ,MAAMC,OAAO;QACX,IAAIvC,MAAM;QACV,IAAI,CAAC3B,qBAAqB,OAAOC,aAAa,aAAa;YACzDgE,YAAY;gBACV,IAAI,CAACjE,mBAAmB;gBACxBC,SAASkE,mBAAmB,CAAC,oBAAoBF;gBACjDA,YAAY5B;gBACZ6B;YACF;YACAjE,SAASmE,gBAAgB,CAAC,oBAAoBH;YAC9C;QACF;QACAD;QACAvC,QAAQC,WAAWwC,MAAMH;IAC3B;IACAtC,QAAQC,WAAWwC,MAAMH;IACzB,OAAO;QACL,IAAIpC,MAAM;QACVA,OAAO;QACPE,aAAaJ;QACb,IAAIwC,aAAa,OAAOhE,aAAa,aAAa;YAChDA,SAASkE,mBAAmB,CAAC,oBAAoBF;QACnD;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/firebase/firestore-stall-recovery.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n disableNetwork,\n enableNetwork,\n type Firestore,\n} from 'firebase/firestore'\n\nimport {\n browserLeaseCheckFor,\n browserWedgeEscalationFor,\n type LeaseCheck,\n} from './firestore-multitab-wedge'\n\n/**\n * RECOVERING A FIRESTORE CLIENT THAT HAS STOPPED SYNCING (AGL-3373).\n *\n * ## The wedge\n *\n * The console runs the persistent cache with `persistentMultipleTabManager`\n * (`firestore-cache.ts`). Only the PRIMARY tab talks to the backend; every\n * other tab reads the shared IndexedDB cache and takes its online state from\n * a `localStorage` record the primary writes. A secondary that believes the\n * client is online answers a `getDocs` only once the primary has synced the\n * query, and raises no first snapshot for a listener whose cache is empty.\n *\n * When the primary dies without handing over — a crashed, discarded or\n * frozen tab — its \"Online\" record outlives it, and until some tab runs the\n * lease election and wins, nothing syncs. The election runs on a 4-second\n * timer inside each tab, which the browser throttles to about once a minute\n * in a hidden tab. On 2026-09-28 no live tab synced for about ten minutes:\n * the notifications page never left its loading state and a staff page sat\n * on its splash until a fresh tab (which wins the election on start) was\n * opened.\n *\n * ## The recovery, and why it is this one\n *\n * `disableNetwork` then `enableNetwork`, from the tab that noticed. Both are\n * public API, and in the multi-tab client each one calls\n * `setNetworkEnabled`, which schedules the lease election for IMMEDIATE\n * execution instead of the next (possibly throttled) timer tick. A visible\n * tab that finds the lease lapsed takes it, starts its own streams and\n * writes its own online state, which replaces the dead tab's. A tab that was\n * already primary with a silently dead stream gets fresh streams.\n *\n * Nothing is lost. Writes made meanwhile sit in the mutation queue (in\n * IndexedDB, under the persistent cache) and are sent when the network comes\n * back; the SDK's own contract for `disableNetwork` is that writes queue.\n *\n * The rejected alternatives:\n *\n * - **Clearing the persistence cache** (`terminate` + `clearIndexedDbPersistence`).\n * It deletes the mutation queue, so pending writes are lost, and\n * `waitForPendingWrites` cannot drain them first because draining is the\n * very thing that is stuck. It also refuses to run while any other tab\n * holds the database, which in a multi-tab wedge is always. And\n * `terminate` invalidates the one `Firestore` instance every hook in the\n * console holds.\n * - **Pruning the dead tab's online-state record at startup**, beside the\n * AGL-2845 prune. The SDK already ignores an online-state record at\n * startup unless its writer is an active, non-zombie client\n * (`WebStorageSharedClientState.handleOnlineStateEvent`), and a freshly\n * started tab wins the election anyway — which is why a fresh tab fixed\n * the incident. The tabs that stayed stuck were the ones ALREADY running,\n * which a startup prune never reaches.\n * - **`persistentSingleTabManager`.** It removes cross-tab dependency, but\n * every tab after the first falls back to a memory cache, so writes made\n * offline in those tabs are lost when they close. And a tab still on the\n * multi-tab build that meets a single-tab lease holder fails its queue\n * with `failed-precondition` until reloaded, so the rollout itself would\n * wedge the tabs left open across it.\n *\n * ## Guards\n *\n * - **Online only.** A browser that reports no network is correctly offline,\n * and the cache answering is the cache doing its job.\n * - **Visible only.** A hidden tab's timers are throttled and its reader is\n * not waiting; if it is stalled, it recovers the moment it is looked at.\n * - **Once per {@link STALL_RECOVERY_COOLDOWN_MS} per client.** Every list on\n * a page stalls together, and one cycle serves them all. A concurrent\n * request shares the cycle already running.\n * - **A client the server is answering is not stalled (AGL-4120).** See below.\n * - **Nor is one waiting on the shared cache, or served by a live lease\n * holder (AGL-4135).** See below.\n * - **The network is always re-enabled**, including when disabling fails.\n * - **Each step is bounded by {@link NETWORK_STEP_TIMEOUT_MS}.** Both calls are\n * queued on the client's AsyncQueue, and when another tab has locked the\n * shared IndexedDB they queue behind an operation that never finishes\n * (AGL-3428). Unbounded, the first such cycle never settled, and every\n * later recovery request shared it forever.\n *\n * ## The cycle is not free, so it needs a silent client (AGL-4120)\n *\n * A stall watch knows one thing: ITS listener has not been confirmed. That used\n * to be enough to cycle, so one slow listener among thirty-five took the whole\n * client off the network, and the cycle did real damage to one that was working.\n * `disableNetwork` makes a primary ineligible for its own lease\n * (`canActAsPrimary`), so it hands the lease over, to a hidden tab if one is\n * waiting: captured in production as `NET-OFF, LEASE-RELEASE, NET-ON`. And while\n * the network is off, every view in a primary goes Offline, so every listener the\n * server had already confirmed reads `fromCache` again until it is confirmed a\n * second time. A contact page read server-confirmed at 9 s and unconfirmed from\n * 14 s to past a minute, on a page nobody touched, refusing every save on it. A\n * slow page was turned into a broken one by the code meant to rescue it.\n *\n * So every server-confirmed snapshot stamps the client\n * ({@link noteFirestoreServerAnswer}), and a recovery within\n * {@link FIRESTORE_STALL_MS} of one answers `'answering'` and does nothing. A\n * client that is working through a page is left to finish. One that has really\n * gone silent stops stamping, and the next watch to fire gets its cycle.\n *\n * ## A client that is waiting is not silent either (AGL-4135)\n *\n * A client can go 8 s without an answer while nothing is wrong with it. Every\n * console tab shares one IndexedDB cache, and every SDK transaction locks every\n * store. A tab that is starved (busy, slow, throttled in the background) keeps\n * each transaction open until its event loop comes back between requests, for\n * seconds at a time. A healthy tab's client waits behind that lock and cannot\n * apply what the server sends, so it raises no confirmed snapshot. Measured in\n * production (v1.5.0, two tabs): the tab holding the lease was blocked for\n * about 12 s, and when its queue drained the cycle it had asked for ran, broadcast\n * `Offline` and put every confirmed view in both tabs back on the cache, the\n * record being saved included. The cycle cannot shorten another tab's\n * transaction, because both of its calls queue behind it.\n *\n * And a client in a tab that does not hold the lease is served by the tab that\n * does. Cycling it cannot reach the holder's stream. It only marks this tab\n * `networkEnabled: false` and reruns an election the live holder wins\n * (`networkEnabled: false` at 5.7 s in the AGL-4132 run).\n *\n * So before a cycle, the client reads the lease ({@link StallRecoveryDeps.checkLease}):\n *\n * - **the read waits** (`waiting`): a transaction holds the store. No cycle.\n * The wedge check below runs in its place, since a store that stays locked is\n * the AGL-3428 wedge whether or not a cycle ran first.\n * - **another tab holds a live lease** (`served`): no cycle. The holder is\n * slow, and nothing this tab does makes it faster.\n * - **anything else** (`silent`): this tab holds the lease and its stream has\n * gone quiet, or the lease has lapsed or is vacant and an election is due.\n * That is what the cycle is for, and it runs.\n *\n * The read takes up to a second (`LEASE_PROMPT_READ_MS`), so the client is\n * asked again afterwards whether the server has answered meanwhile.\n *\n * ## When the cycle is not enough (AGL-3428)\n *\n * A tab frozen partway through an IndexedDB transaction holds every store the\n * SDK uses, and the election the cycle forces cannot run. For a client on the\n * durable multi-tab cache the cycle is followed by the lease check in\n * `firestore-multitab-wedge.ts`, which moves the tab to a memory cache when\n * the lease shows the wedge. A client found `waiting` gets that check without\n * the cycle.\n */\n\n/**\n * How long a server read or a listener's first server-confirmed snapshot may\n * take before the client is treated as stalled. A healthy console answers\n * in well under two seconds; this leaves room for a slow network without\n * leaving a reader on a spinner for long.\n */\nexport const FIRESTORE_STALL_MS = 8_000\n\n/** The least time between two recoveries of the same client. */\nexport const STALL_RECOVERY_COOLDOWN_MS = 30_000\n\n/**\n * The longest the wait between two cycles grows to, on a client that cycling is\n * not bringing back. Doubling, so that a connection too slow to answer inside\n * one cooldown is not restarted before it can.\n */\nexport const STALL_RECOVERY_MAX_COOLDOWN_MS = 5 * 60_000\n\n/**\n * The longest `disableNetwork` or `enableNetwork` may take. Both finish in\n * milliseconds on a client whose queue is moving.\n */\nexport const NETWORK_STEP_TIMEOUT_MS = 5_000\n\n/** What a recovery request did. */\nexport type StallRecoveryOutcome =\n /** The browser reports no network: the cache is the right answer. */\n | 'offline'\n /** The tab is hidden: nobody is waiting on it. */\n | 'hidden'\n /** A recovery ran moments ago; this request rode on it. */\n | 'cooling'\n /** The server answered this client moments ago: it is busy, not stalled. */\n | 'answering'\n /** A transaction holds the shared cache, and this client is queued behind it (AGL-4135). */\n | 'waiting'\n /** Another tab holds a live lease and serves this client (AGL-4135). */\n | 'served'\n /** The network was cycled. */\n | 'recovered'\n /** The cycle threw or timed out; the network was still re-enabled if at all possible. */\n | 'failed'\n /** The multi-tab cache was wedged and this tab is moving to the memory cache. */\n | 'fell-back'\n\nexport interface StallRecoveryDeps {\n /** Take the client off the network. */\n disable: () => Promise<void>\n /** Put it back. */\n enable: () => Promise<void>\n /** `navigator.onLine`, or `true` where there is no navigator. */\n isOnline?: () => boolean\n /** Whether the document is visible, or `true` where there is none. */\n isVisible?: () => boolean\n now?: () => number\n /**\n * When the server last confirmed anything for this client, or `undefined`\n * if it has not. Without one, every stall is taken at its word.\n */\n lastServerAnswerAt?: () => number | undefined\n /** How recent an answer proves the client is alive. */\n answeringWindowMs?: number\n cooldownMs?: number\n /** The bound on each of `disable` and `enable`. */\n stepTimeoutMs?: number\n /**\n * Reads the shared cache's lease before a cycle (AGL-4135). Only a multi-tab\n * client has one; without it, every stall that passes the other guards is\n * cycled.\n */\n checkLease?: () => Promise<LeaseCheck>\n /**\n * The wedge check. Runs after every cycle, and in place of one for a client\n * found `waiting`. Resolves `true` when it has moved the tab off the shared\n * cache. Only a multi-tab client has one.\n */\n escalate?: () => Promise<boolean>\n}\n\nexport interface StallRecovery {\n recover: () => Promise<StallRecoveryOutcome>\n}\n\nconst browserOnline = () =>\n typeof navigator === 'undefined' || navigator.onLine !== false\n\nconst documentVisible = () =>\n typeof document === 'undefined' || document.visibilityState !== 'hidden'\n\n/** The recovery for one client, with its guards. Pure over `deps`. */\nexport function createStallRecovery(deps: StallRecoveryDeps): StallRecovery {\n const {\n disable,\n enable,\n isOnline = browserOnline,\n isVisible = documentVisible,\n now = Date.now,\n lastServerAnswerAt,\n answeringWindowMs = FIRESTORE_STALL_MS,\n cooldownMs = STALL_RECOVERY_COOLDOWN_MS,\n stepTimeoutMs = NETWORK_STEP_TIMEOUT_MS,\n checkLease,\n escalate,\n } = deps\n let lastStartedAt: number | undefined\n /** Cycles in a row that the server has not answered since. */\n let quietCycles = 0\n /** When a client found waiting last had the wedge check (AGL-4135). */\n let lastWaitCheckedAt: number | undefined\n let running: Promise<StallRecoveryOutcome> | undefined\n\n /** Whether `step` settled successfully within `stepTimeoutMs`. */\n const bounded = (step: () => Promise<void>): Promise<boolean> =>\n new Promise((resolve) => {\n const timer = setTimeout(() => resolve(false), stepTimeoutMs)\n const done = (ok: boolean) => {\n clearTimeout(timer)\n resolve(ok)\n }\n try {\n step().then(\n () => done(true),\n () => done(false),\n )\n } catch {\n done(false)\n }\n })\n\n /** Whether the escalation moved the tab off the shared cache. Best effort. */\n const escalated = async (): Promise<boolean> => {\n if (!escalate) return false\n try {\n return await escalate()\n } catch {\n return false\n }\n }\n\n const cycle = async (): Promise<StallRecoveryOutcome> => {\n let outcome: StallRecoveryOutcome = 'recovered'\n if (!(await bounded(disable))) outcome = 'failed'\n if (!(await bounded(enable))) outcome = 'failed'\n // The escalation is best effort; the cycle's own outcome stands.\n return (await escalated()) ? 'fell-back' : outcome\n }\n\n const answeredWithin = (at: number): boolean => {\n const answeredAt = lastServerAnswerAt?.()\n return answeredAt !== undefined && at - answeredAt < answeringWindowMs\n }\n\n /** Past the guards: reads the lease, then cycles only a client nothing explains. */\n const attempt = async (): Promise<StallRecoveryOutcome> => {\n let lease: LeaseCheck = { state: 'silent' }\n if (checkLease) {\n try {\n lease = await checkLease()\n } catch {\n // Unread, the stall is taken at its word, as it always was.\n }\n }\n if (lease.state === 'served') return 'served'\n if (lease.state === 'waiting') {\n // As often as a cycle would have run it, and no more: every check is\n // one more chance for a long wait to read as a wedge.\n const checkedAt = now()\n if (\n lastWaitCheckedAt !== undefined &&\n checkedAt - lastWaitCheckedAt < cooldownMs\n ) {\n return 'waiting'\n }\n lastWaitCheckedAt = checkedAt\n return (await escalated()) ? 'fell-back' : 'waiting'\n }\n // The read took time, and a client that was waiting may have answered.\n const at = now()\n if (answeredWithin(at)) return 'answering'\n if (lastStartedAt !== undefined) {\n const answeredAt = lastServerAnswerAt?.()\n const answeredSince =\n answeredAt !== undefined && answeredAt >= lastStartedAt\n quietCycles = answeredSince ? 0 : quietCycles + 1\n }\n lastStartedAt = at\n return cycle()\n }\n\n return {\n recover: () => {\n if (running) return running\n if (!isOnline()) return Promise.resolve('offline')\n if (!isVisible()) return Promise.resolve('hidden')\n const at = now()\n if (answeredWithin(at)) return Promise.resolve('answering')\n if (lastStartedAt !== undefined) {\n const cooldown = Math.min(\n cooldownMs * 2 ** quietCycles,\n STALL_RECOVERY_MAX_COOLDOWN_MS,\n )\n if (at - lastStartedAt < cooldown) return Promise.resolve('cooling')\n }\n running = attempt().finally(() => {\n running = undefined\n })\n return running\n },\n }\n}\n\nconst recoveries = new WeakMap<Firestore, StallRecovery>()\n\n/** When the server last confirmed a snapshot for each client. */\nconst serverAnswers = new WeakMap<Firestore, number>()\n\n/**\n * Records that the server just confirmed something for `firestore`: the\n * evidence a stall watch does not have that this client is alive. Every listener\n * that arms a watch calls this on a server-confirmed snapshot.\n */\nexport function noteFirestoreServerAnswer(\n firestore: Firestore | null | undefined,\n): void {\n if (firestore && typeof firestore === 'object') {\n serverAnswers.set(firestore, Date.now())\n }\n}\n\n/**\n * Whether the server has confirmed anything for `firestore` in this tab: the\n * boot check's line between a tab still booting and one in use (AGL-4201).\n */\nexport function firestoreHasServerAnswered(\n firestore: Firestore | null | undefined,\n): boolean {\n return Boolean(\n firestore && typeof firestore === 'object' && serverAnswers.has(firestore),\n )\n}\n\n/**\n * When the server last confirmed anything for `firestore` in this tab, or\n * `undefined` if it has not: the page check's line between a page still\n * loading and one the server has reached (AGL-4204).\n */\nexport function firestoreLastServerAnswerAt(\n firestore: Firestore | null | undefined,\n): number | undefined {\n return firestore && typeof firestore === 'object'\n ? serverAnswers.get(firestore)\n : undefined\n}\n\n/**\n * Recovers `firestore` if it has stalled. Safe to call from every reader\n * that notices: the guards above collapse the calls into at most one network\n * cycle per cooldown. Never rejects.\n */\nexport function recoverStalledFirestore(\n firestore: Firestore | null | undefined,\n): Promise<StallRecoveryOutcome> {\n if (!firestore || typeof firestore !== 'object') {\n return Promise.resolve('failed')\n }\n let recovery = recoveries.get(firestore)\n if (!recovery) {\n recovery = createStallRecovery({\n disable: () => disableNetwork(firestore),\n enable: () => enableNetwork(firestore),\n lastServerAnswerAt: () => serverAnswers.get(firestore),\n checkLease: browserLeaseCheckFor(firestore),\n escalate: browserWedgeEscalationFor(firestore),\n })\n recoveries.set(firestore, recovery)\n }\n return recovery.recover().catch(() => 'failed' as const)\n}\n\n/**\n * Arms a stall timer for one read or listen. Until `disarm` is called, `onStall`\n * runs (by default, {@link recoverStalledFirestore}) every `stallMs`. A tab that\n * is hidden when the timer fires waits until it is shown, since that is when a\n * reader is waiting again.\n *\n * It keeps firing because one call can do nothing: the request may land inside\n * a cooldown, or on a client that is still answering. A watch that spent itself\n * there left its listener unconfirmed for life (AGL-4120), which is how a tab's\n * first page worked and a later page's saves were refused. The calls cost nothing\n * until one of them finds a client that really needs a cycle.\n *\n * Returns `disarm`, which is idempotent.\n */\nexport function armFirestoreStallWatch(\n firestore: Firestore | null | undefined,\n options: { stallMs?: number; onStall?: () => void } = {},\n): () => void {\n const { stallMs = FIRESTORE_STALL_MS } = options\n const onStall =\n options.onStall ?? (() => void recoverStalledFirestore(firestore))\n let done = false\n let timer: ReturnType<typeof setTimeout> | undefined\n let onVisible: (() => void) | undefined\n const fire = () => {\n if (done) return\n if (!documentVisible() && typeof document !== 'undefined') {\n onVisible = () => {\n if (!documentVisible()) return\n document.removeEventListener('visibilitychange', onVisible!)\n onVisible = undefined\n fire()\n }\n document.addEventListener('visibilitychange', onVisible)\n return\n }\n onStall()\n timer = setTimeout(fire, stallMs)\n }\n timer = setTimeout(fire, stallMs)\n return () => {\n if (done) return\n done = true\n clearTimeout(timer)\n if (onVisible && typeof document !== 'undefined') {\n document.removeEventListener('visibilitychange', onVisible)\n }\n }\n}\n"],"names":["disableNetwork","enableNetwork","browserLeaseCheckFor","browserWedgeEscalationFor","FIRESTORE_STALL_MS","STALL_RECOVERY_COOLDOWN_MS","STALL_RECOVERY_MAX_COOLDOWN_MS","NETWORK_STEP_TIMEOUT_MS","browserOnline","navigator","onLine","documentVisible","document","visibilityState","createStallRecovery","deps","disable","enable","isOnline","isVisible","now","Date","lastServerAnswerAt","answeringWindowMs","cooldownMs","stepTimeoutMs","checkLease","escalate","lastStartedAt","quietCycles","lastWaitCheckedAt","running","bounded","step","Promise","resolve","timer","setTimeout","done","ok","clearTimeout","then","escalated","cycle","outcome","answeredWithin","at","answeredAt","undefined","attempt","lease","state","checkedAt","answeredSince","recover","cooldown","Math","min","finally","recoveries","WeakMap","serverAnswers","noteFirestoreServerAnswer","firestore","set","firestoreHasServerAnswered","Boolean","has","firestoreLastServerAnswerAt","get","recoverStalledFirestore","recovery","catch","armFirestoreStallWatch","options","stallMs","onStall","onVisible","fire","removeEventListener","addEventListener"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,cAAc,EACdC,aAAa,QAER,qBAAoB;AAE3B,SACEC,oBAAoB,EACpBC,yBAAyB,QAEpB,gCAA4B;AAEnC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0IC,GAED;;;;;CAKC,GACD,OAAO,MAAMC,qBAAqB,KAAK;AAEvC,8DAA8D,GAC9D,OAAO,MAAMC,6BAA6B,MAAM;AAEhD;;;;CAIC,GACD,OAAO,MAAMC,iCAAiC,IAAI,MAAM;AAExD;;;CAGC,GACD,OAAO,MAAMC,0BAA0B,KAAK;AA6D5C,MAAMC,gBAAgB,IACpB,OAAOC,cAAc,eAAeA,UAAUC,MAAM,KAAK;AAE3D,MAAMC,kBAAkB,IACtB,OAAOC,aAAa,eAAeA,SAASC,eAAe,KAAK;AAElE,oEAAoE,GACpE,OAAO,SAASC,oBAAoBC,IAAuB;IACzD,MAAM,EACJC,OAAO,EACPC,MAAM,EACNC,WAAWV,aAAa,EACxBW,YAAYR,eAAe,EAC3BS,MAAMC,KAAKD,GAAG,EACdE,kBAAkB,EAClBC,oBAAoBnB,kBAAkB,EACtCoB,aAAanB,0BAA0B,EACvCoB,gBAAgBlB,uBAAuB,EACvCmB,UAAU,EACVC,QAAQ,EACT,GAAGZ;IACJ,IAAIa;IACJ,4DAA4D,GAC5D,IAAIC,cAAc;IAClB,qEAAqE,GACrE,IAAIC;IACJ,IAAIC;IAEJ,gEAAgE,GAChE,MAAMC,UAAU,CAACC,OACf,IAAIC,QAAQ,CAACC;YACX,MAAMC,QAAQC,WAAW,IAAMF,QAAQ,QA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QACbA,WAAWzD,oBAAoB;YAC7BE,SAAS,IAAMhB,eAAe+D;YAC9B9C,QAAQ,IAAMhB,cAAc8D;YAC5BzC,oBAAoB,IAAMuC,cAAcQ,GAAG,CAACN;YAC5CrC,YAAYxB,qBAAqB6D;YACjCpC,UAAUxB,0BAA0B4D;QACtC;QACAJ,WAAWK,GAAG,CAACD,WAAWQ;IAC5B;IACA,OAAOA,SAASjB,OAAO,GAAGkB,KAAK,CAAC,IAAM;AACxC;AAEA;;;;;;;;;;;;;CAaC,GACD,OAAO,SAASC,uBACdV,SAAuC,EACvCW,UAAsD,CAAC,CAAC;QAItDA;IAFF,MAAM,EAAEC,UAAUvE,kBAAkB,EAAE,GAAGsE;IACzC,MAAME,WACJF,mBAAAA,QAAQE,OAAO,YAAfF,mBAAoB,IAAM,KAAKJ,wBAAwBP;IACzD,IAAIzB,OAAO;IACX,IAAIF;IACJ,IAAIyC;IACJ,MAAMC,OAAO;QACX,IAAIxC,MAAM;QACV,IAAI,CAAC3B,qBAAqB,OAAOC,aAAa,aAAa;YACzDiE,YAAY;gBACV,IAAI,CAAClE,mBAAmB;gBACxBC,SAASmE,mBAAmB,CAAC,oBAAoBF;gBACjDA,YAAY7B;gBACZ8B;YACF;YACAlE,SAASoE,gBAAgB,CAAC,oBAAoBH;YAC9C;QACF;QACAD;QACAxC,QAAQC,WAAWyC,MAAMH;IAC3B;IACAvC,QAAQC,WAAWyC,MAAMH;IACzB,OAAO;QACL,IAAIrC,MAAM;QACVA,OAAO;QACPE,aAAaJ;QACb,IAAIyC,aAAa,OAAOjE,aAAa,aAAa;YAChDA,SAASmE,mBAAmB,CAAC,oBAAoBF;QACnD;IACF;AACF"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* A DIALOG'S DRAFT OF A ROW, KEPT AS EDITS OVER THE LIVE ROW (AGL-4047).
|
|
19
|
+
*
|
|
20
|
+
* {@link useSeedEdits} for the editor that opens on one row of a list: an
|
|
21
|
+
* Edit dialog, a drawer. Those used to copy the row into a
|
|
22
|
+
* `useState<Draft | null>` when they opened, which is the copy the hold in
|
|
23
|
+
* `use-seed-edits` warns about: opened from the cache's row, a Save held
|
|
24
|
+
* until the server answered would then write the cache's values for every
|
|
25
|
+
* field nobody touched.
|
|
26
|
+
*
|
|
27
|
+
* This is a drop-in for that `useState`. `setDraft(row)` opens the editor on
|
|
28
|
+
* a row, `setDraft(null)` closes it, and while it is open every
|
|
29
|
+
* `setDraft({ ...draft, name })` records only the keys that moved, as edits.
|
|
30
|
+
* The draft shown is `live(opened)` (the same row as the list has it NOW)
|
|
31
|
+
* with those edits on top, so the server's copy replaces the cache's under
|
|
32
|
+
* everything the person did not change.
|
|
33
|
+
*/
|
|
34
|
+
import { type Dispatch, type SetStateAction } from 'react';
|
|
35
|
+
import { type SeedEdits } from './use-seed-edits';
|
|
36
|
+
/**
|
|
37
|
+
* The keys of `next` that differ from `values`, as an edit: for an editor
|
|
38
|
+
* that builds its whole next draft, to hand `useSeedEdits`' `edit` only what
|
|
39
|
+
* moved, so every other key keeps following the seed.
|
|
40
|
+
*/
|
|
41
|
+
export declare function seedEditsBetween<T extends object>(values: T, next: T): Partial<T>;
|
|
42
|
+
/**
|
|
43
|
+
* @param live The opened row as the list has it now, in the draft's shape,
|
|
44
|
+
* or `undefined` when the list no longer holds it (a new row, or one
|
|
45
|
+
* paged out of the window). Undefined keeps the row as it was opened.
|
|
46
|
+
* @returns `[draft, setDraft, form]`: the first two exactly as
|
|
47
|
+
* `useState<T | null>(null)` gives them, and the edits underneath.
|
|
48
|
+
*/
|
|
49
|
+
export declare function useSeedDraft<T extends object>(live: (opened: T) => T | undefined): [T | null, Dispatch<SetStateAction<T | null>>, SeedEdits<T>];
|
|
50
|
+
export default useSeedDraft;
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ 'use client';
|
|
17
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
18
|
+
/**
|
|
19
|
+
* A DIALOG'S DRAFT OF A ROW, KEPT AS EDITS OVER THE LIVE ROW (AGL-4047).
|
|
20
|
+
*
|
|
21
|
+
* {@link useSeedEdits} for the editor that opens on one row of a list: an
|
|
22
|
+
* Edit dialog, a drawer. Those used to copy the row into a
|
|
23
|
+
* `useState<Draft | null>` when they opened, which is the copy the hold in
|
|
24
|
+
* `use-seed-edits` warns about: opened from the cache's row, a Save held
|
|
25
|
+
* until the server answered would then write the cache's values for every
|
|
26
|
+
* field nobody touched.
|
|
27
|
+
*
|
|
28
|
+
* This is a drop-in for that `useState`. `setDraft(row)` opens the editor on
|
|
29
|
+
* a row, `setDraft(null)` closes it, and while it is open every
|
|
30
|
+
* `setDraft({ ...draft, name })` records only the keys that moved, as edits.
|
|
31
|
+
* The draft shown is `live(opened)` (the same row as the list has it NOW)
|
|
32
|
+
* with those edits on top, so the server's copy replaces the cache's under
|
|
33
|
+
* everything the person did not change.
|
|
34
|
+
*/ import { useCallback, useRef, useState } from "react";
|
|
35
|
+
import { useSeedEdits } from "./use-seed-edits.js";
|
|
36
|
+
const CLOSED = Object.freeze({});
|
|
37
|
+
function keyOf(seed) {
|
|
38
|
+
try {
|
|
39
|
+
var _JSON_stringify;
|
|
40
|
+
return (_JSON_stringify = JSON.stringify(seed)) != null ? _JSON_stringify : '';
|
|
41
|
+
} catch (unused) {
|
|
42
|
+
return '';
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The keys of `next` that differ from `values`, as an edit: for an editor
|
|
47
|
+
* that builds its whole next draft, to hand `useSeedEdits`' `edit` only what
|
|
48
|
+
* moved, so every other key keeps following the seed.
|
|
49
|
+
*/ export function seedEditsBetween(values, next) {
|
|
50
|
+
const patch = {};
|
|
51
|
+
const keys = new Set([
|
|
52
|
+
...Object.keys(values),
|
|
53
|
+
...Object.keys(next)
|
|
54
|
+
]);
|
|
55
|
+
for (const key of keys){
|
|
56
|
+
if (!Object.is(values[key], next[key])) patch[key] = next[key];
|
|
57
|
+
}
|
|
58
|
+
return patch;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* @param live The opened row as the list has it now, in the draft's shape,
|
|
62
|
+
* or `undefined` when the list no longer holds it (a new row, or one
|
|
63
|
+
* paged out of the window). Undefined keeps the row as it was opened.
|
|
64
|
+
* @returns `[draft, setDraft, form]`: the first two exactly as
|
|
65
|
+
* `useState<T | null>(null)` gives them, and the edits underneath.
|
|
66
|
+
*/ export function useSeedDraft(live) {
|
|
67
|
+
var _live;
|
|
68
|
+
const [opened, setOpened] = useState(null);
|
|
69
|
+
const fresh = opened ? (_live = live(opened)) != null ? _live : opened : CLOSED;
|
|
70
|
+
/*
|
|
71
|
+
* `live` builds a new object on every render. Kept while it says the same
|
|
72
|
+
* thing, so the draft handed to a memoized editor keeps its identity until
|
|
73
|
+
* a keystroke or the server actually changes it.
|
|
74
|
+
*/ const stable = useRef(null);
|
|
75
|
+
const freshKey = keyOf(fresh);
|
|
76
|
+
// A row that cannot be written as JSON is never taken for unchanged.
|
|
77
|
+
if (!stable.current || !freshKey || stable.current.key !== freshKey) {
|
|
78
|
+
stable.current = {
|
|
79
|
+
key: freshKey,
|
|
80
|
+
seed: fresh
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
const seed = stable.current.seed;
|
|
84
|
+
const form = useSeedEdits(seed);
|
|
85
|
+
const draft = opened ? form.values : null;
|
|
86
|
+
/*
|
|
87
|
+
* What the draft is as of the last call, so two calls in one handler (and
|
|
88
|
+
* the updater form) each build on the one before rather than on the
|
|
89
|
+
* render's copy.
|
|
90
|
+
*/ const current = useRef({
|
|
91
|
+
opened,
|
|
92
|
+
draft
|
|
93
|
+
});
|
|
94
|
+
current.current = {
|
|
95
|
+
opened,
|
|
96
|
+
draft
|
|
97
|
+
};
|
|
98
|
+
const { edit, discard } = form;
|
|
99
|
+
const setDraft = useCallback((action)=>{
|
|
100
|
+
const next = typeof action === 'function' ? action(current.current.draft) : action;
|
|
101
|
+
if (next === null) {
|
|
102
|
+
current.current = {
|
|
103
|
+
opened: null,
|
|
104
|
+
draft: null
|
|
105
|
+
};
|
|
106
|
+
setOpened(null);
|
|
107
|
+
discard();
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (!current.current.opened) {
|
|
111
|
+
current.current = {
|
|
112
|
+
opened: next,
|
|
113
|
+
draft: next
|
|
114
|
+
};
|
|
115
|
+
setOpened(next);
|
|
116
|
+
discard();
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
current.current = _extends({}, current.current, {
|
|
120
|
+
draft: next
|
|
121
|
+
});
|
|
122
|
+
edit((values)=>seedEditsBetween(values, next));
|
|
123
|
+
}, [
|
|
124
|
+
edit,
|
|
125
|
+
discard
|
|
126
|
+
]);
|
|
127
|
+
return [
|
|
128
|
+
draft,
|
|
129
|
+
setDraft,
|
|
130
|
+
form
|
|
131
|
+
];
|
|
132
|
+
}
|
|
133
|
+
export default useSeedDraft;
|
|
134
|
+
|
|
135
|
+
//# sourceMappingURL=use-seed-draft.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-seed-draft.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n'use client'\n\n/**\n * A DIALOG'S DRAFT OF A ROW, KEPT AS EDITS OVER THE LIVE ROW (AGL-4047).\n *\n * {@link useSeedEdits} for the editor that opens on one row of a list: an\n * Edit dialog, a drawer. Those used to copy the row into a\n * `useState<Draft | null>` when they opened, which is the copy the hold in\n * `use-seed-edits` warns about: opened from the cache's row, a Save held\n * until the server answered would then write the cache's values for every\n * field nobody touched.\n *\n * This is a drop-in for that `useState`. `setDraft(row)` opens the editor on\n * a row, `setDraft(null)` closes it, and while it is open every\n * `setDraft({ ...draft, name })` records only the keys that moved, as edits.\n * The draft shown is `live(opened)` (the same row as the list has it NOW)\n * with those edits on top, so the server's copy replaces the cache's under\n * everything the person did not change.\n */\n\nimport {\n useCallback,\n useRef,\n useState,\n type Dispatch,\n type SetStateAction,\n} from 'react'\nimport { useSeedEdits, type SeedEdits } from './use-seed-edits'\n\nconst CLOSED = Object.freeze({}) as object\n\nfunction keyOf(seed: object): string {\n try {\n return JSON.stringify(seed) ?? ''\n } catch {\n return ''\n }\n}\n\n/**\n * The keys of `next` that differ from `values`, as an edit: for an editor\n * that builds its whole next draft, to hand `useSeedEdits`' `edit` only what\n * moved, so every other key keeps following the seed.\n */\nexport function seedEditsBetween<T extends object>(\n values: T,\n next: T,\n): Partial<T> {\n const patch: Partial<T> = {}\n const keys = new Set([\n ...Object.keys(values),\n ...Object.keys(next),\n ]) as Set<keyof T>\n for (const key of keys) {\n if (!Object.is(values[key], next[key])) patch[key] = next[key]\n }\n return patch\n}\n\n/**\n * @param live The opened row as the list has it now, in the draft's shape,\n * or `undefined` when the list no longer holds it (a new row, or one\n * paged out of the window). Undefined keeps the row as it was opened.\n * @returns `[draft, setDraft, form]`: the first two exactly as\n * `useState<T | null>(null)` gives them, and the edits underneath.\n */\nexport function useSeedDraft<T extends object>(\n live: (opened: T) => T | undefined,\n): [T | null, Dispatch<SetStateAction<T | null>>, SeedEdits<T>] {\n const [opened, setOpened] = useState<T | null>(null)\n const fresh = opened ? (live(opened) ?? opened) : (CLOSED as T)\n /*\n * `live` builds a new object on every render. Kept while it says the same\n * thing, so the draft handed to a memoized editor keeps its identity until\n * a keystroke or the server actually changes it.\n */\n const stable = useRef<{ key: string; seed: T } | null>(null)\n const freshKey = keyOf(fresh)\n // A row that cannot be written as JSON is never taken for unchanged.\n if (!stable.current || !freshKey || stable.current.key !== freshKey) {\n stable.current = { key: freshKey, seed: fresh }\n }\n const seed = stable.current.seed\n const form = useSeedEdits<T>(seed)\n const draft = opened ? form.values : null\n\n /*\n * What the draft is as of the last call, so two calls in one handler (and\n * the updater form) each build on the one before rather than on the\n * render's copy.\n */\n const current = useRef<{ opened: T | null; draft: T | null }>({\n opened,\n draft,\n })\n current.current = { opened, draft }\n\n const { edit, discard } = form\n const setDraft = useCallback<Dispatch<SetStateAction<T | null>>>(\n (action) => {\n const next =\n typeof action === 'function'\n ? (action as (previous: T | null) => T | null)(current.current.draft)\n : action\n if (next === null) {\n current.current = { opened: null, draft: null }\n setOpened(null)\n discard()\n return\n }\n if (!current.current.opened) {\n current.current = { opened: next, draft: next }\n setOpened(next)\n discard()\n return\n }\n current.current = { ...current.current, draft: next }\n edit((values) => seedEditsBetween(values, next))\n },\n [edit, discard],\n )\n\n return [draft, setDraft, form]\n}\n\nexport default useSeedDraft\n"],"names":["useCallback","useRef","useState","useSeedEdits","CLOSED","Object","freeze","keyOf","seed","JSON","stringify","seedEditsBetween","values","next","patch","keys","Set","key","is","useSeedDraft","live","opened","setOpened","fresh","stable","freshKey","current","form","draft","edit","discard","setDraft","action"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;AAEA;;;;;;;;;;;;;;;;CAgBC,GAED,SACEA,WAAW,EACXC,MAAM,EACNC,QAAQ,QAGH,QAAO;AACd,SAASC,YAAY,QAAwB,sBAAkB;AAE/D,MAAMC,SAASC,OAAOC,MAAM,CAAC,CAAC;AAE9B,SAASC,MAAMC,IAAY;IACzB,IAAI;YACKC;QAAP,QAAOA,kBAAAA,KAAKC,SAAS,CAACF,iBAAfC,kBAAwB;IACjC,EAAE,eAAM;QACN,OAAO;IACT;AACF;AAEA;;;;CAIC,GACD,OAAO,SAASE,iBACdC,MAAS,EACTC,IAAO;IAEP,MAAMC,QAAoB,CAAC;IAC3B,MAAMC,OAAO,IAAIC,IAAI;WAChBX,OAAOU,IAAI,CAACH;WACZP,OAAOU,IAAI,CAACF;KAChB;IACD,KAAK,MAAMI,OAAOF,KAAM;QACtB,IAAI,CAACV,OAAOa,EAAE,CAACN,MAAM,CAACK,IAAI,EAAEJ,IAAI,CAACI,IAAI,GAAGH,KAAK,CAACG,IAAI,GAAGJ,IAAI,CAACI,IAAI;IAChE;IACA,OAAOH;AACT;AAEA;;;;;;CAMC,GACD,OAAO,SAASK,aACdC,IAAkC;QAGVA;IADxB,MAAM,CAACC,QAAQC,UAAU,GA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@@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* Whether a save seeded from this read should be HELD rather than pressed.
|
|
19
|
+
*
|
|
20
|
+
* Unconfirmed, and not failed: a failed read is left to the guard, whose
|
|
21
|
+
* refusal says the values could not be loaded, which no wait would change.
|
|
22
|
+
* The same two flags the call site hands `writeGuardedBySeed`.
|
|
23
|
+
*/
|
|
24
|
+
export declare function isSeedChecking(read: {
|
|
25
|
+
fromCache?: boolean;
|
|
26
|
+
unreadable?: boolean;
|
|
27
|
+
}): boolean;
|
|
28
|
+
/**
|
|
29
|
+
* What a held Save says beside it, so a held control is never unexplained.
|
|
30
|
+
* Takes the same `subject` as the guard ("profile", "language settings") and,
|
|
31
|
+
* like the guard's refusals, reads right for a plural one (AGL-1446).
|
|
32
|
+
*/
|
|
33
|
+
export declare function seedCheckingText(subject: string): string;
|
|
34
|
+
export interface SeedEdits<T extends object> {
|
|
35
|
+
/** The seed with the person's edits on top. What the form shows and saves. */
|
|
36
|
+
values: T;
|
|
37
|
+
/**
|
|
38
|
+
* The edits in force: unsaved ones, plus the ones a save just wrote until
|
|
39
|
+
* the seed shows them. For a form whose display reads which keys were
|
|
40
|
+
* touched rather than only the merged values.
|
|
41
|
+
*/
|
|
42
|
+
edits: Partial<T>;
|
|
43
|
+
/** Something is typed that has not been saved. */
|
|
44
|
+
dirty: boolean;
|
|
45
|
+
/**
|
|
46
|
+
* Record edits. A function receives the current values, for an edit that
|
|
47
|
+
* derives from them.
|
|
48
|
+
*/
|
|
49
|
+
edit: (patch: Partial<T> | ((values: T) => Partial<T>)) => void;
|
|
50
|
+
/** Take back the edit to these keys, so they follow the seed again. */
|
|
51
|
+
revert: (...keys: (keyof T)[]) => void;
|
|
52
|
+
/**
|
|
53
|
+
* The save landed. The edits it wrote stop being unsaved, and stay applied
|
|
54
|
+
* until the seed moves, so the form never flashes back to the values before
|
|
55
|
+
* the save. Pass what the save wrote (`edits` when it began) so a key typed
|
|
56
|
+
* again while the save was in flight stays unsaved; without it, every edit
|
|
57
|
+
* in force now counts as written.
|
|
58
|
+
*/
|
|
59
|
+
settle: (written?: Partial<T>) => void;
|
|
60
|
+
/** Throw every unsaved edit away. */
|
|
61
|
+
discard: () => void;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* A form's edits, kept as edits and replayed onto the seed on every render
|
|
65
|
+
* rather than copied from it once (AGL-4047).
|
|
66
|
+
*
|
|
67
|
+
* Edits are per top-level key. A key the person never touched always shows
|
|
68
|
+
* what the seed says NOW, so a confirmation that changes it is reflected, and
|
|
69
|
+
* a save writes it; a key they did touch keeps their value through any number
|
|
70
|
+
* of snapshots.
|
|
71
|
+
*/
|
|
72
|
+
export declare function useSeedEdits<T extends object>(seed: T): SeedEdits<T>;
|
|
73
|
+
export default useSeedEdits;
|
|
74
|
+
/**
|
|
75
|
+
* The rule {@link useSeedEdits} keeps, for a form that already holds its own
|
|
76
|
+
* buffer and seeds it once (AGL-4047).
|
|
77
|
+
*
|
|
78
|
+
* A key whose value still equals what the previous seed said is UNTOUCHED, so
|
|
79
|
+
* it follows the next seed; a key the person changed keeps their value. Hand it
|
|
80
|
+
* the seed the buffer was built from, the buffer as it stands, and the seed
|
|
81
|
+
* that just arrived, and store the result with the next seed as the new
|
|
82
|
+
* baseline. Compared by content, since a snapshot rebuilds every value.
|
|
83
|
+
*/
|
|
84
|
+
export declare function rebaseSeedEdits<T extends object>(previousSeed: T, current: T, nextSeed: T): T;
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ 'use client';
|
|
17
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
18
|
+
/**
|
|
19
|
+
* A FORM SAVE IS NEVER REFUSED ON ITS FIRST PRESS JUST BECAUSE THE SERVER IS
|
|
20
|
+
* LATE (AGL-4047).
|
|
21
|
+
*
|
|
22
|
+
* `writeGuardedBySeed` waits for the server to confirm a cache-served seed
|
|
23
|
+
* before it writes (AGL-4120), and refuses with "We could not confirm your …
|
|
24
|
+
* with the server yet" when that wait runs past its deadline. Right after a
|
|
25
|
+
* page load on the shared cache the wait routinely ran past it, so the first
|
|
26
|
+
* press of Save was refused and the second, a few seconds later, saved.
|
|
27
|
+
*
|
|
28
|
+
* The fix has two halves, and a surface needs both:
|
|
29
|
+
*
|
|
30
|
+
* 1. HOLD SAVE while the seed is unconfirmed, with the reason beside it
|
|
31
|
+
* ({@link isSeedChecking}, {@link seedCheckingText}). The press then comes
|
|
32
|
+
* after the server answers, when the guard writes at once. The guard still
|
|
33
|
+
* wraps the write, for a read that falls back to the cache after the
|
|
34
|
+
* surface rendered.
|
|
35
|
+
* 2. KEEP THE EDITS AS EDITS ({@link useSeedEdits}), replayed onto whatever the
|
|
36
|
+
* seed is now. Without this, holding Save is a trap: a form that copied the
|
|
37
|
+
* cached values into its own state when they arrived would, once the server
|
|
38
|
+
* confirmed different ones, save the cached values for every field the
|
|
39
|
+
* person never touched, which is the loss the guard exists to stop. A form
|
|
40
|
+
* that reset itself on every snapshot would instead drop what was typed.
|
|
41
|
+
*
|
|
42
|
+
* Forms on `final-form` get the second half from `keepDirtyOnReinitialize`,
|
|
43
|
+
* which is the same rule: a field the person changed keeps their value, every
|
|
44
|
+
* other field follows the new seed.
|
|
45
|
+
*
|
|
46
|
+
* First built for a site's Admin › Plugins (#2552); this is that pattern
|
|
47
|
+
* lifted so every guarded form can share it.
|
|
48
|
+
*/ import { useCallback, useMemo, useRef, useState } from "react";
|
|
49
|
+
/**
|
|
50
|
+
* Whether a save seeded from this read should be HELD rather than pressed.
|
|
51
|
+
*
|
|
52
|
+
* Unconfirmed, and not failed: a failed read is left to the guard, whose
|
|
53
|
+
* refusal says the values could not be loaded, which no wait would change.
|
|
54
|
+
* The same two flags the call site hands `writeGuardedBySeed`.
|
|
55
|
+
*/ export function isSeedChecking(read) {
|
|
56
|
+
return Boolean(read.fromCache) && !read.unreadable;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* What a held Save says beside it, so a held control is never unexplained.
|
|
60
|
+
* Takes the same `subject` as the guard ("profile", "language settings") and,
|
|
61
|
+
* like the guard's refusals, reads right for a plural one (AGL-1446).
|
|
62
|
+
*/ export function seedCheckingText(subject) {
|
|
63
|
+
return `Checking your ${subject} with the server…`;
|
|
64
|
+
}
|
|
65
|
+
function seedKeyOf(seed) {
|
|
66
|
+
try {
|
|
67
|
+
var _JSON_stringify;
|
|
68
|
+
return (_JSON_stringify = JSON.stringify(seed)) != null ? _JSON_stringify : '';
|
|
69
|
+
} catch (unused) {
|
|
70
|
+
return '';
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* A form's edits, kept as edits and replayed onto the seed on every render
|
|
75
|
+
* rather than copied from it once (AGL-4047).
|
|
76
|
+
*
|
|
77
|
+
* Edits are per top-level key. A key the person never touched always shows
|
|
78
|
+
* what the seed says NOW, so a confirmation that changes it is reflected, and
|
|
79
|
+
* a save writes it; a key they did touch keeps their value through any number
|
|
80
|
+
* of snapshots.
|
|
81
|
+
*/ export function useSeedEdits(seed) {
|
|
82
|
+
const [edits, setEdits] = useState({});
|
|
83
|
+
/**
|
|
84
|
+
* What a save just wrote, held against the seed it was written over. The
|
|
85
|
+
* seed normally moves at once, because a local write reaches the cache
|
|
86
|
+
* before the server acknowledges it; this covers the case where it has not.
|
|
87
|
+
*/ const [saved, setSaved] = useState(null);
|
|
88
|
+
const seedKey = seedKeyOf(seed);
|
|
89
|
+
// Dropped the moment the seed moves, so a later change back to the values
|
|
90
|
+
// as they stood before the save is shown as it is, not hidden behind it.
|
|
91
|
+
if (saved && saved.key !== seedKey) setSaved(null);
|
|
92
|
+
const applied = useMemo(()=>saved && saved.key === seedKey ? _extends({}, saved.edits, edits) : edits, [
|
|
93
|
+
saved,
|
|
94
|
+
seedKey,
|
|
95
|
+
edits
|
|
96
|
+
]);
|
|
97
|
+
const values = useMemo(()=>_extends({}, seed, applied), [
|
|
98
|
+
seed,
|
|
99
|
+
applied
|
|
100
|
+
]);
|
|
101
|
+
// Read by `edit`'s updater form and `settle`, which must see what is on
|
|
102
|
+
// screen at the call without re-creating the callbacks on every keystroke.
|
|
103
|
+
const latest = useRef({
|
|
104
|
+
seed,
|
|
105
|
+
seedKey,
|
|
106
|
+
applied
|
|
107
|
+
});
|
|
108
|
+
latest.current = {
|
|
109
|
+
seed,
|
|
110
|
+
seedKey,
|
|
111
|
+
applied
|
|
112
|
+
};
|
|
113
|
+
const edit = useCallback((patch)=>{
|
|
114
|
+
setEdits((current)=>{
|
|
115
|
+
const next = typeof patch === 'function' ? patch(_extends({}, latest.current.seed, latest.current.applied, current)) : patch;
|
|
116
|
+
return _extends({}, current, next);
|
|
117
|
+
});
|
|
118
|
+
}, []);
|
|
119
|
+
const revert = useCallback((...keys)=>{
|
|
120
|
+
setEdits((current)=>{
|
|
121
|
+
const next = _extends({}, current);
|
|
122
|
+
for (const key of keys)delete next[key];
|
|
123
|
+
return next;
|
|
124
|
+
});
|
|
125
|
+
setSaved((current)=>{
|
|
126
|
+
if (!current) return current;
|
|
127
|
+
const next = _extends({}, current.edits);
|
|
128
|
+
for (const key of keys)delete next[key];
|
|
129
|
+
return _extends({}, current, {
|
|
130
|
+
edits: next
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
}, []);
|
|
134
|
+
const settle = useCallback((written)=>{
|
|
135
|
+
const wrote = written != null ? written : latest.current.applied;
|
|
136
|
+
setSaved({
|
|
137
|
+
key: latest.current.seedKey,
|
|
138
|
+
edits: wrote
|
|
139
|
+
});
|
|
140
|
+
setEdits((current)=>{
|
|
141
|
+
const next = {};
|
|
142
|
+
for (const key of Object.keys(current)){
|
|
143
|
+
if (!(key in wrote) || !Object.is(current[key], wrote[key])) {
|
|
144
|
+
next[key] = current[key];
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return next;
|
|
148
|
+
});
|
|
149
|
+
}, []);
|
|
150
|
+
const discard = useCallback(()=>{
|
|
151
|
+
setSaved(null);
|
|
152
|
+
setEdits({});
|
|
153
|
+
}, []);
|
|
154
|
+
return {
|
|
155
|
+
values,
|
|
156
|
+
edits: applied,
|
|
157
|
+
dirty: Object.keys(edits).length > 0,
|
|
158
|
+
edit,
|
|
159
|
+
revert,
|
|
160
|
+
settle,
|
|
161
|
+
discard
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
export default useSeedEdits;
|
|
165
|
+
/**
|
|
166
|
+
* The rule {@link useSeedEdits} keeps, for a form that already holds its own
|
|
167
|
+
* buffer and seeds it once (AGL-4047).
|
|
168
|
+
*
|
|
169
|
+
* A key whose value still equals what the previous seed said is UNTOUCHED, so
|
|
170
|
+
* it follows the next seed; a key the person changed keeps their value. Hand it
|
|
171
|
+
* the seed the buffer was built from, the buffer as it stands, and the seed
|
|
172
|
+
* that just arrived, and store the result with the next seed as the new
|
|
173
|
+
* baseline. Compared by content, since a snapshot rebuilds every value.
|
|
174
|
+
*/ export function rebaseSeedEdits(previousSeed, current, nextSeed) {
|
|
175
|
+
const next = _extends({}, nextSeed);
|
|
176
|
+
for (const key of Object.keys(current)){
|
|
177
|
+
if (seedKeyOf({
|
|
178
|
+
v: current[key]
|
|
179
|
+
}) !== seedKeyOf({
|
|
180
|
+
v: previousSeed[key]
|
|
181
|
+
})) {
|
|
182
|
+
next[key] = current[key];
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return next;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
//# sourceMappingURL=use-seed-edits.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/use-seed-edits.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n'use client'\n\n/**\n * A FORM SAVE IS NEVER REFUSED ON ITS FIRST PRESS JUST BECAUSE THE SERVER IS\n * LATE (AGL-4047).\n *\n * `writeGuardedBySeed` waits for the server to confirm a cache-served seed\n * before it writes (AGL-4120), and refuses with \"We could not confirm your …\n * with the server yet\" when that wait runs past its deadline. Right after a\n * page load on the shared cache the wait routinely ran past it, so the first\n * press of Save was refused and the second, a few seconds later, saved.\n *\n * The fix has two halves, and a surface needs both:\n *\n * 1. HOLD SAVE while the seed is unconfirmed, with the reason beside it\n * ({@link isSeedChecking}, {@link seedCheckingText}). The press then comes\n * after the server answers, when the guard writes at once. The guard still\n * wraps the write, for a read that falls back to the cache after the\n * surface rendered.\n * 2. KEEP THE EDITS AS EDITS ({@link useSeedEdits}), replayed onto whatever the\n * seed is now. Without this, holding Save is a trap: a form that copied the\n * cached values into its own state when they arrived would, once the server\n * confirmed different ones, save the cached values for every field the\n * person never touched, which is the loss the guard exists to stop. A form\n * that reset itself on every snapshot would instead drop what was typed.\n *\n * Forms on `final-form` get the second half from `keepDirtyOnReinitialize`,\n * which is the same rule: a field the person changed keeps their value, every\n * other field follows the new seed.\n *\n * First built for a site's Admin › Plugins (#2552); this is that pattern\n * lifted so every guarded form can share it.\n */\n\nimport { useCallback, useMemo, useRef, useState } from 'react'\n\n/**\n * Whether a save seeded from this read should be HELD rather than pressed.\n *\n * Unconfirmed, and not failed: a failed read is left to the guard, whose\n * refusal says the values could not be loaded, which no wait would change.\n * The same two flags the call site hands `writeGuardedBySeed`.\n */\nexport function isSeedChecking(read: {\n fromCache?: boolean\n unreadable?: boolean\n}): boolean {\n return Boolean(read.fromCache) && !read.unreadable\n}\n\n/**\n * What a held Save says beside it, so a held control is never unexplained.\n * Takes the same `subject` as the guard (\"profile\", \"language settings\") and,\n * like the guard's refusals, reads right for a plural one (AGL-1446).\n */\nexport function seedCheckingText(subject: string): string {\n return `Checking your ${subject} with the server…`\n}\n\nexport interface SeedEdits<T extends object> {\n /** The seed with the person's edits on top. What the form shows and saves. */\n values: T\n /**\n * The edits in force: unsaved ones, plus the ones a save just wrote until\n * the seed shows them. For a form whose display reads which keys were\n * touched rather than only the merged values.\n */\n edits: Partial<T>\n /** Something is typed that has not been saved. */\n dirty: boolean\n /**\n * Record edits. A function receives the current values, for an edit that\n * derives from them.\n */\n edit: (patch: Partial<T> | ((values: T) => Partial<T>)) => void\n /** Take back the edit to these keys, so they follow the seed again. */\n revert: (...keys: (keyof T)[]) => void\n /**\n * The save landed. The edits it wrote stop being unsaved, and stay applied\n * until the seed moves, so the form never flashes back to the values before\n * the save. Pass what the save wrote (`edits` when it began) so a key typed\n * again while the save was in flight stays unsaved; without it, every edit\n * in force now counts as written.\n */\n settle: (written?: Partial<T>) => void\n /** Throw every unsaved edit away. */\n discard: () => void\n}\n\nfunction seedKeyOf(seed: object): string {\n try {\n return JSON.stringify(seed) ?? ''\n } catch {\n return ''\n }\n}\n\n/**\n * A form's edits, kept as edits and replayed onto the seed on every render\n * rather than copied from it once (AGL-4047).\n *\n * Edits are per top-level key. A key the person never touched always shows\n * what the seed says NOW, so a confirmation that changes it is reflected, and\n * a save writes it; a key they did touch keeps their value through any number\n * of snapshots.\n */\nexport function useSeedEdits<T extends object>(seed: T): SeedEdits<T> {\n const [edits, setEdits] = useState<Partial<T>>({})\n /**\n * What a save just wrote, held against the seed it was written over. The\n * seed normally moves at once, because a local write reaches the cache\n * before the server acknowledges it; this covers the case where it has not.\n */\n const [saved, setSaved] = useState<{ key: string; edits: Partial<T> } | null>(\n null,\n )\n const seedKey = seedKeyOf(seed)\n // Dropped the moment the seed moves, so a later change back to the values\n // as they stood before the save is shown as it is, not hidden behind it.\n if (saved && saved.key !== seedKey) setSaved(null)\n\n const applied = useMemo<Partial<T>>(\n () =>\n saved && saved.key === seedKey ? { ...saved.edits, ...edits } : edits,\n [saved, seedKey, edits],\n )\n const values = useMemo<T>(() => ({ ...seed, ...applied }), [seed, applied])\n\n // Read by `edit`'s updater form and `settle`, which must see what is on\n // screen at the call without re-creating the callbacks on every keystroke.\n const latest = useRef({ seed, seedKey, applied })\n latest.current = { seed, seedKey, applied }\n\n const edit = useCallback(\n (patch: Partial<T> | ((values: T) => Partial<T>)) => {\n setEdits((current) => {\n const next =\n typeof patch === 'function'\n ? patch({ ...latest.current.seed, ...latest.current.applied, ...current })\n : patch\n return { ...current, ...next }\n })\n },\n [],\n )\n\n const revert = useCallback((...keys: (keyof T)[]) => {\n setEdits((current) => {\n const next = { ...current }\n for (const key of keys) delete next[key]\n return next\n })\n setSaved((current) => {\n if (!current) return current\n const next = { ...current.edits }\n for (const key of keys) delete next[key]\n return { ...current, edits: next }\n })\n }, [])\n\n const settle = useCallback((written?: Partial<T>) => {\n const wrote = written ?? latest.current.applied\n setSaved({ key: latest.current.seedKey, edits: wrote })\n setEdits((current) => {\n const next: Partial<T> = {}\n for (const key of Object.keys(current) as (keyof T)[]) {\n if (!(key in wrote) || !Object.is(current[key], wrote[key])) {\n next[key] = current[key]\n }\n }\n return next\n })\n }, [])\n\n const discard = useCallback(() => {\n setSaved(null)\n setEdits({})\n }, [])\n\n return {\n values,\n edits: applied,\n dirty: Object.keys(edits).length > 0,\n edit,\n revert,\n settle,\n discard,\n }\n}\n\nexport default useSeedEdits\n\n/**\n * The rule {@link useSeedEdits} keeps, for a form that already holds its own\n * buffer and seeds it once (AGL-4047).\n *\n * A key whose value still equals what the previous seed said is UNTOUCHED, so\n * it follows the next seed; a key the person changed keeps their value. Hand it\n * the seed the buffer was built from, the buffer as it stands, and the seed\n * that just arrived, and store the result with the next seed as the new\n * baseline. Compared by content, since a snapshot rebuilds every value.\n */\nexport function rebaseSeedEdits<T extends object>(\n previousSeed: T,\n current: T,\n nextSeed: T,\n): T {\n const next = { ...nextSeed }\n for (const key of Object.keys(current) as (keyof T)[]) {\n if (seedKeyOf({ v: current[key] }) !== seedKeyOf({ v: previousSeed[key] })) {\n next[key] = current[key]\n }\n }\n return next\n}\n"],"names":["useCallback","useMemo","useRef","useState","isSeedChecking","read","Boolean","fromCache","unreadable","seedCheckingText","subject","seedKeyOf","seed","JSON","stringify","useSeedEdits","edits","setEdits","saved","setSaved","seedKey","key","applied","values","latest","current","edit","patch","next","revert","keys","settle","written","wrote","Object","is","discard","dirty","length","rebaseSeedEdits","previousSeed","nextSeed","v"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;AAEA;;;;;;;;;;;;;;;;;;;;;;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AU,EACVgB,QAAW;IAEX,MAAMb,OAAO,aAAKa;IAClB,KAAK,MAAMpB,OAAOa,OAAOJ,IAAI,CAACL,SAAyB;QACrD,IAAId,UAAU;YAAE+B,GAAGjB,OAAO,CAACJ,IAAI;QAAC,OAAOV,UAAU;YAAE+B,GAAGF,YAAY,CAACnB,IAAI;QAAC,IAAI;YAC1EO,IAAI,CAACP,IAAI,GAAGI,OAAO,CAACJ,IAAI;QAC1B;IACF;IACA,OAAOO;AACT"}
|
package/src/lib/tenant.d.ts
CHANGED
|
@@ -29,6 +29,7 @@ export * from './hooks/helpers/use-modify-doc-callback';
|
|
|
29
29
|
export * from './hooks/helpers/besigner-nodes-converter';
|
|
30
30
|
export * from './hooks/helpers/guarded-nodes-save';
|
|
31
31
|
export * from './hooks/helpers/guarded-seed-write';
|
|
32
|
+
export * from './hooks/use-seed-edits';
|
|
32
33
|
export * from './hooks/firestore-denial-reporter';
|
|
33
34
|
export * from './hooks/use-firestore-collection';
|
|
34
35
|
export * from './hooks/use-paged-collection';
|