@snowcone-app/ui 0.12.2 → 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.
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Typing into a personalization box must not make the pictures flash (snowcone.app engraved tumbler / opener,
3
+ * 2026-12-01):
4
+ * - the picture on screen stays until the next one has loaded AND decoded; a live frame (blob:) then swaps in at once,
5
+ * with no 400 ms crossfade per keystroke; another picture (a new design) still crossfades;
6
+ * - a picture MOUNTED with a live frame (the phone carousel mounting slide 3 as the shopper swipes) keeps that frame:
7
+ * its static store-default picture never replaces it (picture 3 kept "YOUR NAME" while its stamp said current).
8
+ */
9
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
10
+ import React from "react";
11
+ import { act, cleanup, fireEvent, render, waitFor } from "@testing-library/react";
12
+ import { HeroProductImage, pictureSwapOf } from "../HeroProductImage";
13
+
14
+ const ART = { type: "regular", src: "https://example.test/art.png" } as const;
15
+ const PRODUCT = { id: "CFKWA6", placements: [{ label: "Front", key: "front" }] };
16
+
17
+ /** An Image that loads and decodes at once (jsdom fetches nothing). */
18
+ class DecodedImage {
19
+ crossOrigin = "";
20
+ decoding = "auto";
21
+ src = "";
22
+ complete = true;
23
+ naturalWidth = 1;
24
+ onload: (() => void) | null = null;
25
+ onerror: (() => void) | null = null;
26
+ decode() {
27
+ return Promise.resolve();
28
+ }
29
+ }
30
+
31
+ const srcs = (c: HTMLElement) => Array.from(c.querySelectorAll("img")).map((i) => i.getAttribute("src"));
32
+
33
+ describe("pictureSwapOf", () => {
34
+ it("a live frame swaps at once; another picture crossfades", () => {
35
+ expect(pictureSwapOf("blob:https://x/1", "blob:https://x/2")).toBe("instant");
36
+ expect(pictureSwapOf("https://img.test/a", "blob:https://x/2")).toBe("instant");
37
+ expect(pictureSwapOf("blob:https://x/1", "https://img.test/b")).toBe("instant");
38
+ expect(pictureSwapOf("https://img.test/a", "https://img.test/b")).toBe("crossfade");
39
+ expect(pictureSwapOf(null, "https://img.test/b")).toBe("instant");
40
+ });
41
+ });
42
+
43
+ describe("HeroProductImage: swapping pictures without a blank or a smear", () => {
44
+ beforeEach(() => {
45
+ (window as unknown as { snowcone?: unknown }).snowcone = { shop: "shop1" };
46
+ vi.stubGlobal("Image", DecodedImage);
47
+ });
48
+ afterEach(() => {
49
+ cleanup();
50
+ vi.unstubAllGlobals();
51
+ delete (window as unknown as { snowcone?: unknown }).snowcone;
52
+ });
53
+
54
+ const hero = (realtimeUrl: string, mode?: "realtime") => (
55
+ <HeroProductImage productId="CFKWA6" mockupId="HCX799" gvid="gv1" artwork={ART} product={PRODUCT} width={800} realtimeUrl={realtimeUrl} mode={mode} />
56
+ );
57
+
58
+ const root = (c: HTMLElement) => c.querySelector<HTMLElement>("[data-hero-image]")!;
59
+ const layer = (c: HTMLElement) => c.querySelectorAll("img")[1] as HTMLImageElement;
60
+
61
+ it("live frames: the next frame loads hidden over the shown one, then shows at once; the main picture follows under it", async () => {
62
+ const { container, rerender } = render(hero("blob:https://shop.test/frame-1"));
63
+ await waitFor(() => expect(srcs(container)).toEqual(["blob:https://shop.test/frame-1"]));
64
+ rerender(hero("blob:https://shop.test/frame-2"));
65
+ // loading: the shown picture is untouched, the next one invisible above it
66
+ await waitFor(() => expect(srcs(container)).toEqual(["blob:https://shop.test/frame-1", "blob:https://shop.test/frame-2"]));
67
+ expect(root(container).dataset.heroIncoming).toBe("loading");
68
+ expect(layer(container).style.opacity).toBe("0");
69
+ fireEvent.load(layer(container));
70
+ // shown at once (no fade), and the main <img> takes the frame underneath it
71
+ await waitFor(() => expect(root(container).dataset.heroIncoming).toBe("showing"));
72
+ expect(layer(container).style.opacity).toBe("1");
73
+ expect(layer(container).style.transition).toBe("");
74
+ expect(srcs(container)).toEqual(["blob:https://shop.test/frame-2", "blob:https://shop.test/frame-2"]);
75
+ fireEvent.load(container.querySelector("img")!);
76
+ await waitFor(() => expect(srcs(container)).toEqual(["blob:https://shop.test/frame-2"]));
77
+ expect(root(container).dataset.heroIncoming).toBeUndefined();
78
+ });
79
+
80
+ it("another picture: fades in over the old one, which stays until the fade is done", async () => {
81
+ // Only the pictures it is handed (mode "realtime": no static picture of its own). In "auto", a non-live URL handed
82
+ // in at mount is replaced by the hero's own static picture (HeroProductImage.mountsOnLiveFrame.test.tsx).
83
+ const { container, rerender } = render(hero("https://img.test/a.png", "realtime"));
84
+ await waitFor(() => expect(srcs(container)).toEqual(["https://img.test/a.png"]));
85
+ rerender(hero("https://img.test/b.png", "realtime"));
86
+ await waitFor(() => expect(srcs(container)).toEqual(["https://img.test/a.png", "https://img.test/b.png"]));
87
+ fireEvent.load(layer(container));
88
+ await waitFor(() => expect(layer(container).style.opacity).toBe("1"));
89
+ expect(layer(container).style.transition).toContain("opacity");
90
+ expect(srcs(container)[0]).toBe("https://img.test/a.png");
91
+ fireEvent.transitionEnd(layer(container));
92
+ await waitFor(() => expect(srcs(container)).toEqual(["https://img.test/b.png", "https://img.test/b.png"]));
93
+ fireEvent.load(container.querySelector("img")!);
94
+ await waitFor(() => expect(srcs(container)).toEqual(["https://img.test/b.png"]));
95
+ });
96
+
97
+ it("a picture mounted with a live frame keeps it: its static picture never replaces it", async () => {
98
+ const { container } = render(hero("blob:https://shop.test/typed-name"));
99
+ // the static path signs/builds asynchronously; give every effect and promise a turn
100
+ await act(async () => {
101
+ await new Promise((r) => setTimeout(r, 50));
102
+ });
103
+ expect(srcs(container)).toEqual(["blob:https://shop.test/typed-name"]);
104
+ });
105
+ });
@@ -779,6 +779,9 @@ export function RealtimeProvider({
779
779
  // full-frame re-render (see rerenderFullFrame).
780
780
  const fullFrameRerenderIdsRef = useRef<Set<string>>(new Set());
781
781
  const fullFrameRerenderTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
782
+ const rerenderFullFrameRef = useRef<((mockupId: string) => void) | null>(null);
783
+ // Pictures whose newest frame was lost and re-asked (frameFailed), until they show a picture again.
784
+ const lostFrameAskedRef = useRef<Set<string>>(new Set());
782
785
  useEffect(
783
786
  () => () => {
784
787
  if (fullFrameRerenderTimerRef.current) clearTimeout(fullFrameRerenderTimerRef.current);
@@ -859,6 +862,7 @@ export function RealtimeProvider({
859
862
  */
860
863
  const markBlobShown = useCallback((owner: string, url: string, consumer = "default") => {
861
864
  ackUrl(url); // drawn: the box may send this picture's next frame
865
+ lostFrameAskedRef.current.delete(owner); // it shows a picture again: a later lost frame may ask again
862
866
  const list = blobsByOwnerRef.current.get(owner);
863
867
  if (!list || list.indexOf(url) < 0) return;
864
868
  const shown = shownBlobByOwnerRef.current.get(owner) ?? new Map<string, string>();
@@ -867,9 +871,35 @@ export function RealtimeProvider({
867
871
  releaseOlderFrames(owner);
868
872
  }, [releaseOlderFrames, ackUrl]);
869
873
 
870
- /** A picture could not load a delivered frame (its img errored): the client is done with it (frame flow control). */
874
+ /**
875
+ * A picture could not load a delivered frame (its img errored): the client is done with it (frame flow control).
876
+ *
877
+ * When that frame is the picture's NEWEST (still what getMockupUrl hands out) and nothing newer is on its way, the
878
+ * edit would be lost on that picture: it was off screen when its frames came (the phone carousel mounts only the
879
+ * slides near the one shown) and its newest frame died before an element drew it. Forget the dead frame, so no
880
+ * later element is handed it, and re-render exactly that picture (rerenderFullFrame). Once per picture until it
881
+ * shows something again (markBlobShown), so a frame that can never load cannot loop.
882
+ */
871
883
  const frameFailed = useCallback((url: string) => {
872
884
  ackUrl(url);
885
+ if (!url.startsWith("blob:")) return; // a network picture: HeroProductImage's retry and fallback own it
886
+ let mockupId: string | undefined;
887
+ mockupUrlCacheRef.current.forEach((entry, id) => {
888
+ if (entry.url === url) mockupId = id;
889
+ });
890
+ if (!mockupId) return; // not its newest frame: a newer one was delivered
891
+ if (pendingMockupIdsRef.current.has(mockupId)) return; // an edit's frame is on its way
892
+ if (compositeQueueRef.current.has(mockupId) || compositeBusyRef.current.has(mockupId)) return; // its successor composites
893
+ if (lostFrameAskedRef.current.has(mockupId)) return;
894
+ lostFrameAskedRef.current.add(mockupId);
895
+ console.error(
896
+ `[RealtimeProvider] E_FRAME_LOST: ${mockupId}'s newest frame could not be loaded (gone before any element drew it); re-rendering that picture.`
897
+ );
898
+ // Forget it where a later element would be handed it (getMockupUrl(s), the replay to a new subscriber). Not
899
+ // revoked here: a twin element may still show it; it is released like any frame once the re-render is shown.
900
+ mockupUrlCacheRef.current.delete(mockupId);
901
+ mockupResultsRef.current = mockupResultsRef.current.filter((r) => r.imageUrl !== url);
902
+ rerenderFullFrameRef.current?.(mockupId);
873
903
  }, [ackUrl]);
874
904
 
875
905
  /** An element of a picture is gone (unmount): it no longer holds a frame. */
@@ -1022,6 +1052,7 @@ export function RealtimeProvider({
1022
1052
  },
1023
1053
  [sendFullFrameConfig, forceRerenderByConfig, sendRerenderPaced]
1024
1054
  );
1055
+ rerenderFullFrameRef.current = rerenderFullFrame;
1025
1056
 
1026
1057
  /** Flip to cropped delivery once every configured mockup has a frozen
1027
1058
  * background (a cropped frame can't seed one). */
@@ -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
+
@@ -68,7 +68,9 @@ export function PersonalizationInputs({
68
68
  <input
69
69
  key={`text-${field.name}`}
70
70
  type="text"
71
+ aria-label={field.label}
71
72
  placeholder={field.placeholder || field.label}
73
+ maxLength={field.maxLength}
72
74
  value={personValues[field.name] ?? ""}
73
75
  onChange={(e) => updateField(field.name, e.target.value)}
74
76
  onFocus={handleFocus}
@@ -38,7 +38,7 @@ import type {
38
38
  PersonalizationField,
39
39
  PersonalizationValues,
40
40
  } from "./types";
41
- import { normalizeHex, isValidImageUrl, useDebouncedValue } from "./utils";
41
+ import { normalizeHex, isValidImageUrl, useDebouncedValue, canvasFontString, measureTextLine, shrinkFontSizeToFit, anyTyped, textValueFor, type TextLineStyle } from "./utils";
42
42
 
43
43
  // ---------------------------------------------------------------------------
44
44
  // Bridge factory — creates the PersonalizationBridge component from the canvas
@@ -52,7 +52,11 @@ function createBridgeFromCanvas(canvasModule: any): React.ComponentType<{
52
52
  }> {
53
53
  const { useEditor, useCommands, useImageBinding } = canvasModule;
54
54
 
55
- function TextBinder({ name, value }: { name: string; value: string }) {
55
+ /**
56
+ * One text field → its named elements. `value`: the text to draw, or null = the element's own (designed) text, put back
57
+ * when it was changed (a sample field whose boxes were all cleared again). fit "shrink": the size is fitted to the box.
58
+ */
59
+ function TextBinder({ name, value, fit, sample }: { name: string; value: string | null; fit?: "shrink"; sample?: boolean }) {
56
60
  const { elements } = useEditor();
57
61
  const { executeElementUpdate } = useCommands();
58
62
  const elementsRef = React.useRef(elements);
@@ -60,20 +64,53 @@ function createBridgeFromCanvas(canvasModule: any): React.ComponentType<{
60
64
  const executeRef = React.useRef(executeElementUpdate);
61
65
  executeRef.current = executeElementUpdate;
62
66
  const hasUserInput = React.useRef(false);
67
+ // each element's text and size as the designer set them (by element id): what null restores, what fit shrinks from
68
+ const designed = React.useRef(new Map<string, { text: string; fontSize: number }>());
63
69
 
64
70
  React.useEffect(() => {
65
- if (value == null) return;
66
- if (value === "" && !hasUserInput.current) return;
71
+ if (value === null && !hasUserInput.current) return;
72
+ // "" before any input leaves a designer's text alone; on a sample field it means "drawn empty" (something was typed)
73
+ if (value === "" && !hasUserInput.current && !sample) return;
67
74
  hasUserInput.current = true;
68
- const exec = executeRef.current;
69
- for (const el of elementsRef.current) {
70
- if (el.name !== name) continue;
71
- if (!("setText" in el) || typeof (el as any).setText !== "function") continue;
72
- const cloned = el.clone();
73
- (cloned as any).setText(value);
74
- exec(el, cloned);
75
+ let cancelled = false;
76
+ const bound = elementsRef.current.filter((el: any) => el.name === name && typeof el.setText === "function");
77
+ for (const el of bound as any[]) {
78
+ if (!designed.current.has(el.id)) designed.current.set(el.id, { text: typeof el.getText === "function" ? el.getText() : el.text, fontSize: el.fontSize });
79
+ }
80
+ const apply = (sizes: Map<string, number>) => {
81
+ if (cancelled) return;
82
+ const exec = executeRef.current;
83
+ for (const el of elementsRef.current) {
84
+ if (el.name !== name) continue;
85
+ if (!("setText" in el) || typeof (el as any).setText !== "function") continue;
86
+ const own = designed.current.get(el.id);
87
+ const cloned = el.clone();
88
+ (cloned as any).setText(value ?? own?.text ?? "");
89
+ const size = value === null ? own?.fontSize : sizes.get(el.id);
90
+ if (size !== undefined) (cloned as any).fontSize = size;
91
+ exec(el, cloned);
92
+ }
93
+ };
94
+ if (fit !== "shrink" || value === null) {
95
+ apply(new Map());
96
+ return () => { cancelled = true; };
75
97
  }
76
- }, [value, name, elements.length]);
98
+ // Fit each bound element: its designed size, made smaller until one line of the value fits its box width. The
99
+ // element's own font must be loaded before it is measured (else the fallback font's widths are fitted).
100
+ const styled = (bound as any[]).map((el) => {
101
+ const style: TextLineStyle = { fontSize: designed.current.get(el.id)!.fontSize, fontFamily: el.fontFamily, bold: el.bold, italic: el.italic, letterSpacing: el.letterSpacing };
102
+ return { id: el.id as string, style, boxWidth: Number(el.transformData?.width) || 0 };
103
+ });
104
+ const fonts = typeof document !== "undefined" && document.fonts ? Promise.all(styled.map((st) => document.fonts.load(canvasFontString(st.style)).catch(() => []))) : Promise.resolve([]);
105
+ void fonts.then(() => {
106
+ const sizes = new Map<string, number>();
107
+ for (const st of styled) {
108
+ sizes.set(st.id, st.boxWidth > 0 ? shrinkFontSizeToFit(value, st.style, st.boxWidth, (t, size) => measureTextLine(t, st.style, size)) : st.style.fontSize);
109
+ }
110
+ apply(sizes);
111
+ });
112
+ return () => { cancelled = true; };
113
+ }, [value, name, fit, sample, elements.length]);
77
114
  return null;
78
115
  }
79
116
 
@@ -146,11 +183,13 @@ function createBridgeFromCanvas(canvasModule: any): React.ComponentType<{
146
183
  }
147
184
 
148
185
  return function PersonalizationBridge({ fields = [], values = {} }: { fields?: PersonalizationField[]; values?: PersonalizationValues } = {}) {
186
+ // a sample field draws its sample until anything is typed, then exactly its box (textValueFor)
187
+ const typed = anyTyped(fields, values);
149
188
  return (
150
189
  <>
151
190
  {fields.map((field) => {
152
191
  if (field.type === "text") {
153
- return <TextBinder key={`text-${field.name}`} name={field.name} value={values[field.name] ?? ""} />;
192
+ return <TextBinder key={`text-${field.name}`} name={field.name} value={textValueFor(field, values, typed)} fit={field.fit} sample={field.sample} />;
154
193
  }
155
194
  if (field.type === "color") {
156
195
  return <ColorBinder key={`color-${field.color}`} originalColor={field.color} newColor={values[field.color] ?? field.color} />;
@@ -165,6 +204,9 @@ function createBridgeFromCanvas(canvasModule: any): React.ComponentType<{
165
204
  };
166
205
  }
167
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
+
168
210
  // Module-level cache — shared across all provider instances
169
211
  let cachedCanvasComponent: React.ComponentType<any> | null = null;
170
212
  let cachedBridgeComponent: React.ComponentType<any> | null = null;
@@ -291,11 +333,41 @@ export function PersonalizationProvider({
291
333
 
292
334
  // --- Actions ---
293
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
+
294
341
  const updateField = useCallback((key: string, value: string) => {
295
342
  setIsActive(true);
343
+ lastChangeAtRef.current = Date.now();
296
344
  setPersonValues((prev) => ({ ...prev, [key]: value }));
297
345
  }, []);
298
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
+
299
371
  const reset = useCallback(() => {
300
372
  setPersonValues({});
301
373
  setIsActive(false);
@@ -304,6 +376,7 @@ export function PersonalizationProvider({
304
376
 
305
377
  const handleExport = useCallback(
306
378
  (exports: Record<string, string | Blob>) => {
379
+ lastExportAtRef.current = Date.now();
307
380
  // Store blob URLs locally
308
381
  const newUrls: Record<string, string> = {};
309
382
  for (const [name, data] of Object.entries(exports)) {
@@ -337,6 +410,11 @@ export function PersonalizationProvider({
337
410
  [realtime, placementOverride],
338
411
  );
339
412
 
413
+ const handleExportRef = useRef<typeof handleExport | null>(null);
414
+ useEffect(() => {
415
+ handleExportRef.current = handleExport;
416
+ }, [handleExport]);
417
+
340
418
  const handleExportScheduled = useCallback(() => {
341
419
  setIsExporting(true);
342
420
  }, []);
@@ -381,13 +459,16 @@ export function PersonalizationProvider({
381
459
  aria-hidden
382
460
  >
383
461
  <CanvasComponent
462
+ ref={canvasRef}
384
463
  initialElements={canvasState?.elements}
385
464
  artboards={canvasState?.artboards}
386
465
  kit="embed-only"
387
466
  inheritTheme
388
467
  autoExportConfig={{
389
468
  enabled: true,
390
- 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,
391
472
  maxWaitMs: exportConfig?.maxWaitMs ?? 1000,
392
473
  }}
393
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
+ });
@@ -0,0 +1,75 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { shrinkFontSizeToFit, canvasFontString, FIT_MARGIN, anyTyped, textValueFor, type TextLineStyle } from "../utils";
3
+
4
+ // A stand-in font: every character is 0.5 em wide, plus the style's letter spacing (a browser measures the same way:
5
+ // linear in the size, a fixed advance per character).
6
+ const style: TextLineStyle = { fontSize: 72, fontFamily: "Oswald", bold: true };
7
+ const measure = (s: TextLineStyle) => (text: string, size: number) => text.length * size * 0.5 + (s.letterSpacing ?? 0) * text.length;
8
+
9
+ describe("shrinkFontSizeToFit", () => {
10
+ it("keeps the designed size when the text already fits", () => {
11
+ expect(shrinkFontSizeToFit("YOUR NAME", style, 500, measure(style))).toBe(72);
12
+ });
13
+
14
+ it("shrinks a long name until one line of it fits the box (never past the edge)", () => {
15
+ const text = "Maximilian Johnson the Third";
16
+ const size = shrinkFontSizeToFit(text, style, 487, measure(style));
17
+ expect(size).toBeLessThan(72);
18
+ expect(measure(style)(text, size)).toBeLessThanOrEqual(487 * (1 - FIT_MARGIN));
19
+ // and not needlessly small: one more half-pixel would no longer fit
20
+ expect(measure(style)(text, size + 1)).toBeGreaterThan(487 * (1 - FIT_MARGIN));
21
+ });
22
+
23
+ it("never grows the text past the designed size", () => {
24
+ expect(shrinkFontSizeToFit("A", style, 5000, measure(style))).toBe(72);
25
+ });
26
+
27
+ it("accounts for letter spacing (a fixed advance that does not shrink with the size)", () => {
28
+ const spaced = { ...style, letterSpacing: 6 };
29
+ const text = "CHRISTOPHER COLUMBUS";
30
+ const size = shrinkFontSizeToFit(text, spaced, 487, measure(spaced));
31
+ expect(measure(spaced)(text, size)).toBeLessThanOrEqual(487 * (1 - FIT_MARGIN));
32
+ });
33
+
34
+ it("leaves the size alone when nothing can be measured (a server render, no box)", () => {
35
+ expect(shrinkFontSizeToFit("Anything long enough to overflow", style, 487, () => 0)).toBe(72);
36
+ expect(shrinkFontSizeToFit("Anything", style, 0, measure(style))).toBe(72);
37
+ });
38
+ });
39
+
40
+ describe("canvasFontString", () => {
41
+ it("is the canvas's own shorthand (TextMetrics buildFontString)", () => {
42
+ expect(canvasFontString(style)).toBe("bold 72px Oswald");
43
+ expect(canvasFontString({ ...style, italic: true }, 40)).toBe("italic bold 40px Oswald");
44
+ expect(canvasFontString({ fontSize: 12, fontFamily: "Arial" })).toBe("12px Arial");
45
+ });
46
+ });
47
+
48
+ describe("textValueFor / anyTyped (sample text)", () => {
49
+ const line = (n: number, sample = true) => ({ type: "text" as const, name: `line${n}`, label: `Line ${n}`, sample });
50
+ const fields = [line(1), line(2), line(3)];
51
+
52
+ it("draws the samples (null) until anything is typed", () => {
53
+ expect(anyTyped(fields, {})).toBe(false);
54
+ expect(fields.map((f) => textValueFor(f, {}, false))).toEqual([null, null, null]);
55
+ });
56
+
57
+ it("once one box is typed, every sample field draws exactly its box: 'Kevin' alone, not 'Kevin / NAME / HERE'", () => {
58
+ const values = { line1: "Kevin" };
59
+ const typed = anyTyped(fields, values);
60
+ expect(typed).toBe(true);
61
+ expect(fields.map((f) => textValueFor(f, values, typed))).toEqual(["Kevin", "", ""]);
62
+ });
63
+
64
+ it("brings the samples back when every box is cleared (blank counts as cleared)", () => {
65
+ const values = { line1: "", line2: " " };
66
+ expect(anyTyped(fields, values)).toBe(false);
67
+ expect(fields.map((f) => textValueFor(f, values, false))).toEqual([null, null, null]);
68
+ });
69
+
70
+ it("leaves a field that is not a sample as it was: its own box's text, '' until typed", () => {
71
+ const f = line(1, false);
72
+ expect(textValueFor(f, {}, true)).toBe("");
73
+ expect(textValueFor(f, { line1: "Ana" }, true)).toBe("Ana");
74
+ });
75
+ });
@@ -40,4 +40,5 @@ export { usePersonalizationShimmer } from "./usePersonalizationShimmer";
40
40
  export type { UsePersonalizationShimmerReturn } from "./usePersonalizationShimmer";
41
41
 
42
42
  // Utilities (for custom input implementations)
43
- export { scrollInputAboveKeyboard, normalizeHex } from "./utils";
43
+ export { scrollInputAboveKeyboard, normalizeHex, shrinkFontSizeToFit, measureTextLine, canvasFontString, FIT_MARGIN, anyTyped, textValueFor } from "./utils";
44
+ export type { TextLineStyle } from "./utils";
@@ -14,6 +14,22 @@ export interface PersonalizationTextField {
14
14
  label: string;
15
15
  /** Input placeholder */
16
16
  placeholder?: string;
17
+ /** The longest text the input takes (the input's `maxLength`): the designer's limit for the layout. */
18
+ maxLength?: number;
19
+ /**
20
+ * How the buyer's text meets the element's box. `"shrink"`: the text is set at the element's own size and made
21
+ * smaller (never larger) until one line of it fits the box width (a custom text element's `transformData.width`), so
22
+ * a long name never runs past the design's edge or wraps onto a line the layout has no room for. Absent: the text
23
+ * keeps the element's size and wraps or overflows as the element does.
24
+ */
25
+ fit?: "shrink";
26
+ /**
27
+ * The element's own text is a SAMPLE ("YOUR NAME"): it shows only until the buyer types into ANY field of the design;
28
+ * from then on this field draws exactly what is in its box, nothing when it is empty (so "Kevin" typed on line 1 of a
29
+ * three-line sample is engraved alone, not as "Kevin / NAME / HERE"). Every box cleared again: the samples come back.
30
+ * Absent: the element's own text stays until this field itself is typed into.
31
+ */
32
+ sample?: boolean;
17
33
  }
18
34
 
19
35
  /** Color field — buyer can change a color throughout the design */