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

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 (40) hide show
  1. package/lib/src/{CreatedOnBrandCrowd-de-de-DUgkmx89.js → CreatedOnBrandCrowd-de-de-986OpXvU.js} +1 -1
  2. package/lib/src/{CreatedOnBrandCrowd-en-us-C5dQGLuA.js → CreatedOnBrandCrowd-en-us-CTZuZ366.js} +1 -1
  3. package/lib/src/{CreatedOnBrandCrowd-es-es-CjPcnNlq.js → CreatedOnBrandCrowd-es-es-CHrTgX9-.js} +1 -1
  4. package/lib/src/{CreatedOnBrandCrowd-fr-fr-D2wnZOOE.js → CreatedOnBrandCrowd-fr-ca-xJAvxQ-x.js} +1 -1
  5. package/lib/src/{CreatedOnBrandCrowd-fr-ca-D2wnZOOE.js → CreatedOnBrandCrowd-fr-fr-xJAvxQ-x.js} +1 -1
  6. package/lib/src/{CreatedOnBrandCrowd-pt-pt-OQj-IBh_.js → CreatedOnBrandCrowd-pt-br-lpRIGIcs.js} +1 -1
  7. package/lib/src/{CreatedOnBrandCrowd-pt-br-OQj-IBh_.js → CreatedOnBrandCrowd-pt-pt-lpRIGIcs.js} +1 -1
  8. package/lib/src/{CreatedOnDcom-de-de-DLijuIaL.js → CreatedOnDcom-de-de-CZuim3ee.js} +1 -1
  9. package/lib/src/{CreatedOnDcom-en-us-D9M_heGE.js → CreatedOnDcom-en-us-DG4I5f4s.js} +1 -1
  10. package/lib/src/{CreatedOnDcom-es-es-PgWwbBLA.js → CreatedOnDcom-es-es-Hpieh1wX.js} +1 -1
  11. package/lib/src/{CreatedOnDcom-fr-ca-BXiB-abj.js → CreatedOnDcom-fr-ca-DWr5P-df.js} +1 -1
  12. package/lib/src/{CreatedOnDcom-fr-fr-BXhTmu7F.js → CreatedOnDcom-fr-fr-CHfOyS6V.js} +1 -1
  13. package/lib/src/{CreatedOnDcom-pt-br-3e6y567w.js → CreatedOnDcom-pt-br-bQwCCDDI.js} +1 -1
  14. package/lib/src/{CreatedOnDcom-pt-pt-GojOtHmO.js → CreatedOnDcom-pt-pt-bo-i_h0N.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 +63 -277
  19. package/lib/src/index.mjs +1 -1
  20. package/lib/src/{lib-DVs3jUit.js → lib-DNHBgZyy.js} +3887 -3903
  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.ts +70 -333
  37. package/src/shared/content-settings/components/content-settings/ContentSettings.mixin.ts +1 -8
  38. package/src/shared/content-settings/components/page-dropdown-field/PageDropdownField.vue +1 -4
  39. package/src/shared/content-settings/components/payment-config-field/PaymentConfigField.mixin.ts +2 -8
  40. 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,18 @@ 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
- */
156
+ // One-shot flag set by hydration write sites (TipTap mount, lazy
157
+ // paymentConfig fill, stale-page-ref clear, ContentSettings RTE
158
+ // rewrap) before their imperative write. The watcher's next flush
159
+ // consumes the flag and merges the snapshot into the current head
160
+ // instead of pushing — preventing phantom undo entries on first
161
+ // sidebar open / section click. Cleared on apply and reset.
290
162
  const mergeNextFlush = ref(false);
291
163
 
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
- */
164
+ // Returns 'noop' when no-change vs current head, 'oversized' when over
165
+ // MAX_ENTRY_BYTES, else 'committed'. Truncates the redo tail, caps at
166
+ // MAX_ENTRIES, evicts oldest non-baseline to stay under MAX_MEMORY_BYTES.
167
+ // Baseline (index 0) is never evicted.
316
168
  function commitEntry(args: {
317
169
  snapshot: string;
318
170
  source: HistoryEntry['source'];
@@ -323,13 +175,9 @@ export const useHistoryStore = defineStore('history', () => {
323
175
  }): 'committed' | 'oversized' | 'noop' {
324
176
  const current = entries.value[currentIndex.value];
325
177
 
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.
178
+ // Compare both snapshot AND logoEdits sidecar — pre-purchase logo
179
+ // edits don't change brandPageData (base64 is stripped) so the
180
+ // sidecar is the only signal that distinguishes them.
333
181
  if (
334
182
  current &&
335
183
  current.snapshot === args.snapshot &&
@@ -397,26 +245,8 @@ export const useHistoryStore = defineStore('history', () => {
397
245
  return 'committed';
398
246
  }
399
247
 
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.
248
+ // Hoisted so force-commit paths (template switch, AI apply) can cancel
249
+ // any pending auto-capture that would otherwise duplicate their entry.
420
250
  let idleTimerId: ReturnType<typeof setTimeout> | null = null;
421
251
  let maxWaitTimerId: ReturnType<typeof setTimeout> | null = null;
422
252
 
@@ -435,8 +265,6 @@ export const useHistoryStore = defineStore('history', () => {
435
265
  function installWatcher(): void {
436
266
  if (watcherInstalled.value) return;
437
267
 
438
- cachedMakerStore = useBrandPageMakerStore();
439
-
440
268
  const flush = () => {
441
269
  cancelPendingAutoCapture();
442
270
 
@@ -451,28 +279,15 @@ export const useHistoryStore = defineStore('history', () => {
451
279
  const activePageId = getCurrentActivePageId();
452
280
  const logoEdits = serializeCurrentLogoEdits();
453
281
 
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`).
282
+ // Settle window: fold post-init reactive cascades back into the
283
+ // baseline so undo doesn't light up before the user has done
284
+ // anything.
463
285
  const inSettleWindow =
464
286
  currentIndex.value === 0 &&
465
287
  Date.now() - baselineCapturedAt < BASELINE_SETTLE_MS;
466
288
 
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.
289
+ // Merge: a hydration write site flagged this flush — replace the
290
+ // current head in place instead of pushing. Consumed once.
476
291
  const shouldMerge = mergeNextFlush.value;
477
292
 
478
293
  mergeNextFlush.value = false;
@@ -517,12 +332,9 @@ export const useHistoryStore = defineStore('history', () => {
517
332
  });
518
333
  };
519
334
 
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.
335
+ // Monotonic — first mutation arms; subsequent ones inside the window
336
+ // don't reset. Gated on isApplyingSnapshot so undo/redo don't leave
337
+ // a stale timer ticking.
526
338
  const scheduleAutoCapture = (): void => {
527
339
  if (isApplyingSnapshot.value) return;
528
340
 
@@ -532,7 +344,7 @@ export const useHistoryStore = defineStore('history', () => {
532
344
  maxWaitTimerId = setTimeout(flush, CAPTURE_MAX_WAIT_MS);
533
345
  };
534
346
 
535
- watch(() => cachedMakerStore!.brandPageData, scheduleAutoCapture, {
347
+ watch(() => useBrandPageMakerStore().brandPageData, scheduleAutoCapture, {
536
348
  deep: true,
537
349
  });
538
350
 
@@ -541,11 +353,8 @@ export const useHistoryStore = defineStore('history', () => {
541
353
 
542
354
  // --- Actions ---
543
355
 
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
- */
356
+ // Called once per session by BrandPageMaker.mixin.ts after
357
+ // setIsBrandPageLoaded(true). Installs the watcher.
549
358
  function captureBaseline(): void {
550
359
  if (baselineCaptured.value) return;
551
360
 
@@ -555,7 +364,6 @@ export const useHistoryStore = defineStore('history', () => {
555
364
 
556
365
  if (!snapshot) return;
557
366
 
558
- // Baseline starts a fresh stack of exactly 1 entry with pointer at 0.
559
367
  entries.value = [
560
368
  {
561
369
  snapshot,
@@ -573,13 +381,7 @@ export const useHistoryStore = defineStore('history', () => {
573
381
  baselineCapturedAt = Date.now();
574
382
  }
575
383
 
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
- */
384
+ // Force-commit for non-watcher call sites (template switch, AI apply).
583
385
  function capture(args: {
584
386
  source: HistoryEntry['source'];
585
387
  actor: HistoryEntry['actor'];
@@ -601,11 +403,8 @@ export const useHistoryStore = defineStore('history', () => {
601
403
  });
602
404
  }
603
405
 
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
- */
406
+ // Cancel pending auto-capture so the forced entry doesn't duplicate
407
+ // with the watcher's eventual flush.
609
408
  function captureTemplateSwitch(
610
409
  label?: string,
611
410
  ): 'committed' | 'oversized' | 'noop' | 'skipped' {
@@ -614,10 +413,6 @@ export const useHistoryStore = defineStore('history', () => {
614
413
  return capture({ source: 'template_switch', actor: 'user', label });
615
414
  }
616
415
 
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
416
  function captureAiChangeset(
622
417
  label?: string,
623
418
  ): 'committed' | 'oversized' | 'noop' | 'skipped' {
@@ -626,30 +421,12 @@ export const useHistoryStore = defineStore('history', () => {
626
421
  return capture({ source: 'ai_changeset', actor: 'ai_builder', label });
627
422
  }
628
423
 
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
- */
424
+ // Active-page resolution priority:
425
+ // 1. Diff `cameFromIndex` against target — pages present in target
426
+ // but absent from source are being restored/added; navigate there
427
+ // (undo-of-delete, redo-of-add).
428
+ // 2. Walk back from targetIndex for the closest entry whose
429
+ // activePageId still exists (undo-of-add and non-page edits).
653
430
  async function applySnapshotString(
654
431
  snapshotStr: string,
655
432
  targetIndex: number,
@@ -675,9 +452,7 @@ export const useHistoryStore = defineStore('history', () => {
675
452
 
676
453
  let resolvedActivePageId: string | undefined;
677
454
 
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.
455
+ // Step 1: diff cameFromIndex → first page absent from source wins.
681
456
  const sourceEntry = entries.value[cameFromIndex];
682
457
 
683
458
  if (sourceEntry) {
@@ -701,9 +476,7 @@ export const useHistoryStore = defineStore('history', () => {
701
476
  }
702
477
  }
703
478
 
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.
479
+ // Step 2: walk-back fallback for non-page-structural edits.
707
480
  if (!resolvedActivePageId) {
708
481
  for (let i = targetIndex; i >= 0; i--) {
709
482
  const candidate = entries.value[i]?.activePageId;
@@ -718,10 +491,8 @@ export const useHistoryStore = defineStore('history', () => {
718
491
  const targetEntry = entries.value[targetIndex];
719
492
 
720
493
  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.
494
+ // Clear any unconsumed merge flag — a stale flag would fold the
495
+ // post-apply tick into the restored entry and erase the redo.
725
496
  mergeNextFlush.value = false;
726
497
  cancelPendingAutoCapture();
727
498
 
@@ -736,7 +507,6 @@ export const useHistoryStore = defineStore('history', () => {
736
507
  }
737
508
  }
738
509
 
739
- /** Move the pointer back one step and apply the entry at the new position. */
740
510
  async function undo(): Promise<void> {
741
511
  if (!canUndo.value) return;
742
512
 
@@ -744,7 +514,7 @@ export const useHistoryStore = defineStore('history', () => {
744
514
 
745
515
  if (aiThreadStore.isProcessing) return;
746
516
 
747
- // Capture the actor of the entry we're leaving — that's the change being undone.
517
+ // Actor of the entry being undone (the one we're leaving).
748
518
  const undoneActor = entries.value[currentIndex.value]?.actor;
749
519
  const cameFromIndex = currentIndex.value;
750
520
 
@@ -765,7 +535,6 @@ export const useHistoryStore = defineStore('history', () => {
765
535
  });
766
536
  }
767
537
 
768
- /** Move the pointer forward one step and apply the entry at the new position. */
769
538
  async function redo(): Promise<void> {
770
539
  if (!canRedo.value) return;
771
540
 
@@ -786,34 +555,15 @@ export const useHistoryStore = defineStore('history', () => {
786
555
  );
787
556
  }
788
557
 
789
- // Actor of the entry we're moving onto — that's the change being re-applied.
790
558
  eventTracker.sendRedoEvent({
791
559
  entries_count: entries.value.length,
792
560
  actor: target?.actor,
793
561
  });
794
562
  }
795
563
 
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
- */
564
+ // PRD §3: undo history resets on save/publish. Called by
565
+ // brand-page-container-store.saveBrandPage. No-ops when no baseline
566
+ // exists — unflagged sessions never installed the watcher.
817
567
  function reset(): void {
818
568
  if (!baselineCaptured.value) return;
819
569
 
@@ -828,32 +578,19 @@ export const useHistoryStore = defineStore('history', () => {
828
578
  captureBaseline();
829
579
  }
830
580
 
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
- */
581
+ // Hydration write sites call this immediately before their imperative
582
+ // mutation; the next watcher flush merges into the current head
583
+ // instead of pushing. Idempotent and one-shot.
845
584
  function mergeNextMutation(): void {
846
585
  mergeNextFlush.value = true;
847
586
  }
848
587
 
849
588
  // --- Instrumentation (NFR-04a) ---
850
589
 
851
- /** Sum of all entries' serialized sizes in bytes. */
852
590
  function getCurrentSizeBytes(): number {
853
591
  return entries.value.reduce((sum, e) => sum + e.sizeBytes, 0);
854
592
  }
855
593
 
856
- /** Total number of entries currently in the stack. */
857
594
  function getCurrentEntryCount(): number {
858
595
  return entries.value.length;
859
596
  }
@@ -84,14 +84,7 @@ export default defineComponent({
84
84
  },
85
85
  mounted() {
86
86
  if (this.canUseRichTextEditor) {
87
- // `switchAllContentToRTE` walks every content item on every page
88
- // and rewraps plain-text titles/paragraphs in TipTap HTML so they
89
- // render through the inline RTE. That's a hydration write — it
90
- // happens whenever the Content sidebar tab mounts (incl. when the
91
- // user clicks the header in the canvas) and produces no
92
- // user-visible change. Arm the merge flag so the watcher folds
93
- // the resulting flush into the current head entry instead of
94
- // pushing a phantom undo step.
87
+ // RTE rewrap on tab mount — fold into current head.
95
88
  this.historyStore.mergeNextMutation();
96
89
  switchAllContentToRTE(
97
90
  this.pageSettingsStore,
@@ -111,10 +111,7 @@ onMounted(() => {
111
111
  if (routeByPageId) {
112
112
  selectedPage.value = routeByPageId.displayName;
113
113
  } else {
114
- // Stale page-id reference (e.g. the target page was deleted in a
115
- // prior session). Clearing the value happens at mount time, not
116
- // from a user click — arm the merge flag so the watcher folds it
117
- // into the current head instead of pushing a phantom undo entry.
114
+ // Stale page-id clear at mount — fold into current head.
118
115
  historyStore.mergeNextMutation();
119
116
  emit('update:modelValue', {
120
117
  id: props.id,