@designcrowd/library.brand-page 5.18.1-undo-27 → 5.18.1-undo-28

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 (32) hide show
  1. package/lib/src/{CreatedOnBrandCrowd-de-de-COk1RbBS.js → CreatedOnBrandCrowd-de-de-CmaFdOwA.js} +1 -1
  2. package/lib/src/{CreatedOnBrandCrowd-en-us-CB3iIEMt.js → CreatedOnBrandCrowd-en-us-DYcx1zJ5.js} +1 -1
  3. package/lib/src/{CreatedOnBrandCrowd-es-es-CRU0kUB6.js → CreatedOnBrandCrowd-es-es-BW-OyQM7.js} +1 -1
  4. package/lib/src/{CreatedOnBrandCrowd-fr-fr-C5DdVGnT.js → CreatedOnBrandCrowd-fr-ca-DDBKibOe.js} +1 -1
  5. package/lib/src/{CreatedOnBrandCrowd-fr-ca-C5DdVGnT.js → CreatedOnBrandCrowd-fr-fr-DDBKibOe.js} +1 -1
  6. package/lib/src/{CreatedOnBrandCrowd-pt-pt-2L9tw0-m.js → CreatedOnBrandCrowd-pt-br-6OSkxFgf.js} +1 -1
  7. package/lib/src/{CreatedOnBrandCrowd-pt-br-2L9tw0-m.js → CreatedOnBrandCrowd-pt-pt-6OSkxFgf.js} +1 -1
  8. package/lib/src/{CreatedOnDcom-de-de-BDHBukLE.js → CreatedOnDcom-de-de-Ds3pSY3b.js} +1 -1
  9. package/lib/src/{CreatedOnDcom-en-us-D0vKhTnI.js → CreatedOnDcom-en-us-nu_xhm3W.js} +1 -1
  10. package/lib/src/{CreatedOnDcom-es-es-CCYUHgfO.js → CreatedOnDcom-es-es-DeWd8xLJ.js} +1 -1
  11. package/lib/src/{CreatedOnDcom-fr-ca-DnPc5h-w.js → CreatedOnDcom-fr-ca-C30UWAc7.js} +1 -1
  12. package/lib/src/{CreatedOnDcom-fr-fr-CvWbnzbp.js → CreatedOnDcom-fr-fr-ZFAi67Ii.js} +1 -1
  13. package/lib/src/{CreatedOnDcom-pt-br-DdMZYZog.js → CreatedOnDcom-pt-br-Bvtz3TFZ.js} +1 -1
  14. package/lib/src/{CreatedOnDcom-pt-pt-BPvriH9Y.js → CreatedOnDcom-pt-pt-Dr__mA4b.js} +1 -1
  15. package/lib/src/brand-page-maker/composables/rich-text-editor/useRichTextEditor.js +13 -1
  16. package/lib/src/brand-page-maker/stores/history/history-store.d.ts +4 -1
  17. package/lib/src/brand-page-maker/stores/history/history-store.js +103 -443
  18. package/lib/src/brand-page-maker/stores/user/user-store.js +1 -1
  19. package/lib/src/index.mjs +1 -1
  20. package/lib/src/{lib-CcYKXNUY.js → lib-BBItimSg.js} +20947 -21083
  21. package/lib/src/shared/content-settings/components/payment-config-field/PaymentConfigField.mixin.d.ts +64 -0
  22. package/lib/src/shared/content-settings/components/payment-config-field/PaymentConfigField.mixin.js +12 -0
  23. package/package.json +1 -1
  24. package/src/brand-page-maker/components/quick-link-bar/undo-redo-buttons.test.ts +116 -0
  25. package/src/brand-page-maker/composables/rich-text-editor/useRichTextEditor.ts +15 -2
  26. package/src/brand-page-maker/stores/history/history-store.test.ts +184 -894
  27. package/src/brand-page-maker/stores/history/history-store.ts +108 -521
  28. package/src/brand-page-maker/stores/user/user-store.ts +1 -1
  29. package/src/shared/content-settings/components/page-dropdown-field/PageDropdownField.vue +7 -0
  30. package/src/shared/content-settings/components/payment-config-field/PaymentConfigField.mixin.ts +13 -0
  31. package/src/brand-page-maker/components/quick-link-bar/RedoButton.test.ts +0 -166
  32. package/src/brand-page-maker/components/quick-link-bar/UndoButton.test.ts +0 -166
@@ -6,8 +6,8 @@ import { useAiWebsiteBuilderThreadStore } from '../ai-thread/ai-website-builder-
6
6
  import { useEventTracker } from '../../composables/useEventTracker';
7
7
  import { usePageNavigationStore } from '@shared/page-navigation/store/page-navigation-store';
8
8
  import { useUiEditableLogoStore } from '@shared/logo-settings/store/editable-logo-store';
9
+ import { useShopConfigStore } from '@shared/ecommerce-settings/store/shop-settings-store';
9
10
  import { useUiPageSettingsStore } from '@shared/page-settings/store';
10
- import { ESCAPED_NEWLINE_CHARACTER } from '@src/constants/ui';
11
11
 
