@snowcone-app/ui 0.11.17 → 0.12.1

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,126 @@
1
+ /**
2
+ * The tap-to-enlarge viewer opens on the PRODUCT, by the same rule as the phone hero's first view (carousels/firstView.ts).
3
+ *
4
+ * Founder, 2026-11-26, on the phone case page: "I think you largely fixed the crop positioning on Snowcone but when I
5
+ * tap to view it larger we lose the proper crop and can't see the item in frame anymore". The hero's first view now
6
+ * holds the product (#6499); the viewer a tap opens drew the 16:9 picture `object-fit: cover` in the whole 390 x 844
7
+ * screen at the picture's MIDDLE (x 0.37-0.63 of its width), so a product left of centre (the beach picture: the case in
8
+ * her hand, left of the picture's middle) or at the side (PR99HD: a key tag at x 0.19-0.26) was off the screen.
9
+ *
10
+ * The tests read the drawn place off the <img> (its object-position) and work out what part of the picture that puts on
11
+ * screen, so they assert what the shopper sees, not the helper's output.
12
+ */
13
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
14
+ import React from "react";
15
+ import { cleanup, render } from "@testing-library/react";
16
+ import { EnhancedImageViewer } from "../EnhancedImageViewer";
17
+ import type { ZoomImage } from "../types";
18
+ import { slideFirstViewFields } from "../../carousels/firstView";
19
+
20
+ // jsdom has no ResizeObserver; react-zoom-pan-pinch observes its wrapper
21
+ globalThis.ResizeObserver ??= class { observe() {} unobserve() {} disconnect() {} } as unknown as typeof ResizeObserver;
22
+
23
+ const PHONE = { width: 390, height: 844 };
24
+ const IMG = "https://img.snowcone.app/m.webp";
25
+
26
+ // prod KMKMX1 / PR99HD (2026-11-26): the key tag at x 0.19-0.26, its phone window x 0.08-0.41
27
+ const PR99HD = { productBox: { shape: "16:9", x: 0.1861, y: 0.437, w: 0.0708, h: 0.1276 }, phoneWindow: { shape: "2:3", x: 0.0787, w: 0.3333 } } as const;
28
+ // the beach picture's shape (the case in her hand, left of the picture's middle), a real phone case of the same shape:
29
+ // prod BC43BE / R4EW69 (2026-11-26), the case held up at x 0.12-0.25, its phone window x 0-0.375
30
+ const BEACH = { productBox: { shape: "16:9", x: 0.1193, y: 0.1133, w: 0.131, h: 0.4463 }, phoneWindow: { shape: "2:3", x: 0, w: 0.375 } } as const;
31
+ // a control, product and phone window both centred (what the viewer showed already): prod VAJJMF, a key tag on a plain ground
32
+ const CENTRED = { productBox: { shape: "16:9", x: 0.3808, y: 0.3741, w: 0.2384, h: 0.4272 }, phoneWindow: { shape: "2:3", x: 0.3128, w: 0.3747 } } as const;
33
+ // a product wider than the screen's slice of the picture (0.26 of it at 390 x 844), it cannot be held whole: prod Q3YNJK,
34
+ // a mouse pad at x 0.23-0.78
35
+ const WIDE = { productBox: { shape: "16:9", x: 0.225, y: 0.2472, w: 0.5504, h: 0.4972 }, phoneWindow: { shape: "2:3", x: 0.1711, w: 0.6578 } } as const;
36
+
37
+ function open(image: Omit<ZoomImage, "src">, index = 0) {
38
+ const images: ZoomImage[] = [{ src: `${IMG}?0` }, { src: `${IMG}?1` }];
39
+ images[index] = { src: `${IMG}?${index}`, ...image };
40
+ render(<EnhancedImageViewer imageUrl={images[index].src} alt="" onClose={() => {}} images={images} currentIndex={index} />);
41
+ return document.querySelector<HTMLImageElement>('[role="dialog"] img')!;
42
+ }
43
+
44
+ /** The slice of the picture's width on screen, from the drawn object-position (cover, a 16:9 picture in the screen). */
45
+ function sliceOnScreen(img: HTMLImageElement): [number, number] {
46
+ const pos = img.style.objectPosition;
47
+ const pictureWidth = Math.max(PHONE.width, PHONE.height * (16 / 9));
48
+ const m = /^(-?[\d.]+)px 50%$/.exec(pos);
49
+ // "center" / "" = the picture's middle
50
+ const left = m ? Number(m[1]) : (PHONE.width - pictureWidth) / 2;
51
+ return [-left / pictureWidth, (PHONE.width - left) / pictureWidth];
52
+ }
53
+
54
+ describe("the tap-to-enlarge viewer's first view", () => {
55
+ let saved: { w: number; h: number };
56
+ beforeEach(() => {
57
+ saved = { w: window.innerWidth, h: window.innerHeight };
58
+ Object.defineProperty(window, "innerWidth", { configurable: true, value: PHONE.width });
59
+ Object.defineProperty(window, "innerHeight", { configurable: true, value: PHONE.height });
60
+ });
61
+ afterEach(() => {
62
+ cleanup();
63
+ Object.defineProperty(window, "innerWidth", { configurable: true, value: saved.w });
64
+ Object.defineProperty(window, "innerHeight", { configurable: true, value: saved.h });
65
+ });
66
+
67
+ it("PR99HD: opens with the whole key tag on screen, and says so", () => {
68
+ const img = open(PR99HD);
69
+ const [x0, x1] = sliceOnScreen(img);
70
+ expect(x0).toBeLessThanOrEqual(PR99HD.productBox.x);
71
+ expect(x1).toBeGreaterThanOrEqual(PR99HD.productBox.x + PR99HD.productBox.w);
72
+ expect(img.getAttribute("data-first-view")).toBe("phone-window");
73
+ expect(img.getAttribute("data-first-view-product")).toBe("held");
74
+ });
75
+
76
+ it("the beach picture's shape (product left of the middle): the whole product on screen", () => {
77
+ const img = open(BEACH, 1);
78
+ const [x0, x1] = sliceOnScreen(img);
79
+ expect(x0).toBeLessThanOrEqual(BEACH.productBox.x);
80
+ expect(x1).toBeGreaterThanOrEqual(BEACH.productBox.x + BEACH.productBox.w);
81
+ expect(img.getAttribute("data-first-view-product")).toBe("held");
82
+ });
83
+
84
+ it("a centred product: the same view as before (the picture's middle)", () => {
85
+ const [x0, x1] = sliceOnScreen(open(CENTRED));
86
+ const middle = sliceOnScreen(open({}));
87
+ expect(x0).toBeCloseTo(middle[0], 3);
88
+ expect(x1).toBeCloseTo(middle[1], 3);
89
+ });
90
+
91
+ it("a picture without the fields: today's view, drawn by the picture's middle, and says why", () => {
92
+ const img = open({});
93
+ expect(img.style.objectPosition).toBe("");
94
+ expect(img.getAttribute("data-first-view")).toBe("picture-middle");
95
+ });
96
+
97
+ it("a product wider than the screen: centred on the product, reported cut", () => {
98
+ const img = open(WIDE);
99
+ const [x0, x1] = sliceOnScreen(img);
100
+ const mid = WIDE.productBox.x + WIDE.productBox.w / 2;
101
+ expect((x0 + x1) / 2).toBeCloseTo(mid, 3);
102
+ expect(img.getAttribute("data-first-view-product")).toBe("cut");
103
+ });
104
+
105
+ it("fields on a picture that is not the 16:9 one they measure: the middle, as before, and says why", () => {
106
+ const img = open({ ...PR99HD, naturalWidth: 1000, naturalHeight: 1500 });
107
+ expect(img.style.objectPosition).toBe("");
108
+ expect(img.getAttribute("data-first-view")).toBe("picture-middle");
109
+ expect(img.getAttribute("data-first-view-why")).toBe("picture-not-16:9");
110
+ });
111
+
112
+ it("a size picture opened whole (contain): untouched by the rule", () => {
113
+ const img = open({ ...PR99HD, fit: "whole" });
114
+ expect(img.style.objectFit).toBe("contain");
115
+ expect(img.style.objectPosition).toBe("");
116
+ expect(img.getAttribute("data-first-view")).toBe("whole");
117
+ });
118
+ });
119
+
120
+ describe("what the phone carousel hands the viewer", () => {
121
+ it("a real mockup carries its product box and phone window; anything else carries nothing (as the slide stamp)", () => {
122
+ expect(slideFirstViewFields({ isRealMockup: true, ...PR99HD })).toEqual(PR99HD);
123
+ expect(slideFirstViewFields({ isRealMockup: true })).toEqual({});
124
+ expect(slideFirstViewFields({ isRealMockup: false, ...PR99HD })).toEqual({});
125
+ });
126
+ });
@@ -1,3 +1,5 @@
1
+ import type { CarouselImage } from "../carousels/types";
2
+
1
3
  /**
2
4
  * Image interface for zoom components
3
5
  */
