@snowcone-app/ui 0.13.0 → 0.13.2

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.
@@ -274,3 +274,76 @@ describe("composited frames per picture (prod desktop 2026-11-11: 15 ERR_FILE_NO
274
274
  });
275
275
  });
276
276
 
277
+ describe("a picture off screen while its frames came (snowcone.app CFKWA6 picture 3, 2026-12-01)", () => {
278
+ /** Seed every picture (frames that carry versions: the box has `rerender`), flip, then edit m2 `edits` times with no
279
+ * element showing it (the phone carousel had not mounted its slide). */
280
+ async function offScreenEdits(edits: number) {
281
+ const { rerender } = render(<Harness version={1} />);
282
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
283
+ const v = { versions: { Front: 1 } };
284
+ h.state.results = IDS.map((id) => ({ ...fullResult(id, `https://r/${id}-full`), ...v }));
285
+ await act(async () => rerender(<Harness version={2} />));
286
+ await waitFor(() => expect(sentConfigs().some((c) => c.overlayCrop === "auto")).toBe(true));
287
+ for (let e = 1; e <= edits; e++) {
288
+ h.state.results = [croppedResult("m2", `https://r/m2-crop-${e}`)];
289
+ await act(async () => rerender(<Harness version={2 + e} />));
290
+ await waitFor(() => expect(h.compositeCroppedFrame).toHaveBeenCalledTimes(e));
291
+ await act(async () => { await new Promise((r) => setTimeout(r, 10)); });
292
+ }
293
+ return rerender;
294
+ }
295
+
296
+ it("the slide mounts on its NEWEST frame, alive; when that frame is lost it is forgotten and exactly that picture re-renders (once)", async () => {
297
+ const revoked: string[] = [];
298
+ globalThis.URL.revokeObjectURL = vi.fn((u: string) => { revoked.push(u); });
299
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
300
+ await offScreenEdits(5);
301
+ const newest = capturedCtx.getMockupUrl("m2")!;
302
+ expect(newest).toBe("blob:composite-5");
303
+ // The bound drops the OLDEST frames nobody showed (E_BLOB_PICTURE_BOUND), never the newest.
304
+ expect(errSpy.mock.calls.some((c) => String(c[0]).includes("E_BLOB_PICTURE_BOUND"))).toBe(true);
305
+ expect(revoked).not.toContain(newest);
306
+
307
+ // The slide's <img> cannot load it (gone before it was drawn): never handed out again, and m2 alone re-renders.
308
+ h.sendConfig.mockClear();
309
+ act(() => capturedCtx.frameFailed(newest));
310
+ expect(capturedCtx.getMockupUrl("m2")).toBeNull();
311
+ expect(capturedCtx.getMockupUrls(["m2"])).toEqual({ m2: null });
312
+ expect(errSpy.mock.calls.some((c) => String(c[0]).includes("E_FRAME_LOST: m2"))).toBe(true);
313
+ await waitFor(() => expect(h.rerender).toHaveBeenCalledWith(["m2"]));
314
+ // The session is never narrowed: the crop drops on the set in force.
315
+ expect(sentConfigs().every((c) => (c.mockupIds as string[]).length === IDS.length && !c.overlayCrop)).toBe(true);
316
+ errSpy.mockRestore();
317
+ });
318
+
319
+ it("wrong cases: an OLDER frame, a network picture, or the re-render failing again (no loop) never ask", async () => {
320
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
321
+ const rerender = await offScreenEdits(2);
322
+ const older = "blob:composite-1";
323
+ const newest = capturedCtx.getMockupUrl("m2")!;
324
+ expect(newest).toBe("blob:composite-2");
325
+ act(() => capturedCtx.frameFailed(older)); // a newer frame was delivered: nothing is lost
326
+ act(() => capturedCtx.frameFailed("https://r/m3-full")); // a network picture: the element's retry owns it
327
+ await act(async () => { await new Promise((r) => setTimeout(r, 20)); });
328
+ expect(h.rerender).not.toHaveBeenCalled();
329
+ expect(capturedCtx.getMockupUrl("m2")).toBe(newest);
330
+
331
+ act(() => capturedCtx.frameFailed(newest));
332
+ await waitFor(() => expect(h.rerender).toHaveBeenCalledTimes(1));
333
+ // Its re-render arrives (a full frame) and cannot be loaded either: asked once, until m2 shows something again.
334
+ h.state.results = [fullResult("m2", "blob:sdk-m2-r1")];
335
+ await act(async () => rerender(<Harness version={50} />));
336
+ expect(capturedCtx.getMockupUrl("m2")).toBe("blob:sdk-m2-r1");
337
+ act(() => capturedCtx.frameFailed("blob:sdk-m2-r1"));
338
+ await act(async () => { await new Promise((r) => setTimeout(r, 700)); });
339
+ expect(h.rerender).toHaveBeenCalledTimes(1);
340
+ // m2 shows a picture again: a later lost frame may ask again.
341
+ capturedCtx.markBlobShown("m2", "https://r/m2-static");
342
+ h.state.results = [fullResult("m2", "blob:sdk-m2-r2")];
343
+ await act(async () => rerender(<Harness version={51} />));
344
+ act(() => capturedCtx.frameFailed("blob:sdk-m2-r2"));
345
+ await waitFor(() => expect(h.rerender).toHaveBeenCalledTimes(2));
346
+ errSpy.mockRestore();
347
+ });
348
+ });
349
+
@@ -204,6 +204,9 @@ function createBridgeFromCanvas(canvasModule: any): React.ComponentType<{
204
204
  };