12
12
  /**
13
13
  * A single history entry.
@@ -121,35 +121,22 @@ const MAX_ENTRY_BYTES = 25 * 1024 * 1024;
121
121
  // that would otherwise make undo light up before the user has done anything.
122
122
  const BASELINE_SETTLE_MS = 2000;
123
123
 
124
- // Content-level wrapper keys whose `paymentConfig` child is the user's
125
- // Stripe Connect linkage — backend-confirmed state, not native authoring
126
- // intent (per `project-guardrails.md`). It must be invariant under undo /
127
- // redo regardless of what other edits the user makes.
124
+ // Content-level wrapper keys whose `paymentConfig` child is a denormalised
125
+ // cache of `shopConfigStore.paymentConfig` (the user's Stripe Connect
126
+ // linkage). Stripe Connect linkage state is backend-confirmed (per
127
+ // `project-guardrails.md`) and must NEVER ride along on the undo/redo stack.
128
128
  //
129
- // paymentConfig is kept invariant by `applySnapshotString`:
130
- // - Before applying the target snapshot, harvest each live
131
- // wrapper.paymentConfig keyed by content id.
132
- // - applyHistorySnapshot rebuilds page contents from the snapshot
133
- // (which may carry a stale or absent paymentConfig).
134
- // - After the apply resolves, walk the rebuilt live pages and re-stamp
135
- // wrapper.paymentConfig from the harvest, so each wrapper holds the
136
- // same paymentConfig it had immediately before the apply.
137
- //
138
- // Snapshots themselves still carry paymentConfig (we don't strip at
139
- // capture time) — there's nothing to gain from stripping when the live
140
- // value is preserved across the apply, and keeping snapshots whole avoids
141
- // any data-loss risk for any future code path that might read paymentConfig
142
- // from a snapshot directly. The dedup-side strip below ignores
143
- // `paymentConfig` for the byte-compare so a click-without-edit doesn't
144
- // generate a phantom entry.
129
+ // paymentConfig is kept invariant under undo/redo by re-stamping every live
130
+ // wrapper from `shopConfigStore.paymentConfig` after every restore — see
131
+ // `restorePaymentConfigsOnLivePages`. The shop store itself is never
132
+ // touched by undo/redo (see `applyHistorySnapshot` step 6), so the live
133
+ // wrapper always equals the live shop store regardless of what's in the
134
+ // snapshot bytes.
145
135
  const PAYMENT_CONFIG_WRAPPER_KEYS = [
146
136
  'supportMeConfig',
147
137
  'requestPaymentConfig',
148
138
  'shopPaymentConfig',
149
139
  ] as const;
150
- const PAYMENT_CONFIG_WRAPPER_KEY_SET = new Set<string>(
151
- PAYMENT_CONFIG_WRAPPER_KEYS,
152
- );
153
140
 
154
141
  export const useHistoryStore = defineStore('history', () => {
155
142
  const eventTracker = useEventTracker();
@@ -229,404 +216,31 @@ export const useHistoryStore = defineStore('history', () => {
229
216
  }
230
217
 
231
218
  /**
232
- * Normalize a snapshot for the dedup byte-compare. Strips/canonicalizes
233
- * fields that get mutated by sidebar-open reactive cascades but aren't
234
- * user-visible edits — without this, opening a content panel produces an
235
- * undo step that "does nothing" when replayed.
236
- *
237
- * Known phantom sources (BP-5506):
238
- * - TipTap RTE writing back its empty-paragraph default on first mount
239
- * (e.g. `""` → `<p style="text-align: center;"></p>`).
240
- * - TipTap RTE writing back its default-style hydration on first mount
241
- * (e.g. plain `"Hello"` → `<p style="..."><span style="..."><mark ...>Hello</mark></span></p>`).
242
- * - TipTap re-emitting whole-content `<strong>`/`<em>`/`<u>`/`<s>` tags
243
- * to mirror the resolved `textStyle.fontWeight / fontStyle /
244
- * textDecoration` (e.g. plain `"text"` →
245
- * `<p>...<span>...<strong>text</strong></span></p>`).
246
- * - TipTap rendering the codebase's URL-encoded newline
247
- * (`ESCAPED_NEWLINE_CHARACTER` = `%0A`) as `<br>` on first hydration
248
- * (e.g. plain `"A%0AB"` → `<p><span>A<br>B</span></p>`). Plain-side
249
- * `%0A` is decoded to `\n` and attributeless `<br>` is collapsed to
250
- * `\n` in `extractCanonicalText`, so the two sides converge.
251
- * - Lazy hydration of `*Style` objects when a content settings panel —
252
- * or section selection on the canvas — resolves `textStyleType` and
253
- * writes the full resolved style (fontFamily, fontSize, color,
254
- * fontWeight, fontStyle, letterSpacing, lineHeight, textDecoration)
255
- * onto the model. The `textStyleType` itself is the authoring
256
- * intent; the resolved keys are just cached values.
257
- * - `isModifiedAfterTemplateApplied` flipping on first edit gesture.
219
+ * One-shot "fold next mutation back into the baseline (or current entry)
220
+ * rather than pushing a new entry" flag.
258
221
  *
259
- * Note: `logoImageBase64Url` (the rendered logo PNG) is NOT stripped here.
260
- * Pre-purchase logo-tab edits (text, support text, logo colors, fonts)
261
- * land in `editableLogoStore.logoEdits` (sidecar — see
262
- * `HistoryEntry.logoEdits`) AND trigger a fabric-render that writes the
263
- * new base64 into `pageHeaderDesktop.logoImageBase64Url` + per-page
264
- * logo content. The base64 IS the canonical signal that a logo edit
265
- * happened; stripping it would dedup real logo edits as no-ops. The
266
- * 2-second `BASELINE_SETTLE_MS` window already collapses initial-load
267
- * base64 churn into the baseline.
222
+ * Hydration write sites (TipTap mount, lazy paymentConfig fill,
223
+ * stale-page-ref clear) all run from a lifecycle hook on first sidebar
224
+ * open / section click. Each site mutates `brandPageData` exactly once
225
+ * with a value the user can't see as a change — but the deep watcher
226
+ * fires anyway, and without this gate the next idle flush would land a
227
+ * phantom undo entry.
268
228
  *
269
- * RTE strings are canonicalized by parsing the HTML with DOMParser and
270
- * walking the tree; only attributeless format wrappers (and a tightly
271
- * scoped set of hydration styles on `<p>` / `<span>` / `<mark>`) are
272
- * collapsed. Real authoring intent (links, custom colors, partial-text
273
- * formatting like `Hello <strong>world</strong>`) survives the walk
274
- * because at least one node falls outside the hydration whitelist,
275
- * and the walker bails to "preserve original" the moment that happens.
229
+ * Each call site sets the flag immediately before the imperative write
230
+ * it knows is a hydration. The watcher's flush consumes the flag (clears
231
+ * it) and merges the resulting snapshot into `entries[currentIndex]`
232
+ * instead of pushing. No TTL — the flag stays armed until either:
233
+ * - the watcher fires and consumes it, or
234
+ * - a snapshot apply (undo/redo) clears it (we don't want a hydration
235
+ * flag set immediately before an apply to swallow the post-apply
236
+ * watcher tick), or
237
+ * - `reset()` clears it on save.
276
238
  *
277
- * Used ONLY for dedup comparison. Stored snapshots remain unchanged so
278
- * `applyHistorySnapshot` always sees the real state.
239
+ * Multiple call sites in the same burst all set the same flag — they
240
+ * collapse together into a single merge into the current head, which is
241
+ * the semantics we want.
279
242
  */
