@designcrowd/library.brand-page 5.18.1-undo-32 → 5.18.1-undo-34

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.
Files changed (41) hide show
  1. package/lib/src/{CreatedOnBrandCrowd-de-de-DUgkmx89.js → CreatedOnBrandCrowd-de-de-D-2WhY-F.js} +1 -1
  2. package/lib/src/{CreatedOnBrandCrowd-en-us-C5dQGLuA.js → CreatedOnBrandCrowd-en-us-B7ldKpJK.js} +1 -1
  3. package/lib/src/{CreatedOnBrandCrowd-es-es-CjPcnNlq.js → CreatedOnBrandCrowd-es-es-BatQY8Tt.js} +1 -1
  4. package/lib/src/{CreatedOnBrandCrowd-fr-fr-D2wnZOOE.js → CreatedOnBrandCrowd-fr-ca-CFivOJkN.js} +1 -1
  5. package/lib/src/{CreatedOnBrandCrowd-fr-ca-D2wnZOOE.js → CreatedOnBrandCrowd-fr-fr-CFivOJkN.js} +1 -1
  6. package/lib/src/{CreatedOnBrandCrowd-pt-pt-OQj-IBh_.js → CreatedOnBrandCrowd-pt-br-wHkXfYLP.js} +1 -1
  7. package/lib/src/{CreatedOnBrandCrowd-pt-br-OQj-IBh_.js → CreatedOnBrandCrowd-pt-pt-wHkXfYLP.js} +1 -1
  8. package/lib/src/{CreatedOnDcom-de-de-DLijuIaL.js → CreatedOnDcom-de-de--HwniV-Y.js} +1 -1
  9. package/lib/src/{CreatedOnDcom-en-us-D9M_heGE.js → CreatedOnDcom-en-us-Bqm5NnRX.js} +1 -1
  10. package/lib/src/{CreatedOnDcom-es-es-PgWwbBLA.js → CreatedOnDcom-es-es-COGQIuEn.js} +1 -1
  11. package/lib/src/{CreatedOnDcom-fr-ca-BXiB-abj.js → CreatedOnDcom-fr-ca-eVDHO7MX.js} +1 -1
  12. package/lib/src/{CreatedOnDcom-fr-fr-BXhTmu7F.js → CreatedOnDcom-fr-fr-BhGKbdoG.js} +1 -1
  13. package/lib/src/{CreatedOnDcom-pt-br-3e6y567w.js → CreatedOnDcom-pt-br-5kDZKPZc.js} +1 -1
  14. package/lib/src/{CreatedOnDcom-pt-pt-GojOtHmO.js → CreatedOnDcom-pt-pt-CnTcVxct.js} +1 -1
  15. package/lib/src/brand-page-maker/composables/rich-text-editor/useRichTextEditor.js +2 -11
  16. package/lib/src/brand-page-maker/stores/brandpage-maker/brandpage-maker-store.js +15 -47
  17. package/lib/src/brand-page-maker/stores/history/history-store.d.ts +7 -47
  18. package/lib/src/brand-page-maker/stores/history/history-store.js +98 -283
  19. package/lib/src/index.mjs +1 -1
  20. package/lib/src/{lib-DVs3jUit.js → lib-B5jbN-ro.js} +31 -44
  21. package/lib/src/shared/content-settings/components/GenericTextInput.mixin.d.ts +1 -1
  22. package/lib/src/shared/content-settings/components/content-settings/ContentSettings.mixin.js +1 -8
  23. package/lib/src/shared/content-settings/components/email-field/EmailField.mixin.d.ts +1 -1
  24. package/lib/src/shared/content-settings/components/payment-config-field/PaymentConfigField.mixin.js +2 -8
  25. package/lib/src/shared/content-settings/components/radio-field/RadioField.mixin.d.ts +1 -1
  26. package/lib/src/shared/content-settings/components/tel-field/TelField.mixin.d.ts +1 -1
  27. package/lib/src/shared/content-settings/components/text-field/TextField.mixin.d.ts +1 -1
  28. package/lib/src/shared/content-settings/components/textarea-field/TextareaField.mixin.d.ts +1 -1
  29. package/lib/src/shared/content-settings/components/url-field/UrlField.mixin.d.ts +1 -1
  30. package/lib/src/shared/content-settings/components/youtube-video-field/YoutubeVideoField.mixin.d.ts +1 -1
  31. package/lib/src/shared/logo-settings/store/editable-logo-store.d.ts +0 -18
  32. package/lib/src/shared/logo-settings/store/editable-logo-store.js +6 -24
  33. package/package.json +1 -1
  34. package/src/brand-page-maker/composables/rich-text-editor/useRichTextEditor.ts +2 -11
  35. package/src/brand-page-maker/stores/brandpage-maker/brandpage-maker-store.ts +15 -47
  36. package/src/brand-page-maker/stores/history/history-store.test.ts +32 -0
  37. package/src/brand-page-maker/stores/history/history-store.ts +107 -340
  38. package/src/shared/content-settings/components/content-settings/ContentSettings.mixin.ts +1 -8
  39. package/src/shared/content-settings/components/page-dropdown-field/PageDropdownField.vue +1 -4
  40. package/src/shared/content-settings/components/payment-config-field/PaymentConfigField.mixin.ts +2 -8
  41. package/src/shared/logo-settings/store/editable-logo-store.ts +9 -29
