@snowcone-app/ui 0.10.1 → 0.10.3

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@snowcone-app/ui",
3
- "version": "0.10.1",
3
+ "version": "0.10.3",
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.26.0"
106
+ "@snowcone-app/sdk": "0.27.0"
107
107
  },
108
108
  "devDependencies": {
109
109
  "@chromatic-com/storybook": "^4.1.2",
@@ -591,6 +591,8 @@ export const HeroProductImage = memo(function HeroProductImage({
591
591
  const getLatestSentVersions = realtimeContext?.getLatestSentVersions;
592
592
  const refusalCodeRef = useRef<string | null>(null);
593
593
  refusalCodeRef.current = unavailable?.code ?? null;
594
+ const frameFailedRef = useRef(realtimeContext?.frameFailed);
595
+ frameFailedRef.current = realtimeContext?.frameFailed;
594
596
  const sessionErrorCodeRef = useRef<string | null>(null);
595
597
  sessionErrorCodeRef.current = realtimeContext?.renderError?.code ?? null;
596
598
  const getCanvasVersion = realtimeContext?.getCanvasVersion;
@@ -598,6 +600,14 @@ export const HeroProductImage = memo(function HeroProductImage({
598
600
  const applyRenderStamp = useCallback(() => {
599
601
  const node = containerRef.current;
600
602
  if (!node) return;
603
+ // A static picture is not rendered by the realtime session: it is not behind the canvas, it is not live. Say so
604
+ // (never "stale" forever, never "current" over an old render).
605
+ if (mode === "static") {
606
+ delete node.dataset.canvasVersion;
607
+ delete node.dataset.renderVersion;
608
+ node.dataset.renderState = "static";
609
+ return;
610
+ }
601
611
  const canvas = getCanvasVersion?.() ?? 0;
602
612
  if (canvas <= 0) {
603
613
  delete node.dataset.canvasVersion;
@@ -632,7 +642,7 @@ export const HeroProductImage = memo(function HeroProductImage({
632
642
  node.dataset.wantedWidth = String(shape.width);
633
643
  node.dataset.sessionPhase = shape.phase;
634
644
  }
635
- }, [getCanvasVersion, getLatestSentVersions, getSessionShape]);
645
+ }, [getCanvasVersion, getLatestSentVersions, getSessionShape, mode]);
636
646
  const applyRenderStampRef = useRef(applyRenderStamp);
637
647
  applyRenderStampRef.current = applyRenderStamp;
638
648
  // Re-apply after every render (the root node can change; refusals are state).
@@ -1136,6 +1146,7 @@ export const HeroProductImage = memo(function HeroProductImage({
1136
1146
  // its data-render-version stays behind, so the picture reads stale, never current over an old image.
1137
1147
  preload.onerror = () => {
1138
1148
  frameErrorRef.current = "E_FRAME_UNAVAILABLE";
1149
+ frameFailedRef.current?.(displayUrl); // done with it (frame flow control): the box may send the next one
1139
1150
  applyRenderStampRef.current?.();
1140
1151
  };
1141
1152
 
@@ -1271,6 +1282,7 @@ export const HeroProductImage = memo(function HeroProductImage({
1271
1282
  // image is still available to keep).
1272
1283
  setImgFailed(true);
1273
1284
  setFirstImageLoaded(true);
1285
+ if (renderedUrl) realtimeContext?.frameFailed?.(renderedUrl);
1274
1286
  onError?.();
1275
1287
  // Dev-only guidance for the most common signed-shop trap: a mockup
1276
1288
  // <img> that loads an UNSIGNED resolver URL gets a 403 "Missing
@@ -888,6 +888,8 @@ export const MobileProductCarousel = memo(function MobileProductCarousel({
888
888
  <div
889
889
  key={index}
890
890
  className="w-full h-full flex-shrink-0 relative select-none"
891
+ data-gallery-role={image.galleryRole}
892
+ data-mockup-id={image.galleryRole ? image.mockupId : undefined}
891
893
  >
892
894
  {!isWithinDecodeWindow ? (
893
895
  <div className="w-full h-full bg-muted" />
@@ -50,6 +50,13 @@ export interface CarouselImage {
50
50
 
51
51
  /** Aspect ratio of the mockup (e.g., 1.78 for 16:9) */
52
52
  aspectRatio?: number;
53
+
54
+ /**
55
+ * What this picture is in the gallery. 'size-picture': the picture of the chosen size (exactly one, last). The
56
+ * realtime session renders it like any picture (the box renders each mockup at the variant it lists, rc#858).
57
+ * Stamped data-gallery-role on the slide.
58
+ */
59
+ galleryRole?: "size-picture";
53
60
  }
54
61
 
55
62
  /**
@@ -37,7 +37,7 @@ import React, {
37
37
  useMemo,
38
38
  } from "react";
39
39
  import { useRealtimeMockup } from "@snowcone-app/sdk/react";
40
- import { resolvePreviewVariantId, resolveVariantId as resolveVariantIdUtil } from "@snowcone-app/sdk";
40
+ import { gallerySizePicture, mockupRole, resolvePreviewVariantId, resolveVariantId as resolveVariantIdUtil } from "@snowcone-app/sdk";
41
41
  import type {
42
42
  RealtimeRenderError,
43
43
  MockupResult as SdkMockupResult,
@@ -329,6 +329,9 @@ export interface RealtimeContextValue {
329
329
 
330
330
  /** A picture's <img> loaded `url` (from getMockupUrl): its older composited frames are released. */
331
331
  markBlobShown: (mockupId: string, url: string, consumer?: string) => void;
332
+ /** A picture's img failed to load a delivered frame. With frame flow control, every frame must be reported done
333
+ * (drawn via markBlobShown, or failed here), or the box waits for it until its ack timeout (E_RT_ACK_TIMEOUT). */
334
+ frameFailed: (url: string) => void;
332
335
 
333
336
  /** An element that called markBlobShown unmounted: it no longer holds its frame. */
334
337
  releaseBlobConsumer: (mockupId: string, consumer: string) => void;
@@ -445,6 +448,8 @@ export function RealtimeProvider({
445
448
 
446
449
  // Track last sent variantId to detect when we need to re-send config
447
450
  const lastSentVariantIdRef = useRef<string | null>(null);
451
+ // The size picture in the session (the chosen size's; null = none): a size change re-sends the config.
452
+ const lastSentSizePictureRef = useRef<string | null>(null);
448
453
  const lastSentBgRef = useRef<string | undefined>(undefined);
449
454
  // Spread crop geometry (ADR-0060) declared via setSpreadCrops. Ref holds
450
455
  // the payload; the version state re-runs the config effect on change.
@@ -546,6 +551,7 @@ export function RealtimeProvider({
546
551
  getLatestSentVersions,
547
552
  rerender: rerenderRaw,
548
553
  isFrameSuperseded,
554
+ ackFrame,
549
555
  } = realtimeMockup;
550
556
  // Read through a ref: the composite pump's callbacks stay stable across renders.
551
557
  const isFrameSupersededRef = useRef(isFrameSuperseded);
@@ -601,7 +607,19 @@ export function RealtimeProvider({
601
607
  // it (+ when it went out). "Settled" fires once per version, when its last
602
608
  // mockup lands, so the export service can keep N edits in flight (pipeline
603
609
  // depth) and count landings exactly. Blob sends keep the throttle-queue rule.
604
- const dueByVersionRef = useRef<Map<number, { due: number; at: number }>>(new Map());
610
+ const dueByVersionRef = useRef<Map<number, { due: number; at: number; seen?: Set<string> }>>(new Map());
611
+ // Frame flow control: the frame (mockup, seq) behind every URL this provider delivered, so the moment a picture
612
+ // draws it (markBlobShown) or fails it (frameFailed) the box hears "done". Bounded.
613
+ const frameByUrlRef = useRef<Map<string, { mockupId: string; seq: number }>>(new Map());
614
+ const ackFrameRef = useRef<((mockupId: string, seq: number) => boolean) | null>(null);
615
+ ackFrameRef.current = ackFrame;
616
+ const ackUrl = useCallback((url: string) => {
617
+ const f = frameByUrlRef.current.get(url);
618
+ if (f) ackFrameRef.current?.(f.mockupId, f.seq);
619
+ }, []);
620
+ const ackResultFrame = useCallback((result: { mockupId: string; seq?: number }) => {
621
+ if (typeof result.seq === "number") ackFrameRef.current?.(result.mockupId, result.seq);
622
+ }, []);
605
623
  const configuredMockupIdsRef = useRef<string[]>([]);
606
624
 
607
625
  // Centralized mockup URL cache - stores URLs by mockupId
@@ -775,13 +793,19 @@ export function RealtimeProvider({
775
793
  * when they are older than what every element shows.
776
794
  */
777
795
  const markBlobShown = useCallback((owner: string, url: string, consumer = "default") => {
796
+ ackUrl(url); // drawn: the box may send this picture's next frame
778
797
  const list = blobsByOwnerRef.current.get(owner);
779
798
  if (!list || list.indexOf(url) < 0) return;
780
799
  const shown = shownBlobByOwnerRef.current.get(owner) ?? new Map<string, string>();
781
800
  shown.set(consumer, url);
782
801
  shownBlobByOwnerRef.current.set(owner, shown);
783
802
  releaseOlderFrames(owner);
784
- }, [releaseOlderFrames]);
803
+ }, [releaseOlderFrames, ackUrl]);
804
+
805
+ /** A picture could not load a delivered frame (its img errored): the client is done with it (frame flow control). */
806
+ const frameFailed = useCallback((url: string) => {
807
+ ackUrl(url);
808
+ }, [ackUrl]);
785
809
 
786
810
  /** An element of a picture is gone (unmount): it no longer holds a frame. */
787
811
  const releaseBlobConsumer = useCallback((owner: string, consumer: string) => {
@@ -1055,6 +1079,19 @@ export function RealtimeProvider({
1055
1079
  pendingRerenderRef.current = pendingRerenderRef.current.filter((id) => !delivered.has(id));
1056
1080
  }
1057
1081
 
1082
+ // Frame flow control: remember which frame each URL is, and say "done" at once for the frames no element will
1083
+ // draw: no picture shows this mockup, or the picture already shows this exact URL (nothing new to load).
1084
+ results.forEach((result) => {
1085
+ const seq = (result as { seq?: number }).seq;
1086
+ if (typeof seq !== "number") return;
1087
+ const byUrl = frameByUrlRef.current;
1088
+ byUrl.set(result.imageUrl, { mockupId: result.mockupId, seq });
1089
+ if (byUrl.size > 1024) byUrl.delete(byUrl.keys().next().value as string);
1090
+ const shownUrl = mockupUrlCacheRef.current.get(result.mockupId)?.url;
1091
+ const watched = (mockupSubscribersByIdRef.current.get(result.mockupId)?.size ?? 0) > 0;
1092
+ if (!watched || shownUrl === result.imageUrl) ackFrameRef.current?.(result.mockupId, seq);
1093
+ });
1094
+
1058
1095
  const clearedPlacements = new Set<string>();
1059
1096
  results.forEach((result) => {
1060
1097
  const wasPending = pendingMockupIdsRef.current.has(result.mockupId);
@@ -1099,18 +1136,24 @@ export function RealtimeProvider({
1099
1136
  let settledVersions = 0;
1100
1137
  let newestSettled = 0;
1101
1138
  const due = dueByVersionRef.current;
1139
+ // A frame at version w answers every due version <= w for its mockup, once per mockup: with frame flow
1140
+ // control (and the box's render coalescing) a mockup's intermediate versions never arrive, only its newest.
1102
1141
  results.forEach((result) => {
1103
- const v = result.requestVersion;
1104
- if (v === undefined) return;
1105
- const entry = due.get(v);
1106
- if (!entry) return;
1107
- if (entry.due <= 1) {
1108
- due.delete(v);
1109
- settledVersions += 1;
1110
- newestSettled = Math.max(newestSettled, v);
1111
- } else {
1112
- entry.due -= 1;
1113
- }
1142
+ const w = result.requestVersion;
1143
+ if (w === undefined) return;
1144
+ due.forEach((entry, v) => {
1145
+ if (v > w) return;
1146
+ const seen = (entry.seen ??= new Set<string>());
1147
+ if (seen.has(result.mockupId)) return;
1148
+ seen.add(result.mockupId);
1149
+ if (entry.due <= 1) {
1150
+ due.delete(v);
1151
+ settledVersions += 1;
1152
+ newestSettled = Math.max(newestSettled, v);
1153
+ } else {
1154
+ entry.due -= 1;
1155
+ }
1156
+ });
1114
1157
  });
1115
1158
  due.forEach((entry, v) => {
1116
1159
  if (now - entry.at > 10_000) due.delete(v);
@@ -1147,6 +1190,7 @@ export function RealtimeProvider({
1147
1190
  console.error(
1148
1191
  `[RealtimeProvider] E_OVERLAY_NO_BACKGROUND: cropped frame for ${result.mockupId} has no frozen background — falling back to full-frame and re-rendering it.`
1149
1192
  );
1193
+ ackResultFrame(result); // never drawn; the re-render comes as a new frame
1150
1194
  rerenderFullFrame(result.mockupId);
1151
1195
  return;
1152
1196
  }
@@ -1162,10 +1206,15 @@ export function RealtimeProvider({
1162
1206
  rect: result.cropRect!,
1163
1207
  canvas: compositeCanvasRef.current ?? undefined,
1164
1208
  });
1165
- // Scene changed while compositing (variant/bg flip) — stale, drop.
1166
- if (gen !== sceneGenRef.current) return;
1209
+ // Scene changed while compositing (variant/bg flip) — stale, drop (and done with it: flow control).
1210
+ if (gen !== sceneGenRef.current) {
1211
+ ackResultFrame(result);
1212
+ return;
1213
+ }
1167
1214
  deliverResults([{ ...result, imageUrl: registerBlobUrl(blob, undefined, result.mockupId) }]);
1168
1215
  } catch (err) {
1216
+ // Whatever happens next, this frame will not be drawn: done with it (flow control; a re-render is a new frame).
1217
+ ackResultFrame(result);
1169
1218
  // A newer frame for this mockup already arrived: the SDK revokes a
1170
1219
  // mockup's previous blob: frame the moment the next one lands, so a
1171
1220
  // composite still loading the old frame fails mid-drag. That is
@@ -1222,7 +1271,7 @@ export function RealtimeProvider({
1222
1271
  rerenderFullFrame(result.mockupId);
1223
1272
  }
1224
1273
  },
1225
- [deliverResults, registerBlobUrl, rerenderFullFrame]
1274
+ [deliverResults, registerBlobUrl, rerenderFullFrame, ackResultFrame]
1226
1275
  );
1227
1276
 
1228
1277
  /** Serial per-mockup composite pump (latest-wins). */
@@ -1440,6 +1489,12 @@ export function RealtimeProvider({
1440
1489
  const isFirstSend = !configSentRef.current;
1441
1490
  const variantChanged = lastSentVariantIdRef.current !== null &&
1442
1491
  lastSentVariantIdRef.current !== variantId;
1492
+ // The ONE size picture the gallery shows (the SELECTED size's, not the preview variant's): the session renders it
1493
+ // too. The box renders each mockup at the variant it lists (rendercenter rc#858), so a size picture renders at its
1494
+ // own size in a session whose variant is another size.
1495
+ const sizePicture = gallerySizePicture(product.mockups, resolveVariantIdUtil(productContext, undefined, undefined));
1496
+ const sizePictureId = sizePicture?.id ?? null;
1497
+ const sizePictureChanged = configSentRef.current && lastSentSizePictureRef.current !== sizePictureId;
1443
1498
  // 3. Background changed (theme flip swaps the MockupBackground hex)
1444
1499
  const bgChanged = configSentRef.current && lastSentBgRef.current !== mockupBg;
1445
1500
  // 4. Spread crop geometry changed (spread-mode editor mounted/unmounted)
@@ -1447,7 +1502,7 @@ export function RealtimeProvider({
1447
1502
  const spreadCropsChanged =
1448
1503
  configSentRef.current && lastSentSpreadCropsRef.current !== spreadCropsJson;
1449
1504
 
1450
- if (!isFirstSend && !variantChanged && !bgChanged && !spreadCropsChanged) {
1505
+ if (!isFirstSend && !variantChanged && !bgChanged && !spreadCropsChanged && !sizePictureChanged) {
1451
1506
  return; // Nothing changed, skip
1452
1507
  }
1453
1508
 
@@ -1459,15 +1514,22 @@ export function RealtimeProvider({
1459
1514
  invalidateBackgrounds();
1460
1515
  }
1461
1516
 
1462
- // Get mockup IDs from product.mockups
1517
+ // Get mockup IDs from product.mockups: every ordinary picture, plus the chosen size's picture (the other sizes'
1518
+ // pictures are never shown, so never rendered).
1463
1519
  const mockupIds: string[] = [];
1464
1520
  if (product.mockups && Array.isArray(product.mockups)) {
1465
1521
  product.mockups.forEach((mockup: any) => {
1466
- if (mockup.id) {
1522
+ if (mockup.id && mockupRole(mockup) === "ordinary") {
1467
1523
  mockupIds.push(mockup.id);
1468
1524
  }
1469
1525
  });
1470
1526
  }
1527
+ if (sizePictureId) mockupIds.push(sizePictureId);
1528
+ // A newly configured picture has no frozen cropped-delivery background yet: send this config full-frame so it
1529
+ // seeds one; maybeFlipCrop re-arms cropped delivery once every configured picture has.
1530
+ if (croppedActiveRef.current && mockupIds.some((id) => !backgroundsRef.current.has(id))) {
1531
+ croppedActiveRef.current = false;
1532
+ }
1471
1533
  configuredMockupIdsRef.current = mockupIds;
1472
1534
  // The viewport policy shapes even the first config (sessionShape.ts):
1473
1535
  // with no gallery opted in it is every picture at mockupWidth (today).
@@ -1488,6 +1550,10 @@ export function RealtimeProvider({
1488
1550
  ...(mockupBg ? { bg: mockupBg } : {}),
1489
1551
  ...(spreadCropsRef.current ? { spreadCrops: spreadCropsRef.current } : {}),
1490
1552
  placementSettings: { ...placementSettingsOverridesRef.current },
1553
+ // Frame flow control: this provider acks every frame it is done with (drawn / superseded / not shown /
1554
+ // failed), so the box can coalesce instead of queueing a backlog behind Cloudflare. Dormant on boxes
1555
+ // that don't negotiate it.
1556
+ acks: true,
1491
1557
  }
1492
1558
  : {
1493
1559
  productId,
@@ -1499,6 +1565,10 @@ export function RealtimeProvider({
1499
1565
  ...(mockupBg ? { bg: mockupBg } : {}),
1500
1566
  ...(spreadCropsRef.current ? { spreadCrops: spreadCropsRef.current } : {}),
1501
1567
  placementSettings: { ...placementSettingsOverridesRef.current },
1568
+ // Frame flow control: this provider acks every frame it is done with (drawn / superseded / not shown /
1569
+ // failed), so the box can coalesce instead of queueing a backlog behind Cloudflare. Dormant on boxes
1570
+ // that don't negotiate it.
1571
+ acks: true,
1502
1572
  };
1503
1573
 
1504
1574
  // If variant changed, trigger shimmer on all image placements
@@ -1523,6 +1593,7 @@ export function RealtimeProvider({
1523
1593
 
1524
1594
  configSentRef.current = true;
1525
1595
  lastSentVariantIdRef.current = variantId;
1596
+ lastSentSizePictureRef.current = sizePictureId;
1526
1597
  lastSentBgRef.current = mockupBg;
1527
1598
  lastSentSpreadCropsRef.current = spreadCropsJson;
1528
1599
 
@@ -1794,6 +1865,8 @@ export function RealtimeProvider({
1794
1865
  const pendingIds: string[] = [];
1795
1866
  if (productContext?.product?.mockups) {
1796
1867
  productContext.product.mockups.forEach((mockup: any) => {
1868
+ // Only the size picture the session renders (the chosen size's) can be pending; the others never render.
1869
+ if (mockupRole(mockup) !== "ordinary" && !configuredMockupIdsRef.current.includes(mockup.id)) return;
1797
1870
  if (mockup.placement === placement || !mockup.placement) {
1798
1871
  pendingMockupIdsRef.current.add(mockup.id);
1799
1872
  pendingIds.push(mockup.id);
@@ -2032,6 +2105,7 @@ export function RealtimeProvider({
2032
2105
  isMockupLoading,
2033
2106
  registerBlobUrl,
2034
2107
  markBlobShown,
2108
+ frameFailed,
2035
2109
  releaseBlobConsumer,
2036
2110
  // WebRTC streaming
2037
2111
  subscribeRTCTiming,
@@ -2069,6 +2143,7 @@ export function RealtimeProvider({
2069
2143
  isMockupLoading,
2070
2144
  registerBlobUrl,
2071
2145
  markBlobShown,
2146
+ frameFailed,
2072
2147
  releaseBlobConsumer,
2073
2148
  ]
2074
2149
  );
@@ -72,7 +72,7 @@ vi.mock("@snowcone-app/sdk/react", () => ({
72
72
  },
73
73
  }));
74
74
 
75
- vi.mock("@snowcone-app/sdk", () => ({
75
+ vi.mock("@snowcone-app/sdk", () => ({ mockupRole: (m: any) => (m?.linkedAs === "size-picture" ? "size-picture" : "ordinary"), gallerySizePicture: () => null,
76
76
  resolveVariantId: () => "gv1",
77
77
  resolvePreviewVariantId: (_context: unknown, variantId: string) => variantId,
78
78
  }));
@@ -74,7 +74,7 @@ vi.mock("@snowcone-app/sdk/react", () => ({
74
74
  },
75
75
  }));
76
76
 
77
- vi.mock("@snowcone-app/sdk", () => ({
77
+ vi.mock("@snowcone-app/sdk", () => ({ mockupRole: (m: any) => (m?.linkedAs === "size-picture" ? "size-picture" : "ordinary"), gallerySizePicture: () => null,
78
78
  resolveVariantId: () => "gv1",
79
79
  resolvePreviewVariantId: (_context: unknown, variantId: string) => variantId,
80
80
  }));
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Frame flow control (wire agreed with rendercenter, 2026-11-11): the provider tells the box it is done with every
3
+ * frame — drawn (an element's img load), not shown (no element watches the mockup, or the picture already shows that
4
+ * exact URL), failed (img error / composite failure) — and a mockup's skipped (coalesced) versions still settle.
5
+ */
6
+ import { describe, expect, it, beforeEach, vi } from "vitest";
7
+ import React from "react";
8
+ import { render, waitFor, act, cleanup } from "@testing-library/react";
9
+ import { RealtimeProvider, useRealtime, type RealtimeContextValue } from "../RealtimeProvider";
10
+
11
+ const h = vi.hoisted(() => ({
12
+ state: { results: [] as Array<Record<string, unknown>> },
13
+ version: 0,
14
+ ackFrame: vi.fn((_m: string, _s: number) => true),
15
+ sendConfig: vi.fn(),
16
+ sendCanvasState: vi.fn(() => true),
17
+ stable: {
18
+ sendCanvasBlob: vi.fn(), sendColorBlob: vi.fn(), updateMockupIds: vi.fn(), updatePlacementSettings: vi.fn(),
19
+ connect: vi.fn(), disconnect: vi.fn(), flushPendingBlobs: vi.fn(), hasPendingBlobs: vi.fn(() => false),
20
+ getLatestSentVersions: vi.fn(() => ({})), rerender: vi.fn(() => true), isFrameSuperseded: vi.fn(() => false),
21
+ },
22
+ }));
23
+ vi.mock("@snowcone-app/sdk/react", () => ({
24
+ useRealtimeMockup: () => ({
25
+ isConnected: true, isConfigured: true, renderError: null, acks: { window: 2, timeoutMs: 5000, timeouts: 0, badAcks: 0 },
26
+ mockupResults: h.state.results, sendConfig: h.sendConfig, sendCanvasState: h.sendCanvasState,
27
+ getLastSentVersion: () => h.version, ackFrame: h.ackFrame, ...h.stable,
28
+ }),
29
+ }));
30
+ vi.mock("@snowcone-app/sdk", () => ({ mockupRole: (m: any) => (m?.linkedAs === "size-picture" ? "size-picture" : "ordinary"), gallerySizePicture: () => null, resolveVariantId: () => "gv1", resolvePreviewVariantId: (_c: unknown, v: string) => v }));
31
+ vi.mock("../Product", () => {
32
+ const product = { id: "p1", placements: [{ label: "Front", type: "image" }], mockups: [{ id: "A" }, { id: "B" }] };
33
+ return { useProductOptional: () => ({ product, selection: {} }) };
34
+ });
35
+ vi.mock("../MockupBackground", () => ({ useMockupBackgroundOptional: () => undefined }));
36
+
37
+ let ctx: RealtimeContextValue;
38
+ function Capture() { ctx = useRealtime(); return null; }
39
+ function Harness({ v }: { v: number }) {
40
+ void v;
41
+ return <RealtimeProvider autoEnable delivery="full-frame"><Capture /></RealtimeProvider>;
42
+ }
43
+ const frame = (id: string, v: number, seq: number) =>
44
+ ({ mockupId: id, imageUrl: `https://r/${id}-v${v}`, renderUrl: `https://r/${id}-v${v}`, imageSize: 1, placement: "Front", requestVersion: v, seq });
45
+ const acked = () => h.ackFrame.mock.calls.map(([m, s]) => `${m}#${s}`);
46
+
47
+ beforeEach(() => {
48
+ cleanup();
49
+ vi.clearAllMocks();
50
+ h.state.results = [];
51
+ h.version = 0;
52
+ });
53
+
54
+ describe("frame flow control (acks)", () => {
55
+ it("asks the box for acks in its config", async () => {
56
+ render(<Harness v={1} />);
57
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
58
+ expect(h.sendConfig.mock.calls[0][0]).toMatchObject({ acks: true });
59
+ });
60
+
61
+ it("acks a frame when an element DRAWS it, not before; a mockup nobody shows is acked at delivery", async () => {
62
+ const { rerender } = render(<Harness v={1} />);
63
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
64
+ const unsub = ctx.subscribeMockupResultById("A", () => {});
65
+ h.state.results = [frame("A", 1, 7), frame("B", 1, 8)];
66
+ await act(async () => rerender(<Harness v={2} />));
67
+ expect(acked()).toEqual(["B#8"]); // B: no element watches it
68
+ await act(async () => ctx.markBlobShown("A", "https://r/A-v1", "el-1"));
69
+ expect(acked()).toEqual(["B#8", "A#7"]);
70
+ unsub();
71
+ });
72
+
73
+ it("acks a frame whose img failed to load", async () => {
74
+ const { rerender } = render(<Harness v={1} />);
75
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
76
+ const unsub = ctx.subscribeMockupResultById("A", () => {});
77
+ const unsubB = ctx.subscribeMockupResultById("B", () => {});
78
+ h.state.results = [frame("A", 1, 3), frame("B", 1, 4)];
79
+ await act(async () => rerender(<Harness v={2} />));
80
+ expect(acked()).toEqual([]);
81
+ await act(async () => ctx.frameFailed("https://r/A-v1"));
82
+ expect(acked()).toEqual(["A#3"]);
83
+ unsub(); unsubB();
84
+ });
85
+
86
+ it("a version the box coalesced away still settles once every mockup has a NEWER frame", async () => {
87
+ const { rerender } = render(<Harness v={1} />);
88
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
89
+ const settled = vi.fn();
90
+ ctx.subscribePipelineSettled(settled);
91
+ await act(async () => { h.version = 1; ctx.sendCanvasState("Front", { a: 1 }); });
92
+ await act(async () => { h.version = 2; ctx.sendCanvasState("Front", { a: 2 }); });
93
+ await act(async () => { h.version = 3; ctx.sendCanvasState("Front", { a: 3 }); });
94
+ // Only v3 arrives (v1, v2 dropped by the box's window).
95
+ h.state.results = [frame("A", 3, 10), frame("B", 3, 11)];
96
+ await act(async () => rerender(<Harness v={2} />));
97
+ expect(settled).toHaveBeenCalledTimes(3); // v1, v2, v3 all answered by the v3 frames
98
+ });
99
+ });
@@ -28,7 +28,7 @@ vi.mock("@snowcone-app/sdk/react", () => ({
28
28
  sendConfig: h.sendConfig, sendCanvasState: h.sendCanvasState, getLastSentVersion: () => h.version, ...h.stable,
29
29
  }),
30
30
  }));
31
- vi.mock("@snowcone-app/sdk", () => ({ resolveVariantId: () => "gv1", resolvePreviewVariantId: (_c: unknown, v: string) => v }));
31
+ vi.mock("@snowcone-app/sdk", () => ({ mockupRole: (m: any) => (m?.linkedAs === "size-picture" ? "size-picture" : "ordinary"), gallerySizePicture: () => null, resolveVariantId: () => "gv1", resolvePreviewVariantId: (_c: unknown, v: string) => v }));
32
32
  const IDS = ["M0", "M1", "M2", "M3", "M4", "M5"];
33
33
  vi.mock("../Product", () => {
34
34
  const product = { id: "p1", placements: [{ label: "Front", type: "image" }], mockups: ["M0", "M1", "M2", "M3", "M4", "M5"].map((id) => ({ id })) };
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Size pictures (json.linkedAs 'size-picture') in the realtime session: the session renders every ordinary picture
3
+ * plus the chosen size's picture (the box renders each mockup at the variant it lists, rendercenter rc#858). A size
4
+ * change sends ONE config with the new size's picture; the other sizes are never rendered and never pending.
5
+ */
6
+ import { describe, expect, it, beforeEach, vi } from "vitest";
7
+ import React from "react";
8
+ import { render, waitFor, act, cleanup } from "@testing-library/react";
9
+ import { RealtimeProvider, useRealtime, type RealtimeContextValue } from "../RealtimeProvider";
10
+
11
+ const h = vi.hoisted(() => ({
12
+ selected: "gS",
13
+ selection: { size: "S" } as Record<string, string>,
14
+ sendConfig: vi.fn(),
15
+ stable: {
16
+ sendCanvasBlob: vi.fn(), sendColorBlob: vi.fn(), updateMockupIds: vi.fn(), updatePlacementSettings: vi.fn(),
17
+ connect: vi.fn(), disconnect: vi.fn(), flushPendingBlobs: vi.fn(), hasPendingBlobs: vi.fn(() => false),
18
+ getLatestSentVersions: vi.fn(() => ({})), rerender: vi.fn(() => true), isFrameSuperseded: vi.fn(() => false),
19
+ sendCanvasState: vi.fn(() => true), ackFrame: vi.fn(() => false),
20
+ },
21
+ }));
22
+ vi.mock("@snowcone-app/sdk/react", () => ({
23
+ useRealtimeMockup: () => ({
24
+ isConnected: true, isConfigured: true, renderError: null, acks: null, mockupResults: [],
25
+ sendConfig: h.sendConfig, getLastSentVersion: () => 0, ...h.stable,
26
+ }),
27
+ }));
28
+ vi.mock("@snowcone-app/sdk", () => {
29
+ const role = (m: any) => (m?.linkedAs === "size-picture" ? "size-picture" : "ordinary");
30
+ return {
31
+ mockupRole: role,
32
+ gallerySizePicture: (ms: any[], g: string) => ms.find((m) => role(m) === "size-picture" && m.gvids.includes(g)) ?? null,
33
+ resolveVariantId: () => h.selected,
34
+ resolvePreviewVariantId: () => "gXL", // the ordinary pictures list XL only (the hoodie)
35
+ };
36
+ });
37
+ vi.mock("../Product", () => {
38
+ const product = {
39
+ id: "XTNA6J",
40
+ placements: [{ label: "Front", type: "image" }],
41
+ mockups: [
42
+ { id: "ORD001", gvids: ["gXL"] },
43
+ { id: "YTGD3Q", gvids: ["gS"], linkedAs: "size-picture" },
44
+ { id: "EVAD6V", gvids: ["gXL"], linkedAs: "size-picture" },
45
+ ],
46
+ };
47
+ return { useProductOptional: () => ({ product, selection: h.selection }) };
48
+ });
49
+ vi.mock("../MockupBackground", () => ({ useMockupBackgroundOptional: () => undefined }));
50
+
51
+ let ctx: RealtimeContextValue;
52
+ function Capture() { ctx = useRealtime(); return null; }
53
+ function Harness({ v }: { v: number }) {
54
+ void v;
55
+ return <RealtimeProvider autoEnable delivery="full-frame"><Capture /></RealtimeProvider>;
56
+ }
57
+
58
+ beforeEach(() => { cleanup(); vi.clearAllMocks(); h.selected = "gS"; h.selection = { size: "S" }; });
59
+
60
+ describe("size pictures in the realtime session", () => {
61
+ it("renders the ordinary pictures + the chosen size's picture; a size change sends ONE config with the new one", async () => {
62
+ const { rerender } = render(<Harness v={1} />);
63
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
64
+ expect(h.sendConfig.mock.calls.map((c) => c[0].mockupIds)).toEqual([["ORD001", "YTGD3Q"]]);
65
+ await act(async () => ctx.notifyPendingExport("Front"));
66
+ expect(ctx.isMockupLoading("YTGD3Q")).toBe(true);
67
+ expect(ctx.isMockupLoading("EVAD6V")).toBe(false); // another size's picture: never rendered, never pending
68
+ h.sendConfig.mockClear();
69
+ h.selected = "gXL";
70
+ h.selection = { size: "XL" }; // a new selection object, as the Product context makes on a pick
71
+ await act(async () => rerender(<Harness v={2} />));
72
+ await waitFor(() => expect(h.sendConfig).toHaveBeenCalled());
73
+ expect(h.sendConfig.mock.calls.map((c) => c[0].mockupIds)).toEqual([["ORD001", "EVAD6V"]]);
74
+ });
75
+ });