280
- // Tags TipTap re-emits purely to mirror the resolved textStyle on first
281
- // hydration. None carry user authoring intent on their own when they are
282
- // the sole element-child wrapping the entire content:
283
- // - <p>: only its `text-align` style is meaningful, and that's already
284
- // captured in `textStyle.textAlign`.
285
- // - <span>: TipTap wraps content in a span with `font-family`, `font-size`,
286
- // `color`, `letter-spacing`, `line-height` resolved from the
287
- // textStyle. The textStyle object on the same content is the
288
- // authoritative source.
289
- // - <mark>: TipTap's highlight extension default — collapses regardless
290
- // of `data-color` / `style` attrs, mirroring the original
291
- // regex's behavior on a hydrated highlight.
292
- // - <strong>/<em>/<u>/<s>: attributeless tags that mirror
293
- // `fontWeight: bold` / `fontStyle: italic` / `textDecoration:
294
- // underline / line-through`. ONLY recognized as hydration when
295
- // they are the sole child of their parent — partial-content
296
- // usage like `Hello <strong>world</strong>` is a real edit.
297
- // Anything else (`<a>`, `<br>`, `<span style="color: red">`, attributes on
298
- // <strong>/<em>, etc.) is preserved as a real diff.
299
- const STRUCTURAL_HYDRATION_TAGS = new Set(['P', 'SPAN', 'MARK']);
300
- const FORMAT_HYDRATION_TAGS = new Set(['STRONG', 'EM', 'U', 'S']);
301
-
302
- // Default style properties TipTap emits on a hydration <span> /
303
- // <mark>. The textStyle resolver writes all of these onto the live
304
- // model, so when TipTap re-emits them as inline style on its
305
- // hydration span/mark there is no user-visible delta.
306
- // Anything outside this whitelist (e.g. `text-decoration` mid-content,
307
- // `text-shadow`, `text-transform`) is treated as a real edit.
308
- const HYDRATION_INLINE_STYLE_PROPS = new Set([
309
- 'font-family',
310
- 'font-size',
311
- 'letter-spacing',
312
- 'line-height',
313
- 'color',
314
- 'background-color',
315
- ]);
316
-
317
- // Empty paragraph forms TipTap emits when an editor mounts on an empty
318
- // string. Treated as equivalent to `""` for dedup.
319
- function isEmptyRteHtml(value: unknown): boolean {
320
- if (typeof value !== 'string') return false;
321
-
322
- return /^<p(\s[^>]*)?>(<br\s*\/?>)?<\/p>$/.test(value);
323
- }
324
-
325
- function isHydrationOnlyAttributes(el: Element): boolean {
326
- // Format tags (<strong>/<em>/<u>/<s>) must be attributeless. Anything
327
- // with class/style/data-*/etc. is a real edit.
328
- if (FORMAT_HYDRATION_TAGS.has(el.tagName))
329
- return el.attributes.length === 0;
330
-
331
- for (const attr of Array.from(el.attributes)) {
332
- // <mark> may carry a `data-color` attr (TipTap highlight extension's
333
- // default-and-resolved value). The accompanying `style` is checked
334
- // against the same hydration-prop whitelist as <span>.
335
- if (
336
- el.tagName === 'MARK' &&
337
- (attr.name === 'data-color' || attr.name === 'style')
338
- ) {
339
- if (attr.name === 'data-color') continue;
340
- } else if (attr.name !== 'style') {
341
- return false;
342
- }
343
-
344
- const decls = attr.value
345
- .split(';')
346
- .map((d) => d.trim())
347
- .filter(Boolean);
348
-
349
- if (el.tagName === 'P') {
350
- for (const decl of decls) {
351
- const [prop] = decl.split(':').map((s) => s.trim());
352
-
353
- if (prop !== 'text-align') return false;
354
- }
355
- } else if (el.tagName === 'SPAN' || el.tagName === 'MARK') {
356
- for (const decl of decls) {
357
- const [prop, value] = decl.split(':').map((s) => s.trim());
358
-
359
- // Allow `color: inherit` on <mark> (TipTap stamps it on the
360
- // default highlight to inherit the span's color). Otherwise
361
- // require the prop to be in the hydration whitelist.
362
- if (
363
- el.tagName === 'MARK' &&
364
- prop === 'color' &&
365
- value === 'inherit'
366
- ) {
367
- continue;
368
- }
369
-
370
- if (!HYDRATION_INLINE_STYLE_PROPS.has(prop)) return false;
371
- }
372
- } else {
373
- return false;
374
- }
375
- }
376
-
377
- return true;
378
- }
379
-
380
- /**
381
- * Walk a parsed HTML node tree. Return the joined text content if every
382
- * descendant is hydration noise; return null if any node carries real
383
- * authoring intent (links, partial formatting, custom styles, etc.).
384
- *
385
- * `isFormatTag` differs in how it's allowed to appear: a structural tag
386
- * (P/SPAN/MARK) can have siblings; a format tag (STRONG/EM/U/S) is only
387
- * allowed when it's the SOLE child of its parent. The caller enforces
388
- * that at the iteration site.
389
- */
390
- function extractCanonicalText(node: Node): string | null {
391
- if (node.nodeType === 3 /* TEXT_NODE */) return node.textContent ?? '';
392
-
393
- if (node.nodeType !== 1 /* ELEMENT_NODE */) {
394
- // Comments, CDATA, etc. — treat as opaque (preserve original).
395
- return null;
396
- }
397
-
398
- const el = node as Element;
399
-
400
- // Attributeless <br> is TipTap's deterministic emission of a hard break.
401
- // Treated as `\n` so a hydrated `<p><span>A<br>B</span></p>` canonicalizes
402
- // to `"A\nB"` and matches the plain-side `"A%0AB"` after newline decoding.
403
- // <br> with any attribute (e.g. `<br data-x>`) bails as before.
404
- if (el.tagName === 'BR') {
405
- return el.attributes.length === 0 ? '\n' : null;
406
- }
407
-
408
- const isStructural = STRUCTURAL_HYDRATION_TAGS.has(el.tagName);
409
- const isFormat = FORMAT_HYDRATION_TAGS.has(el.tagName);
410
-
411
- if (!isStructural && !isFormat) return null;
412
-
413
- if (!isHydrationOnlyAttributes(el)) return null;
414
-
415
- const children = Array.from(el.childNodes);
416
- let out = '';
417
-
418
- for (const child of children) {
419
- // Format tags only count as hydration when they wrap the ENTIRE
420
- // content of their parent. If a <strong>/<em>/<u>/<s> appears
421
- // alongside any sibling (text or element), it's partial-content
422
- // formatting — a real edit that can't be expressed via textStyle —
423
- // so bail.
424
- if (
425
- child.nodeType === 1 &&
426
- FORMAT_HYDRATION_TAGS.has((child as Element).tagName) &&
427
- children.length > 1
428
- ) {
429
- return null;
430
- }
431
-
432
- const part = extractCanonicalText(child);
433
-
434
- if (part === null) return null;
435
-
436
- out += part;
437
- }
438
-
439
- return out;
440
- }
441
-
442
- /**
443
- * If `value` is TipTap's default-hydration wrapper around plain text
444
- * (only hydration-noise elements wrapping bare text), return that bare
445
- * text. Otherwise return the original string unchanged.
446
- *
447
- * This collapses the BP-5506 phantom where opening a content sidebar —
448
- * or selecting a section on the canvas — mounts every RTE editor at
449
- * once and writes back wrapped HTML with no user-visible delta.
450
- */
451
- function canonicalizeRteString(value: string): string {
452
- // Decode the codebase's URL-encoded newline (`%0A` — see
453
- // `ESCAPED_NEWLINE_CHARACTER`) on the plain-text side. The hydrated side
454
- // emits `<br>` for the same logical newline, and `extractCanonicalText`
455
- // collapses attributeless `<br>` to `\n`, so the two converge.
456
- // `split`/`join` rather than `decodeURIComponent` keeps this narrow —
457
- // we don't want to decode `%20`, `%3C`, etc., which would change real
458
- // user content.
459
- const decodeNewlines = (s: string): string =>
460
- s.split(ESCAPED_NEWLINE_CHARACTER).join('\n');
461
-
462
- // Cheap exit: no tags at all. Still decode `%0A` so a plain-text entry
463
- // matches a hydrated entry whose only diff is `<br>`-vs-newline.
464
- if (!value.includes('<')) return decodeNewlines(value);
465
-
466
- if (isEmptyRteHtml(value)) return '';
467
-
468
- // DOMParser is unavailable in some non-browser test environments;
469
- // fall back to leaving the value as-is so the caller produces a
470
- // real diff (i.e. fail open — never falsely collapse).
471
- if (typeof DOMParser === 'undefined') return decodeNewlines(value);
472
-
473
- let doc: Document;
474
-
475
- try {
476
- doc = new DOMParser().parseFromString(
477
- `<div id="__rte_root__">${value}</div>`,
478
- 'text/html',
479
- );
480
- } catch {
481
- return decodeNewlines(value);
482
- }
483
-
484
- const root = doc.getElementById('__rte_root__');
485
-
486
- if (!root) return decodeNewlines(value);
487
-
488
- // Join top-level blocks with `\n`. TipTap renders an Enter keypress as
489
- // a new top-level `<p>` sibling — without the join, `<p>Hello</p>` and
490
- // `<p>Hello</p><p></p>` (or `<p>Hello</p><p>World</p>`) collapse to the
491
- // same canonical text and the Enter is invisible to dedup. The join
492
- // also matches plain-side `%0A` between paragraphs (e.g. stored
493
- // `Hello%0AWorld` ↔ hydrated `<p>Hello</p><p>World</p>`).
494
- const parts: string[] = [];
495
-
496
- for (const child of Array.from(root.childNodes)) {
497
- const part = extractCanonicalText(child);
498
-
499
- if (part === null) return decodeNewlines(value);
500
-
501
- parts.push(part);
502
- }
503
-
504
- return parts.join('\n');
505
- }
506
-
507
- function normalizeNode(node: unknown): unknown {
508
- if (Array.isArray(node)) return node.map(normalizeNode);
509
-
510
- if (node === null || typeof node !== 'object') return node;
511
-
512
- const out: Record<string, unknown> = {};
513
-
514
- for (const key of Object.keys(node as Record<string, unknown>)) {
515
- let v: unknown = (node as Record<string, unknown>)[key];
516
-
517
- // Strip the template-modified flag — it's meta-state that flips on
518
- // first edit gesture (e.g. clicking into a panel) and does not
519
- // represent a user-visible change.
520
- if (key === 'isModifiedAfterTemplateApplied') continue;
521
-
522
- // Strip lazily-hydrated `paymentConfig` from payment-config wrappers
523
- // (`supportMeConfig` / `requestPaymentConfig` / `shopPaymentConfig`)
524
- // for the dedup byte-compare. paymentConfig is preserved across
525
- // every undo/redo by `applySnapshotString`'s harvest+re-stamp pair,
526
- // so capturing a wrapper-only diff (e.g. lazy hydration on first
527
- // section click) would generate a phantom undo entry that, on
528
- // playback, has no user-visible effect. Same reasoning as the
529
- // `*Style` / RTE hydration carve-outs above. See
530
- // `PAYMENT_CONFIG_WRAPPER_KEYS`.
531
- if (
532
- PAYMENT_CONFIG_WRAPPER_KEY_SET.has(key) &&
533
- v !== null &&
534
- typeof v === 'object' &&
535
- !Array.isArray(v) &&
536
- 'paymentConfig' in (v as Record<string, unknown>)
537
- ) {
538
- const wrapper = v as Record<string, unknown>;
539
- const stripped: Record<string, unknown> = {};
540
-
541
- for (const k of Object.keys(wrapper)) {
542
- if (k === 'paymentConfig') continue;
543
-
544
- stripped[k] = wrapper[k];
545
- }
546
-
547
- v = stripped;
548
- }
549
-
550
- // Collapse RTE default-hydration wrappers down to the plain text
551
- // they wrap. Plain "X" and `<p style="..."><span ...><mark ...>X
552
- // </mark></span></p>` share the same canonical "X" so a sidebar
553
- // open that mounts every editor at once doesn't generate phantom
554
- // undo steps.
555
- if (typeof v === 'string') {
556
- v = canonicalizeRteString(v);
557
- }
558
-
559
- // Empty TipTap paragraphs collapse to "" — and an empty string is
560
- // equivalent to the key being absent (JSON.stringify drops `undefined`),
561
- // so skip the key entirely. Otherwise the normalizer would emit
562
- // `"description": ""` here while the baseline snapshot — captured when
563
- // `description` was `undefined` — has no `description` key at all,
564
- // and the two normalized strings would differ.
565
- if (isEmptyRteHtml(v) || v === '') continue;
566
-
567
- // textStyle / descriptionStyle / titleStyle / *Style objects.
568
- //
569
- // When `textStyleType` is set, the live store lazily fills in the
570
- // resolved values (fontFamily, fontSize, color, fontWeight,
571
- // fontStyle, letterSpacing, lineHeight, textDecoration, etc.) the
572
- // first time a settings panel — or section-selection on the canvas
573
- // — resolves `textStyleType` against `styles.textStyles.textStyleOptions`.
574
- // None of those lazy fields represent a real user edit; the
575
- // `textStyleType` itself is the authoring intent.
576
- //
577
- // Real user edits via the inline RTE toolbar set `textStyleType: undefined`
578
- // (see useRichTextEditor.ts `fontStyleChanges = { ..., textStyleType: undefined }`),
579
- // so we leave every key intact in that case — those values ARE the
580
- // real authoring intent.
581
- //
582
- // Per-content style edits via the global Style panel land in
583
- // `snapshot.styles.textStyles` (a separate sub-tree), so they still
584
- // produce a real diff outside this branch.
585
- if (
586
- v !== null &&
587
- typeof v === 'object' &&
588
- !Array.isArray(v) &&
589
- /Style$/.test(key)
590
- ) {
591
- const styleObj = v as Record<string, unknown>;
592
- const hasTextStyleType =
593
- styleObj.textStyleType !== undefined &&
594
- styleObj.textStyleType !== null;
595
-
596
- if (hasTextStyleType) {
597
- // Drop everything except `textStyleType` itself + `textAlign`,
598
- // which is the user's per-instance alignment override (preserved
599
- // on hydration via `globalContentStyle = { ...resolved, textAlign: style?.textAlign }`).
600
- out[key] = {
601
- textStyleType: styleObj.textStyleType,
602
- ...(styleObj.textAlign !== undefined
603
- ? { textAlign: styleObj.textAlign }
604
- : {}),
605
- };
606
- continue;
607
- }
608
-
609
- // No textStyleType — these are real per-content overrides. Recurse
610
- // normally so nested objects still get the standard treatment.
611
- out[key] = normalizeNode(styleObj);
612
- continue;
613
- }
614
-
615
- out[key] = normalizeNode(v);
616
- }
617
-
618
- return out;
619
- }
620
-
621
- function normalizeSnapshotForDedup(snapshotStr: string): string {
622
- try {
623
- const parsed = JSON.parse(snapshotStr);
624
-
625
- return JSON.stringify(normalizeNode(parsed));
626
- } catch {
627
- return snapshotStr;
628
- }
629
- }
243
+ const mergeNextFlush = ref(false);
630
244
 
