@aglyn/tenant-feature-instance 1.21.0 → 1.22.1

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-feature-instance",
3
- "version": "1.21.0",
3
+ "version": "1.22.1",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,15 +25,15 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.21.0",
29
- "@aglyn/shared-data-enums": "1.21.0",
30
- "@aglyn/shared-ui-jsx": "1.21.0",
31
- "@aglyn/shared-util-email": "1.21.0",
32
- "@aglyn/shared-util-http": "1.21.0",
33
- "@aglyn/shared-util-timestamp": "1.21.0",
34
- "@swc/helpers": "0.5.23",
28
+ "@aglyn/aglyn": "1.22.1",
29
+ "@aglyn/shared-data-enums": "1.22.1",
30
+ "@aglyn/shared-ui-jsx": "1.22.1",
31
+ "@aglyn/shared-util-email": "1.22.1",
32
+ "@aglyn/shared-util-http": "1.22.1",
33
+ "@aglyn/shared-util-timestamp": "1.22.1",
34
+ "@swc/helpers": "0.5.24",
35
35
  "lodash-es": "^4.18.1",
36
- "mobx": "^7.0.5"
36
+ "mobx": "^7.1.6"
37
37
  },
38
38
  "peerDependencies": {
39
39
  "@mui/material": "^9.3.1",
@@ -70,6 +70,12 @@ export declare const SEED_CONFIRM_WAIT_MS = 12000;
70
70
  * default (no argument) when done, the way `setStaleSessionCheck` is unregistered.
71
71
  */
72
72
  export declare function setSeedConfirmWaitMs(ms?: number): void;
73
+ /**
74
+ * How long a save waits, as set now: for a Save pressed while it is held
75
+ * (`useHeldSave`, AGL-4047), which keeps the press for exactly as long as the
76
+ * guard would have waited for it.
77
+ */
78
+ export declare function seedConfirmWaitMs(): number;
73
79
  /** The part of a document snapshot {@link sameDocument} reads. */
74
80
  interface DocumentValues {
75
81
  exists: () => boolean;
@@ -69,6 +69,13 @@ let confirmWaitMs = SEED_CONFIRM_WAIT_MS;
69
69
  */ export function setSeedConfirmWaitMs(ms = SEED_CONFIRM_WAIT_MS) {
70
70
  confirmWaitMs = ms;
71
71
  }
72
+ /**
73
+ * How long a save waits, as set now: for a Save pressed while it is held
74
+ * (`useHeldSave`, AGL-4047), which keeps the press for exactly as long as the
75
+ * guard would have waited for it.
76
+ */ export function seedConfirmWaitMs() {
77
+ return confirmWaitMs;
78
+ }
72
79
  /**
73
80
  * Whether two snapshots of one document hold the same values. Read only on the
74
81
  * step from a cached snapshot to a confirmed one, never on every update, because
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/helpers/listen-confirmation.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/**\n * THE LISTENERS THE SERVER HAS NOT CONFIRMED YET, FOR A SAVE THAT NEEDS ONE\n * (AGL-4120).\n *\n * `writeGuardedBySeed` was handed one boolean, read when the button was\n * clicked, and refused the moment it was true. So a save made a second before\n * the server answered was thrown back at the person who made it, with an\n * instruction to reload — though nothing was wrong and waiting would have\n * done. Under load that window ran to a minute (measured in production, beta.297).\n *\n * A guard cannot watch a value it was passed by copy, and fifty-eight call\n * sites pass one. So the four hooks that produce `fromCache` report here, and\n * the guard asks this module instead of its caller: every listener that was\n * unconfirmed at the click has now heard from the server.\n *\n * ## Which listeners\n *\n * The seed's own, when the save names it (AGL-4135). Each hook that produces\n * `fromCache` also returns a {@link ListenHandle}, which always points at that\n * hook's current listener, and a call site that passes it to the guard waits\n * on that read alone ({@link whenListenConfirmed}).\n *\n * Otherwise all of them, because the guard cannot name its own. That errs one\n * way only: a listener nobody is saving can make a save wait, or refuse it, by\n * being slow, refused or torn down during the wait. It can never let a save\n * through on an unconfirmed seed, because the seed's own listener is in the set\n * being waited on. Measured in production with another tab starving the shared\n * cache (AGL-4135), every listener on a page is slow at once, so waiting on all\n * of them is waiting on the slowest one.\n *\n * Waiting on one listener keeps the same promise. A refusal or a teardown\n * never counts as a confirmation: the wait goes on, for the retry that reports\n * again or for the listener that replaces it, and ends unconfirmed at the\n * deadline if neither comes.\n *\n * ## A confirmation can change what is on screen\n *\n * The seed being protected may be out of date, which is the whole point of the\n * guard. When a listener's confirmation brought values that differ from the\n * ones it had shown, the form the person edited was built from the old ones,\n * so writing it now would overwrite the new ones: the exact loss the guard\n * exists to stop. That settles as `refreshed` and the save is refused for one\n * click, so they see the new values first.\n */\n\n/**\n * How long a save waits for a confirmation before saying so. Past the 8 s stall\n * window, so a client that really is silent has been recovered by the time the\n * wait ends, and short enough to read as a slow save rather than a dead button.\n */\nexport const SEED_CONFIRM_WAIT_MS = 12_000\n\nlet confirmWaitMs = SEED_CONFIRM_WAIT_MS\n\n/**\n * How long a save waits. For a spec that pins what happens when the confirmation\n * never comes, which is the refusal and not the wait: pass `0`, and restore the\n * default (no argument) when done, the way `setStaleSessionCheck` is unregistered.\n */\nexport function setSeedConfirmWaitMs(ms: number = SEED_CONFIRM_WAIT_MS): void {\n confirmWaitMs = ms\n}\n\n/** The part of a document snapshot {@link sameDocument} reads. */\ninterface DocumentValues {\n exists: () => boolean\n data: () => unknown\n}\n\n/**\n * Whether two snapshots of one document hold the same values. Read only on the\n * step from a cached snapshot to a confirmed one, never on every update, because\n * the SDK hands a doc listener no list of what changed.\n */\nexport function sameDocument(a: DocumentValues, b: DocumentValues): boolean {\n if (a.exists() !== b.exists()) return false\n return JSON.stringify(a.data()) === JSON.stringify(b.data())\n}\n\n/** How the wait ended. */\nexport type ListenSettlement =\n /** Every listener that was unconfirmed at the start has heard from the server. */\n | 'confirmed'\n /** They did, and at least one brought different values from the ones it showed. */\n | 'refreshed'\n /** The wait ran out, or a listener was refused or went away before answering. */\n | 'unconfirmed'\n /**\n * No listener here was unconfirmed, so whatever said the seed is unconfirmed\n * is not one this module can vouch for. The caller's answer stands.\n */\n | 'untracked'\n\n/** One listener's line in the record. */\ninterface Token {\n /** Where its last word left it. A refusal or a teardown is never `confirmed`. */\n state: 'unconfirmed' | 'confirmed' | 'released'\n /** Its latest confirmation brought values that differ from the ones it showed. */\n changed: boolean\n}\n\ninterface Waiter {\n pending: Set<Token>\n refreshed: boolean\n lost: boolean\n finish: (settlement: ListenSettlement) => void\n}\n\n/** A save waiting on one listener (AGL-4135). */\ninterface SeedWaiter {\n handle: HandleState\n finish: (settlement: ListenSettlement) => void\n}\n\ndeclare const listenHandleBrand: unique symbol\n\n/**\n * One hook's listener, for a save that waits on it alone (AGL-4135). Stable\n * for the life of the hook, and always points at the hook's CURRENT listener,\n * so a listener replaced during the wait (new deps, a reopen) is the one\n * waited on. Opaque: a call site only hands it to `writeGuardedBySeed`.\n */\nexport interface ListenHandle {\n readonly [listenHandleBrand]: true\n}\n\ninterface HandleState {\n token: Token | null\n}\n\n/** A handle for one hook instance. Create it once (`useState(createListenHandle)`). */\nexport function createListenHandle(): ListenHandle {\n const state: HandleState = { token: null }\n return state as unknown as ListenHandle\n}\n\nconst unconfirmed = new Set<Token>()\nconst waiters = new Set<Waiter>()\nconst seedWaiters = new Set<SeedWaiter>()\n\nfunction settleWaiters(token: Token, how: { changed?: boolean; lost?: boolean }) {\n for (const waiter of [...waiters]) {\n if (!waiter.pending.delete(token)) continue\n if (how.changed) waiter.refreshed = true\n if (how.lost) waiter.lost = true\n if (waiter.pending.size > 0) continue\n if (waiter.lost) waiter.finish('unconfirmed')\n else waiter.finish(waiter.refreshed ? 'refreshed' : 'confirmed')\n }\n}\n\nfunction settleSeedWaiters(token: Token) {\n for (const waiter of [...seedWaiters]) {\n if (waiter.handle.token !== token) continue\n waiter.finish(token.changed ? 'refreshed' : 'confirmed')\n }\n}\n\nexport interface ListenConfirmation {\n /**\n * A snapshot arrived. `changed` says a confirmation brought different values\n * from the ones this listener had shown; a first answer showed nothing, so\n * it cannot have changed anything.\n */\n report: (fromCache: boolean, changed?: boolean) => void\n /**\n * The listener was refused. A wait on every listener ends unconfirmed; a wait\n * on this one goes on, for the retry.\n */\n release: () => void\n /**\n * The listener was torn down. As `release`, and its handle no longer points\n * at it, so a wait on this one goes on for the listener that replaces it.\n */\n close: () => void\n}\n\n/**\n * One listener's line in the record. Unconfirmed from the start, for the same\n * reason every hook's `fromCache` state starts true. With `handle`, the handle\n * points at this listener from now on.\n */\nexport function trackListenConfirmation(\n handle?: ListenHandle,\n): ListenConfirmation {\n const token: Token = { state: 'unconfirmed', changed: false }\n unconfirmed.add(token)\n const bound = handle as unknown as HandleState | undefined\n if (bound) bound.token = token\n const release = () => {\n token.state = 'released'\n token.changed = false\n unconfirmed.delete(token)\n settleWaiters(token, { lost: true })\n }\n return {\n report: (fromCache, changed = false) => {\n if (fromCache) {\n token.state = 'unconfirmed'\n token.changed = false\n unconfirmed.add(token)\n return\n }\n token.state = 'confirmed'\n token.changed = changed\n unconfirmed.delete(token)\n settleWaiters(token, { changed })\n settleSeedWaiters(token)\n },\n release,\n close: () => {\n release()\n if (bound?.token === token) bound.token = null\n },\n }\n}\n\n/**\n * Resolves when every listener unconfirmed right now has settled, or after\n * `timeoutMs`. Never rejects.\n */\nexport function whenListensConfirmed(\n timeoutMs: number = confirmWaitMs,\n): Promise<ListenSettlement> {\n if (unconfirmed.size === 0) return Promise.resolve('untracked')\n return new Promise((resolve) => {\n const waiter: Waiter = {\n pending: new Set(unconfirmed),\n refreshed: false,\n lost: false,\n finish: (settlement) => {\n clearTimeout(timer)\n waiters.delete(waiter)\n resolve(settlement)\n },\n }\n const timer = setTimeout(() => waiter.finish('unconfirmed'), timeoutMs)\n waiters.add(waiter)\n })\n}\n\n/**\n * Resolves when the listener `handle` points at is confirmed, or after\n * `timeoutMs` (AGL-4135). Never rejects.\n *\n * - **Already confirmed**: at once, `refreshed` if that confirmation changed\n * the values on screen. The caller read `fromCache` before it landed.\n * - **Unconfirmed, refused or torn down**: waits. A refused listener retries\n * and reports again; a torn-down one is replaced, and the handle points at\n * the replacement. Neither is ever taken for a confirmation.\n * - **No listener behind the handle** (its hook has not listened, or has\n * stopped): `untracked`, so the caller's answer stands.\n */\nexport function whenListenConfirmed(\n handle: ListenHandle,\n timeoutMs: number = confirmWaitMs,\n): Promise<ListenSettlement> {\n const state = handle as unknown as HandleState\n const token = state.token\n if (!token) return Promise.resolve('untracked')\n if (token.state === 'confirmed') {\n return Promise.resolve(token.changed ? 'refreshed' : 'confirmed')\n }\n return new Promise((resolve) => {\n const waiter: SeedWaiter = {\n handle: state,\n finish: (settlement) => {\n clearTimeout(timer)\n seedWaiters.delete(waiter)\n resolve(settlement)\n },\n }\n const timer = setTimeout(() => waiter.finish('unconfirmed'), timeoutMs)\n seedWaiters.add(waiter)\n })\n}\n"],"names":["SEED_CONFIRM_WAIT_MS","confirmWaitMs","setSeedConfirmWaitMs","ms","sameDocument","a","b","exists","JSON","stringify","data","createListenHandle","state","token","unconfirmed","Set","waiters","seedWaiters","settleWaiters","how","waiter","pending","delete","changed","refreshed","lost","size","finish","settleSeedWaiters","handle","trackListenConfirmation","add","bound","release","report","fromCache","close","whenListensConfirmed","timeoutMs","Promise","resolve","settlement","clearTimeout","timer","setTimeout","whenListenConfirmed"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CC,GAED;;;;CAIC,GACD,OAAO,MAAMA,uBAAuB,MAAM;AAE1C,IAAIC,gBAAgBD;AAEpB;;;;CAIC,GACD,OAAO,SAASE,qBAAqBC,KAAaH,oBAAoB;IACpEC,gBAAgBE;AAClB;AA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AAO,IAAIgB,QAAQ,CAACC;QAClB,MAAMpB,SAAqB;YACzBS,QAAQjB;YACRe,QAAQ,CAACc;gBACPC,aAAaC;gBACb1B,YAAYK,MAAM,CAACF;gBACnBoB,QAAQC;YACV;QACF;QACA,MAAME,QAAQC,WAAW,IAAMxB,OAAOO,MAAM,CAAC,gBAAgBW;QAC7DrB,YAAYc,GAAG,CAACX;IAClB;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../../libs/tenant/feature/instance/src/lib/hooks/helpers/listen-confirmation.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/**\n * THE LISTENERS THE SERVER HAS NOT CONFIRMED YET, FOR A SAVE THAT NEEDS ONE\n * (AGL-4120).\n *\n * `writeGuardedBySeed` was handed one boolean, read when the button was\n * clicked, and refused the moment it was true. So a save made a second before\n * the server answered was thrown back at the person who made it, with an\n * instruction to reload — though nothing was wrong and waiting would have\n * done. Under load that window ran to a minute (measured in production, beta.297).\n *\n * A guard cannot watch a value it was passed by copy, and fifty-eight call\n * sites pass one. So the four hooks that produce `fromCache` report here, and\n * the guard asks this module instead of its caller: every listener that was\n * unconfirmed at the click has now heard from the server.\n *\n * ## Which listeners\n *\n * The seed's own, when the save names it (AGL-4135). Each hook that produces\n * `fromCache` also returns a {@link ListenHandle}, which always points at that\n * hook's current listener, and a call site that passes it to the guard waits\n * on that read alone ({@link whenListenConfirmed}).\n *\n * Otherwise all of them, because the guard cannot name its own. That errs one\n * way only: a listener nobody is saving can make a save wait, or refuse it, by\n * being slow, refused or torn down during the wait. It can never let a save\n * through on an unconfirmed seed, because the seed's own listener is in the set\n * being waited on. Measured in production with another tab starving the shared\n * cache (AGL-4135), every listener on a page is slow at once, so waiting on all\n * of them is waiting on the slowest one.\n *\n * Waiting on one listener keeps the same promise. A refusal or a teardown\n * never counts as a confirmation: the wait goes on, for the retry that reports\n * again or for the listener that replaces it, and ends unconfirmed at the\n * deadline if neither comes.\n *\n * ## A confirmation can change what is on screen\n *\n * The seed being protected may be out of date, which is the whole point of the\n * guard. When a listener's confirmation brought values that differ from the\n * ones it had shown, the form the person edited was built from the old ones,\n * so writing it now would overwrite the new ones: the exact loss the guard\n * exists to stop. That settles as `refreshed` and the save is refused for one\n * click, so they see the new values first.\n */\n\n/**\n * How long a save waits for a confirmation before saying so. Past the 8 s stall\n * window, so a client that really is silent has been recovered by the time the\n * wait ends, and short enough to read as a slow save rather than a dead button.\n */\nexport const SEED_CONFIRM_WAIT_MS = 12_000\n\nlet confirmWaitMs = SEED_CONFIRM_WAIT_MS\n\n/**\n * How long a save waits. For a spec that pins what happens when the confirmation\n * never comes, which is the refusal and not the wait: pass `0`, and restore the\n * default (no argument) when done, the way `setStaleSessionCheck` is unregistered.\n */\nexport function setSeedConfirmWaitMs(ms: number = SEED_CONFIRM_WAIT_MS): void {\n confirmWaitMs = ms\n}\n\n/**\n * How long a save waits, as set now: for a Save pressed while it is held\n * (`useHeldSave`, AGL-4047), which keeps the press for exactly as long as the\n * guard would have waited for it.\n */\nexport function seedConfirmWaitMs(): number {\n return confirmWaitMs\n}\n\n/** The part of a document snapshot {@link sameDocument} reads. */\ninterface DocumentValues {\n exists: () => boolean\n data: () => unknown\n}\n\n/**\n * Whether two snapshots of one document hold the same values. Read only on the\n * step from a cached snapshot to a confirmed one, never on every update, because\n * the SDK hands a doc listener no list of what changed.\n */\nexport function sameDocument(a: DocumentValues, b: DocumentValues): boolean {\n if (a.exists() !== b.exists()) return false\n return JSON.stringify(a.data()) === JSON.stringify(b.data())\n}\n\n/** How the wait ended. */\nexport type ListenSettlement =\n /** Every listener that was unconfirmed at the start has heard from the server. */\n | 'confirmed'\n /** They did, and at least one brought different values from the ones it showed. */\n | 'refreshed'\n /** The wait ran out, or a listener was refused or went away before answering. */\n | 'unconfirmed'\n /**\n * No listener here was unconfirmed, so whatever said the seed is unconfirmed\n * is not one this module can vouch for. The caller's answer stands.\n */\n | 'untracked'\n\n/** One listener's line in the record. */\ninterface Token {\n /** Where its last word left it. A refusal or a teardown is never `confirmed`. */\n state: 'unconfirmed' | 'confirmed' | 'released'\n /** Its latest confirmation brought values that differ from the ones it showed. */\n changed: boolean\n}\n\ninterface Waiter {\n pending: Set<Token>\n refreshed: boolean\n lost: boolean\n finish: (settlement: ListenSettlement) => void\n}\n\n/** A save waiting on one listener (AGL-4135). */\ninterface SeedWaiter {\n handle: HandleState\n finish: (settlement: ListenSettlement) => void\n}\n\ndeclare const listenHandleBrand: unique symbol\n\n/**\n * One hook's listener, for a save that waits on it alone (AGL-4135). Stable\n * for the life of the hook, and always points at the hook's CURRENT listener,\n * so a listener replaced during the wait (new deps, a reopen) is the one\n * waited on. Opaque: a call site only hands it to `writeGuardedBySeed`.\n */\nexport interface ListenHandle {\n readonly [listenHandleBrand]: true\n}\n\ninterface HandleState {\n token: Token | null\n}\n\n/** A handle for one hook instance. Create it once (`useState(createListenHandle)`). */\nexport function createListenHandle(): ListenHandle {\n const state: HandleState = { token: null }\n return state as unknown as ListenHandle\n}\n\nconst unconfirmed = new Set<Token>()\nconst waiters = new Set<Waiter>()\nconst seedWaiters = new Set<SeedWaiter>()\n\nfunction settleWaiters(token: Token, how: { changed?: boolean; lost?: boolean }) {\n for (const waiter of [...waiters]) {\n if (!waiter.pending.delete(token)) continue\n if (how.changed) waiter.refreshed = true\n if (how.lost) waiter.lost = true\n if (waiter.pending.size > 0) continue\n if (waiter.lost) waiter.finish('unconfirmed')\n else waiter.finish(waiter.refreshed ? 'refreshed' : 'confirmed')\n }\n}\n\nfunction settleSeedWaiters(token: Token) {\n for (const waiter of [...seedWaiters]) {\n if (waiter.handle.token !== token) continue\n waiter.finish(token.changed ? 'refreshed' : 'confirmed')\n }\n}\n\nexport interface ListenConfirmation {\n /**\n * A snapshot arrived. `changed` says a confirmation brought different values\n * from the ones this listener had shown; a first answer showed nothing, so\n * it cannot have changed anything.\n */\n report: (fromCache: boolean, changed?: boolean) => void\n /**\n * The listener was refused. A wait on every listener ends unconfirmed; a wait\n * on this one goes on, for the retry.\n */\n release: () => void\n /**\n * The listener was torn down. As `release`, and its handle no longer points\n * at it, so a wait on this one goes on for the listener that replaces it.\n */\n close: () => void\n}\n\n/**\n * One listener's line in the record. Unconfirmed from the start, for the same\n * reason every hook's `fromCache` state starts true. With `handle`, the handle\n * points at this listener from now on.\n */\nexport function trackListenConfirmation(\n handle?: ListenHandle,\n): ListenConfirmation {\n const token: Token = { state: 'unconfirmed', changed: false }\n unconfirmed.add(token)\n const bound = handle as unknown as HandleState | undefined\n if (bound) bound.token = token\n const release = () => {\n token.state = 'released'\n token.changed = false\n unconfirmed.delete(token)\n settleWaiters(token, { lost: true })\n }\n return {\n report: (fromCache, changed = false) => {\n if (fromCache) {\n token.state = 'unconfirmed'\n token.changed = false\n unconfirmed.add(token)\n return\n }\n token.state = 'confirmed'\n token.changed = changed\n unconfirmed.delete(token)\n settleWaiters(token, { changed })\n settleSeedWaiters(token)\n },\n release,\n close: () => {\n release()\n if (bound?.token === token) bound.token = null\n },\n }\n}\n\n/**\n * Resolves when every listener unconfirmed right now has settled, or after\n * `timeoutMs`. Never rejects.\n */\nexport function whenListensConfirmed(\n timeoutMs: number = confirmWaitMs,\n): Promise<ListenSettlement> {\n if (unconfirmed.size === 0) return Promise.resolve('untracked')\n return new Promise((resolve) => {\n const waiter: Waiter = {\n pending: new Set(unconfirmed),\n refreshed: false,\n lost: false,\n finish: (settlement) => {\n clearTimeout(timer)\n waiters.delete(waiter)\n resolve(settlement)\n },\n }\n const timer = setTimeout(() => waiter.finish('unconfirmed'), timeoutMs)\n waiters.add(waiter)\n })\n}\n\n/**\n * Resolves when the listener `handle` points at is confirmed, or after\n * `timeoutMs` (AGL-4135). Never rejects.\n *\n * - **Already confirmed**: at once, `refreshed` if that confirmation changed\n * the values on screen. The caller read `fromCache` before it landed.\n * - **Unconfirmed, refused or torn down**: waits. A refused listener retries\n * and reports again; a torn-down one is replaced, and the handle points at\n * the replacement. Neither is ever taken for a confirmation.\n * - **No listener behind the handle** (its hook has not listened, or has\n * stopped): `untracked`, so the caller's answer stands.\n */\nexport function whenListenConfirmed(\n handle: ListenHandle,\n timeoutMs: number = confirmWaitMs,\n): Promise<ListenSettlement> {\n const state = handle as unknown as HandleState\n const token = state.token\n if (!token) return Promise.resolve('untracked')\n if (token.state === 'confirmed') {\n return Promise.resolve(token.changed ? 'refreshed' : 'confirmed')\n }\n return new Promise((resolve) => {\n const waiter: SeedWaiter = {\n handle: state,\n finish: (settlement) => {\n clearTimeout(timer)\n seedWaiters.delete(waiter)\n resolve(settlement)\n },\n }\n const timer = setTimeout(() => waiter.finish('unconfirmed'), timeoutMs)\n seedWaiters.add(waiter)\n })\n}\n"],"names":["SEED_CONFIRM_WAIT_MS","confirmWaitMs","setSeedConfirmWaitMs","ms","seedConfirmWaitMs","sameDocument","a","b","exists","JSON","stringify","data","createListenHandle","state","token","unconfirmed","Set","waiters","seedWaiters","settleWaiters","how","waiter","pending","delete","changed","refreshed","lost","size","finish","settleSeedWaiters","handle","trackListenConfirmation","add","bound","release","report","fromCache","close","whenListensConfirmed","timeoutMs","Promise","resolve","settlement","clearTimeout","timer","setTimeout","whenListenConfirmed"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2CC,GAED;;;;CAIC,GACD,OAAO,MAAMA,uBAAuB,MAAM;AAE1C,IAAIC,gBAAgBD;AAEpB;;;;CAIC,GACD,OAAO,SAASE,qBAAqBC,KAAaH,oBAAoB;IACpEC,gBAAgBE;AAClB;AAEA;;;;CA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B,MAAMU,OAAO,GAAG,cAAc;IACvD;IACA,OAAO,IAAIgB,QAAQ,CAACC;QAClB,MAAMpB,SAAqB;YACzBS,QAAQjB;YACRe,QAAQ,CAACc;gBACPC,aAAaC;gBACb1B,YAAYK,MAAM,CAACF;gBACnBoB,QAAQC;YACV;QACF;QACA,MAAME,QAAQC,WAAW,IAAMxB,OAAOO,MAAM,CAAC,gBAAgBW;QAC7DrB,YAAYc,GAAG,CAACX;IAClB;AACF"}
@@ -31,6 +31,71 @@ export declare function isSeedChecking(read: {
31
31
  * like the guard's refusals, reads right for a plural one (AGL-1446).
32
32
  */
33
33
  export declare function seedCheckingText(subject: string): string;
34
+ /**
35
+ * What the guard says when a held press waited and no confirmation came: the
36
+ * same refusal a save that waited itself would show.
37
+ */
38
+ export declare function seedUnconfirmedText(subject: string): string;
39
+ export interface HeldSaveOptions {
40
+ /** The seed is unconfirmed: {@link isSeedChecking} of the save's read. */
41
+ checking: boolean;
42
+ /**
43
+ * What is saved, as the guard names it ("store settings"), for the
44
+ * refusal. A surface handed only a `checkingText` may leave it out: the
45
+ * refusal then names "your changes".
46
+ */
47
+ subject?: string;
48
+ /**
49
+ * Show the refusal, where the surface shows a refused save's message
50
+ * (a snackbar, the form's error line). Called when the hold outlasts the
51
+ * guard's wait; nothing is saved then.
52
+ */
53
+ onRefused?: (message: string) => void;
54
+ }
55
+ export interface HeldSave {
56
+ /**
57
+ * Press Save. Runs it at once when nothing is held; while the seed is held,
58
+ * keeps the press and runs it once the seed is confirmed. A press while one
59
+ * is already kept or running is the same press.
60
+ */
61
+ press: () => void;
62
+ /**
63
+ * From the press until the save it starts has finished, including the
64
+ * time a kept press waits: what makes the button say "Saving…".
65
+ */
66
+ saving: boolean;
67
+ /** A press is kept, waiting for the confirmation. */
68
+ waiting: boolean;
69
+ /** The refusal, while the last kept press stands refused; cleared by the next press. */
70
+ refusal: string | null;
71
+ }
72
+ /**
73
+ * A Save pressed while its seed is held is KEPT, not dropped (AGL-4047).
74
+ *
75
+ * The hold disables nothing any more: the button stays pressable, a press
76
+ * during the hold says "Saving…" at once, and the save runs when the seed is
77
+ * confirmed. It runs THE SAVE OF THAT RENDER, not the one pressed, so what it
78
+ * writes is the person's edits replayed onto the confirmed seed
79
+ * ({@link useSeedEdits}, or `keepDirtyOnReinitialize`), never the cached
80
+ * values the press was made over. That is the loss the hold exists to stop,
81
+ * so a kept press keeps the hold's promise.
82
+ *
83
+ * A read that fails while the press is kept ends the hold too, and the save
84
+ * it then runs is refused by its guard ("could not be loaded"). A
85
+ * confirmation that never comes ends the press after the guard's own wait
86
+ * ({@link seedConfirmWaitMs}), with the guard's own refusal, and nothing is
87
+ * saved.
88
+ *
89
+ * @param save The surface's save, as written for this render. It still goes
90
+ * through `writeGuardedBySeed`, which is what refuses a seed that falls
91
+ * back to the cache after the press.
92
+ */
93
+ export declare function useHeldSave(save: () => unknown, options: HeldSaveOptions): HeldSave;
94
+ /**
95
+ * The label a held-press Save shows: "Saving…" from the press until the save
96
+ * has finished, otherwise its own.
97
+ */
98
+ export declare function heldSaveLabel(held: Pick<HeldSave, 'saving'>, label: string): string;
34
99
  export interface SeedEdits<T extends object> {
35
100
  /** The seed with the person's edits on top. What the form shows and saves. */
36
101
  values: T;
@@ -43,9 +43,18 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
43
43
  * which is the same rule: a field the person changed keeps their value, every
44
44
  * other field follows the new seed.
45
45
  *
46
+ * A press made DURING the hold is kept, not dropped ({@link useHeldSave}): the
47
+ * button says "Saving…" from the press, and the save runs the moment the seed
48
+ * is confirmed, over the confirmed values. If no confirmation comes within the
49
+ * guard's own wait, the guard's refusal shows and nothing is saved. Before
50
+ * this, the press landed on a disabled button and did nothing, so the person
51
+ * took Save to be broken (the 11/11 production check).
52
+ *
46
53
  * First built for a site's Admin › Plugins (#2552); this is that pattern
47
54
  * lifted so every guarded form can share it.
48
- */ import { useCallback, useMemo, useRef, useState } from "react";
55
+ */ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
56
+ import { checkSeedFreshness } from "./helpers/guarded-seed-write.js";
57
+ import { seedConfirmWaitMs } from "./helpers/listen-confirmation.js";
49
58
  /**
50
59
  * Whether a save seeded from this read should be HELD rather than pressed.
51
60
  *
@@ -62,6 +71,127 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
62
71
  */ export function seedCheckingText(subject) {
63
72
  return `Checking your ${subject} with the server…`;
64
73
  }
74
+ /**
75
+ * What the guard says when a held press waited and no confirmation came: the
76
+ * same refusal a save that waited itself would show.
77
+ */ export function seedUnconfirmedText(subject) {
78
+ var _checkSeedFreshness_message;
79
+ return (_checkSeedFreshness_message = checkSeedFreshness({
80
+ subject,
81
+ fromCache: true,
82
+ checkSession: false
83
+ }).message) != null ? _checkSeedFreshness_message : '';
84
+ }
85
+ /**
86
+ * A Save pressed while its seed is held is KEPT, not dropped (AGL-4047).
87
+ *
88
+ * The hold disables nothing any more: the button stays pressable, a press
89
+ * during the hold says "Saving…" at once, and the save runs when the seed is
90
+ * confirmed. It runs THE SAVE OF THAT RENDER, not the one pressed, so what it
91
+ * writes is the person's edits replayed onto the confirmed seed
92
+ * ({@link useSeedEdits}, or `keepDirtyOnReinitialize`), never the cached
93
+ * values the press was made over. That is the loss the hold exists to stop,
94
+ * so a kept press keeps the hold's promise.
95
+ *
96
+ * A read that fails while the press is kept ends the hold too, and the save
97
+ * it then runs is refused by its guard ("could not be loaded"). A
98
+ * confirmation that never comes ends the press after the guard's own wait
99
+ * ({@link seedConfirmWaitMs}), with the guard's own refusal, and nothing is
100
+ * saved.
101
+ *
102
+ * @param save The surface's save, as written for this render. It still goes
103
+ * through `writeGuardedBySeed`, which is what refuses a seed that falls
104
+ * back to the cache after the press.
105
+ */ export function useHeldSave(save, options) {
106
+ const { checking } = options;
107
+ const [waiting, setWaiting] = useState(false);
108
+ const [running, setRunning] = useState(false);
109
+ const [refusal, setRefusal] = useState(null);
110
+ const latest = useRef({
111
+ save,
112
+ options
113
+ });
114
+ latest.current = {
115
+ save,
116
+ options
117
+ };
118
+ const busy = useRef(false);
119
+ const mounted = useRef(true);
120
+ const timer = useRef(null);
121
+ useEffect(()=>{
122
+ mounted.current = true;
123
+ return ()=>{
124
+ mounted.current = false;
125
+ if (timer.current) clearTimeout(timer.current);
126
+ };
127
+ }, []);
128
+ const run = useCallback(async ()=>{
129
+ busy.current = true;
130
+ setRunning(true);
131
+ try {
132
+ await latest.current.save();
133
+ } finally{
134
+ busy.current = false;
135
+ if (mounted.current) setRunning(false);
136
+ }
137
+ }, []);
138
+ const press = useCallback(()=>{
139
+ if (busy.current) return;
140
+ setRefusal(null);
141
+ if (!latest.current.options.checking) {
142
+ void run();
143
+ return;
144
+ }
145
+ busy.current = true;
146
+ setWaiting(true);
147
+ timer.current = setTimeout(()=>{
148
+ var _latest_current_options_subject;
149
+ timer.current = null;
150
+ busy.current = false;
151
+ if (!mounted.current) return;
152
+ const message = seedUnconfirmedText((_latest_current_options_subject = latest.current.options.subject) != null ? _latest_current_options_subject : 'changes');
153
+ setWaiting(false);
154
+ setRefusal(message);
155
+ latest.current.options.onRefused == null ? void 0 : latest.current.options.onRefused.call(latest.current.options, message);
156
+ }, seedConfirmWaitMs());
157
+ }, [
158
+ run
159
+ ]);
160
+ useEffect(()=>{
161
+ if (!waiting || checking) return;
162
+ if (timer.current) clearTimeout(timer.current);
163
+ timer.current = null;
164
+ // One state to the next with no render between, so the label never
165
+ // flashes back to its own while the kept press hands over to the save.
166
+ setRunning(true);
167
+ setWaiting(false);
168
+ /*
169
+ * After this commit, not inside it: a `final-form` form re-initializes
170
+ * onto the new seed in its own effect, which runs after this one (a
171
+ * parent's effects run after its children's), and the save must read the
172
+ * re-initialized values.
173
+ */ setTimeout(()=>{
174
+ if (mounted.current) void run();
175
+ else busy.current = false;
176
+ }, 0);
177
+ }, [
178
+ waiting,
179
+ checking,
180
+ run
181
+ ]);
182
+ return {
183
+ press,
184
+ saving: waiting || running,
185
+ waiting,
186
+ refusal
187
+ };
188
+ }
189
+ /**
190
+ * The label a held-press Save shows: "Saving…" from the press until the save
191
+ * has finished, otherwise its own.
192
+ */ export function heldSaveLabel(held, label) {
193
+ return held.saving ? 'Saving…' : label;
194
+ }
65
195
  function seedKeyOf(seed) {
66
196
  try {
67
197
  var _JSON_stringify;
@@ -1 +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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BC,GAED,SAASA,WAAW,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AAE9D;;;;;;CAMC,GACD,OAAO,SAASC,eAAeC,IAG9B;IACC,OAAOC,QAAQD,KAAKE,SAAS,KAAK,CAACF,KAAKG,UAAU;AACpD;AAEA;;;;CAIC,GACD,OAAO,SAASC,iBAAiBC,OAAe;IAC9C,OAAO,CAAC,cAAc,EAAEA,QAAQ,iBAAiB,CAAC;AACpD;AAgCA,SAASC,UAAUC,IAAY;IAC7B,IAAI;YACKC;QAAP,QAAOA,kBAAAA,KAAKC,SAAS,CAACF,iBAAfC,kBAAwB;IACjC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OY;;QAC9B;IACF,GAAG,EAAE;IAEL,MAAMG,SAAS/B,YAAY,CAACgC;QAC1B,MAAMC,QAAQD,kBAAAA,UAAWR,OAAOC,OAAO,CAACH,OAAO;QAC/CH,SAAS;YAAEE,KAAKG,OAAOC,OAAO,CAACL,OAAO;YAAEJ,OAAOiB;QAAM;QACrDhB,SAAS,CAACQ;YACR,MAAMG,OAAmB,CAAC;YAC1B,KAAK,MAAMP,OAAOa,OAAOJ,IAAI,CAACL,SAAyB;gBACrD,IAAI,CAAEJ,CAAAA,OAAOY,KAAI,KAAM,CAACC,OAAOC,EAAE,CAACV,OAAO,CAACJ,IAAI,EAAEY,KAAK,CAACZ,IAAI,GAAG;oBAC3DO,IAAI,CAACP,IAAI,GAAGI,OAAO,CAACJ,IAAI;gBAC1B;YACF;YACA,OAAOO;QACT;IACF,GAAG,EAAE;IAEL,MAAMQ,UAAUpC,YAAY;QAC1BmB,SAAS;QACTF,SAAS,CAAC;IACZ,GAAG,EAAE;IAEL,OAAO;QACLM;QACAP,OAAOM;QACPe,OAAOH,OAAOJ,IAAI,CAACd,OAAOsB,MAAM,GAAG;QACnCZ;QACAG;QACAE;QACAK;IACF;AACF;AAEA,eAAerB,aAAY;AAE3B;;;;;;;;;CASC,GACD,OAAO,SAASwB,gBACdC,YAAe,EACff,OAAU,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"}
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 * A press made DURING the hold is kept, not dropped ({@link useHeldSave}): the\n * button says \"Saving…\" from the press, and the save runs the moment the seed\n * is confirmed, over the confirmed values. If no confirmation comes within the\n * guard's own wait, the guard's refusal shows and nothing is saved. Before\n * this, the press landed on a disabled button and did nothing, so the person\n * took Save to be broken (the 11/11 production check).\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, useEffect, useMemo, useRef, useState } from 'react'\nimport { checkSeedFreshness } from './helpers/guarded-seed-write'\nimport { seedConfirmWaitMs } from './helpers/listen-confirmation'\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\n/**\n * What the guard says when a held press waited and no confirmation came: the\n * same refusal a save that waited itself would show.\n */\nexport function seedUnconfirmedText(subject: string): string {\n return (\n checkSeedFreshness({ subject, fromCache: true, checkSession: false })\n .message ?? ''\n )\n}\n\nexport interface HeldSaveOptions {\n /** The seed is unconfirmed: {@link isSeedChecking} of the save's read. */\n checking: boolean\n /**\n * What is saved, as the guard names it (\"store settings\"), for the\n * refusal. A surface handed only a `checkingText` may leave it out: the\n * refusal then names \"your changes\".\n */\n subject?: string\n /**\n * Show the refusal, where the surface shows a refused save's message\n * (a snackbar, the form's error line). Called when the hold outlasts the\n * guard's wait; nothing is saved then.\n */\n onRefused?: (message: string) => void\n}\n\nexport interface HeldSave {\n /**\n * Press Save. Runs it at once when nothing is held; while the seed is held,\n * keeps the press and runs it once the seed is confirmed. A press while one\n * is already kept or running is the same press.\n */\n press: () => void\n /**\n * From the press until the save it starts has finished, including the\n * time a kept press waits: what makes the button say \"Saving…\".\n */\n saving: boolean\n /** A press is kept, waiting for the confirmation. */\n waiting: boolean\n /** The refusal, while the last kept press stands refused; cleared by the next press. */\n refusal: string | null\n}\n\n/**\n * A Save pressed while its seed is held is KEPT, not dropped (AGL-4047).\n *\n * The hold disables nothing any more: the button stays pressable, a press\n * during the hold says \"Saving…\" at once, and the save runs when the seed is\n * confirmed. It runs THE SAVE OF THAT RENDER, not the one pressed, so what it\n * writes is the person's edits replayed onto the confirmed seed\n * ({@link useSeedEdits}, or `keepDirtyOnReinitialize`), never the cached\n * values the press was made over. That is the loss the hold exists to stop,\n * so a kept press keeps the hold's promise.\n *\n * A read that fails while the press is kept ends the hold too, and the save\n * it then runs is refused by its guard (\"could not be loaded\"). A\n * confirmation that never comes ends the press after the guard's own wait\n * ({@link seedConfirmWaitMs}), with the guard's own refusal, and nothing is\n * saved.\n *\n * @param save The surface's save, as written for this render. It still goes\n * through `writeGuardedBySeed`, which is what refuses a seed that falls\n * back to the cache after the press.\n */\nexport function useHeldSave(\n save: () => unknown,\n options: HeldSaveOptions,\n): HeldSave {\n const { checking } = options\n const [waiting, setWaiting] = useState(false)\n const [running, setRunning] = useState(false)\n const [refusal, setRefusal] = useState<string | null>(null)\n const latest = useRef({ save, options })\n latest.current = { save, options }\n const busy = useRef(false)\n const mounted = useRef(true)\n const timer = useRef<ReturnType<typeof setTimeout> | null>(null)\n\n useEffect(() => {\n mounted.current = true\n return () => {\n mounted.current = false\n if (timer.current) clearTimeout(timer.current)\n }\n }, [])\n\n const run = useCallback(async () => {\n busy.current = true\n setRunning(true)\n try {\n await latest.current.save()\n } finally {\n busy.current = false\n if (mounted.current) setRunning(false)\n }\n }, [])\n\n const press = useCallback(() => {\n if (busy.current) return\n setRefusal(null)\n if (!latest.current.options.checking) {\n void run()\n return\n }\n busy.current = true\n setWaiting(true)\n timer.current = setTimeout(() => {\n timer.current = null\n busy.current = false\n if (!mounted.current) return\n const message = seedUnconfirmedText(\n latest.current.options.subject ?? 'changes',\n )\n setWaiting(false)\n setRefusal(message)\n latest.current.options.onRefused?.(message)\n }, seedConfirmWaitMs())\n }, [run])\n\n useEffect(() => {\n if (!waiting || checking) return\n if (timer.current) clearTimeout(timer.current)\n timer.current = null\n // One state to the next with no render between, so the label never\n // flashes back to its own while the kept press hands over to the save.\n setRunning(true)\n setWaiting(false)\n /*\n * After this commit, not inside it: a `final-form` form re-initializes\n * onto the new seed in its own effect, which runs after this one (a\n * parent's effects run after its children's), and the save must read the\n * re-initialized values.\n */\n setTimeout(() => {\n if (mounted.current) void run()\n else busy.current = false\n }, 0)\n }, [waiting, checking, run])\n\n return { press, saving: waiting || running, waiting, refusal }\n}\n\n/**\n * The label a held-press Save shows: \"Saving…\" from the press until the save\n * has finished, otherwise its own.\n */\nexport function heldSaveLabel(held: Pick<HeldSave, 'saving'>, label: string): string {\n return held.saving ? 'Saving…' : label\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","useEffect","useMemo","useRef","useState","checkSeedFreshness","seedConfirmWaitMs","isSeedChecking","read","Boolean","fromCache","unreadable","seedCheckingText","subject","seedUnconfirmedText","checkSession","message","useHeldSave","save","options","checking","waiting","setWaiting","running","setRunning","refusal","setRefusal","latest","current","busy","mounted","timer","clearTimeout","run","press","setTimeout","onRefused","saving","heldSaveLabel","held","label","seedKeyOf","seed","JSON","stringify","useSeedEdits","edits","setEdits","saved","setSaved","seedKey","key","applied","values","edit","patch","next","revert","keys","settle","written","wrote","Object","is","discard","dirty","length","rebaseSeedEdits","previousSeed","nextSeed","v"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCC,GAED,SAASA,WAAW,EAAEC,SAAS,EAAEC,OAAO,EAAEC,MAAM,EAAEC,QAAQ,QAAQ,QAAO;AACzE,SAASC,kBAAkB,QAAQ,kCAA8B;AACjE,SAASC,iBAAiB,QAAQ,mCAA+B;AAEjE;;;;;;CAMC,GACD,OAAO,SAASC,eAAeC,IAG9B;IACC,OAAOC,QAAQD,KAAKE,SAAS,KAAK,CAACF,KAAKG,UAAU;AACpD;AAEA;;;;CAIC,GACD,OAAO,SAASC,iBAAiBC,OAAe;IAC9C,OAAO,CAAC,cAAc,EAAEA,QAA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