@@ -11,4 +13,11 @@ export interface ZoomImage {
11
13
  mockupId?: string;
12
14
  /** `whole`: open the picture whole (contain), not cropped to the screen: the gallery's size picture (a diagram). */
13
15
  fit?: "cover" | "whole";
16
+ /**
17
+ * Where the product and the mockup's phone window are in this (16:9) picture, as the phone carousel's slide carries
18
+ * them (carousels/firstView.ts). The viewer opens on them by the hero's first-view rule, so the product is on screen.
19
+ * Absent = the picture's middle (as before).
20
+ */
21
+ productBox?: CarouselImage["productBox"];
22
+ phoneWindow?: CarouselImage["phoneWindow"];
14
23
  }
package/src/index.ts CHANGED
@@ -158,6 +158,21 @@ export type {
158
158
  RealtimeState,
159
159
  } from "./patterns/RealtimeProvider";
160
160
 
161
+ // GallerySkip - a picture whose render cannot draw THIS design (a hand that cannot hold it) is left out of the gallery
162
+ export {
163
+ GallerySkipProvider,
164
+ useGallerySkipOptional,
165
+ useGallerySkipState,
166
+ } from "./patterns/GallerySkip";
167
+ export type { GallerySkipValue } from "./patterns/GallerySkip";
168
+ export {
169
+ gallerySkipVerdict,
170
+ galleryWithoutSkipped,
171
+ gallerySkippedStamp,
172
+ NO_GALLERY_SKIPS,
173
+ } from "./patterns/gallerySkipRules";
174
+ export type { GallerySkips, GallerySkipVerdict } from "./patterns/gallerySkipRules";
175
+
161
176
  // MockupPriorityProvider - priority-based mockup rendering coordination