@@ -9,115 +9,41 @@ import { usePageNavigationStore } from '@shared/page-navigation/store/page-navig
9
9
  import { useUiEditableLogoStore } from '@shared/logo-settings/store/editable-logo-store';
10
10
 
11
11
  /**
12
- * A single history entry.
13
- *
14
- * `snapshot` is a **JSON-stringified** `BrandPageModel`, not a plain object.
15
- * Stringifying up-front has two benefits:
16
- * 1. Pinia's reactive proxy treats the string as a primitive — no traversal,
17
- * no per-field getters/setters on our entries, no accidental shared refs
18
- * with the live store.
19
- * 2. `sizeBytes === snapshot.length` is automatic and accurate for the V2
20
- * memory-budget instrumentation.
21
- *
22
- * Sidecar state that doesn't live on `brandPageData` (the variations grid in
23
- * the Logo sidebar, the active `logoTemplateAsset`, the active
24
- * `logoDraftToken`) is restored on undo by `_syncLogoSettingsFromSnapshot`
25
- * via per-draft-token caches on the logo / editable-logo stores — keyed off
26
- * `logoImage.logoDraftToken` which IS in the snapshot. Pre-purchase logo-tab
27
- * property edits (text, support text, logo colors, font, outline, shadow)
28
- * live on `editableLogoStore.logoEdits` and ride along on the `logoEdits`
29
- * sidecar below.
12
+ * A single history entry. `snapshot` is JSON-stringified up-front so Pinia
13
+ * treats it as opaque (no per-field reactivity) and `sizeBytes` is exact.
14
+ * Sidecar state not in `brandPageData` rides along on this entry —
15
+ * `activePageId` for page-tab restore, `logoEdits` for pre-purchase logo
16
+ * form state.
30
17
  */
31
18
  export interface HistoryEntry {
32
- /** JSON.stringify(BrandPageModel) at the moment of capture. */
33
19
  snapshot: string;
34
-
35
- /** ISO-8601 timestamp of when the entry was captured. */
36
20
  timestamp: string;
37
-
38
- /** What kind of change produced this entry. */
39
21
  source: 'manual_edit' | 'template_switch' | 'ai_changeset' | 'rich_text';
40
-
41
- /** Who authored the change. */
42
22
  actor: 'user' | 'ai_builder';
43
-
44
- /** Optional human-readable short description. Reserved for V2 UI / debugging. */
45
23
  label?: string;
46
-
47
- /** Serialized size in bytes (= snapshot.length in JS string semantics). */
48
24
  sizeBytes: number;
49
-
50
- /**
51
- * The page the user was viewing when this entry was captured. Sidecar to the
52
- * `BrandPageModel` snapshot — page-tab "selected" styling and the sidebar's
53
- * `currentPage` getter both key off this id (via the route URL → routeStore →
54
- * `pageNavigation.activePageId`). Snapshots only contain the document model,
55
- * so without this we can't restore the URL/active-page on undo and the
56
- * carousel highlight bleeds through to the page that no longer exists.
57
- *
58
- * Empty string when no page is active yet (e.g. earliest baseline before
59
- * first router push). Always a real id once the editor has settled.
60
- */
25
+ /** Active page id at capture time. Empty before first router push. */
61
26
  activePageId: string;
62
-
63
- /**
64
- * `JSON.stringify(editableLogoStore.logoEdits)` at the moment of capture.
65
- * Sidecar — `logoEdits` is NOT part of `brandPageData` but its state
66
- * (logo text, support text, logo colors, fonts, outlines, shadows) drives
67
- * what the pre-purchase save path POSTs to fabric-render to regenerate
68
- * the persisted draft metadata. Without restoring it on undo, save after
69
- * an undo would re-derive metadata from the post-edit `logoEdits` and
70
- * silently reapply the change the user just undid.
71
- *
72
- * Undefined for sessions where the editable-logo store has never been
73
- * touched (no logo tab interaction yet) — restore is a no-op in that case.
74
- */
27
+ /** JSON-stringified `editableLogoStore.logoEdits`. Undefined if logo tab never opened. */
75
28
  logoEdits?: string;
76
29
  }
77
30
 