631
245
  /**
632
246
  * Commit a new entry into the stack at the current pointer position.
@@ -662,21 +276,7 @@ export const useHistoryStore = defineStore('history', () => {
662
276
  }): 'committed' | 'oversized' | 'noop' {
663
277
  const current = entries.value[currentIndex.value];
664
278
 
665
- if (current) {
666
- if (current.snapshot === args.snapshot) return 'noop';
667
-
668
- // Phantom-edit dedup: normalize both snapshots to ignore
669
- // sidebar-open reactive cascades (RTE empty-paragraph init, lazy
670
- // textStyle hydration, isModifiedAfterTemplateApplied flips). If
671
- // they're equal after normalization, this capture has no
672
- // user-visible diff vs. the entry at the pointer.
673
- if (
674
- normalizeSnapshotForDedup(current.snapshot) ===
675
- normalizeSnapshotForDedup(args.snapshot)
676
- ) {
677
- return 'noop';
678
- }
679
- }
279
+ if (current && current.snapshot === args.snapshot) return 'noop';
680
280
 
681
281
  if (args.snapshot.length > MAX_ENTRY_BYTES) {
682
282
  eventTracker.sendHistoryOversizedEvent({
@@ -804,6 +404,19 @@ export const useHistoryStore = defineStore('history', () => {
804
404
  currentIndex.value === 0 &&
805
405
  Date.now() - baselineCapturedAt < BASELINE_SETTLE_MS;
806
406
 
407
+ // Merge branch — a hydration write site (TipTap mount, lazy
408
+ // paymentConfig fill, stale-page-ref clear) flagged this flush as
409
+ // "fold into the head, don't push". Replace `entries[currentIndex]`
410
+ // in place so the user-visible undo stack stays exactly as it was
411
+ // before the hydration burst arrived. Consume the flag whether or
412
+ // not we're in the settle window — `inSettleWindow` already merges
413
+ // into the baseline, but past that window the same merge has to
414
+ // happen against the current head for hydrations that fire when the
415
+ // user clicks into a section after the settle elapsed.
416
+ const shouldMerge = mergeNextFlush.value;
417
+
418
+ mergeNextFlush.value = false;
419
+
807
420
  if (inSettleWindow) {
808
421
  entries.value = [
809
422
  {
@@ -819,6 +432,22 @@ export const useHistoryStore = defineStore('history', () => {
819
432
  return;
820
433
  }
821
434
 
435
+ if (shouldMerge && entries.value[currentIndex.value]) {
436
+ const next = entries.value.slice();
437
+
438
+ next[currentIndex.value] = {
439
+ ...next[currentIndex.value],
440
+ snapshot,
441
+ timestamp: new Date().toISOString(),
442
+ sizeBytes: snapshot.length,
443
+ activePageId,
444
+ logoEdits,
445
+ };
446
+ entries.value = next;
447
+
448
+ return;
449
+ }
450
+
822
451
  commitEntry({
823
452
  snapshot,
824
453
  source: 'manual_edit',
@@ -1028,18 +657,13 @@ export const useHistoryStore = defineStore('history', () => {
1028
657
 
1029
658
  const targetEntry = entries.value[targetIndex];
1030
659
 
1031
- // Harvest the LIVE `wrapper.paymentConfig` from every payment-config
1032
- // wrapper BEFORE applying the snapshot. The snapshot may carry a
1033
- // stale or absent paymentConfig (e.g. baseline captured before the
1034
- // wrapper was hydrated), but the live value reflects the current
1035
- // truth — wherever it came from (server bootstrap, Stripe Connect
1036
- // onboarding via PaymentConfigField, or the shop store's lazy hydration).
1037
- // We re-stamp this harvest onto the rebuilt live wrappers after the
1038
- // apply so paymentConfig is invariant under undo/redo regardless of
1039
- // what other content edits the user made. See `PAYMENT_CONFIG_WRAPPER_KEYS`.
1040
- const paymentConfigHarvest = harvestLivePaymentConfigsByContentId();
1041
-
1042
660
  isApplyingSnapshot.value = true;
661
+ // Drop any merge flag a hydration site might have armed but the
662
+ // watcher hasn't yet consumed — otherwise the post-apply watcher
663
+ // tick would silently fold the freshly-restored snapshot into the
664
+ // entry at the new pointer position and erase the user's redo.
665
+ mergeNextFlush.value = false;
666
+ cancelPendingAutoCapture();
1043
667
 
1044
668
  try {
1045
669
  await brandPageMakerStore.applyHistorySnapshot(
@@ -1049,112 +673,55 @@ export const useHistoryStore = defineStore('history', () => {
1049
673
  );
1050
674
  await nextTick();
1051
675
 
1052
- restorePaymentConfigsFromHarvest(paymentConfigHarvest);
676
+ // Re-stamp `wrapper.paymentConfig` on every payment-config wrapper in
677
+ // the freshly-restored content tree from the live shop store. Stripe
678
+ // Connect linkage is backend-confirmed (per `project-guardrails.md`)
679
+ // and must NEVER come from the snapshot — the captured value can be
680
+ // arbitrarily stale (an entry captured before
681
+ // `PaymentConfigField.mixin.ts:created()` lazily filled in the
682
+ // wrapper carries `paymentConfig: undefined`) and using it would
683
+ // re-surface the "Please enable a payment provider" warning on
684
+ // undo. The shop store's value is itself never undoable (see
685
+ // `applyHistorySnapshot` step 6).
686
+ restorePaymentConfigsOnLivePages();
1053
687
  } finally {
1054
688
  isApplyingSnapshot.value = false;
1055
689
  }
1056
690
  }
1057
691
 
1058
692
  /**
1059
- * Map of content id → { wrapperKey → paymentConfig } captured from the
1060
- * live `pageSettingsStore.pages` immediately before an undo/redo apply.
1061
- * Read on the next line in `applySnapshotString`; never persisted.
693
+ * Walk the live `pageSettingsStore.pages` and stamp
694
+ * `wrapper.paymentConfig = shopConfigStore.paymentConfig` on every
695
+ * payment-config wrapper. Called from `applySnapshotString` after
696
+ * `applyHistorySnapshot` rebuilds page contents.
1062
697
  */