162
177
  export {
163
178
  MockupPriorityProvider,
@@ -0,0 +1,113 @@
1
+ "use client";
2
+
3
+ /**
4
+ * GallerySkip: the pictures a product gallery leaves out for the design shown now, because their render cannot draw
5
+ * THIS design (a hand that cannot hold it; the rule is gallerySkipRules.ts, the codes `@snowcone-app/sdk` DESIGN_REFUSALS).
6
+ *
7
+ * Two paths report here, with no opt-in per product:
8
+ * - the plain path: a HeroProductImage whose <img> failed reads the answer's typed code (renderRefusalProbe.ts);
9
+ * - the realtime path: the session's typed refusal for one mockup (RealtimeContext.subscribeDesignRefusals).
10
+ *
11
+ * A skip holds for the design it was reported on. A new design (an upload, a chat design, a placement map) asks every
12
+ * picture again; a new realtime frame for a left-out mockup (an edit it can now draw) brings it back at once.
13
+ *
14
+ * The host owns the gallery list: `useGallerySkipState(design)` gives the skips, `galleryWithoutSkipped` filters the
15
+ * list (order kept), `<GallerySkipProvider value>` lets the pictures report and the gallery roots stamp
16
+ * `data-gallery-skipped`. Without a provider a picture that cannot draw the design says it is unavailable (loud).
17
+ */
18
+ import React, { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
19
+ import type { DesignRefusalCode } from "@snowcone-app/sdk";
20
+ import { useRealtimeOptional } from "./RealtimeProvider";
21
+ import type { GallerySkips } from "./gallerySkipRules";
22
+
23
+ export interface GallerySkipValue {
24
+ /** The pictures left out for the design shown now: mockupId -> code. */
25
+ skipped: GallerySkips;
26
+ /** A picture's render answered a design refusal (after its retry, for a retry-once code): leave it out for this design. */
27
+ report: (mockupId: string, code: DesignRefusalCode) => void;
28
+ }
29
+
30
+ interface Entry {
31
+ code: DesignRefusalCode;
32
+ /** The design it was reported on: it holds for that design only. */
33
+ design: string;
34
+ /** The realtime frame this mockup had when it was left out: a different one means it drew a design since. */
35
+ realtimeUrl: string | null;
36
+ }
37
+
38
+ const GallerySkipContext = createContext<GallerySkipValue | undefined>(undefined);
39
+
40
+ /**
41
+ * The gallery's skip state for `design` (any string that changes when the design shown changes: the artwork's src
42
+ * and, for a product printed piece by piece, its per-placement map).
43
+ */
44
+ export function useGallerySkipState(design: string): GallerySkipValue {
45
+ const realtime = useRealtimeOptional();
46
+ const [entries, setEntries] = useState<ReadonlyMap<string, Entry>>(() => new Map());
47
+ const entriesRef = useRef(entries);
48
+ entriesRef.current = entries;
49
+ const designRef = useRef(design);
50
+ designRef.current = design;
51
+ // The frame each mockup holds now (the results snapshot: a pending mockup still holds its last frame).
52
+ const getResults = realtime?.getMockupResultsImmediate;
53
+ const frameOfRef = useRef((mockupId: string): string | null => getResults?.().find((r) => r.mockupId === mockupId)?.imageUrl ?? null);
54
+ frameOfRef.current = (mockupId: string) => getResults?.().find((r) => r.mockupId === mockupId)?.imageUrl ?? null;
55
+
56
+ const report = useCallback((mockupId: string, code: DesignRefusalCode) => {
57
+ const at = designRef.current;
58
+ const realtimeUrl = frameOfRef.current(mockupId);
59
+ setEntries((prev) => {
60
+ const e = prev.get(mockupId);
61
+ if (e && e.code === code && e.design === at) return prev;
62
+ return new Map(prev).set(mockupId, { code, design: at, realtimeUrl });
63
+ });
64
+ }, []);
65
+
66
+ // The realtime session's typed refusal for one mockup (after E_HOLD_GRIP_BUSY's one retry).
67
+ const subscribeDesignRefusals = realtime?.subscribeDesignRefusals;
68
+ useEffect(() => {
69
+ if (!subscribeDesignRefusals) return;
70
+ return subscribeDesignRefusals((refusal) => report(refusal.mockupId, refusal.code));
71
+ }, [subscribeDesignRefusals, report]);
72
+
73
+ // A NEW realtime frame for a left-out mockup: it drew the design after all (an edit it can hold), so it is back.
74
+ // The all-results subscription, never the per-mockup one: watching a mockup by id changes its frame acks.
75
+ const subscribeMockupResults = realtime?.subscribeMockupResults;
76
+ useEffect(() => {
77
+ if (!subscribeMockupResults) return;
78
+ return subscribeMockupResults((results) => {
79
+ const current = entriesRef.current;
80
+ if (current.size === 0) return;
81
+ const back = results.filter((r) => {
82
+ const e = current.get(r.mockupId);
83
+ if (!e) return false;
84
+ return !!r.imageUrl && r.imageUrl !== e.realtimeUrl;
85
+ });
86
+ if (back.length === 0) return;
87
+ setEntries((prev) => {
88
+ const next = new Map(prev);
89
+ back.forEach((r) => next.delete(r.mockupId));
90
+ return next;
91
+ });
92
+ });
93
+ }, [subscribeMockupResults]);
94
+
95
+ const skipped = useMemo<GallerySkips>(() => {
96
+ const m = new Map<string, DesignRefusalCode>();
97
+ entries.forEach((e, id) => {
98
+ if (e.design === design) m.set(id, e.code);
99
+ });
100
+ return m;
101
+ }, [entries, design]);
102
+
103
+ return useMemo(() => ({ skipped, report }), [skipped, report]);
104
+ }
105
+
106
+ export function GallerySkipProvider({ value, children }: { value: GallerySkipValue; children?: React.ReactNode }) {
107
+ return <GallerySkipContext.Provider value={value}>{children}</GallerySkipContext.Provider>;
108
+ }
109
+
110
+ /** The gallery's skip state, or undefined outside a GallerySkipProvider. */
111
+ export function useGallerySkipOptional(): GallerySkipValue | undefined {
112
+ return useContext(GallerySkipContext);
113
+ }
@@ -40,8 +40,10 @@ import { useRealtimeMockup } from "@snowcone-app/sdk/react";
40
40
  import { gallerySizePicture, mockupRole, resolvePreviewVariantId, resolveVariantId as resolveVariantIdUtil, type MockupView } from "@snowcone-app/sdk";
41
41
  import type {
42
42
  RealtimeRenderError,
43
+ RealtimeDesignRefusal,
43
44
  MockupResult as SdkMockupResult,
44
45
  } from "@snowcone-app/sdk";
46
+ import { gallerySkipVerdict } from "./gallerySkipRules";
45
47
  import { readEnv } from "../lib/env";
46
48
  import { useProductOptional } from "./Product";
47
49
  import type { ReactProductContext } from "./Product";
@@ -123,6 +125,12 @@ export interface RealtimeContextValue {
123
125
  * — never as a stale or blank image.
124
126
  */
125
127
  unavailableMockups: ReadonlyMap<string, RealtimeRenderError>;
128
+ /**
129
+ * The box cannot draw THIS design on a mockup (a hand that cannot hold it: E_HOLD_NO_GRIP; E_HOLD_GRIP_BUSY after
130
+ * its one retry, which this provider sends). Never `renderError`, never `unavailableMockups`: a gallery
131
+ * (GallerySkip) leaves that picture out for this design. Returns the unsubscribe.
132
+ */
133
+ subscribeDesignRefusals: (callback: (refusal: RealtimeDesignRefusal) => void) => () => void;
126
134
 
127
135
  // Debug/tracking state (now refs, won't trigger re-renders)
128
136
  isPendingMockups: boolean;
@@ -492,6 +500,11 @@ export function RealtimeProvider({
492
500
  );
493
501
 
494
502
  const resetSessionRef = useRef<() => void>(() => {});
503
+ // A mockup that cannot draw THIS design (designRefusal.ts): the gallery's listeners, the busy answers seen per
504
+ // mockup since its last frame (E_HOLD_GRIP_BUSY is asked once more, then reported), and the re-ask (set below).
505
+ const designRefusalSubscribersRef = useRef(new Set<(refusal: RealtimeDesignRefusal) => void>());
506
+ const designBusySeenRef = useRef(new Map<string, number>());
507
+ const designRetryRef = useRef<((mockupIds: string[]) => void) | null>(null);
495
508
  const realtimeMockup = useRealtimeMockup({
496
509
  wsUrl,
497
510
  getToken: useSessionGrant ? getToken : undefined,
@@ -543,6 +556,24 @@ export function RealtimeProvider({
543
556
  setUnavailableMockups((prev) => (prev.get(id)?.code === detail.code ? prev : new Map(prev).set(id, detail)));
544
557
  }
545
558
  },
559
+ onDesignRefusal: (refusal) => {
560
+ const seen = designBusySeenRef.current.get(refusal.mockupId) ?? 0;
561
+ const verdict = gallerySkipVerdict(refusal.code, seen);
562
+ if (verdict === "retry") {
563
+ designBusySeenRef.current.set(refusal.mockupId, seen + 1);
564
+ designRetryRef.current?.([refusal.mockupId]);
565
+ return;
566
+ }
567
+ if (verdict !== "skip") return; // unreachable: the SDK sends only design-refusal codes here
568
+ if (designRefusalSubscribersRef.current.size === 0) {
569
+ // No gallery leaves pictures out here (no GallerySkip): never silent, that one picture says it is unavailable.
570
+ const id = refusal.mockupId;
571
+ const detail: RealtimeRenderError = { code: refusal.code, message: refusal.message, mockupId: id };
572
+ setUnavailableMockups((prev) => (prev.get(id)?.code === detail.code ? prev : new Map(prev).set(id, detail)));
573
+ return;
574
+ }
575
+ designRefusalSubscribersRef.current.forEach((cb) => cb(refusal));
576
+ },
546
577
  });
547
578
 
548
579
  // RTC timing subscription (legacy — kept for API compatibility)
@@ -954,6 +985,8 @@ export function RealtimeProvider({
954
985
  },
955
986
  [rerenderRaw]
956
987
  );
988
+ // E_HOLD_GRIP_BUSY's one retry: the picture is asked again, paced like every re-ask.
989
+ designRetryRef.current = sendRerenderPaced;
957
990
 
958
991
  const rerenderFullFrame = useCallback(
959
992
  (mockupId: string) => {
@@ -1146,6 +1179,8 @@ export function RealtimeProvider({
1146
1179
  else merged.push(result);
1147
1180
  });
1148
1181
  mockupResultsRef.current = merged;
1182
+ // a frame for a mockup resets its busy count: its next E_HOLD_GRIP_BUSY gets its one retry again
1183
+ results.forEach((result) => designBusySeenRef.current.delete(result.mockupId));
1149
1184
  if (pendingRerenderRef.current.length > 0) {
1150
1185
  const delivered = new Set(results.map((r) => r.mockupId));
1151
1186
  pendingRerenderRef.current = pendingRerenderRef.current.filter((id) => !delivered.has(id));
@@ -1521,6 +1556,7 @@ export function RealtimeProvider({
1521
1556
  const resetSession = useCallback(() => {
1522
1557
  configSentRef.current = false;
1523
1558
  dueByVersionRef.current.clear(); // versions restart at 1 on the next socket
1559
+ designBusySeenRef.current.clear(); // a new session asks every picture afresh
1524
1560
  setUnavailableMockups((prev) => (prev.size ? new Map() : prev)); // a fixed mockup stops being refused
1525
1561
  lastSentVariantIdRef.current = null;
1526
1562
  lastSentBgRef.current = undefined;
@@ -2064,6 +2100,14 @@ export function RealtimeProvider({
2064
2100
  subscribePipelineSettledRef.current = subscribePipelineSettled;
2065
2101
  subscribePendingExportCancelledRef.current = subscribePendingExportCancelled;
2066
2102
 
2103
+ const subscribeDesignRefusals = useCallback((callback: (refusal: RealtimeDesignRefusal) => void) => {
2104
+ const subscribers = designRefusalSubscribersRef.current;
2105
+ subscribers.add(callback);
2106
+ return () => {
2107
+ subscribers.delete(callback);
2108
+ };
2109
+ }, []);
2110
+
2067
2111
  // Stable wrappers that delegate to the ref
2068
2112
  const stableSubscribeMockupResults = useCallback(
2069
2113
  (callback: (results: MockupResult[]) => void) => {
@@ -2147,6 +2191,7 @@ export function RealtimeProvider({
2147
2191
  isConfigured,
2148
2192
  renderError,
2149
2193
  unavailableMockups,
2194
+ subscribeDesignRefusals,
2150
2195
  // Read from ref - this is a snapshot at render time, NOT reactive
2151
2196
  // For reactive updates, use getMockupResultsImmediate() or subscribe functions
2152
2197
  get mockupResults() {
@@ -2203,6 +2248,7 @@ export function RealtimeProvider({
2203
2248
  isConfigured,
2204
2249
  renderError,
2205
2250
  unavailableMockups,
2251
+ subscribeDesignRefusals,
2206
2252
  // mockupResults removed from deps - it's a getter that reads from ref
2207
2253
  canvasExportSize,
2208
2254
  mockupWidth,
@@ -0,0 +1,125 @@
1
+ /**
2
+ * The realtime path of the gallery skip: a session's typed "cannot draw this design" refusal for one mockup
3
+ * (E_HOLD_NO_GRIP; E_HOLD_GRIP_BUSY after its one retry) leaves that picture out of the gallery (GallerySkip) for this
4
+ * design: never the session's error bar, never the "Mockup unavailable" overlay. A new design, or a new frame for it,
5
+ * brings it back. Without a gallery listening, the one picture says it is unavailable (never silent).
6
+ */
7
+ import { describe, expect, it, beforeEach, vi } from "vitest";
8
+ import React from "react";
9
+ import { render, waitFor, act, cleanup } from "@testing-library/react";
10
+ import { RealtimeProvider, useRealtime, type RealtimeContextValue } from "../RealtimeProvider";
11
+ import { useGallerySkipState, type GallerySkipValue } from "../GallerySkip";
12
+
13
+ const h = vi.hoisted(() => ({
14
+ opts: null as null | { onDesignRefusal?: (r: { mockupId: string; code: string; message: string }) => void },
15
+ state: { results: [] as Array<Record<string, unknown>> },
16
+ sendConfig: vi.fn(),
17
+ rerender: vi.fn((_ids: string[]) => 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(() => ({})), isFrameSuperseded: vi.fn(() => false),
22
+ sendCanvasState: vi.fn(() => true), ackFrame: vi.fn(() => false),
23
+ },
24
+ }));
25
+ vi.mock("@snowcone-app/sdk/react", () => ({
26
+ useRealtimeMockup: (opts: typeof h.opts) => {
27
+ h.opts = opts;
28
+ return {
29
+ isConnected: true, isConfigured: true, renderError: null, acks: null, mockupResults: h.state.results,
30
+ sendConfig: h.sendConfig, getLastSentVersion: () => 0, rerender: h.rerender, ...h.stable,
31
+ };
32
+ },
33
+ }));
34
+ vi.mock("@snowcone-app/sdk", async (importOriginal) => ({
35
+ ...(await importOriginal<typeof import("@snowcone-app/sdk")>()),
36
+ mockupRole: () => "ordinary",
37
+ gallerySizePicture: () => null,
38
+ resolveVariantId: () => "gv1",
39
+ resolvePreviewVariantId: (_c: unknown, v: string) => v,
40
+ }));
41
+ vi.mock("../Product", () => {
42
+ const product = {
43
+ id: "MXRC3J",
44
+ placements: [{ label: "Front", type: "image" }],
45
+ mockups: [{ id: "VJ6VEC" }, { id: "NQKEK3" }, { id: "VWCBAP" }],
46
+ };
47
+ return { useProductOptional: () => ({ product, selection: {} }) };
48
+ });
49
+ vi.mock("../MockupBackground", () => ({ useMockupBackgroundOptional: () => undefined }));
50
+
51
+ let ctx: RealtimeContextValue;
52
+ let skip: GallerySkipValue;
53
+ function Capture() { ctx = useRealtime(); return null; }
54
+ function Gallery({ design }: { design: string }) { skip = useGallerySkipState(design); return null; }
55
+ function Harness({ design, gallery = true, v = 0 }: { design: string; gallery?: boolean; v?: number }) {
56
+ void v;
57
+ return (
58
+ <RealtimeProvider autoEnable delivery="full-frame">
59
+ <Capture />
60
+ {gallery && <Gallery design={design} />}
61
+ </RealtimeProvider>
62
+ );
63
+ }
64
+ const refuse = (mockupId: string, code: string) =>
65
+ act(async () => h.opts?.onDesignRefusal?.({ mockupId, code, message: `${mockupId} ${code}` }));
66
+ const frame = (id: string, n: number) =>
67
+ ({ mockupId: id, imageUrl: `https://r/${id}-${n}`, renderUrl: `https://r/${id}-${n}`, imageSize: 1, placement: "Front", requestVersion: n });
68
+
69
+ beforeEach(() => {
70
+ cleanup();
71
+ vi.clearAllMocks();
72
+ h.opts = null;
73
+ h.state.results = [];
74
+ });
75
+
76
+ describe("realtime: a mockup that cannot draw this design is left out of the gallery", () => {
77
+ it("E_HOLD_NO_GRIP: skipped for this design, no unavailable overlay, no session error", async () => {
78
+ render(<Harness design="giraffe" />);
79
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
80
+ await refuse("NQKEK3", "E_HOLD_NO_GRIP");
81
+ expect([...skip.skipped]).toEqual([["NQKEK3", "E_HOLD_NO_GRIP"]]);
82
+ expect(ctx.unavailableMockups.size).toBe(0);
83
+ expect(ctx.renderError).toBeNull();
84
+ });
85
+
86
+ it("E_HOLD_GRIP_BUSY: asked once more (rerender), then left out quietly", async () => {
87
+ render(<Harness design="giraffe" />);
88
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
89
+ await refuse("VWCBAP", "E_HOLD_GRIP_BUSY");
90
+ expect(h.rerender).toHaveBeenCalledWith(["VWCBAP"]);
91
+ expect(skip.skipped.size).toBe(0);
92
+ await refuse("VWCBAP", "E_HOLD_GRIP_BUSY");
93
+ expect([...skip.skipped]).toEqual([["VWCBAP", "E_HOLD_GRIP_BUSY"]]);
94
+ expect(h.rerender).toHaveBeenCalledTimes(1);
95
+ });
96
+
97
+ it("a new design asks again; a NEW frame for the mockup brings it back, a re-delivered old one does not", async () => {
98
+ h.state.results = [frame("VJ6VEC", 1), frame("NQKEK3", 1)];
99
+ const { rerender } = render(<Harness design="giraffe" v={1} />);
100
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
101
+ await refuse("NQKEK3", "E_HOLD_NO_GRIP");
102
+ expect(skip.skipped.has("NQKEK3")).toBe(true);
103
+ // the same frames again (a summary re-delivers every picture's latest): still out
104
+ h.state.results = [frame("VJ6VEC", 1), frame("NQKEK3", 1)];
105
+ await act(async () => rerender(<Harness design="giraffe" v={2} />));
106
+ expect(skip.skipped.has("NQKEK3")).toBe(true);
107
+ // a new design: asked again
108
+ await act(async () => rerender(<Harness design="toucan" v={2} />));
109
+ expect(skip.skipped.size).toBe(0);
110
+ // refused on the new design too, then an edit it can hold renders a NEW frame: back
111
+ await refuse("NQKEK3", "E_HOLD_NO_GRIP");
112
+ expect(skip.skipped.has("NQKEK3")).toBe(true);
113
+ h.state.results = [frame("VJ6VEC", 2), frame("NQKEK3", 2)];
114
+ await act(async () => rerender(<Harness design="toucan" v={3} />));
115
+ expect(skip.skipped.size).toBe(0);
116
+ });
117
+
118
+ it("no gallery listening: that one picture says it is unavailable (never silent), the session error stays clear", async () => {
119
+ render(<Harness design="giraffe" gallery={false} />);
120
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
121
+ await refuse("NQKEK3", "E_HOLD_NO_GRIP");
122
+ expect(ctx.unavailableMockups.get("NQKEK3")?.code).toBe("E_HOLD_NO_GRIP");
123
+ expect(ctx.renderError).toBeNull();
124
+ });
125
+ });
@@ -0,0 +1,71 @@
1
+ /**
2
+ * The gallery's skip rule (gallerySkipRules.ts): which answers leave a picture out (a hand that cannot hold THIS design)
3
+ * and which stay loud, and the gallery's order after a skip (MXRC3J: the clean shot VJ6VEC first, the two hand
4
+ * pictures NQKEK3 / VWCBAP left out for a design they cannot hold).
5
+ */
6
+ import { describe, expect, it } from "vitest";
7
+ import type { DesignRefusalCode } from "@snowcone-app/sdk";
8
+ import { gallerySkippedStamp, gallerySkipVerdict, galleryWithoutSkipped, NO_GALLERY_SKIPS } from "../gallerySkipRules";
9
+
10
+ describe("gallerySkipVerdict: which codes skip, which stay loud", () => {
11
+ it("E_HOLD_NO_GRIP is left out at once", () => {
12
+ expect(gallerySkipVerdict("E_HOLD_NO_GRIP", 0)).toBe("skip");
13
+ expect(gallerySkipVerdict("E_HOLD_NO_GRIP", 1)).toBe("skip");
14
+ });
15
+
16
+ it("E_HOLD_GRIP_BUSY is retried once, then left out quietly", () => {
17
+ expect(gallerySkipVerdict("E_HOLD_GRIP_BUSY", 0)).toBe("retry");
18
+ expect(gallerySkipVerdict("E_HOLD_GRIP_BUSY", 1)).toBe("skip");
19
+ expect(gallerySkipVerdict("E_HOLD_GRIP_BUSY", 2)).toBe("skip");
20
+ });
21
+
22
+ it("a genuine render error stays loud: other typed codes, untyped answers, no answer", () => {
23
+ for (const code of ["E_MOCKUP_NOT_BLESSED", "E_PREWARP_EMPTY", "E_HOLD_NOTHING_TO_HOLD", "E_SERVE_BUSY", "E_RENDER_ORIGIN_TIMEOUT", "render_failed", null, undefined, ""]) {
24
+ expect(gallerySkipVerdict(code, 0)).toBe("loud");
25
+ expect(gallerySkipVerdict(code, 1)).toBe("loud");
26
+ }
27
+ });
28
+ });
29
+
30
+ type Img = { mockupId?: string; isRealMockup?: boolean; label?: string };
31
+ const gallery: Img[] = [
32
+ { mockupId: "VJ6VEC", isRealMockup: true }, // the clean shot
33
+ { mockupId: "LAPTOP", isRealMockup: true },
34
+ { mockupId: "NQKEK3", isRealMockup: true }, // a woman's hand
35
+ { mockupId: "BOTTLE", isRealMockup: true },
36
+ { mockupId: "VWCBAP", isRealMockup: true }, // a man's hand
37
+ { isRealMockup: false, label: "AI Generated" },
38
+ ];
39
+ const skips = (entries: Array<[string, DesignRefusalCode]>) => new Map(entries);
40
+
41
+ describe("galleryWithoutSkipped: the gallery after a skip", () => {
42
+ it("leaves out the skipped pictures; the clean shot stays first and the rest keep their order", () => {
43
+ const out = galleryWithoutSkipped(gallery, skips([["NQKEK3", "E_HOLD_NO_GRIP"], ["VWCBAP", "E_HOLD_NO_GRIP"]]));
44
+ expect(out.map((i) => i.mockupId ?? i.label)).toEqual(["VJ6VEC", "LAPTOP", "BOTTLE", "AI Generated"]);
45
+ });
46
+
47
+ it("nothing skipped: the same array (no re-render churn)", () => {
48
+ expect(galleryWithoutSkipped(gallery, NO_GALLERY_SKIPS)).toBe(gallery);
49
+ expect(galleryWithoutSkipped(gallery, skips([["OTHER1", "E_HOLD_NO_GRIP"]]))).toBe(gallery);
50
+ });
51
+
52
+ it("only real mockups are left out; never an empty gallery (then every picture stays and says so)", () => {
53
+ const one: Img[] = [{ mockupId: "NQKEK3", isRealMockup: true }];
54
+ expect(galleryWithoutSkipped(one, skips([["NQKEK3", "E_HOLD_NO_GRIP"]]))).toBe(one);
55
+ const notReal: Img[] = [{ mockupId: "VJ6VEC", isRealMockup: true }, { mockupId: "NQKEK3", isRealMockup: false }];
56
+ expect(galleryWithoutSkipped(notReal, skips([["NQKEK3", "E_HOLD_NO_GRIP"]]))).toBe(notReal);
57
+ });
58
+ });
59
+
60
+ describe("gallerySkippedStamp: data-gallery-skipped", () => {
61
+ it("names each left-out picture as <mockupId>:<code>, in a stable order", () => {
62
+ const s = skips([["VWCBAP", "E_HOLD_GRIP_BUSY"], ["NQKEK3", "E_HOLD_NO_GRIP"]]);
63
+ expect(gallerySkippedStamp(s, galleryWithoutSkipped(gallery, s))).toBe("NQKEK3:E_HOLD_NO_GRIP VWCBAP:E_HOLD_GRIP_BUSY");
64
+ expect(gallerySkippedStamp(skips([["NQKEK3", "E_HOLD_NO_GRIP"]]), [{ mockupId: "VJ6VEC" }])).toBe("NQKEK3:E_HOLD_NO_GRIP");
65
+ });
66
+
67
+ it("says nothing when nothing is left out, or when the host did not leave it out (truthful)", () => {
68
+ expect(gallerySkippedStamp(NO_GALLERY_SKIPS, gallery)).toBeUndefined();
69
+ expect(gallerySkippedStamp(skips([["NQKEK3", "E_HOLD_NO_GRIP"]]), gallery)).toBeUndefined();
70
+ });
71
+ });
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The gallery's skip rule: a picture whose render cannot draw THIS design (a hand that cannot hold it,
3
+ * `@snowcone-app/sdk` DESIGN_REFUSALS) is not in that shopper's gallery, for that design. Pure, so the rule is
4
+ * testable without a render.
5
+ *
6
+ * - `E_HOLD_NO_GRIP` (422): left out at once.
7
+ * - `E_HOLD_GRIP_BUSY` (503): asked once more; a second design refusal leaves it out quietly.
8
+ * - Anything else (another `E_*`, a 500, a network failure, no code): LOUD, exactly as before (the picture says it is
9
+ * unavailable). The list is closed: a code nobody classified is never hidden.
10
+ *
11
+ * Machine-readable: a gallery that left pictures out stamps `data-gallery-skipped="<mockupId>:<code> …"` on its root.
12
+ */
13
+ import { designRefusalKind, type DesignRefusalCode } from "@snowcone-app/sdk";
14
+
15
+ export type GallerySkipVerdict = "skip" | "retry" | "loud";
16
+
17
+ /** What a gallery does with a picture whose render answered `code` (null: no typed code), `attempt` answers in (0 = the first). */
18
+ export function gallerySkipVerdict(code: string | null | undefined, attempt: number): GallerySkipVerdict {
19
+ const kind = designRefusalKind(code);
20
+ if (kind === "skip") return "skip";
21
+ if (kind === "retry-once") return attempt < 1 ? "retry" : "skip";
22
+ return "loud";
23
+ }
24
+
25
+ /** The pictures left out of the gallery for the design shown now: mockupId -> the code its render answered. */
26
+ export type GallerySkips = ReadonlyMap<string, DesignRefusalCode>;
27
+
28
+ export const NO_GALLERY_SKIPS: GallerySkips = new Map();
29
+
30
+ /**
31
+ * The gallery without the pictures left out, every other picture in its order (the first stays first). Only real
32
+ * mockups are left out (an AI picture or a placeholder never is). Never empties a gallery: when every picture would
33
+ * go, all stay and each says it is unavailable (loud). The same array comes back when nothing is left out.
34
+ */
35
+ export function galleryWithoutSkipped<T extends { mockupId?: string; isRealMockup?: boolean }>(
36
+ images: T[],
37
+ skipped: GallerySkips,
38
+ ): T[] {
39
+ if (skipped.size === 0) return images;
40
+ const kept = images.filter((img) => !(img.isRealMockup && img.mockupId && skipped.has(img.mockupId)));
41
+ if (kept.length === images.length || kept.length === 0) return images;
42
+ return kept;
43
+ }
44
+
45
+ /**
46
+ * `data-gallery-skipped` for a gallery showing `shown`: each left-out picture as `<mockupId>:<code>`, space separated,
47
+ * in a stable order. Only pictures really absent from `shown` (a host that did not filter stamps nothing).
48
+ */
49
+ export function gallerySkippedStamp(skipped: GallerySkips, shown: ReadonlyArray<{ mockupId?: string }>): string | undefined {
50
+ if (skipped.size === 0) return undefined;
51
+ const shownIds = new Set(shown.map((img) => img.mockupId).filter(Boolean));
52
+ const parts = [...skipped]
53
+ .filter(([id]) => !shownIds.has(id))
54
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
55
+ .map(([id, code]) => `${id}:${code}`);
56
+ return parts.length ? parts.join(" ") : undefined;
57
+ }