@snowcone-app/ui 0.12.0 → 0.12.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.
- package/CHANGELOG.md +16 -0
- package/dist/index.cjs +838 -654
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +62 -2
- package/dist/index.d.ts +62 -2
- package/dist/index.js +753 -575
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/composed/HeroProductImage.tsx +45 -3
- package/src/composed/__tests__/HeroProductImage.designRefusal.test.tsx +117 -0
- package/src/composed/carousels/MobileProductCarousel.tsx +7 -2
- package/src/composed/renderRefusalProbe.ts +35 -0
- package/src/index.ts +15 -0
- package/src/patterns/GallerySkip.tsx +113 -0
- package/src/patterns/RealtimeProvider.tsx +46 -0
- package/src/patterns/__tests__/RealtimeProvider.designRefusal.test.tsx +125 -0
- package/src/patterns/__tests__/gallerySkipRules.test.ts +71 -0
- package/src/patterns/gallerySkipRules.ts +57 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@snowcone-app/ui",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.2",
|
|
4
4
|
"description": "React components for merchandise visualization and customization",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react",
|
|
@@ -103,7 +103,7 @@
|
|
|
103
103
|
"react-instantsearch": "^7.15.5",
|
|
104
104
|
"react-zoom-pan-pinch": "^3.6.4",
|
|
105
105
|
"tailwind-merge": "^3.0.0",
|
|
106
|
-
"@snowcone-app/sdk": "0.33.
|
|
106
|
+
"@snowcone-app/sdk": "0.33.4"
|
|
107
107
|
},
|
|
108
108
|
"devDependencies": {
|
|
109
109
|
"@chromatic-com/storybook": "^4.1.2",
|
|
@@ -18,6 +18,9 @@ import { useRealtimeOptional } from "../patterns/RealtimeProvider";
|
|
|
18
18
|
import { useMockupPriorityOptional } from "../patterns/MockupPriorityProvider";
|
|
19
19
|
import { useMockupBackgroundOptional } from "../patterns/MockupBackground";
|
|
20
20
|
import { placementArtFor, usePlacementArtOptional } from "../patterns/PlacementArt";
|
|
21
|
+
import { useGallerySkipOptional } from "../patterns/GallerySkip";
|
|
22
|
+
import { gallerySkipVerdict } from "../patterns/gallerySkipRules";
|
|
23
|
+
import { probeRenderAnswer } from "./renderRefusalProbe";
|
|
21
24
|
import { LoadingOverlayPrismCandyInline } from "../components/LoadingOverlayPrismCandy";
|
|
22
25
|
import {
|
|
23
26
|
createDesignForPlacements,
|
|
@@ -26,6 +29,7 @@ import {
|
|
|
26
29
|
resolvePreviewVariantId,
|
|
27
30
|
resolveMockupId,
|
|
28
31
|
SNOWCONE_HOSTS,
|
|
32
|
+
isDesignRefusalCode,
|
|
29
33
|
type MockupView,
|
|
30
34
|
} from "@snowcone-app/sdk";
|
|
31
35
|
import { heroMockupUrl, type HeroSize, type PlacementLike } from "./heroMockupUrl";
|
|
@@ -77,6 +81,8 @@ import { useContainerWidth } from "../hooks/viewport/useContainerWidth";
|
|
|
77
81
|
import { observe } from "../hooks/visibility/observerPool";
|
|
78
82
|
|
|
79
83
|
const EMPTY_IMAGES: DesignElement[] = [];
|
|
84
|
+
/** E_HOLD_GRIP_BUSY (the grip plan ran out of time on the box): its one retry waits this long first. */
|
|
85
|
+
const DESIGN_BUSY_RETRY_MS = 1500;
|
|
80
86
|
|
|
81
87
|
export interface HeroProductImageProps {
|
|
82
88
|
productId?: string;
|
|
@@ -250,6 +256,11 @@ export const HeroProductImage = memo(function HeroProductImage({
|
|
|
250
256
|
const placementArt = usePlacementArtOptional();
|
|
251
257
|
// What the picture shows: the artwork, and the per-placement map when there is one (a new map is new art).
|
|
252
258
|
const placementArtKey = placementArt ? JSON.stringify(placementArt) : "";
|
|
259
|
+
// The gallery this picture is in, when it can leave a picture out (GallerySkip): a render that cannot draw THIS
|
|
260
|
+
// design (a hand that cannot hold it) is reported there instead of painting "Preview unavailable".
|
|
261
|
+
const gallerySkip = useGallerySkipOptional();
|
|
262
|
+
const gallerySkipRef = useRef(gallerySkip);
|
|
263
|
+
gallerySkipRef.current = gallerySkip;
|
|
253
264
|
const priorityContextRef = useRef(priorityContext);
|
|
254
265
|
priorityContextRef.current = priorityContext;
|
|
255
266
|
|
|
@@ -1111,6 +1122,10 @@ export const HeroProductImage = memo(function HeroProductImage({
|
|
|
1111
1122
|
// useEffect runs and overlays prevUrl (showing OLD on top), then prevUrl
|
|
1112
1123
|
// fades out to reveal NEW again — i.e. the new → old → new flash.
|
|
1113
1124
|
const [renderedUrl, setRenderedUrl] = useState<string | null>(displayUrl);
|
|
1125
|
+
const renderedUrlRef = useRef(renderedUrl);
|
|
1126
|
+
renderedUrlRef.current = renderedUrl;
|
|
1127
|
+
// The typed "cannot draw this design" code the shown URL answered (E_HOLD_NO_GRIP …): data-design-refused.
|
|
1128
|
+
const [designRefused, setDesignRefused] = useState<string | null>(null);
|
|
1114
1129
|
// `renderedUrl` is set as soon as a URL exists, but the <img> paints nothing
|
|
1115
1130
|
// until the render is actually fetched (seconds, on a cold render). Keep the
|
|
1116
1131
|
// rainbow loader up until the first image has painted.
|
|
@@ -1155,6 +1170,7 @@ export const HeroProductImage = memo(function HeroProductImage({
|
|
|
1155
1170
|
// New URL to try — clear any prior load failure so the <img> remounts,
|
|
1156
1171
|
// and give this URL a fresh retry budget.
|
|
1157
1172
|
setImgFailed(false);
|
|
1173
|
+
setDesignRefused(null);
|
|
1158
1174
|
retriedUrlRef.current = null;
|
|
1159
1175
|
|
|
1160
1176
|
// Initial load — no crossfade. Just update rendered URL.
|
|
@@ -1260,6 +1276,7 @@ export const HeroProductImage = memo(function HeroProductImage({
|
|
|
1260
1276
|
data-picture-failed={imgFailed ? "E_PICTURE_UNDISPLAYED" : undefined}
|
|
1261
1277
|
data-picture-failed-src={failedSrc}
|
|
1262
1278
|
data-mockup-unavailable={unavailable ? unavailable.code : undefined}
|
|
1279
|
+
data-design-refused={designRefused ?? undefined}
|
|
1263
1280
|
>
|
|
1264
1281
|
{unavailable && (
|
|
1265
1282
|
<div
|
|
@@ -1316,11 +1333,36 @@ export const HeroProductImage = memo(function HeroProductImage({
|
|
|
1316
1333
|
// headers). `cache:"reload"` bypasses the poisoned entry and
|
|
1317
1334
|
// stores a fresh CORS-tagged copy; the key-bumped <img> remount
|
|
1318
1335
|
// then loads that copy under the same canonical URL.
|
|
1336
|
+
// The same fetch reads the answer's typed code (an <img> never sees it): a render that cannot draw THIS
|
|
1337
|
+
// design (E_HOLD_NO_GRIP; E_HOLD_GRIP_BUSY after its one retry) is left out of the gallery, never a grey
|
|
1338
|
+
// panel. Every other answer takes the retry and, failing again, the loud fallback below.
|
|
1319
1339
|
if (renderedUrl && retriedUrlRef.current !== renderedUrl) {
|
|
1320
1340
|
retriedUrlRef.current = renderedUrl;
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1341
|
+
const url = renderedUrl;
|
|
1342
|
+
const mockupIdNow = actualMockupId;
|
|
1343
|
+
void (async () => {
|
|
1344
|
+
let answer = await probeRenderAnswer(url);
|
|
1345
|
+
let verdict = answer.ok ? "loud" : gallerySkipVerdict(answer.code, 0);
|
|
1346
|
+
if (verdict === "retry") {
|
|
1347
|
+
await new Promise((r) => setTimeout(r, DESIGN_BUSY_RETRY_MS));
|
|
1348
|
+
if (renderedUrlRef.current !== url) return;
|
|
1349
|
+
answer = await probeRenderAnswer(url);
|
|
1350
|
+
verdict = answer.ok ? "loud" : gallerySkipVerdict(answer.code, 1);
|
|
1351
|
+
}
|
|
1352
|
+
// A newer picture was asked meanwhile (a new design): this answer is not about what is shown.
|
|
1353
|
+
if (renderedUrlRef.current !== url) return;
|
|
1354
|
+
if (verdict === "skip" && isDesignRefusalCode(answer.code)) {
|
|
1355
|
+
setDesignRefused(answer.code);
|
|
1356
|
+
const skip = gallerySkipRef.current;
|
|
1357
|
+
if (skip && mockupIdNow) {
|
|
1358
|
+
skip.report(mockupIdNow, answer.code);
|
|
1359
|
+
realtimeContext?.frameFailed?.(url);
|
|
1360
|
+
return; // the gallery leaves this picture out: the loader stays until it does
|
|
1361
|
+
}
|
|
1362
|
+
// No gallery to leave it out of: the loud path (the retry, then "Preview unavailable").
|
|
1363
|
+
}
|
|
1364
|
+
setRetryNonce((n) => n + 1);
|
|
1365
|
+
})();
|
|
1324
1366
|
return;
|
|
1325
1367
|
}
|
|
1326
1368
|
// Retry also failed → genuine failure. Unmount the broken <img> so
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The plain-image path of the gallery skip. An <img> never sees its answer, so a picture whose <img> failed asks the
|
|
3
|
+
* same URL with fetch and reads the typed code: a hand that cannot hold THIS design (422 E_HOLD_NO_GRIP; 503
|
|
4
|
+
* E_HOLD_GRIP_BUSY after one retry) is reported to the gallery (GallerySkip), never a grey "Preview unavailable".
|
|
5
|
+
* Every other failure stays loud, exactly as before. Without a gallery to leave it out of, it is loud too.
|
|
6
|
+
*/
|
|
7
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
8
|
+
import React from "react";
|
|
9
|
+
import { render, waitFor, fireEvent, act, cleanup } from "@testing-library/react";
|
|
10
|
+
import { HeroProductImage } from "../HeroProductImage";
|
|
11
|
+
import { GallerySkipProvider, type GallerySkipValue } from "../../patterns/GallerySkip";
|
|
12
|
+
|
|
13
|
+
const ART = { src: "https://example.test/art.png" } as never;
|
|
14
|
+
const URL_ = "https://img.example.test/MXRC3J?mockup=NQKEK3&width=1200&signature=s";
|
|
15
|
+
const answer = (status: number, body: unknown) =>
|
|
16
|
+
new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
17
|
+
|
|
18
|
+
function mount(gallery: GallerySkipValue | null) {
|
|
19
|
+
const hero = <HeroProductImage productId="MXRC3J" mockupId="NQKEK3" realtimeUrl={URL_} artwork={ART} unavailableText="Preview unavailable" />;
|
|
20
|
+
return render(gallery ? <GallerySkipProvider value={gallery}>{hero}</GallerySkipProvider> : hero);
|
|
21
|
+
}
|
|
22
|
+
const img = (c: HTMLElement) => c.querySelector("img[alt^='Product mockup']") as HTMLImageElement | null;
|
|
23
|
+
const root = (c: HTMLElement) => c.querySelector("[data-hero-image]") as HTMLElement;
|
|
24
|
+
|
|
25
|
+
afterEach(() => {
|
|
26
|
+
cleanup();
|
|
27
|
+
vi.unstubAllGlobals();
|
|
28
|
+
vi.useRealTimers();
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
describe("HeroProductImage: a render that cannot draw this design", () => {
|
|
32
|
+
it("422 E_HOLD_NO_GRIP: reported to the gallery, no panel, stamped data-design-refused", async () => {
|
|
33
|
+
const fetchMock = vi.fn(() => Promise.resolve(answer(422, { success: false, error: "E_HOLD_NO_GRIP", lines: ["E_GRIP_THUMB_AREA"] })));
|
|
34
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
35
|
+
const report = vi.fn();
|
|
36
|
+
const { container, queryByText } = mount({ skipped: new Map(), report });
|
|
37
|
+
await waitFor(() => expect(img(container)).not.toBeNull());
|
|
38
|
+
await act(async () => { fireEvent.error(img(container)!); });
|
|
39
|
+
await waitFor(() => expect(report).toHaveBeenCalledWith("NQKEK3", "E_HOLD_NO_GRIP"));
|
|
40
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
41
|
+
expect(fetchMock.mock.calls[0]).toEqual([URL_, expect.objectContaining({ mode: "cors", cache: "reload" })]);
|
|
42
|
+
expect(root(container).dataset.designRefused).toBe("E_HOLD_NO_GRIP");
|
|
43
|
+
expect(root(container).dataset.pictureFailed).toBeUndefined();
|
|
44
|
+
expect(queryByText("Preview unavailable")).toBeNull();
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it("503 E_HOLD_GRIP_BUSY twice: retried once, then reported quietly", async () => {
|
|
48
|
+
vi.useFakeTimers({ shouldAdvanceTime: true });
|
|
49
|
+
const fetchMock = vi.fn(() => Promise.resolve(answer(503, { success: false, error: "E_HOLD_GRIP_BUSY" })));
|
|
50
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
51
|
+
const report = vi.fn();
|
|
52
|
+
const { container, queryByText } = mount({ skipped: new Map(), report });
|
|
53
|
+
await waitFor(() => expect(img(container)).not.toBeNull());
|
|
54
|
+
await act(async () => { fireEvent.error(img(container)!); });
|
|
55
|
+
await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));
|
|
56
|
+
expect(report).not.toHaveBeenCalled();
|
|
57
|
+
await act(async () => { await vi.advanceTimersByTimeAsync(1600); });
|
|
58
|
+
await waitFor(() => expect(report).toHaveBeenCalledWith("NQKEK3", "E_HOLD_GRIP_BUSY"));
|
|
59
|
+
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
60
|
+
expect(queryByText("Preview unavailable")).toBeNull();
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it("503 E_HOLD_GRIP_BUSY, then the retry draws it: shown, not reported", async () => {
|
|
64
|
+
vi.useFakeTimers({ shouldAdvanceTime: true });
|
|
65
|
+
const fetchMock = vi
|
|
66
|
+
.fn()
|
|
67
|
+
.mockResolvedValueOnce(answer(503, { success: false, error: "E_HOLD_GRIP_BUSY" }))
|
|
68
|
+
.mockResolvedValueOnce(new Response("img", { status: 200, headers: { "content-type": "image/avif" } }));
|
|
69
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
70
|
+
const report = vi.fn();
|
|
71
|
+
const { container } = mount({ skipped: new Map(), report });
|
|
72
|
+
await waitFor(() => expect(img(container)).not.toBeNull());
|
|
73
|
+
const first = img(container);
|
|
74
|
+
await act(async () => { fireEvent.error(first!); });
|
|
75
|
+
await act(async () => { await vi.advanceTimersByTimeAsync(1600); });
|
|
76
|
+
await waitFor(() => expect(img(container)).not.toBe(first)); // remounted on the same URL (the cache re-primed)
|
|
77
|
+
await act(async () => { fireEvent.load(img(container)!); });
|
|
78
|
+
expect(report).not.toHaveBeenCalled();
|
|
79
|
+
expect(root(container).dataset.pictureFailed).toBeUndefined();
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it("a genuine render error stays loud: never reported, the retry, then the panel and data-picture-failed", async () => {
|
|
83
|
+
vi.stubGlobal("fetch", vi.fn(() => Promise.resolve(answer(500, { success: false, error: "Service Error" }))));
|
|
84
|
+
const report = vi.fn();
|
|
85
|
+
const { container, findByText } = mount({ skipped: new Map(), report });
|
|
86
|
+
await waitFor(() => expect(img(container)).not.toBeNull());
|
|
87
|
+
await act(async () => { fireEvent.error(img(container)!); }); // the retry
|
|
88
|
+
await waitFor(() => expect(img(container)).not.toBeNull());
|
|
89
|
+
await act(async () => { fireEvent.error(img(container)!); }); // fails again
|
|
90
|
+
await findByText("Preview unavailable");
|
|
91
|
+
expect(root(container).dataset.pictureFailed).toBe("E_PICTURE_UNDISPLAYED");
|
|
92
|
+
expect(report).not.toHaveBeenCalled();
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it("another typed code (E_MOCKUP_NOT_BLESSED) is not a design refusal: loud", async () => {
|
|
96
|
+
vi.stubGlobal("fetch", vi.fn(() => Promise.resolve(answer(422, { success: false, error: "E_SCENE_NOT_BLESSED" }))));
|
|
97
|
+
const report = vi.fn();
|
|
98
|
+
const { container, findByText } = mount({ skipped: new Map(), report });
|
|
99
|
+
await waitFor(() => expect(img(container)).not.toBeNull());
|
|
100
|
+
await act(async () => { fireEvent.error(img(container)!); });
|
|
101
|
+
await waitFor(() => expect(img(container)).not.toBeNull());
|
|
102
|
+
await act(async () => { fireEvent.error(img(container)!); });
|
|
103
|
+
await findByText("Preview unavailable");
|
|
104
|
+
expect(report).not.toHaveBeenCalled();
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it("no gallery to leave it out of: E_HOLD_NO_GRIP is loud (the panel), stamped with its code", async () => {
|
|
108
|
+
vi.stubGlobal("fetch", vi.fn(() => Promise.resolve(answer(422, { success: false, error: "E_HOLD_NO_GRIP" }))));
|
|
109
|
+
const { container, findByText } = mount(null);
|
|
110
|
+
await waitFor(() => expect(img(container)).not.toBeNull());
|
|
111
|
+
await act(async () => { fireEvent.error(img(container)!); });
|
|
112
|
+
await waitFor(() => expect(img(container)).not.toBeNull());
|
|
113
|
+
await act(async () => { fireEvent.error(img(container)!); });
|
|
114
|
+
await findByText("Preview unavailable");
|
|
115
|
+
expect(root(container).dataset.designRefused).toBe("E_HOLD_NO_GRIP");
|
|
116
|
+
});
|
|
117
|
+
});
|
|
@@ -57,6 +57,8 @@ import { LoadingOverlayPrismCandyInline } from "../../components/LoadingOverlayP
|
|
|
57
57
|
import type { ArtworkData } from "@snowcone-app/sdk";
|
|
58
58
|
import { useMockupPriorityOptional } from "../../patterns/MockupPriorityProvider";
|
|
59
59
|
import { useRealtimeOptional } from "../../patterns/RealtimeProvider";
|
|
60
|
+
import { useGallerySkipOptional } from "../../patterns/GallerySkip";
|
|
61
|
+
import { gallerySkippedStamp, NO_GALLERY_SKIPS } from "../../patterns/gallerySkipRules";
|
|
60
62
|
|
|
61
63
|
/**
|
|
62
64
|
* Static (non-mockup) carousel image with a graceful fallback. A reload or
|
|
@@ -208,6 +210,8 @@ export const MobileProductCarousel = memo(function MobileProductCarousel({
|
|
|
208
210
|
unavailableText,
|
|
209
211
|
}: MobileProductCarouselProps) {
|
|
210
212
|
const [activeIndex, setActiveIndex] = useState(currentIndex);
|
|
213
|
+
// Pictures the gallery left out for this design (GallerySkip): stamped on the root as data-gallery-skipped.
|
|
214
|
+
const skippedStamp = gallerySkippedStamp(useGallerySkipOptional()?.skipped ?? NO_GALLERY_SKIPS, images ?? []);
|
|
211
215
|
const [touchStart, setTouchStart] = useState<{ x: number; y: number } | null>(
|
|
212
216
|
null
|
|
213
217
|
);
|
|
@@ -847,7 +851,7 @@ export const MobileProductCarousel = memo(function MobileProductCarousel({
|
|
|
847
851
|
}
|
|
848
852
|
|
|
849
853
|
return (
|
|
850
|
-
<div className={`relative w-full h-full ${className}`}>
|
|
854
|
+
<div className={`relative w-full h-full ${className}`} data-gallery="product" data-gallery-skipped={skippedStamp}>
|
|
851
855
|
{/* Main carousel container */}
|
|
852
856
|
<div
|
|
853
857
|
ref={carouselRef}
|
|
@@ -891,7 +895,8 @@ export const MobileProductCarousel = memo(function MobileProductCarousel({
|
|
|
891
895
|
|
|
892
896
|
return (
|
|
893
897
|
<div
|
|
894
|
-
|
|
898
|
+
// A slide is its picture: a picture left out (GallerySkip) never hands its element to the next one.
|
|
899
|
+
key={image.mockupId ? `m:${image.mockupId}` : `i:${index}`}
|
|
895
900
|
className="w-full h-full flex-shrink-0 relative select-none"
|
|
896
901
|
data-gallery-role={image.galleryRole}
|
|
897
902
|
data-mockup-id={image.galleryRole ? image.mockupId : undefined}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a mockup URL answered, read the one way a page can: an <img> that failed never sees its response (no status,
|
|
3
|
+
* no body), so the picture asks the SAME URL again with fetch and reads the typed code from the JSON body (the
|
|
4
|
+
* resolver passes the renderer's 422/503 body through with CORS). The fetch also re-primes the browser's cache with a
|
|
5
|
+
* CORS-tagged copy, which is what HeroProductImage's one cache-recovery retry needs anyway: on a failure only, never on
|
|
6
|
+
* the happy path.
|
|
7
|
+
*/
|
|
8
|
+
import { renderRefusalCodeOf } from "@snowcone-app/sdk";
|
|
9
|
+
|
|
10
|
+
export interface RenderAnswer {
|
|
11
|
+
/** The answer was a picture (2xx): the retry can show it. */
|
|
12
|
+
ok: boolean;
|
|
13
|
+
/** HTTP status; 0 when the request itself failed (network, a revoked blob:). */
|
|
14
|
+
status: number;
|
|
15
|
+
/** The typed `E_*` code of a failed answer, or null (none sent, or unreadable). */
|
|
16
|
+
code: string | null;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function probeRenderAnswer(url: string, fetchImpl: typeof fetch = fetch): Promise<RenderAnswer> {
|
|
20
|
+
let res: Response;
|
|
21
|
+
try {
|
|
22
|
+
res = await fetchImpl(url, { mode: "cors", cache: "reload", credentials: "omit" });
|
|
23
|
+
} catch {
|
|
24
|
+
return { ok: false, status: 0, code: null };
|
|
25
|
+
}
|
|
26
|
+
if (res.ok) return { ok: true, status: res.status, code: null };
|
|
27
|
+
let body: unknown = null;
|
|
28
|
+
try {
|
|
29
|
+
const text = await res.text();
|
|
30
|
+
body = text ? JSON.parse(text) : null;
|
|
31
|
+
} catch {
|
|
32
|
+
body = null;
|
|
33
|
+
}
|
|
34
|
+
return { ok: false, status: res.status, code: renderRefusalCodeOf(body, res.headers.get("x-render-reason")) };
|
|
35
|
+
}
|
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,
|