1063
- type PaymentConfigHarvest = Map<
1064
- string,
1065
- Partial<Record<(typeof PAYMENT_CONFIG_WRAPPER_KEYS)[number], unknown>>
1066
- >;
1067
-
1068
- function harvestLivePaymentConfigsByContentId(): PaymentConfigHarvest {
1069
- const out: PaymentConfigHarvest = new Map();
1070
-
698
+ function restorePaymentConfigsOnLivePages(): void {
1071
699
  try {
700
+ const shopStore = useShopConfigStore();
1072
701
  const pageSettingsStore = useUiPageSettingsStore();
702
+ const livePaymentConfig = shopStore.paymentConfig;
1073
703
 
1074
704
  for (const page of pageSettingsStore.pages) {
1075
705
  for (const item of page.contents) {
1076
706
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
1077
707
  const content: any = item.settings.content;
1078
- const id: string | undefined = content?.id;
1079
-
1080
- if (!id) continue;
1081
-
1082
- let entryRecord: ReturnType<PaymentConfigHarvest['get']> = undefined;
1083
708
 
1084
709
  for (const key of PAYMENT_CONFIG_WRAPPER_KEYS) {
1085
710
  const wrapper = content?.[key];
1086
711
 
1087
- if (
1088
- wrapper &&
1089
- typeof wrapper === 'object' &&
1090
- !Array.isArray(wrapper) &&
1091
- 'paymentConfig' in (wrapper as Record<string, unknown>)
1092
- ) {
1093
- if (!entryRecord) entryRecord = {};
1094
-
1095
- entryRecord[key] = (
1096
- wrapper as { paymentConfig: unknown }
1097
- ).paymentConfig;
1098
- }
1099
- }
1100
-
1101
- if (entryRecord) out.set(id, entryRecord);
1102
- }
1103
- }
1104
- } catch (error) {
1105
- console.error(
1106
- 'history-store: failed to harvest live paymentConfig before apply',
1107
- error,
1108
- );
1109
- }
1110
-
1111
- return out;
1112
- }
1113
-
1114
- /**
1115
- * Re-stamp `wrapper.paymentConfig` onto every matching live wrapper from
1116
- * the pre-apply harvest. Wrappers whose content id is missing from the
1117
- * harvest are left as-is (e.g. a content item that didn't exist before
1118
- * this restore — there's nothing to preserve).
1119
- */
1120
- function restorePaymentConfigsFromHarvest(
1121
- harvest: PaymentConfigHarvest,
1122
- ): void {
1123
- if (harvest.size === 0) return;
1124
-
1125
- try {
1126
- const pageSettingsStore = useUiPageSettingsStore();
1127
-
1128
- for (const page of pageSettingsStore.pages) {
1129
- for (const item of page.contents) {
1130
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
1131
- const content: any = item.settings.content;
1132
- const id: string | undefined = content?.id;
1133
-
1134
- if (!id) continue;
1135
-
1136
- const harvestedRecord = harvest.get(id);
1137
-
1138
- if (!harvestedRecord) continue;
1139
-
1140
- for (const key of PAYMENT_CONFIG_WRAPPER_KEYS) {
1141
- if (!(key in harvestedRecord)) continue;
1142
-
1143
- const wrapper = content?.[key];
1144
-
1145
712
  if (
1146
713
  wrapper &&
1147
714
  typeof wrapper === 'object' &&
1148
715
  !Array.isArray(wrapper)
1149
716
  ) {
1150
- wrapper.paymentConfig = harvestedRecord[key];
717
+ wrapper.paymentConfig = livePaymentConfig;
1151
718
  }
1152
719
  }
1153
720
  }
1154
721
  }
1155
722
  } catch (error) {
1156
723
  console.error(
1157
- 'history-store: failed to restore paymentConfig from harvest',
724
+ 'history-store: failed to restore paymentConfig on live pages',
1158
725
  error,
1159
726
  );
1160
727
  }
@@ -1242,6 +809,7 @@ export const useHistoryStore = defineStore('history', () => {
1242
809
  if (!baselineCaptured.value) return;
1243
810
 
1244
811
  cancelPendingAutoCapture();
812
+ mergeNextFlush.value = false;
1245
813
 
1246
814
  entries.value = [];
1247
815
  currentIndex.value = -1;
@@ -1251,6 +819,24 @@ export const useHistoryStore = defineStore('history', () => {
1251
819
  captureBaseline();
1252
820
  }
1253
821
 
822
+ /**
823
+ * Arm the next watcher flush to fold its snapshot into the current head
824
+ * entry instead of pushing a new one. Hydration write sites (TipTap mount,
825
+ * lazy paymentConfig fill, stale-page-ref clear) call this immediately
826
+ * before the imperative `update:modelValue` / `$emit` they know is a
827
+ * hydration mutation. The next flush consumes (clears) the flag.
828
+ *
829
+ * Idempotent — multiple call sites in the same burst all set the same
830
+ * flag and collapse together into a single merge into the current head.
831
+ *
832
+ * No-op when the watcher hasn't yet baselined: hydration writes inside
833
+ * the settle window already merge into the baseline; outside a flagged
834
+ * session the flag has no observable effect.
835
+ */
836
+ function mergeNextMutation(): void {
837
+ mergeNextFlush.value = true;
838
+ }
839
+
1254
840
  // --- Instrumentation (NFR-04a) ---
1255
841
 
1256
842
  /** Sum of all entries' serialized sizes in bytes. */
@@ -1279,6 +865,7 @@ export const useHistoryStore = defineStore('history', () => {
1279
865
  capture,
1280
866
  captureTemplateSwitch,
1281
867
  captureAiChangeset,
868
+ mergeNextMutation,
1282
869
  undo,
1283
870
  redo,
1284
871
  reset,