78
- /**
79
- * Single-stack history model with a pointer instead of two stacks.
80
- *
81
- * entries: [e0, e1, e2, e3, e4]
82
- * ^
83
- * currentIndex
84
- *
85
- * canUndo = currentIndex > 0
86
- * canRedo = currentIndex < entries.length - 1
87
- *
88
- * capture → entries = entries.slice(0, currentIndex + 1); push; currentIndex = end
89
- * undo → currentIndex--; applySnapshot(entries[currentIndex])
90
- * redo → currentIndex++; applySnapshot(entries[currentIndex])
91
- *
92
- * This model:
93
- * - eliminates the two-stack-desync risk class (mutating two refs in sequence)
94
- * - makes FR-11 "clear redo on new change" a single array truncation
95
- * - makes it trivial to build a V2 timeline UI (iterate entries, highlight
96
- * currentIndex)
97
- */
98
- // Collapses multi-step mutations into a single capture. Monotonic: first
99
- // mutation starts the timer, further mutations inside the window do not
100
- // reset it. A max-wait ceiling forces a commit during continuous activity
101
- // so a user holding down a key for 15 s still gets periodic snapshots.
31
+ // Monotonic burst — first mutation starts the timer, subsequent mutations
32
+ // don't reset it; max-wait ceiling forces a commit during continuous typing.
102
33
  const CAPTURE_DEBOUNCE_MS = 1700;
103
34
  const CAPTURE_MAX_WAIT_MS = 10000;
104
35
 
105
- // FR-12: 40-entry cap. FR-13: 100 MB memory budget. FR-13c: per-entry
106
- // oversize threshold — entries above this are skipped + emit telemetry.
107
- // 25 MB accommodates a high-res BYO logo upload, which renders ~2.5 MB
108
- // of base64 PNG into each of four viewport sections (~10 MB) plus per-page
109
- // logo content blocks. The variations grid (~10 MB) does NOT live in the
110
- // snapshot — it sits on the editable-logo store keyed by draft token, and
111
- // is restored on undo from there. The 100 MB total budget still evicts
112
- // oldest non-baseline entries to keep memory bounded.
36
+ // FR-12 / FR-13 / FR-13c. 25 MB per-entry accommodates a high-res BYO logo
37
+ // rendered into 4 viewport sections + per-page logo blocks. Oversize
38
+ // entries are skipped with telemetry; 100 MB total evicts oldest
39
+ // non-baseline entries.
113
40
  const MAX_ENTRIES = 40;
114
41
  const MAX_MEMORY_BYTES = 100 * 1024 * 1024;
115
42
  const MAX_ENTRY_BYTES = 25 * 1024 * 1024;
116
43
 
117
- // Window after baseline-capture during which any auto-captured snapshot
118
- // REPLACES the baseline rather than pushing a new entry. Covers post-init
119
- // reactive cascades (template loadPageNo, router afterEach, layout settle)
120
- // that would otherwise make undo light up before the user has done anything.
44
+ // Window after baseline during which captured mutations REPLACE the
45
+ // baseline instead of pushing — covers async post-init cascades
46
+ // (template load, router afterEach, layout settle).
121
47
  const BASELINE_SETTLE_MS = 2000;
122
48
 
