@snowcone-app/ui 0.9.7 → 0.10.0

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.
@@ -43,6 +43,7 @@ const h = vi.hoisted(() => {
43
43
  getLastSentVersion: vi.fn(() => 0),
44
44
  getLatestSentVersions: vi.fn(() => ({})),
45
45
  rerender: vi.fn((_ids: string[]) => true),
46
+ isFrameSuperseded: vi.fn((_url: string) => false),
46
47
  opts: null as null | { onError?: (msg: string, detail: Record<string, unknown>) => void },
47
48
  };
48
49
  });
@@ -68,6 +69,7 @@ vi.mock("@snowcone-app/sdk/react", () => ({
68
69
  getLastSentVersion: h.getLastSentVersion,
69
70
  getLatestSentVersions: h.getLatestSentVersions,
70
71
  rerender: h.rerender,
72
+ isFrameSuperseded: h.isFrameSuperseded,
71
73
  };
72
74
  },
73
75
  }));
@@ -435,6 +437,31 @@ describe("RealtimeProvider cropped delivery", () => {
435
437
  errSpy.mockRestore();
436
438
  });
437
439
 
440
+ it("a frame the SDK superseded is dropped at once, even when the newer batch reaches React after the grace (prod phone case, 20d5eaf, 2026-11-11)", async () => {
441
+ const { rerender } = render(<Harness version={1} />);
442
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
443
+ await seedAndFlip(rerender);
444
+ h.sendConfig.mockClear();
445
+ const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
446
+ // v3's frame arrived in the SDK (v2 revoked) at the START of a 31-picture batch; the batch's
447
+ // all_mockups_rendered — the only thing that updates React — came 2.3 s later.
448
+ h.isFrameSuperseded.mockImplementation((url: string) => url === "blob:v2-m1");
449
+ h.compositeCroppedFrame.mockImplementationOnce(() =>
450
+ Promise.reject(new Error("E_OVERLAY_FRAME_LOAD: image failed to load: blob:v2-m1"))
451
+ );
452
+ h.state.results = [croppedResult("m1", "blob:v2-m1"), fullResult("m2", "https://r/m2-full")];
453
+ await act(async () => rerender(<Harness version={4} />));
454
+ await act(async () => { await new Promise((r) => setTimeout(r, 2300)); });
455
+ expect(h.sendConfig).not.toHaveBeenCalled(); // cropped delivery stays on: no fallback config
456
+ expect(h.rerender).not.toHaveBeenCalled();
457
+ expect(errSpy.mock.calls.some((c) => String(c[0]).includes("E_OVERLAY_COMPOSITE_FAILED"))).toBe(false);
458
+ // The late batch composites normally.
459
+ h.state.results = [croppedResult("m1", "blob:v3-m1"), fullResult("m2", "https://r/m2-full")];
460
+ await act(async () => rerender(<Harness version={5} />));
461
+ await waitFor(() => expect(h.compositeCroppedFrame).toHaveBeenLastCalledWith(expect.objectContaining({ frameUrl: "blob:v3-m1" })));
462
+ errSpy.mockRestore();
463
+ });
464
+
438
465
  it("a revoked frame with no newer frame within the grace window is a real failure: full-frame re-render", async () => {
439
466
  const { rerender } = render(<Harness version={1} />);
440
467
  await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
@@ -0,0 +1,126 @@
1
+ /**
2
+ * The phone viewport policy end to end in the provider (lane-editor design, approved 2026-11-11). Conditions:
3
+ * 1. ONE config per change, holding the whole set wanted (the server keeps the last config).
4
+ * 3. The catch-up when the edit stops (every picture, editing width, one config) and its cancel by a new edit.
5
+ * 4. A swipe during an edit adds the new slide in one config.
6
+ * Done renders the slide on screen at hero width; desktop (no reports) sends exactly what it sends today.
7
+ */
8
+ import { describe, expect, it, beforeEach, vi } from "vitest";
9
+ import React from "react";
10
+ import { render, waitFor, act, cleanup } from "@testing-library/react";
11
+ import { RealtimeProvider, useRealtime, type RealtimeContextValue } from "../RealtimeProvider";
12
+
13
+ const h = vi.hoisted(() => ({
14
+ state: { results: [] as Array<Record<string, unknown>> },
15
+ sendConfig: vi.fn(),
16
+ version: 0,
17
+ sendCanvasState: vi.fn(() => true),
18
+ stable: {
19
+ sendCanvasBlob: vi.fn(), sendColorBlob: vi.fn(), updateMockupIds: vi.fn(), updatePlacementSettings: vi.fn(),
20
+ connect: vi.fn(), disconnect: vi.fn(), flushPendingBlobs: vi.fn(), hasPendingBlobs: vi.fn(() => false),
21
+ getLatestSentVersions: vi.fn(() => ({})), rerender: vi.fn(() => true),
22
+ },
23
+ }));
24
+
25
+ vi.mock("@snowcone-app/sdk/react", () => ({
26
+ useRealtimeMockup: () => ({
27
+ isConnected: true, isConfigured: true, renderError: null, mockupResults: h.state.results,
28
+ sendConfig: h.sendConfig, sendCanvasState: h.sendCanvasState, getLastSentVersion: () => h.version, ...h.stable,
29
+ }),
30
+ }));
31
+ vi.mock("@snowcone-app/sdk", () => ({ resolveVariantId: () => "gv1", resolvePreviewVariantId: (_c: unknown, v: string) => v }));
32
+ const IDS = ["M0", "M1", "M2", "M3", "M4", "M5"];
33
+ vi.mock("../Product", () => {
34
+ const product = { id: "p1", placements: [{ label: "Front", type: "image" }], mockups: ["M0", "M1", "M2", "M3", "M4", "M5"].map((id) => ({ id })) };
35
+ return { useProductOptional: () => ({ product, selection: {} }) };
36
+ });
37
+ vi.mock("../MockupBackground", () => ({ useMockupBackgroundOptional: () => undefined }));
38
+
39
+ let ctx: RealtimeContextValue;
40
+ function Capture() { ctx = useRealtime(); return null; }
41
+ function Harness({ v, editorOpen }: { v: number; editorOpen?: boolean }) {
42
+ void v;
43
+ return <RealtimeProvider autoEnable delivery="full-frame" mockupWidth={3000} editorOpen={editorOpen}><Capture /></RealtimeProvider>;
44
+ }
45
+ const configs = () => h.sendConfig.mock.calls.map((c) => c[0] as { mockupIds: string[]; width: number });
46
+ const shapes = () => configs().map((c) => `${c.mockupIds.join(",")}@${c.width}`);
47
+ const wait = (ms: number) => act(async () => { await new Promise((r) => setTimeout(r, ms)); });
48
+ // iPhone 14 in the editor: M0 on screen (342 css px x 3), M1 its neighbour.
49
+ function phoneGallery(onScreen = "M0", neighbours = ["M1"]) {
50
+ IDS.forEach((id) => ctx.reportPictureView(`${id}#el`, {
51
+ mockupId: id, onScreen: id === onScreen, inSet: id === onScreen || neighbours.includes(id), devicePx: id === onScreen || neighbours.includes(id) ? 1026 : 0,
52
+ }));
53
+ }
54
+ function edit() { h.version += 1; ctx.sendCanvasState("Front", { v: h.version }); }
55
+ const frame = (id: string, v: number) => ({ mockupId: id, imageUrl: `https://r/${id}-v${v}`, renderUrl: `https://r/${id}-v${v}`, imageSize: 1, placement: "Front", requestVersion: v });
56
+
57
+ beforeEach(() => {
58
+ cleanup();
59
+ vi.clearAllMocks();
60
+ h.state.results = [];
61
+ h.version = 0;
62
+ h.sendCanvasState.mockImplementation(() => true);
63
+ });
64
+
65
+ describe("viewport policy (phone gallery)", () => {
66
+ it("desktop / no gallery reports: one config, every picture at the page width, nothing more on edits (today)", async () => {
67
+ render(<Harness v={1} />);
68
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
69
+ await act(async () => { edit(); edit(); });
70
+ await wait(150);
71
+ expect(shapes()).toEqual([`${IDS.join(",")}@3000`]);
72
+ });
73
+
74
+ it("an edit renders the set in view at the screen's width, in ONE config; more edit steps send none", async () => {
75
+ render(<Harness v={1} />);
76
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
77
+ await act(async () => phoneGallery());
78
+ await wait(150);
79
+ h.sendConfig.mockClear();
80
+ await act(async () => { edit(); edit(); edit(); });
81
+ expect(shapes()).toEqual(["M0,M1@1200"]);
82
+ });
83
+
84
+ it("a swipe during the edit adds the new slide in ONE config", async () => {
85
+ render(<Harness v={1} />);
86
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
87
+ await act(async () => phoneGallery());
88
+ await wait(150);
89
+ await act(async () => edit());
90
+ h.sendConfig.mockClear();
91
+ await act(async () => phoneGallery("M1", ["M0", "M2"]));
92
+ await wait(150);
93
+ expect(shapes()).toEqual(["M0,M1,M2@1200"]);
94
+ });
95
+
96
+ it("when the edit settles: one catch-up config, every picture at the editing width; a new edit cancels it", async () => {
97
+ const { rerender } = render(<Harness v={1} />);
98
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
99
+ await act(async () => phoneGallery());
100
+ await wait(150);
101
+ await act(async () => edit());
102
+ h.sendConfig.mockClear();
103
+ // v1's frames for the set land: the pipeline settles.
104
+ h.state.results = [frame("M0", 1), frame("M1", 1)];
105
+ await act(async () => rerender(<Harness v={2} />));
106
+ await wait(300);
107
+ // A new edit inside the quiet window cancels the catch-up.
108
+ await act(async () => edit());
109
+ await wait(700);
110
+ expect(shapes()).toEqual([]);
111
+ h.state.results = [frame("M0", 2), frame("M1", 2)];
112
+ await act(async () => rerender(<Harness v={3} />));
113
+ await wait(700);
114
+ expect(shapes()).toEqual([`${IDS.join(",")}@1200`]);
115
+ });
116
+
117
+ it("Done: the slide on screen at hero width, in ONE config", async () => {
118
+ const { rerender } = render(<Harness v={1} />);
119
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
120
+ await act(async () => phoneGallery());
121
+ await wait(150);
122
+ h.sendConfig.mockClear();
123
+ await act(async () => rerender(<Harness v={2} editorOpen={false} />));
124
+ expect(shapes()).toEqual(["M0@3000"]);
125
+ });
126
+ });
@@ -0,0 +1,62 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { ladderWidth, sameShape, sessionShape, type PictureView } from "../sessionShape";
3
+
4
+ const ALL = Array.from({ length: 31 }, (_, i) => `M${i}`); // the phone case has 31 pictures
5
+ const view = (inSet: boolean, onScreen: boolean, devicePx = 1026): PictureView => ({ inSet, onScreen, devicePx });
6
+ // iPhone 14 in the editor: slide M0 on screen (342 css px x 3 = 1026 device px), M1 its neighbour.
7
+ const phone = new Map<string, PictureView>(ALL.map((id, i) => [id, view(i <= 1, i === 0, i <= 1 ? 1026 : 0)]));
8
+
9
+ describe("sessionShape", () => {
10
+ it("no viewport policy (desktop): every picture at the page width, exactly as today", () => {
11
+ expect(sessionShape({ allMockupIds: ALL, views: new Map(), heroWidth: 1280, editorOpen: true, editLive: true }))
12
+ .toEqual({ mockupIds: ALL, width: 1280, phase: "no-policy" });
13
+ });
14
+
15
+ it("a live edit renders only the set in view, at the width the screen shows (1026 -> 1200)", () => {
16
+ expect(sessionShape({ allMockupIds: ALL, views: phone, heroWidth: 3000, editorOpen: true, editLive: true }))
17
+ .toEqual({ mockupIds: ["M0", "M1"], width: 1200, phase: "editing" });
18
+ });
19
+
20
+ it("when the edit stops: every picture, still at the editing width (the catch-up)", () => {
21
+ expect(sessionShape({ allMockupIds: ALL, views: phone, heroWidth: 3000, editorOpen: true, editLive: false }))
22
+ .toEqual({ mockupIds: ALL, width: 1200, phase: "catch-up" });
23
+ });
24
+
25
+ it("Done: the slide on screen at hero width", () => {
26
+ expect(sessionShape({ allMockupIds: ALL, views: phone, heroWidth: 3000, editorOpen: false, editLive: false }))
27
+ .toEqual({ mockupIds: ["M0"], width: 3000, phase: "done" });
28
+ });
29
+
30
+ it("width comes from the element, not a breakpoint: a tablet slide 700 css px at 2x asks 1600", () => {
31
+ const tablet = new Map<string, PictureView>([["M0", view(true, true, 1400)], ["M1", view(true, false, 1400)]]);
32
+ expect(sessionShape({ allMockupIds: ALL, views: tablet, heroWidth: 3000, editorOpen: true, editLive: true }).width).toBe(1600);
33
+ });
34
+
35
+ it("keeps gallery order and never returns an empty set", () => {
36
+ const none = new Map<string, PictureView>([["M5", view(false, false, 0)]]);
37
+ expect(sessionShape({ allMockupIds: ALL, views: none, heroWidth: 3000, editorOpen: true, editLive: true }).mockupIds).toEqual(ALL);
38
+ expect(sessionShape({ allMockupIds: ALL, views: none, heroWidth: 3000, editorOpen: false, editLive: false }).mockupIds).toEqual(ALL);
39
+ });
40
+ });
41
+
42
+ describe("ladderWidth / sameShape", () => {
43
+ it("rounds UP to a ladder step", () => {
44
+ expect(ladderWidth(1026)).toBe(1200);
45
+ expect(ladderWidth(1200)).toBe(1200);
46
+ expect(ladderWidth(5000)).toBe(4000);
47
+ });
48
+ it("compares like the server: sorted ids and width", () => {
49
+ expect(sameShape({ mockupIds: ["b", "a"], width: 1200 }, { mockupIds: ["a", "b"], width: 1200 })).toBe(true);
50
+ expect(sameShape({ mockupIds: ["a"], width: 1200 }, { mockupIds: ["a"], width: 3000 })).toBe(false);
51
+ expect(sameShape(null, { mockupIds: ["a"], width: 1 })).toBe(false);
52
+ });
53
+
54
+ it("a mockup rendered twice (two elements) counts as on screen if either is", () => {
55
+ const twice = new Map<string, PictureView>([
56
+ ["M0#a", { mockupId: "M0", inSet: true, onScreen: true, devicePx: 1026 }],
57
+ ["M0#b", { mockupId: "M0", inSet: false, onScreen: false, devicePx: 0 }],
58
+ ]);
59
+ expect(sessionShape({ allMockupIds: ALL, views: twice, heroWidth: 3000, editorOpen: false, editLive: false }).mockupIds).toEqual(["M0"]);
60
+ });
61
+ });
62
+
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Which pictures a realtime session renders, and at what width (lane-editor phone design, approved 2026-11-11).
3
+ *
4
+ * The server renders exactly the LAST config's mockupIds at its width. Today a phone renders every picture at 3000 px
5
+ * on every edit step while it shows one slide 1026 device px wide (phone case: 31 pictures, 3.57 MB a step; on a
6
+ * 1.6 Mbps link a drag never caught up in 90 s). The shape:
7
+ *
8
+ * - no viewport policy (desktop, or a gallery that did not opt in): every picture at the page's width (today);
9
+ * - editor open, edit LIVE: the pictures in view (+ neighbours) at the width the screen shows them;
10
+ * - editor open, edit STOPPED: every picture at that width (the catch-up; a new edit takes it back to the view set);
11
+ * - editor closed (Done): the pictures in view at the hero width; others when they come into view.
12
+ *
13
+ * Pure: the provider feeds it state and sends ONE config whenever the result changes.
14
+ */
15
+
16
+ /** Widths a session asks for: the screen's need rounded UP to one of these (render tiers re-key any width anyway). */
17
+ export const WIDTH_LADDER = [400, 600, 800, 1000, 1200, 1600, 2000, 3000, 4000] as const;
18
+
19
+ export function ladderWidth(devicePx: number): number {
20
+ for (const w of WIDTH_LADDER) if (w >= devicePx) return w;
21
+ return WIDTH_LADDER[WIDTH_LADDER.length - 1];
22
+ }
23
+
24
+ export interface PictureView {
25
+ /** Optional when the map is keyed by mockup id; set when keyed per element (a mockup may render twice). */
26
+ mockupId?: string;
27
+ /** In view or a neighbour of the picture in view (the set an edit renders). */
28
+ inSet: boolean;
29
+ /** Actually on screen now (the set Done renders at hero width). */
30
+ onScreen: boolean;
31
+ /** Displayed width in device pixels (CSS width x devicePixelRatio). */
32
+ devicePx: number;
33
+ }
34
+
35
+ export interface ShapeInput {
36
+ /** Every mockup of the product, in gallery order. */
37
+ allMockupIds: readonly string[];
38
+ /** Pictures that opted into the viewport policy (the phone gallery), keyed by element (or by mockup id). Empty = no policy. */
39
+ views: ReadonlyMap<string, PictureView>;
40
+ /** The page's width for its pictures outside the editor (the phone hero: 3000). */
41
+ heroWidth: number;
42
+ editorOpen: boolean;
43
+ editLive: boolean;
44
+ }
45
+
46
+ export interface SessionShape {
47
+ mockupIds: string[];
48
+ width: number;
49
+ /** Why, for traces and data attributes. */
50
+ phase: "no-policy" | "editing" | "catch-up" | "done";
51
+ }
52
+
53
+ export function sessionShape(input: ShapeInput): SessionShape {
54
+ const { allMockupIds, views, heroWidth, editorOpen, editLive } = input;
55
+ if (views.size === 0) return { mockupIds: [...allMockupIds], width: heroWidth, phase: "no-policy" };
56
+ // Merge every element of a mockup (a gallery can render one twice): in set / on screen if ANY is, widest width.
57
+ const byMockup = new Map<string, PictureView>();
58
+ views.forEach((v, key) => {
59
+ const id = v.mockupId ?? key;
60
+ const prev = byMockup.get(id);
61
+ byMockup.set(id, prev
62
+ ? { inSet: prev.inSet || v.inSet, onScreen: prev.onScreen || v.onScreen, devicePx: Math.max(prev.devicePx, v.devicePx) }
63
+ : { inSet: v.inSet, onScreen: v.onScreen, devicePx: v.devicePx });
64
+ });
65
+ const ordered = (pick: (v: PictureView) => boolean) => allMockupIds.filter((id) => { const v = byMockup.get(id); return v ? pick(v) : false; });
66
+ const inSet = ordered((v) => v.inSet);
67
+ const onScreen = ordered((v) => v.onScreen);
68
+ const shown = [...byMockup.values()].filter((v) => v.inSet && v.devicePx > 0).map((v) => v.devicePx);
69
+ const editingWidth = shown.length ? ladderWidth(Math.max(...shown)) : heroWidth;
70
+ if (!editorOpen) {
71
+ const set = onScreen.length ? onScreen : inSet;
72
+ return { mockupIds: set.length ? set : [...allMockupIds], width: heroWidth, phase: "done" };
73
+ }
74
+ if (editLive && inSet.length) return { mockupIds: inSet, width: editingWidth, phase: "editing" };
75
+ return { mockupIds: [...allMockupIds], width: editingWidth, phase: "catch-up" };
76
+ }
77
+
78
+ /** Same render request? (The server compares sorted mockupIds and width.) */
79
+ export function sameShape(a: Pick<SessionShape, "mockupIds" | "width"> | null, b: Pick<SessionShape, "mockupIds" | "width">): boolean {
80
+ if (!a) return false;
81
+ return a.width === b.width && [...a.mockupIds].sort().join(",") === [...b.mockupIds].sort().join(",");
82
+ }