205
205
  }
206
206
 
207
+ /** How long the canvas waits after the last keystroke before exporting a render (exportConfig.debounceMs default). */
208
+ export const PERSONALIZATION_EXPORT_DEBOUNCE_MS = 250;
209
+
207
210
  // Module-level cache — shared across all provider instances
208
211
  let cachedCanvasComponent: React.ComponentType<any> | null = null;
209
212
  let cachedBridgeComponent: React.ComponentType<any> | null = null;
@@ -330,11 +333,41 @@ export function PersonalizationProvider({
330
333
 
331
334
  // --- Actions ---
332
335
 
336
+ // The hidden canvas (SnowconeCanvasHandle), and when the shopper last changed a value / the last export arrived.
337
+ const canvasRef = useRef<{ exportArtboards?: (o?: { format?: "dataUrl" | "blob"; scale?: number; all?: boolean }) => Promise<Record<string, string | Blob>> } | null>(null);
338
+ const lastChangeAtRef = useRef(0);
339
+ const lastExportAtRef = useRef(0);
340
+
333
341
  const updateField = useCallback((key: string, value: string) => {
334
342
  setIsActive(true);
343
+ lastChangeAtRef.current = Date.now();
335
344
  setPersonValues((prev) => ({ ...prev, [key]: value }));
336
345
  }, []);
337
346
 
347
+ // THE LAST KEYSTROKE ALWAYS EXPORTS. The canvas's auto-export ignores a change that lands within 200 ms of its last
348
+ // export (AutoExportManager: "re-render artifacts") and only picks it up on a LATER change; the last keystroke of a
349
+ // name has none, so it was lost: typed "Hello Kev!", every picture and the bag's print said "Hello Kev" (prod
350
+ // 2026-12-01, and E_PDP_TYPED_EXPORT_PENDING on Add to Bag). Once typing has settled, a change with no export after
351
+ // it is exported here, from the canvas as it is now.
352
+ const settleMs = (exportConfig?.debounceMs ?? PERSONALIZATION_EXPORT_DEBOUNCE_MS) + (exportConfig?.maxWaitMs ?? 1000) + 300;
353
+ useEffect(() => {
354
+ if (!isActive || lastChangeAtRef.current === 0) return;
355
+ const changedAt = lastChangeAtRef.current;
356
+ const timer = setTimeout(() => {
357
+ if (lastExportAtRef.current >= changedAt) return;
358
+ const exportArtboards = canvasRef.current?.exportArtboards;
359
+ if (!exportArtboards) return;
360
+ void exportArtboards({ format: "blob", scale: exportConfig?.scale ?? 1, all: false })
361
+ .then((exports) => {
362
+ // a newer change (or its export) since: that one is the latest, not this
363
+ if (lastChangeAtRef.current !== changedAt || lastExportAtRef.current >= changedAt) return;
364
+ if (exports && Object.keys(exports).length > 0) handleExportRef.current?.(exports);
365
+ })
366
+ .catch(() => { /* the auto-export path stays; nothing else to do */ });
367
+ }, settleMs);
368
+ return () => clearTimeout(timer);
369
+ }, [personValues, isActive, settleMs, exportConfig?.scale]);
370
+
338
371
  const reset = useCallback(() => {
339
372
  setPersonValues({});
340
373
  setIsActive(false);
@@ -343,6 +376,7 @@ export function PersonalizationProvider({
343
376
 
344
377
  const handleExport = useCallback(
345
378
  (exports: Record<string, string | Blob>) => {
379
+ lastExportAtRef.current = Date.now();
346
380
  // Store blob URLs locally
347
381
  const newUrls: Record<string, string> = {};
348
382
  for (const [name, data] of Object.entries(exports)) {
@@ -376,6 +410,11 @@ export function PersonalizationProvider({
376
410
  [realtime, placementOverride],
377
411
  );
378
412
 
413
+ const handleExportRef = useRef<typeof handleExport | null>(null);
414
+ useEffect(() => {
415
+ handleExportRef.current = handleExport;
416
+ }, [handleExport]);
417
+
379
418
  const handleExportScheduled = useCallback(() => {
380
419
  setIsExporting(true);
381
420
  }, []);
@@ -420,13 +459,16 @@ export function PersonalizationProvider({
420
459
  aria-hidden
421
460
  >
422
461
  <CanvasComponent
462
+ ref={canvasRef}
423
463
  initialElements={canvasState?.elements}
424
464
  artboards={canvasState?.artboards}
425
465
  kit="embed-only"
426
466
  inheritTheme
427
467
  autoExportConfig={{
428
468
  enabled: true,
429
- debounceMs: exportConfig?.debounceMs ?? 100,
469
+ // Typing cadence (~100-200 ms a key): one render per pause, not one per key (each render is a new picture
470
+ // on every mockup); maxWaitMs still shows progress during a long burst.
471
+ debounceMs: exportConfig?.debounceMs ?? PERSONALIZATION_EXPORT_DEBOUNCE_MS,
430
472
  maxWaitMs: exportConfig?.maxWaitMs ?? 1000,
431
473
  }}
432
474
  autoExportFormat="blob"
@@ -0,0 +1,81 @@
1
+ /**
2
+ * The last keystroke always exports. The canvas's auto-export drops a change that lands within 200 ms of its last
3
+ * export until a later change comes; the last keystroke of a name has none, so "Hello Kev!" printed and rendered as
4
+ * "Hello Kev" (prod 2026-12-01). Once typing has settled, the provider exports a change nothing exported.
5
+ */
6
+ import React, { forwardRef, useImperativeHandle } from "react";
7
+ import { act, render, waitFor } from "@testing-library/react";
8
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
9
+ import { PersonalizationProvider } from "../PersonalizationProvider";
10
+ import { usePersonalizationOptional } from "../usePersonalization";
11
+
12
+ const exportArtboards = vi.fn(async () => ({ Front: new Blob(["typed"], { type: "image/png" }) }));
13
+ /** A canvas whose auto-export never fires (the dropped last keystroke); its handle exports on demand. */
14
+ const canvasModule = {
15
+ SnowconeCanvas: forwardRef(function Stub(_props: unknown, ref) {
16
+ useImperativeHandle(ref, () => ({ exportArtboards }));
17
+ return null;
18
+ }),
19
+ useEditor: () => ({ elements: [] }),
20
+ useCommands: () => ({ executeElementUpdate: () => {} }),
21
+ useImageBinding: () => ({ setImageUrl: () => {} }),
22
+ };
23
+
24
+ let typed: ((v: string) => void) | null = null;
25
+ let exportCount = 0;
26
+ function Box() {
27
+ const ctx = usePersonalizationOptional();
28
+ typed = (v) => ctx?.updateField("Name", v);
29
+ exportCount = ctx?.exportCount ?? 0;
30
+ return null;
31
+ }
32
+
33
+ describe("PersonalizationProvider: the last keystroke always exports", () => {
34
+ beforeEach(() => {
35
+ exportArtboards.mockClear();
36
+ URL.createObjectURL = vi.fn(() => "blob:https://shop.test/typed");
37
+ URL.revokeObjectURL = vi.fn();
38
+ });
39
+ afterEach(() => {
40
+ typed = null;
41
+ });
42
+
43
+ it("a change the canvas never exported is exported once typing settles", async () => {
44
+ render(
45
+ <PersonalizationProvider
46
+ fields={[{ type: "text", name: "Name", label: "Name" } as never]}
47
+ canvasState={{ elements: [{ id: "t1" }] }}
48
+ canvasImport={() => Promise.resolve(canvasModule)}
49
+ exportConfig={{ debounceMs: 10, maxWaitMs: 10 }}
50
+ lazy
51
+ >
52
+ <Box />
53
+ </PersonalizationProvider>,
54
+ );
55
+ await waitFor(() => expect(typed).not.toBeNull());
56
+ act(() => typed!("Hello Kev!"));
57
+ await waitFor(() => expect(exportArtboards).toHaveBeenCalledTimes(1), { timeout: 2000 });
58
+ await waitFor(() => expect(exportCount).toBe(1));
59
+ });
60
+
61
+ it("WRONG CASE: nothing more while the shopper keeps typing (each change restarts the wait)", async () => {
62
+ render(
63
+ <PersonalizationProvider
64
+ fields={[{ type: "text", name: "Name", label: "Name" } as never]}
65
+ canvasState={{ elements: [{ id: "t1" }] }}
66
+ canvasImport={() => Promise.resolve(canvasModule)}
67
+ exportConfig={{ debounceMs: 100, maxWaitMs: 100 }}
68
+ lazy
69
+ >
70
+ <Box />
71
+ </PersonalizationProvider>,
72
+ );
73
+ await waitFor(() => expect(typed).not.toBeNull());
74
+ for (const v of ["H", "He", "Hel", "Hell"]) {
75
+ act(() => typed!(v));
76
+ await new Promise((r) => setTimeout(r, 150)); // under the 500 ms settle
77
+ }
78
+ expect(exportArtboards).not.toHaveBeenCalled();
79
+ await waitFor(() => expect(exportArtboards).toHaveBeenCalledTimes(1), { timeout: 2000 });
80
+ });
81
+ });