123
49
  export const useHistoryStore = defineStore('history', () => {
@@ -125,12 +51,9 @@ export const useHistoryStore = defineStore('history', () => {
125
51
 
126
52
  // --- State ---
127
53
 
128
- /**
129
- * `shallowRef` keeps the array ref reactive (so dependent computeds recompute
130
- * when we swap the array) but prevents Pinia / Vue from proxying every entry
131
- * object inside. Combined with string snapshots, entries are fully opaque to
132
- * reactivity traversal — which is what we want for a history log.
133
- */
54
+ // shallowRef keeps the array reactive but prevents Pinia from proxying
55
+ // every entry — combined with stringified snapshots, entries are
56
+ // fully opaque to reactivity traversal.
134
57
  const entries = shallowRef<HistoryEntry[]>([]);
135
58
  const currentIndex = ref(-1); // -1 means "no baseline yet"
136
59
  const isApplyingSnapshot = ref(false);
@@ -148,25 +71,10 @@ export const useHistoryStore = defineStore('history', () => {
148
71
 
149
72
  // --- Internals ---
150
73
 
151
- /**
152
- * Cached reference to the maker store. Set once when the watcher installs so
153
- * the capture hot path is synchronous.
154
- */
155
- let cachedMakerStore: ReturnType<typeof useBrandPageMakerStore> | null = null;
156
-
157
- /**
158
- * Walk `brandPageData` and null `logoImageBase64Url` on every logo
159
- * placement (header/footer × desktop/mobile + per-page logo content).
160
- * Pre-purchase only — the same gate the save path uses
161
- * (see `brand-page-container-store.ts:805`).
162
- *
163
- * Each rendered base64 is ~2-4 MB and the brand-site templates put the
164
- * same logo in 6-8 places, so unstripped pre-purchase snapshots run
165
- * 18-24 MB and bump the 25 MB per-entry cap, which silently drops the
166
- * entry. The base64 is repopulated on undo by `_syncLogoSettingsFromSnapshot`
167
- * (designed: re-issue fabric-render; BYO: stamp from per-token cache),
168
- * so the snapshot doesn't need to carry it.
169
- */
74
+ // Pre-purchase only (matches the save-path strip in
75
+ // `brand-page-container-store.ts:805`). Each rendered base64 is ~2-4 MB
76
+ // across 6-8 placements, so unstripped snapshots bump the 25 MB cap.
77
+ // `_syncLogoSettingsFromSnapshot` repopulates on undo.
170
78
  function stripLogoBase64IfPrePurchase(data: {
171
79
  pages?: { contents?: { logoImageBase64Url?: string }[] }[];
172
80
  pageHeaderDesktop?: { logoImageBase64Url?: string };
@@ -213,17 +121,10 @@ export const useHistoryStore = defineStore('history', () => {
213
121
  }
214
122
  }
215
123
 
216
- /**
217
- * Serialize the current `brandPageData` into a detached JSON string.
218
- * Synchronous — safe to call inside a microtask without racing a follow-up
219
- * mutation.
220
- */
221
124
  function serializeCurrentSnapshot(): string | null {
222
- if (!cachedMakerStore) return null;
223
-
224
125
  try {
225
126
  const cloned = JSON.parse(
226
- JSON.stringify(toRaw(cachedMakerStore.brandPageData)),
127
+ JSON.stringify(toRaw(useBrandPageMakerStore().brandPageData)),
227
128
  );
228
129
 
229
130
  stripLogoBase64IfPrePurchase(cloned);
@@ -236,20 +137,10 @@ export const useHistoryStore = defineStore('history', () => {
236
137
  }
237
138
  }
238
139
 
239
- /**
240
- * Read the currently active pageId from `pageNavigationStore`. Sidecar to
241
- * the snapshot string — see `HistoryEntry.activePageId`. Empty string when
242
- * no page is active yet.
243
- */
244
140
  function getCurrentActivePageId(): string {
245
141
  return usePageNavigationStore().activePageId ?? '';
246
142
  }
247
143
 
248
- /**
249
- * Serialize the current `editableLogoStore.logoEdits` as a sidecar to the
250
- * snapshot — see `HistoryEntry.logoEdits`. Returns undefined when the
251
- * editable-logo store hasn't initialized yet (no logo tab interaction).
252
- */
253
144
  function serializeCurrentLogoEdits(): string | undefined {
254
145
  try {
255
146
  const editableLogoStore = useUiEditableLogoStore();
@@ -262,57 +153,24 @@ export const useHistoryStore = defineStore('history', () => {
262
153
  }
263
154
  }
264
155
 
265
- /**
266
- * One-shot "fold next mutation back into the baseline (or current entry)
267
- * rather than pushing a new entry" flag.
268
- *
269
- * Hydration write sites (TipTap mount, lazy paymentConfig fill,
270
- * stale-page-ref clear) all run from a lifecycle hook on first sidebar
271
- * open / section click. Each site mutates `brandPageData` exactly once
272
- * with a value the user can't see as a change — but the deep watcher
273
- * fires anyway, and without this gate the next idle flush would land a
274
- * phantom undo entry.
275
- *
276
- * Each call site sets the flag immediately before the imperative write
277
- * it knows is a hydration. The watcher's flush consumes the flag (clears
278
- * it) and merges the resulting snapshot into `entries[currentIndex]`
279
- * instead of pushing. No TTL — the flag stays armed until either:
280
- * - the watcher fires and consumes it, or
281
- * - a snapshot apply (undo/redo) clears it (we don't want a hydration
282
- * flag set immediately before an apply to swallow the post-apply
283
- * watcher tick), or
284
- * - `reset()` clears it on save.
285
- *
286
- * Multiple call sites in the same burst all set the same flag — they
287
- * collapse together into a single merge into the current head, which is
288
- * the semantics we want.
289
- */
290
- const mergeNextFlush = ref(false);
291
-
292
- /**
293
- * Commit a new entry into the stack at the current pointer position.
294
- *
295
- * Returns 'committed' when the entry lands in the stack, 'oversized' when
296
- * the entry exceeds `MAX_ENTRY_BYTES` and is skipped (FR-13c), or 'noop'
297
- * when the snapshot is byte-identical to the entry at the current pointer.
298
- * Callers can use the return to emit telemetry — analytics wiring lives
299
- * in U5.
300
- *
301
- * Enforces these invariants in order:
302
- * 1. Drop no-op duplicates — if the new snapshot is identical to the
303
- * entry at the current pointer, skip it. Color/text settle paths,
304
- * template-switch confirms with no real diff, and AI applies that
305
- * land identical state would otherwise create undo/redo steps that
306
- * do nothing visible.
307
- * 2. FR-13c — if the new entry exceeds 5 MB, skip it entirely.
308
- * 3. FR-11 — truncate any redo tail.
309
- * 4. FR-12 — cap at 40 entries; drop oldest non-baseline on overflow.
310
- * 5. FR-13 — keep total memory under 100 MB; drop oldest non-baseline
311
- * repeatedly until we're under budget.
312
- *
313
- * Baseline (entry 0) is never evicted so "undo everything" always returns
314
- * to session start.
315
- */
156
+ // Two-phase merge flag. Hydration write sites call `mergeNextMutation()`
157
+ // immediately before their imperative write, which sets `mergeArmed`.
158
+ // When the watcher's `scheduleAutoCapture` arms a new idle timer, it
159
+ // transfers `mergeArmed` into `pendingTimerIsMerge`. The flush then
160
+ // consumes `pendingTimerIsMerge` and merges into the current head
161
+ // instead of pushing.
162
+ //
163
+ // The microtask cleanup on `mergeArmed` prevents stale flags surviving
164
+ // when the user navigates away (e.g. sidebar tab switch) before the
165
+ // flagged write actually happens — a previously-set arm is dropped
166
+ // synchronously after the current tick if no watcher fired.
167
+ const mergeArmed = ref(false);
168
+ let pendingTimerIsMerge = false;
169
+
170
+ // Returns 'noop' when no-change vs current head, 'oversized' when over
171
+ // MAX_ENTRY_BYTES, else 'committed'. Truncates the redo tail, caps at
172
+ // MAX_ENTRIES, evicts oldest non-baseline to stay under MAX_MEMORY_BYTES.
173
+ // Baseline (index 0) is never evicted.
316
174
  function commitEntry(args: {
317
175
  snapshot: string;
318
176
  source: HistoryEntry['source'];
@@ -323,13 +181,9 @@ export const useHistoryStore = defineStore('history', () => {
323
181
  }): 'committed' | 'oversized' | 'noop' {
324
182
  const current = entries.value[currentIndex.value];
325
183
 
326
- // Compare both the snapshot bytes AND the logoEdits sidecar.
327
- // Pre-purchase logo-tab edits (text/color/font) live in the
328
- // `editableLogoStore.logoEdits` sidecar, NOT in `brandPageData`.
329
- // The accompanying base64 writeback is also stripped from the
330
- // snapshot (size cap), so a pure logo edit would produce a
331
- // byte-identical snapshot to the previous entry — without the
332
- // sidecar comparison every logo edit would dedup as a no-op.
184
+ // Compare both snapshot AND logoEdits sidecar — pre-purchase logo
185
+ // edits don't change brandPageData (base64 is stripped) so the
186
+ // sidecar is the only signal that distinguishes them.
333
187
  if (
334
188
  current &&
335
189
  current.snapshot === args.snapshot &&
@@ -397,26 +251,8 @@ export const useHistoryStore = defineStore('history', () => {
397
251
  return 'committed';
398
252
  }
399
253
 
400
- /**
401
- * Install a deep watcher on `brandPageData` that auto-captures mutations.
402
- *
403
- * Debounce strategy (FR-16 / ADR-005):
404
- * - Monotonic — the first mutation starts the idle timer; subsequent
405
- * mutations inside the window DO NOT reset it. This is what collapses
406
- * e.g. an RTE italic click's sync style write + ~100 ms-later HTML
407
- * update into a single capture.
408
- * - Idle flush — the idle timer fires CAPTURE_DEBOUNCE_MS after the
409
- * first mutation in a burst (2 s by default).
410
- * - Max-wait ceiling — if mutations keep arriving and the idle timer
411
- * keeps being "one more edit away", a second timer forces a commit at
412
- * CAPTURE_MAX_WAIT_MS after the burst started (10 s by default). This
413
- * is what keeps a user holding down a key from losing undo resolution.
414
- *
415
- * Both timers clear after a commit fires, so the next mutation starts a
416
- * fresh burst.
417
- */
418
- // Hoisted so force-commit paths (template switch, AI apply) can cancel any
419
- // pending auto-capture that would otherwise duplicate their entry.
254
+ // Hoisted so force-commit paths (template switch, AI apply) can cancel
255
+ // any pending auto-capture that would otherwise duplicate their entry.
420
256
  let idleTimerId: ReturnType<typeof setTimeout> | null = null;
421
257
  let maxWaitTimerId: ReturnType<typeof setTimeout> | null = null;
422
258
 
@@ -435,8 +271,6 @@ export const useHistoryStore = defineStore('history', () => {
435
271
  function installWatcher(): void {
436
272
  if (watcherInstalled.value) return;
437
273
 
438
- cachedMakerStore = useBrandPageMakerStore();
439
-
440
274
  const flush = () => {
441
275
  cancelPendingAutoCapture();
442
276
 
@@ -451,31 +285,19 @@ export const useHistoryStore = defineStore('history', () => {
451
285
  const activePageId = getCurrentActivePageId();
452
286
  const logoEdits = serializeCurrentLogoEdits();
453
287
 
454
- // During the post-init settle window, fold any captured mutation back
455
- // into the baseline (entry 0). Async cascades like template
456
- // `loadPageNo`, the router's `afterEach`, and layout settling all
457
- // mutate `brandPageData` after baseline is taken — without this they
458
- // would each look like an undoable user edit on first paint. The
459
- // baseline's `activePageId` is also overwritten so it tracks where
460
- // the user actually settled (the router's `afterEach` runs inside
461
- // this window, so the post-init `activePageId` is more accurate
462
- // than the pre-router value captured in `captureBaseline`).
288
+ // Settle window: fold post-init reactive cascades back into the
289
+ // baseline so undo doesn't light up before the user has done
290
+ // anything.
463
291
  const inSettleWindow =
464
292
  currentIndex.value === 0 &&
465
293
  Date.now() - baselineCapturedAt < BASELINE_SETTLE_MS;
466
294
 
467
- // Merge branch — a hydration write site (TipTap mount, lazy
468
- // paymentConfig fill, stale-page-ref clear) flagged this flush as
469
- // "fold into the head, don't push". Replace `entries[currentIndex]`
470
- // in place so the user-visible undo stack stays exactly as it was
471
- // before the hydration burst arrived. Consume the flag whether or
472
- // not we're in the settle window — `inSettleWindow` already merges
473
- // into the baseline, but past that window the same merge has to
474
- // happen against the current head for hydrations that fire when the
475
- // user clicks into a section after the settle elapsed.
476
- const shouldMerge = mergeNextFlush.value;
295
+ // Merge: the timer that fired this flush was armed during a
296
+ // hydration burst — replace the current head in place instead of
297
+ // pushing. Consumed once.
298
+ const shouldMerge = pendingTimerIsMerge;
477
299
 
478
- mergeNextFlush.value = false;
300
+ pendingTimerIsMerge = false;
479
301
 
480
302
  if (inSettleWindow) {
481
303
  entries.value = [
@@ -517,22 +339,27 @@ export const useHistoryStore = defineStore('history', () => {
517
339
  });
518
340
  };
519
341
 
520
- // Monotonic burst arming. `isApplyingSnapshot` is gated here so an
521
- // undo/redo doesn't leave a stale timer ticking that later flushes
522
- // mid-keystroke when the user starts editing inside the debounce
523
- // window. `baselineCaptured` is not gated here — `installWatcher` is
524
- // only called from `captureBaseline`, so by the time this fires it is
525
- // always true, and `flush` re-checks it.
342
+ // Monotonic — first mutation arms; subsequent ones inside the window
343
+ // don't reset. Gated on isApplyingSnapshot so undo/redo don't leave
344
+ // a stale timer ticking. If a hydration site armed `mergeArmed`
345
+ // immediately before the mutation that triggered this run, transfer
346
+ // the intent into `pendingTimerIsMerge` so the resulting flush
347
+ // merges instead of commits.
526
348
  const scheduleAutoCapture = (): void => {
527
349
  if (isApplyingSnapshot.value) return;
528
350
 
529
351
  if (idleTimerId !== null) return;
530
352
 
353
+ if (mergeArmed.value) {
354
+ pendingTimerIsMerge = true;
355
+ mergeArmed.value = false;
356
+ }
357
+
531
358
  idleTimerId = setTimeout(flush, CAPTURE_DEBOUNCE_MS);
532
359
  maxWaitTimerId = setTimeout(flush, CAPTURE_MAX_WAIT_MS);
533
360
  };
534
361
 
535
- watch(() => cachedMakerStore!.brandPageData, scheduleAutoCapture, {
362
+ watch(() => useBrandPageMakerStore().brandPageData, scheduleAutoCapture, {
536
363
  deep: true,
537
364
  });
538
365
 
@@ -541,11 +368,8 @@ export const useHistoryStore = defineStore('history', () => {
541
368
 
542
369
  // --- Actions ---
543
370
 
544
- /**
545
- * Captures the baseline entry. Called once per session, typically by
546
- * `BrandPageMaker.mixin.ts` immediately after `setIsBrandPageLoaded(true)`.
547
- * Installs the reactive watcher so subsequent mutations auto-capture.
548
- */
371
+ // Called once per session by BrandPageMaker.mixin.ts after
372
+ // setIsBrandPageLoaded(true). Installs the watcher.
549
373
  function captureBaseline(): void {
550
374
  if (baselineCaptured.value) return;
551
375
 
@@ -555,7 +379,6 @@ export const useHistoryStore = defineStore('history', () => {
555
379
 
556
380
  if (!snapshot) return;
557
381
 
558
- // Baseline starts a fresh stack of exactly 1 entry with pointer at 0.
559
382
  entries.value = [
560
383
  {
561
384
  snapshot,
@@ -573,13 +396,7 @@ export const useHistoryStore = defineStore('history', () => {
573
396
  baselineCapturedAt = Date.now();
574
397
  }
575
398
 
576
- /**
577
- * Force-commit capture used by non-watcher call sites (template switch,
578
- * AI apply). The watcher path commits atomically on its own.
579
- *
580
- * Returns the `commitEntry` result so force-commit callers can log
581
- * oversized telemetry — analytics wiring lives in U5.
582
- */
399
+ // Force-commit for non-watcher call sites (template switch, AI apply).
583
400
  function capture(args: {
584
401
  source: HistoryEntry['source'];
585
402
  actor: HistoryEntry['actor'];
@@ -601,11 +418,8 @@ export const useHistoryStore = defineStore('history', () => {
601
418
  });
602
419
  }
603
420
 
604
- /**
605
- * Force-commit a `template_switch` entry. Cancels any pending auto-capture
606
- * so the template-switch change lands as exactly one entry (not a duplicate
607
- * with the watcher's eventual flush).
608
- */
421
+ // Cancel pending auto-capture so the forced entry doesn't duplicate
422
+ // with the watcher's eventual flush.
609
423
  function captureTemplateSwitch(
610
424
  label?: string,
611
425
  ): 'committed' | 'oversized' | 'noop' | 'skipped' {
@@ -614,10 +428,6 @@ export const useHistoryStore = defineStore('history', () => {
614
428
  return capture({ source: 'template_switch', actor: 'user', label });
615
429
  }
616
430
 
617
- /**
618
- * Force-commit an `ai_changeset` entry. Cancels any pending auto-capture
619
- * so the AI apply lands as exactly one entry per prompt (US-E1).
620
- */
621
431
  function captureAiChangeset(
622
432
  label?: string,
623
433
  ): 'committed' | 'oversized' | 'noop' | 'skipped' {
@@ -626,30 +436,12 @@ export const useHistoryStore = defineStore('history', () => {
626
436
  return capture({ source: 'ai_changeset', actor: 'ai_builder', label });
627
437
  }
628
438
 
629
- /**
630
- * Parse a stringified snapshot and push it through the maker store's
631
- * dedicated `applyHistorySnapshot` action, which rehydrates every Pinia
632
- * source store + own-store scalar fields that `brandPageData` reads from.
633
- *
634
- * Holds `isApplyingSnapshot` for the duration of the apply so the
635
- * watcher guard suppresses the cascade of mutations from being
636
- * re-captured as a spurious duplicate entry.
637
- *
638
- * Active-page resolution priority:
639
- * 1. Diff against `cameFromIndex` — any page present in the target
640
- * snapshot but absent from the source snapshot is being "restored"
641
- * by this transition. Navigate there. Covers undo-of-delete (lands
642
- * on the deleted page) and redo-of-add (lands on the newly-added
643
- * page) — both of which the user expects to "follow" the change.
644
- * Without this, undo of a page-delete would resolve via walk-back
645
- * to whatever page the user was on at the previous baseline, not
646
- * the page they just un-deleted.
647
- * 2. Walk back from `targetIndex` to find the closest entry whose
648
- * captured `activePageId` still exists in the restored snapshot.
649
- * Covers undo-of-add (falls back to the page the user was on
650
- * before they added the new one) and any non-page-structural
651
- * edits.
652
- */
439
+ // Active-page resolution priority:
440
+ // 1. Diff `cameFromIndex` against target — pages present in target
441
+ // but absent from source are being restored/added; navigate there
442
+ // (undo-of-delete, redo-of-add).
443
+ // 2. Walk back from targetIndex for the closest entry whose
444
+ // activePageId still exists (undo-of-add and non-page edits).
653
445
  async function applySnapshotString(
654
446
  snapshotStr: string,
655
447
  targetIndex: number,
@@ -675,9 +467,7 @@ export const useHistoryStore = defineStore('history', () => {
675
467
 
676
468
  let resolvedActivePageId: string | undefined;
677
469
 
678
- // Step 1: diff against the source-of-transition. The first page in
679
- // the target snapshot whose id is absent from the source is the page
680
- // being restored/added by this apply.
470
+ // Step 1: diff cameFromIndex → first page absent from source wins.
681
471
  const sourceEntry = entries.value[cameFromIndex];
682
472
 
683
473
  if (sourceEntry) {
@@ -701,9 +491,7 @@ export const useHistoryStore = defineStore('history', () => {
701
491
  }
702
492
  }
703
493
 
704
- // Step 2: walk-back fallback. Used when no page-structural diff
705
- // applies (style/content edits) or when the diff produced nothing
706
- // viable.
494
+ // Step 2: walk-back fallback for non-page-structural edits.
707
495
  if (!resolvedActivePageId) {
708
496
  for (let i = targetIndex; i >= 0; i--) {
709
497
  const candidate = entries.value[i]?.activePageId;
@@ -718,11 +506,10 @@ export const useHistoryStore = defineStore('history', () => {
718
506
  const targetEntry = entries.value[targetIndex];
719
507
 
720
508
  isApplyingSnapshot.value = true;
721
- // Drop any merge flag a hydration site might have armed but the
722
- // watcher hasn't yet consumed — otherwise the post-apply watcher
723
- // tick would silently fold the freshly-restored snapshot into the
724
- // entry at the new pointer position and erase the user's redo.
725
- mergeNextFlush.value = false;
509
+ // Clear any unconsumed merge intent — a stale flag would fold the
510
+ // post-apply tick into the restored entry and erase the redo.
511
+ mergeArmed.value = false;
512
+ pendingTimerIsMerge = false;
726
513
  cancelPendingAutoCapture();
727
514
 
728
515
  try {
@@ -736,7 +523,6 @@ export const useHistoryStore = defineStore('history', () => {
736
523
  }
737
524
  }
738
525
 
739
- /** Move the pointer back one step and apply the entry at the new position. */
740
526
  async function undo(): Promise<void> {
741
527
  if (!canUndo.value) return;
742
528
 
@@ -744,7 +530,7 @@ export const useHistoryStore = defineStore('history', () => {
744
530
 
745
531
  if (aiThreadStore.isProcessing) return;
746
532
 
747
- // Capture the actor of the entry we're leaving — that's the change being undone.
533
+ // Actor of the entry being undone (the one we're leaving).
748
534
  const undoneActor = entries.value[currentIndex.value]?.actor;
749
535
  const cameFromIndex = currentIndex.value;
750
536
 
@@ -765,7 +551,6 @@ export const useHistoryStore = defineStore('history', () => {
765
551
  });
766
552
  }
767
553
 
768
- /** Move the pointer forward one step and apply the entry at the new position. */
769
554
  async function redo(): Promise<void> {
770
555
  if (!canRedo.value) return;
771
556
 
@@ -786,39 +571,21 @@ export const useHistoryStore = defineStore('history', () => {
786
571
  );
787
572
  }
788
573
 
789
- // Actor of the entry we're moving onto — that's the change being re-applied.
790
574
  eventTracker.sendRedoEvent({
791
575
  entries_count: entries.value.length,
792
576
  actor: target?.actor,
793
577
  });
794
578
  }
795
579
 
796
- /**
797
- * Clear the stack and re-baseline against the just-saved state.
798
- *
799
- * PRD §3 Non-Goals: undo history resets on save/publish — the saved state
800
- * becomes the new clean baseline so a user can't accidentally undo back
801
- * past a save. Called by `brand-page-container-store.saveBrandPage` on a
802
- * successful save (covers both Save Progress and Publish, since publish
803
- * routes through `saveBrandPage`).
804
- *
805
- * No-ops when no baseline has ever been captured — the undo/redo feature
806
- * is gated by `userStore.features.canUseUndoRedo` (see
807
- * BrandPageMaker.mixin.ts), and only flagged sessions install the watcher
808
- * + capture a baseline. Without this guard, calling reset() in an
809
- * unflagged session would install the watcher and start eating memory
810
- * for snapshots the user can never see.
811
- *
812
- * Re-runs `captureBaseline` synchronously so the next mutation lands as
813
- * an actual undoable edit rather than disappearing into a fresh settle
814
- * window. The watcher stays installed; `installWatcher` early-returns
815
- * if `watcherInstalled` is already true.
816
- */
580
+ // PRD §3: undo history resets on save/publish. Called by
581
+ // brand-page-container-store.saveBrandPage. No-ops when no baseline
582
+ // exists — unflagged sessions never installed the watcher.
817
583
  function reset(): void {
818
584
  if (!baselineCaptured.value) return;
819
585
 
820
586
  cancelPendingAutoCapture();
821
- mergeNextFlush.value = false;
587
+ mergeArmed.value = false;
588
+ pendingTimerIsMerge = false;
822
589
 
823
590
  entries.value = [];
824
591
  currentIndex.value = -1;
@@ -828,32 +595,32 @@ export const useHistoryStore = defineStore('history', () => {
828
595
  captureBaseline();
829
596
  }
830
597
 
831
- /**
832
- * Arm the next watcher flush to fold its snapshot into the current head
833
- * entry instead of pushing a new one. Hydration write sites (TipTap mount,
834
- * lazy paymentConfig fill, stale-page-ref clear) call this immediately
835
- * before the imperative `update:modelValue` / `$emit` they know is a
836
- * hydration mutation. The next flush consumes (clears) the flag.
837
- *
838
- * Idempotent — multiple call sites in the same burst all set the same
839
- * flag and collapse together into a single merge into the current head.
840
- *
841
- * No-op when the watcher hasn't yet baselined: hydration writes inside
842
- * the settle window already merge into the baseline; outside a flagged
843
- * session the flag has no observable effect.
844
- */
598
+ // Hydration write sites call this immediately before their imperative
599
+ // mutation. The arm is auto-cleared on the next Vue tick — `nextTick`
600
+ // runs AFTER all queued reactive effects (including the watcher), so
601
+ // if the hydration write triggered `scheduleAutoCapture`, the arm has
602
+ // already been transferred into `pendingTimerIsMerge` before this
603
+ // cleanup fires. If no mutation followed (e.g. the user navigated
604
+ // away before the flagged write), the cleanup drops the stale arm so
605
+ // it can't be consumed by an unrelated future mutation.
845
606
  function mergeNextMutation(): void {
846
- mergeNextFlush.value = true;
607
+ mergeArmed.value = true;
608
+ // setTimeout(0) is a macrotask — runs AFTER the synchronous write
609
+ // and AFTER Vue's microtask flush of the watcher's reactive effect.
610
+ // If `scheduleAutoCapture` fired in between (the imperative write
611
+ // triggered the watcher), the arm has already been transferred into
612
+ // `pendingTimerIsMerge` before this cleanup runs.
613
+ setTimeout(() => {
614
+ mergeArmed.value = false;
615
+ }, 0);
847
616
  }
848
617
 
849
618
  // --- Instrumentation (NFR-04a) ---
850
619
 
851
- /** Sum of all entries' serialized sizes in bytes. */
852
620
  function getCurrentSizeBytes(): number {
853
621
  return entries.value.reduce((sum, e) => sum + e.sizeBytes, 0);
854
622
  }
855
623
 
856
- /** Total number of entries currently in the stack. */
857
624
  function getCurrentEntryCount(): number {
858
625
  return entries.value.length;
859
626
  }