@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.
- package/CHANGELOG.md +15 -0
- package/dist/index.cjs +937 -676
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +185 -60
- package/dist/index.d.ts +185 -60
- package/dist/index.js +847 -597
- 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 +10 -3
- package/src/composed/carousels/firstView.ts +81 -0
- package/src/composed/renderRefusalProbe.ts +35 -0
- package/src/composed/zoom/EnhancedImageViewer.tsx +68 -1
- package/src/composed/zoom/__tests__/EnhancedImageViewer.firstView.test.tsx +126 -0
- package/src/composed/zoom/types.ts +9 -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.
|
|
3
|
+
"version": "0.12.1",
|
|
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.3"
|
|
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
|
+
});
|
|
@@ -50,13 +50,15 @@ import React, {
|
|
|
50
50
|
} from "react";
|
|
51
51
|
import type { CarouselImage } from "./types";
|
|
52
52
|
import { slideFit, zoomFit } from "./fit";
|
|
53
|
-
import { slideFirstViewProps } from "./firstView";
|
|
53
|
+
import { slideFirstViewFields, slideFirstViewProps } from "./firstView";
|
|
54
54
|
import { EnhancedImageViewer } from "../zoom/EnhancedImageViewer";
|
|
55
55
|
import { HeroProductImage } from "../HeroProductImage";
|
|
56
56
|
import { LoadingOverlayPrismCandyInline } from "../../components/LoadingOverlayPrismCandy";
|
|
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}
|
|
@@ -1036,6 +1041,8 @@ export const MobileProductCarousel = memo(function MobileProductCarousel({
|
|
|
1036
1041
|
naturalWidth: img.naturalWidth,
|
|
1037
1042
|
naturalHeight: img.naturalHeight,
|
|
1038
1043
|
...(zoomFit(img.galleryRole) === "whole" ? { fit: "whole" as const } : {}),
|
|
1044
|
+
// the viewer opens on the product by the hero's first-view rule (EnhancedImageViewer viewerFirstView)
|
|
1045
|
+
...slideFirstViewFields(img),
|
|
1039
1046
|
} : null;
|
|
1040
1047
|
})
|
|
1041
1048
|
.filter((img): img is NonNullable<typeof img> => img !== null);
|
|
@@ -35,6 +35,87 @@ export interface SlideFirstViewProps {
|
|
|
35
35
|
|
|
36
36
|
const r4 = (n: number) => Math.round(n * 10000) / 10000;
|
|
37
37
|
|
|
38
|
+
/** The phone hero's default picture is 16:9 (a plate's `frames['16:9']` window; rendercenter shared/shapes.ts). */
|
|
39
|
+
export const FIRST_VIEW_PICTURE_ASPECT = 16 / 9;
|
|
40
|
+
|
|
41
|
+
/** The share of the view's width kept clear on each side of the product (the frame gate's product-on-a-surface margin). */
|
|
42
|
+
export const FIRST_VIEW_MARGIN = 0.03;
|
|
43
|
+
|
|
44
|
+
/** The product's box in a mockup's default 16:9 picture, as fractions of that picture (`mockups[].productBox`). */
|
|
45
|
+
export type FirstViewProductBox = NonNullable<CarouselImage["productBox"]>;
|
|
46
|
+
/** The mockup's own phone window (its 2:3 frame) along the default picture's width (`mockups[].phoneWindow`). */
|
|
47
|
+
export type FirstViewPhoneWindow = NonNullable<CarouselImage["phoneWindow"]>;
|
|
48
|
+
|
|
49
|
+
/** What a first view is centred on, and the product it then holds. */
|
|
50
|
+
export type FirstViewAnchor =
|
|
51
|
+
/** The mockup's own phone window (a plate). `product` null: its record has no product box, so nothing is held or judged. */
|
|
52
|
+
| { by: "phone-window"; window: FirstViewPhoneWindow; product: FirstViewProductBox | null }
|
|
53
|
+
/** A product box but no phone window. */
|
|
54
|
+
| { by: "product"; product: FirstViewProductBox }
|
|
55
|
+
/** Neither (a mockup from before plates): its phone window is the centred one its 2:3 gate judged. */
|
|
56
|
+
| { by: "picture-middle"; why: "no-phone-window-no-product-box" };
|
|
57
|
+
|
|
58
|
+
export interface FirstView {
|
|
59
|
+
/** The slice of the picture's width the box shows, as fractions of the picture (0 = its left edge, 1 = its right). */
|
|
60
|
+
x0: number;
|
|
61
|
+
x1: number;
|
|
62
|
+
/** The picture's drawn width and its left edge relative to the box's left edge, px (left <= 0). */
|
|
63
|
+
pictureWidth: number;
|
|
64
|
+
left: number;
|
|
65
|
+
/** `held`: the whole product is in view. `cut`: part of it is outside. `unjudged`: no product box to judge by. */
|
|
66
|
+
product: "held" | "cut" | "unjudged";
|
|
67
|
+
/** The share of the product's width that is in view (1 = all of it); null when unjudged. */
|
|
68
|
+
inView: number | null;
|
|
69
|
+
/** The part of the product in view as a share of the view's width; null when unjudged. */
|
|
70
|
+
share: number | null;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The anchor of a slide's (already parsed) fields: its phone window, else its product, else the picture's middle. */
|
|
74
|
+
export function firstViewAnchorOfSlide(image: Pick<CarouselImage, "productBox" | "phoneWindow">): FirstViewAnchor {
|
|
75
|
+
const { productBox: product, phoneWindow: window } = image;
|
|
76
|
+
if (window) return { by: "phone-window", window, product: product ?? null };
|
|
77
|
+
if (product) return { by: "product", product };
|
|
78
|
+
return { by: "picture-middle", why: "no-phone-window-no-product-box" };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* THE first-view rule (one copy: the www phone hero's CSS, heroFirstView.ts, and the tap-to-enlarge viewer,
|
|
83
|
+
* EnhancedImageViewer, both draw by it). What a box of `width` x `height` CSS px shows of a picture drawn
|
|
84
|
+
* `object-fit: cover`: the picture is the box's height (or its width, when the box is wider than the picture), centred
|
|
85
|
+
* on the anchor, slid as little as it must to hold the whole product with FIRST_VIEW_MARGIN of the view clear on each
|
|
86
|
+
* side (a product too wide for that is centred in the view, reported `cut`), and never past its own edges.
|
|
87
|
+
*/
|
|
88
|
+
export function firstView(box: { width: number; height: number }, anchor: FirstViewAnchor, pictureAspect: number = FIRST_VIEW_PICTURE_ASPECT): FirstView {
|
|
89
|
+
const { width: W, height: H } = box;
|
|
90
|
+
const pictureWidth = Math.max(W, H * pictureAspect);
|
|
91
|
+
const product = anchor.by === "picture-middle" ? null : anchor.product;
|
|
92
|
+
const wanted = anchor.by === "phone-window" ? anchor.window.x + anchor.window.w / 2 : anchor.by === "product" ? anchor.product.x + anchor.product.w / 2 : 0.5;
|
|
93
|
+
// the view's centre, px along the picture: the wanted one, held between the two centres that keep the product (with
|
|
94
|
+
// its margin) in view; a product too wide for that leaves no such centre, and its own middle is used
|
|
95
|
+
let centrePx = wanted * pictureWidth;
|
|
96
|
+
if (product) {
|
|
97
|
+
const mid = (product.x + product.w / 2) * pictureWidth;
|
|
98
|
+
const lo = (product.x + product.w) * pictureWidth + FIRST_VIEW_MARGIN * W - W / 2;
|
|
99
|
+
const hi = product.x * pictureWidth - FIRST_VIEW_MARGIN * W + W / 2;
|
|
100
|
+
centrePx = Math.max(Math.min(lo, mid), Math.min(centrePx, Math.max(hi, mid)));
|
|
101
|
+
}
|
|
102
|
+
const left = Math.max(Math.min(0, W - pictureWidth), Math.min(W / 2 - centrePx, 0));
|
|
103
|
+
const x0 = -left / pictureWidth, x1 = (W - left) / pictureWidth;
|
|
104
|
+
if (!product) return { x0, x1, pictureWidth, left, product: "unjudged", inView: null, share: null };
|
|
105
|
+
const seen = Math.max(0, Math.min(product.x + product.w, x1) - Math.max(product.x, x0));
|
|
106
|
+
const inView = seen / product.w;
|
|
107
|
+
return { x0, x1, pictureWidth, left, product: inView > 1 - 1e-6 ? "held" : "cut", inView, share: seen / (x1 - x0) };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* The fields a phone carousel slide hands the tap-to-enlarge viewer: a real mockup's product box and phone window (the
|
|
112
|
+
* same pictures the slide stamps, `image.isRealMockup ? image : {}`), nothing for any other picture.
|
|
113
|
+
*/
|
|
114
|
+
export function slideFirstViewFields(image: Pick<CarouselImage, "isRealMockup" | "productBox" | "phoneWindow">): Pick<CarouselImage, "productBox" | "phoneWindow"> {
|
|
115
|
+
if (!image.isRealMockup) return {};
|
|
116
|
+
return { ...(image.productBox ? { productBox: image.productBox } : {}), ...(image.phoneWindow ? { phoneWindow: image.phoneWindow } : {}) };
|
|
117
|
+
}
|
|
118
|
+
|
|
38
119
|
/** The attributes and CSS variables for one slide; `{}` when the picture has neither a phone window nor a product box. */
|
|
39
120
|
export function slideFirstViewProps(image: Pick<CarouselImage, "productBox" | "phoneWindow">): SlideFirstViewProps {
|
|
40
121
|
const { productBox: box, phoneWindow: phone } = image;
|
|
@@ -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
|
+
}
|
|
@@ -20,6 +20,12 @@ import type {
|
|
|
20
20
|
} from "react-zoom-pan-pinch";
|
|
21
21
|
import { X } from "lucide-react";
|
|
22
22
|
import type { ZoomImage } from "./types";
|
|
23
|
+
import {
|
|
24
|
+
FIRST_VIEW_PICTURE_ASPECT,
|
|
25
|
+
firstView,
|
|
26
|
+
firstViewAnchorOfSlide,
|
|
27
|
+
type FirstView,
|
|
28
|
+
} from "../carousels/firstView";
|
|
23
29
|
|
|
24
30
|
// Cast to fix React 19 type compatibility with react-zoom-pan-pinch
|
|
25
31
|
const TransformWrapper = OriginalTransformWrapper as ComponentType<
|
|
@@ -41,6 +47,37 @@ interface EnhancedImageViewerProps {
|
|
|
41
47
|
currentIndex?: number; // Add explicit current index prop
|
|
42
48
|
}
|
|
43
49
|
|
|
50
|
+
/**
|
|
51
|
+
* Where the viewer opens a picture it draws `object-fit: cover` in the whole screen: by the phone hero's first-view rule
|
|
52
|
+
* (carousels/firstView.ts `firstView`), so a product off the picture's middle is on screen (founder 2026-11-26: "when I
|
|
53
|
+
* tap to view it larger we lose the proper crop and can't see the item in frame anymore"). Stamped on the <img> as
|
|
54
|
+
* `data-first-view` (`phone-window` | `product` | `picture-middle` | `whole`), `data-first-view-why` (why the middle),
|
|
55
|
+
* `data-first-view-product` (`held` | `cut` | `unjudged`) and `data-first-view-slice="x0,x1"` (the picture's width on screen).
|
|
56
|
+
*/
|
|
57
|
+
type ViewerFirstView =
|
|
58
|
+
/** A picture opened whole (contain): nothing is cut, no rule. */
|
|
59
|
+
| { by: "whole" }
|
|
60
|
+
/** Drawn by the picture's middle, as before: it carries neither field, or it is not the 16:9 picture they measure. */
|
|
61
|
+
| { by: "picture-middle"; why: "no-phone-window-no-product-box" | "picture-not-16:9" }
|
|
62
|
+
| { by: "phone-window" | "product"; view: FirstView };
|
|
63
|
+
|
|
64
|
+
function viewerFirstView(
|
|
65
|
+
image: ZoomImage | undefined,
|
|
66
|
+
screen: { width: number; height: number },
|
|
67
|
+
pictureAspect: number | undefined,
|
|
68
|
+
): ViewerFirstView {
|
|
69
|
+
if (image?.fit === "whole") return { by: "whole" };
|
|
70
|
+
const anchor = firstViewAnchorOfSlide(image ?? {});
|
|
71
|
+
if (anchor.by === "picture-middle") return anchor;
|
|
72
|
+
// the fields are fractions of the mockup's default 16:9 picture; on any other picture they would point elsewhere
|
|
73
|
+
if (pictureAspect !== undefined && Math.abs(pictureAspect / FIRST_VIEW_PICTURE_ASPECT - 1) > 0.01) {
|
|
74
|
+
return { by: "picture-middle", why: "picture-not-16:9" };
|
|
75
|
+
}
|
|
76
|
+
return { by: anchor.by, view: firstView(screen, anchor) };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const r4 = (n: number) => Math.round(n * 10000) / 10000;
|
|
80
|
+
|
|
44
81
|
// Enhanced Image Viewer Component with react-zoom-pan-pinch (On.com style)
|
|
45
82
|
export const EnhancedImageViewer = ({
|
|
46
83
|
imageUrl,
|
|
@@ -56,6 +93,8 @@ export const EnhancedImageViewer = ({
|
|
|
56
93
|
const [cropDimensions, setCropDimensions] = useState({ width: 0, height: 0 });
|
|
57
94
|
const [currentZoomScale, setCurrentZoomScale] = useState(1);
|
|
58
95
|
const imgRef = useRef<HTMLImageElement>(null);
|
|
96
|
+
// The drawn picture's own shape, once it has loaded (the first-view fields only apply to the 16:9 picture).
|
|
97
|
+
const [loadedAspect, setLoadedAspect] = useState<{ src: string; aspect: number } | null>(null);
|
|
59
98
|
|
|
60
99
|
// Swipe detection refs
|
|
61
100
|
const touchStartRef = useRef<{ x: number; y: number; time: number } | null>(
|
|
@@ -83,6 +122,10 @@ export const EnhancedImageViewer = ({
|
|
|
83
122
|
|
|
84
123
|
const handleImageLoad = useCallback(() => {
|
|
85
124
|
calculateScale();
|
|
125
|
+
const img = imgRef.current;
|
|
126
|
+
if (img && img.naturalWidth > 0 && img.naturalHeight > 0) {
|
|
127
|
+
setLoadedAspect({ src: img.currentSrc || img.src, aspect: img.naturalWidth / img.naturalHeight });
|
|
128
|
+
}
|
|
86
129
|
}, [calculateScale]);
|
|
87
130
|
|
|
88
131
|
// Mark as client-side and calculate initial scale
|
|
@@ -216,6 +259,24 @@ export const EnhancedImageViewer = ({
|
|
|
216
259
|
[handleSwipeNavigation]
|
|
217
260
|
);
|
|
218
261
|
|
|
262
|
+
// The picture on screen and where it opens (the first-view rule; see viewerFirstView).
|
|
263
|
+
const shownIndex = propCurrentIndex ?? images.findIndex((img) => img.src === imageUrl);
|
|
264
|
+
const shown = images[shownIndex];
|
|
265
|
+
const shownAspect =
|
|
266
|
+
loadedAspect && (loadedAspect.src === imageUrl || loadedAspect.src.endsWith(imageUrl))
|
|
267
|
+
? loadedAspect.aspect
|
|
268
|
+
: shown?.naturalWidth && shown?.naturalHeight
|
|
269
|
+
? shown.naturalWidth / shown.naturalHeight
|
|
270
|
+
: undefined;
|
|
271
|
+
const opening = viewerFirstView(
|
|
272
|
+
shown,
|
|
273
|
+
{
|
|
274
|
+
width: cropDimensions.width || (typeof window === "undefined" ? 0 : window.innerWidth),
|
|
275
|
+
height: cropDimensions.height || (typeof window === "undefined" ? 0 : window.innerHeight),
|
|
276
|
+
},
|
|
277
|
+
shownAspect,
|
|
278
|
+
);
|
|
279
|
+
|
|
219
280
|
if (!isMounted || !isClient) {
|
|
220
281
|
return createPortal(
|
|
221
282
|
<div
|
|
@@ -340,11 +401,17 @@ export const EnhancedImageViewer = ({
|
|
|
340
401
|
crossOrigin="anonymous"
|
|
341
402
|
key={`${imageUrl}-${propCurrentIndex}`}
|
|
342
403
|
onLoad={handleImageLoad}
|
|
404
|
+
data-first-view={opening.by}
|
|
405
|
+
data-first-view-why={opening.by === "picture-middle" ? opening.why : undefined}
|
|
406
|
+
data-first-view-product={"view" in opening ? opening.view.product : undefined}
|
|
407
|
+
data-first-view-slice={"view" in opening ? `${r4(opening.view.x0)},${r4(opening.view.x1)}` : undefined}
|
|
343
408
|
style={{
|
|
344
409
|
width: "100%",
|
|
345
410
|
height: "100%",
|
|
346
411
|
// Crop 16:9 to fill the screen (a hero), or the whole picture for a size picture (a diagram).
|
|
347
|
-
objectFit:
|
|
412
|
+
objectFit: opening.by === "whole" ? "contain" : "cover",
|
|
413
|
+
// Opened on the product by the hero's first-view rule; a picture without the fields keeps the middle.
|
|
414
|
+
...("view" in opening ? { objectPosition: `${Math.round(opening.view.left * 100) / 100}px 50%` } : {}),
|
|
348
415
|
}}
|
|
349
416
|
/>
|
|
350
417
|
</div>
|