@snowcone-app/sdk 0.25.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/dist/{chunk-P3ZDE6LZ.js → chunk-IW7DXXGY.js} +103 -2
- package/dist/index.cjs +149 -17
- package/dist/index.d.cts +47 -3
- package/dist/index.d.ts +47 -3
- package/dist/index.js +41 -16
- package/dist/react.cjs +127 -4
- package/dist/react.d.cts +6 -1
- package/dist/react.d.ts +6 -1
- package/dist/react.js +25 -3
- package/dist/{websocket-Cy0Y29CW.d.cts → websocket-CvN0UU2j.d.cts} +65 -1
- package/dist/{websocket-Cy0Y29CW.d.ts → websocket-CvN0UU2j.d.ts} +65 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export { createDevFetcher } from './dev-fetcher.js';
|
|
2
2
|
import { PublicDesign, PublicFill, PublicOptions } from '@snowcone-app/mockup-url';
|
|
3
|
-
import { O as OptionAttribute, a as OptionSelection, C as Combination, F as FrameworkAdapter, b as ComponentProps, c as ComponentDescriptor, d as ComponentState, e as ComponentContext, f as ComponentLifecycleHooks, E as EventHandler, g as FrameworkUtilities, P as PlacementSettings, M as MockupResult, R as RealtimeRenderError, h as RealtimeMockupService } from './websocket-
|
|
4
|
-
export { A as AdapterRegistry, i as ProductComponentContext, j as RealtimeMockupCallbacks, k as RealtimeMockupState, l as RenderResult, W as WebSocketConfig, m as WebSocketMessage, n as adapterRegistry, o as computeDisabledChoices, p as createComponent, q as defineComponent, r as deriveDefaultSelection, s as findBestCombination, t as getPricePreview, u as isOptionAvailable, v as resolveBestCombination } from './websocket-
|
|
3
|
+
import { O as OptionAttribute, a as OptionSelection, C as Combination, F as FrameworkAdapter, b as ComponentProps, c as ComponentDescriptor, d as ComponentState, e as ComponentContext, f as ComponentLifecycleHooks, E as EventHandler, g as FrameworkUtilities, P as PlacementSettings, M as MockupResult, R as RealtimeRenderError, h as RealtimeMockupService } from './websocket-CvN0UU2j.js';
|
|
4
|
+
export { A as AdapterRegistry, i as ProductComponentContext, j as RealtimeMockupCallbacks, k as RealtimeMockupState, l as RenderResult, W as WebSocketConfig, m as WebSocketMessage, n as adapterRegistry, o as computeDisabledChoices, p as createComponent, q as defineComponent, r as deriveDefaultSelection, s as findBestCombination, t as getPricePreview, u as isOptionAvailable, v as resolveBestCombination } from './websocket-CvN0UU2j.js';
|
|
5
5
|
|
|
6
6
|
interface CatalogProduct {
|
|
7
7
|
id: string;
|
|
@@ -23,6 +23,10 @@ interface CatalogProduct {
|
|
|
23
23
|
picks?: {
|
|
24
24
|
[k: string]: string;
|
|
25
25
|
};
|
|
26
|
+
/**
|
|
27
|
+
* What this mockup is on the product page. 'size-picture': the picture of ONE size (its gvids are that size). The gallery shows only the chosen size's one, last; ordinary-picture lookups (a variant's picture, a card) never return it. Absent on ordinary mockups.
|
|
28
|
+
*/
|
|
29
|
+
linkedAs?: "size-picture";
|
|
26
30
|
}[];
|
|
27
31
|
options?: {
|
|
28
32
|
selected?: {
|
|
@@ -471,6 +475,45 @@ interface BffSignerOptions {
|
|
|
471
475
|
}
|
|
472
476
|
declare function bffSigner(endpoint?: string, opts?: BffSignerOptions): (url: string) => Promise<string>;
|
|
473
477
|
|
|
478
|
+
/**
|
|
479
|
+
* What a mockup IS on a product page: an ordinary picture, or the picture of ONE size (`json.linkedAs =
|
|
480
|
+
* 'size-picture'`: its gvids are that size; a hoodie has eight, S..5XL).
|
|
481
|
+
*
|
|
482
|
+
* The rule (lead + Kevin, 2026-11-11): the gallery shows exactly ONE size picture, the chosen size's, last; and no
|
|
483
|
+
* "the picture for this product / this variant" lookup (cards, links, a variant's preview) ever returns a size
|
|
484
|
+
* picture. Every such lookup goes through `pictureForVariant` / `primaryMockup`, which search `ordinaryMockups` only: a
|
|
485
|
+
* branded list, so code that forgot the filter does not type-check where an ordinary list is required.
|
|
486
|
+
*/
|
|
487
|
+
declare const SIZE_PICTURE: "size-picture";
|
|
488
|
+
type MockupRole = "ordinary" | typeof SIZE_PICTURE;
|
|
489
|
+
type WithRole = {
|
|
490
|
+
id?: unknown;
|
|
491
|
+
linkedAs?: unknown;
|
|
492
|
+
};
|
|
493
|
+
type WithGvids = {
|
|
494
|
+
id?: string;
|
|
495
|
+
gvids?: string[] | null;
|
|
496
|
+
};
|
|
497
|
+
declare function mockupRole(m: WithRole | null | undefined): MockupRole;
|
|
498
|
+
declare const ORDINARY: unique symbol;
|
|
499
|
+
/** A product's ordinary pictures (never a size picture). Only `ordinaryMockups` makes one. */
|
|
500
|
+
type OrdinaryMockups<T> = readonly T[] & {
|
|
501
|
+
readonly [ORDINARY]: true;
|
|
502
|
+
};
|
|
503
|
+
declare function ordinaryMockups<T extends WithRole>(mockups: readonly T[] | null | undefined): OrdinaryMockups<T>;
|
|
504
|
+
/**
|
|
505
|
+
* The picture for a variant: the first ordinary mockup that lists it, else the product's first ordinary mockup (its
|
|
506
|
+
* fallback picture), else null. Never a size picture, even when a size picture is the only mockup listing the variant.
|
|
507
|
+
*/
|
|
508
|
+
declare function pictureForVariant<T extends WithRole & WithGvids>(mockups: readonly T[] | null | undefined, variantId: string | null | undefined): T | null;
|
|
509
|
+
/** The product's picture for cards, links and previews: its first ordinary mockup. Never a size picture. */
|
|
510
|
+
declare function primaryMockup<T extends WithRole>(mockups: readonly T[] | null | undefined): T | null;
|
|
511
|
+
/**
|
|
512
|
+
* The ONE size picture the gallery shows: the size picture whose gvids list the chosen variant, or null (no size
|
|
513
|
+
* pictures, or none for this size: never another size's picture).
|
|
514
|
+
*/
|
|
515
|
+
declare function gallerySizePicture<T extends WithRole & WithGvids>(mockups: readonly T[] | null | undefined, selectedVariantId: string | null | undefined): T | null;
|
|
516
|
+
|
|
474
517
|
/**
|
|
475
518
|
* Framework-agnostic state management utilities
|
|
476
519
|
* Provides consistent state management patterns for React and Web Components
|
|
@@ -1057,6 +1100,7 @@ declare function getVariant(selection: UserSelection, product: {
|
|
|
1057
1100
|
mockups: Array<{
|
|
1058
1101
|
id: string;
|
|
1059
1102
|
gvids?: string[];
|
|
1103
|
+
linkedAs?: unknown;
|
|
1060
1104
|
}>;
|
|
1061
1105
|
attributes?: Record<string, any>;
|
|
1062
1106
|
}): {
|
|
@@ -3436,4 +3480,4 @@ declare function searchDesigns(query?: string, options?: SearchDesignsOptions):
|
|
|
3436
3480
|
*/
|
|
3437
3481
|
declare function createClient(config: SdkConfig): SnowconeClient;
|
|
3438
3482
|
|
|
3439
|
-
export { AbstractTemplateRenderer, type AddToCartOptions, Animations, type ArtSelectorContext, type ArtSelectorDescriptor, type ArtSelectorOptions, type ArtworkData, type AspectRatio, Attributes, type BaseDescriptor, type BlendConfig, type BuildMockupUrlConfig, type CartDetail, type CatalogDesign, type CatalogListResponse, type CatalogProduct, ClassNames, type ColorDesignElement, ColorPickerUtils, Combination, CommonProps, ComponentContext, type ComponentDefinition, ComponentDescriptor, ComponentEventManager, ComponentFactory, ComponentLifecycle, ComponentLifecycleHooks, type ComponentMetadata, ComponentProps, ComponentRegistry, ComponentState, type ComponentTemplate, ComponentTemplates, type ContainerDescriptor, ContextBridge, type ContextComparator, type ContextConsumer, ContextInjector, type ContextProviderConfig, type ContextSubscriber, ContextSynchronizer, type CreateDesignStateInput, type CreatedDesignState, DEFAULT_ARTWORK_URL, DEFAULT_ASPECT_RATIO, DEFAULT_BUY_BASE, DEFAULT_COLOR, DEFAULT_GRANT_BASE, DEFAULT_MOCKUP_BASE, DEFAULT_PLACEMENT_DIMENSIONS, type Descriptor, type Design, type DesignElement, type DesignGenerationContext, type DesignLike, type DesignsSearchResponse, type Effects, Elements, type ErrorContext, type ErrorHandler, ErrorManager, type EventDefinition, EventDelegator, EventEmitter, EventHandler, type EventListener, type EventPayload, type FailedAsset, type FetchMockupImageOptions, type Fill, Focus, FrameworkAdapter, FrameworkUtilities, type GetMockupUrlOptions, type ImageAlignment, type ImageDesignElement, type LifecycleHook, LifecycleManager, type LifecyclePhase, type LifecycleTransition, LitAdapter, type MaskOverride, type MockupGenerationOptions, type MockupImage, MockupResult, type MockupService, type MockupServiceConfig, OptionAttribute, type OptionChoice, type OptionChoiceRenderData, type OptionRenderData, OptionSelection, type Placement, type PlacementDesign, PlacementSettings, type ProductArtAlignmentContext, type ProductArtAlignmentDescriptor, type ProductArtAlignmentOptions, type ProductContext, type ProductContextEvents, ProductContextManager, type ProductData, type ProductFetcher, type ProductImageDescriptor, type ProductImageOptions, ProductLoader, type ProductMockupData, type ProductOptionChoice, type ProductOptionData, type ProductOptionsDescriptor, type ProductOptionsOptions, type ProductPlacement, type ProductPriceDescriptor, type ProductPriceOptions, ProductProps, type ProductSpec, type ProductTitleDescriptor, type ProductTitleOptions, type ProductVariant, type PropDefinition, type PropSchema, type PropType, PropertyManager, REALTIME_WS_URL, type RateLimitState, type RealtimeGrant, RealtimeMockupService, RealtimeRenderError, type RegularArtwork, type RenderProduct, type RenderProductAttribute, type RenderProductAttributeChoice, type RenderProductCombination, type RenderProductMockup, type RenderProductOptions, type RenderProductRequiredPlacement, RenderSession, type RenderSessionOptions, type RenderState, type SdkConfig, type SeamlessPattern, type SearchDesignsOptions, type SignedUrlResponse, type SnowconeClient, SnowconeSdkError, type SnowconeSdkErrorCode, StandardComponents, StandardEvents, StateManager, type StateManagerOptions, type StateMiddleware, type StateSelector, type StateSubscriber, type StateUpdater, Styles, SvelteAdapter, SwatchUtils, type TagName, TemplateBuilder, type TemplateNode, type TemplateNodeType, type TemplateRenderer, type TextDescriptor, type TileCount, UniversalContextProvider, type UserSelection, type ValidationError, type ValidationResult, VueAdapter, assertVariantSelected, autoRegister, bffSigner, buildMockupUrl, componentRegistry, createAddToCartEvent, createAddToCartHandler, createCartDetail, createClient, createContextProvider, createDesignForPlacements, createDesignState, createErrorHandler, createEventManager, createLifecycle, createLitComponent, createProductContext, createProductLoader, createPropertyManager, createStateHook, createStateStore, createSvelteComponent, createUniversalProvider, createVueComponent, describeArtSelector, describeProductArtAlignment, describeProductImage, describeProductOptions, describeProductPrice, describeProductTitle, extractProductId, fetchMockupImage, fetchRealtimeGrant, filterImagePlacements, findClosestSnapPoint, findVariantForSelection, formatPrice, formatValidationErrors, getBuyUrl, getDefaultVariantId, getEffectiveAlignment, getIncompleteSelectionMessage, getMissingSelections, getMockupUrl, getOptionRenderType, getProduct, getSelectionDisplayText, getSnapPoints, getVariant, handleOptionChange, imageKindOf, isSelectionComplete, isSnowconeSdkError, isValidAlignment, isValidTileCount, listProducts, mintRealtimeGrant, mockupUrl, normalizeChoice, prepareOptionRenderData, registerStandardComponents, resolveMockupId, resolvePreviewVariantId, resolveVariantId, retryOperation, searchDesigns, simulateCartOperation, toCombinations, toOptionAttributes, useFrameworkAdapter as useVueAdapter, validateAlignment, validateDesignElement, validateEffects, validateImageUrl, validateMockupOptions, validateProductSelection, validateProductSpec, validateRequiredOptions, validateTileCount, warnVariantNotSelected, withContext, withErrorHandling, withSyncErrorHandling };
|
|
3483
|
+
export { AbstractTemplateRenderer, type AddToCartOptions, Animations, type ArtSelectorContext, type ArtSelectorDescriptor, type ArtSelectorOptions, type ArtworkData, type AspectRatio, Attributes, type BaseDescriptor, type BlendConfig, type BuildMockupUrlConfig, type CartDetail, type CatalogDesign, type CatalogListResponse, type CatalogProduct, ClassNames, type ColorDesignElement, ColorPickerUtils, Combination, CommonProps, ComponentContext, type ComponentDefinition, ComponentDescriptor, ComponentEventManager, ComponentFactory, ComponentLifecycle, ComponentLifecycleHooks, type ComponentMetadata, ComponentProps, ComponentRegistry, ComponentState, type ComponentTemplate, ComponentTemplates, type ContainerDescriptor, ContextBridge, type ContextComparator, type ContextConsumer, ContextInjector, type ContextProviderConfig, type ContextSubscriber, ContextSynchronizer, type CreateDesignStateInput, type CreatedDesignState, DEFAULT_ARTWORK_URL, DEFAULT_ASPECT_RATIO, DEFAULT_BUY_BASE, DEFAULT_COLOR, DEFAULT_GRANT_BASE, DEFAULT_MOCKUP_BASE, DEFAULT_PLACEMENT_DIMENSIONS, type Descriptor, type Design, type DesignElement, type DesignGenerationContext, type DesignLike, type DesignsSearchResponse, type Effects, Elements, type ErrorContext, type ErrorHandler, ErrorManager, type EventDefinition, EventDelegator, EventEmitter, EventHandler, type EventListener, type EventPayload, type FailedAsset, type FetchMockupImageOptions, type Fill, Focus, FrameworkAdapter, FrameworkUtilities, type GetMockupUrlOptions, type ImageAlignment, type ImageDesignElement, type LifecycleHook, LifecycleManager, type LifecyclePhase, type LifecycleTransition, LitAdapter, type MaskOverride, type MockupGenerationOptions, type MockupImage, MockupResult, type MockupRole, type MockupService, type MockupServiceConfig, OptionAttribute, type OptionChoice, type OptionChoiceRenderData, type OptionRenderData, OptionSelection, type OrdinaryMockups, type Placement, type PlacementDesign, PlacementSettings, type ProductArtAlignmentContext, type ProductArtAlignmentDescriptor, type ProductArtAlignmentOptions, type ProductContext, type ProductContextEvents, ProductContextManager, type ProductData, type ProductFetcher, type ProductImageDescriptor, type ProductImageOptions, ProductLoader, type ProductMockupData, type ProductOptionChoice, type ProductOptionData, type ProductOptionsDescriptor, type ProductOptionsOptions, type ProductPlacement, type ProductPriceDescriptor, type ProductPriceOptions, ProductProps, type ProductSpec, type ProductTitleDescriptor, type ProductTitleOptions, type ProductVariant, type PropDefinition, type PropSchema, type PropType, PropertyManager, REALTIME_WS_URL, type RateLimitState, type RealtimeGrant, RealtimeMockupService, RealtimeRenderError, type RegularArtwork, type RenderProduct, type RenderProductAttribute, type RenderProductAttributeChoice, type RenderProductCombination, type RenderProductMockup, type RenderProductOptions, type RenderProductRequiredPlacement, RenderSession, type RenderSessionOptions, type RenderState, SIZE_PICTURE, type SdkConfig, type SeamlessPattern, type SearchDesignsOptions, type SignedUrlResponse, type SnowconeClient, SnowconeSdkError, type SnowconeSdkErrorCode, StandardComponents, StandardEvents, StateManager, type StateManagerOptions, type StateMiddleware, type StateSelector, type StateSubscriber, type StateUpdater, Styles, SvelteAdapter, SwatchUtils, type TagName, TemplateBuilder, type TemplateNode, type TemplateNodeType, type TemplateRenderer, type TextDescriptor, type TileCount, UniversalContextProvider, type UserSelection, type ValidationError, type ValidationResult, VueAdapter, assertVariantSelected, autoRegister, bffSigner, buildMockupUrl, componentRegistry, createAddToCartEvent, createAddToCartHandler, createCartDetail, createClient, createContextProvider, createDesignForPlacements, createDesignState, createErrorHandler, createEventManager, createLifecycle, createLitComponent, createProductContext, createProductLoader, createPropertyManager, createStateHook, createStateStore, createSvelteComponent, createUniversalProvider, createVueComponent, describeArtSelector, describeProductArtAlignment, describeProductImage, describeProductOptions, describeProductPrice, describeProductTitle, extractProductId, fetchMockupImage, fetchRealtimeGrant, filterImagePlacements, findClosestSnapPoint, findVariantForSelection, formatPrice, formatValidationErrors, gallerySizePicture, getBuyUrl, getDefaultVariantId, getEffectiveAlignment, getIncompleteSelectionMessage, getMissingSelections, getMockupUrl, getOptionRenderType, getProduct, getSelectionDisplayText, getSnapPoints, getVariant, handleOptionChange, imageKindOf, isSelectionComplete, isSnowconeSdkError, isValidAlignment, isValidTileCount, listProducts, mintRealtimeGrant, mockupRole, mockupUrl, normalizeChoice, ordinaryMockups, pictureForVariant, prepareOptionRenderData, primaryMockup, registerStandardComponents, resolveMockupId, resolvePreviewVariantId, resolveVariantId, retryOperation, searchDesigns, simulateCartOperation, toCombinations, toOptionAttributes, useFrameworkAdapter as useVueAdapter, validateAlignment, validateDesignElement, validateEffects, validateImageUrl, validateMockupOptions, validateProductSelection, validateProductSpec, validateRequiredOptions, validateTileCount, warnVariantNotSelected, withContext, withErrorHandling, withSyncErrorHandling };
|
package/dist/index.js
CHANGED
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
import {
|
|
5
5
|
REALTIME_WS_URL,
|
|
6
6
|
RealtimeMockupService
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-IW7DXXGY.js";
|
|
8
8
|
import {
|
|
9
9
|
buildMockupUrl,
|
|
10
10
|
buildPublicMockupUrl,
|
|
@@ -24,7 +24,13 @@ var CatalogProductSchema = z.object({
|
|
|
24
24
|
lowestPrice: z.number().int().optional(),
|
|
25
25
|
highestPrice: z.number().int().optional(),
|
|
26
26
|
mockups: z.array(
|
|
27
|
-
z.object({
|
|
27
|
+
z.object({
|
|
28
|
+
id: z.string(),
|
|
29
|
+
ar: z.number(),
|
|
30
|
+
gvids: z.array(z.string()),
|
|
31
|
+
// Kept through a successful parse (zod strips undeclared keys): the PDP shows one size picture, the chosen size's.
|
|
32
|
+
linkedAs: z.literal("size-picture").optional()
|
|
33
|
+
})
|
|
28
34
|
).optional(),
|
|
29
35
|
options: z.object({
|
|
30
36
|
selected: z.record(z.string(), z.union([z.string(), z.number(), z.null()])).optional(),
|
|
@@ -629,6 +635,30 @@ function bffSigner(endpoint = "/api/sign", opts) {
|
|
|
629
635
|
};
|
|
630
636
|
}
|
|
631
637
|
|
|
638
|
+
// src/mockup/mockupRole.ts
|
|
639
|
+
var SIZE_PICTURE = "size-picture";
|
|
640
|
+
function mockupRole(m) {
|
|
641
|
+
return m?.linkedAs === SIZE_PICTURE ? SIZE_PICTURE : "ordinary";
|
|
642
|
+
}
|
|
643
|
+
function ordinaryMockups(mockups) {
|
|
644
|
+
return (mockups ?? []).filter((m) => mockupRole(m) === "ordinary");
|
|
645
|
+
}
|
|
646
|
+
function pictureForVariant(mockups, variantId) {
|
|
647
|
+
const ordinary = ordinaryMockups(mockups);
|
|
648
|
+
if (variantId) {
|
|
649
|
+
const listed = ordinary.find((m) => (m.gvids ?? []).includes(variantId));
|
|
650
|
+
if (listed) return listed;
|
|
651
|
+
}
|
|
652
|
+
return ordinary[0] ?? null;
|
|
653
|
+
}
|
|
654
|
+
function primaryMockup(mockups) {
|
|
655
|
+
return ordinaryMockups(mockups)[0] ?? null;
|
|
656
|
+
}
|
|
657
|
+
function gallerySizePicture(mockups, selectedVariantId) {
|
|
658
|
+
if (!selectedVariantId) return null;
|
|
659
|
+
return (mockups ?? []).find((m) => mockupRole(m) === SIZE_PICTURE && (m.gvids ?? []).includes(selectedVariantId)) ?? null;
|
|
660
|
+
}
|
|
661
|
+
|
|
632
662
|
// src/state/optionSelection.ts
|
|
633
663
|
function resolveBestCombination(selection, attributes, combinations) {
|
|
634
664
|
const relevant = Object.fromEntries(
|
|
@@ -1478,10 +1508,7 @@ function getVariant(selection, product) {
|
|
|
1478
1508
|
const variantId = combination?.variantId;
|
|
1479
1509
|
let mockupId;
|
|
1480
1510
|
if (variantId && product.mockups && product.mockups.length > 0) {
|
|
1481
|
-
|
|
1482
|
-
(m) => m.gvids && m.gvids.includes(variantId)
|
|
1483
|
-
);
|
|
1484
|
-
mockupId = mockupForVariant?.id || product.mockups[0].id;
|
|
1511
|
+
mockupId = pictureForVariant(product.mockups, variantId)?.id;
|
|
1485
1512
|
}
|
|
1486
1513
|
return {
|
|
1487
1514
|
variantId,
|
|
@@ -1520,7 +1547,7 @@ var SIZE_ATTRIBUTE = /^size$/i;
|
|
|
1520
1547
|
var NOT_THE_PICTURE = /* @__PURE__ */ new Set(["variantId", "price"]);
|
|
1521
1548
|
function resolvePreviewVariantId(context, variantId, mockupId) {
|
|
1522
1549
|
const all = context?.product?.mockups ?? [];
|
|
1523
|
-
const mockups = mockupId ? all.filter((m) => m.id === mockupId) : all;
|
|
1550
|
+
const mockups = mockupId ? all.filter((m) => m.id === mockupId) : [...ordinaryMockups(all)];
|
|
1524
1551
|
const lists = (m, id) => (m.gvids ?? []).includes(id);
|
|
1525
1552
|
if (mockups.length === 0 || mockups.some((m) => lists(m, variantId))) return variantId;
|
|
1526
1553
|
const combinations = context?.combinations ?? [];
|
|
@@ -1548,15 +1575,7 @@ function resolvePreviewVariantId(context, variantId, mockupId) {
|
|
|
1548
1575
|
function resolveMockupId(context, variantId, providedMockupId) {
|
|
1549
1576
|
if (providedMockupId) return providedMockupId;
|
|
1550
1577
|
if (context?.product?.mockups?.length) {
|
|
1551
|
-
|
|
1552
|
-
const mockupForVariant = context.product.mockups.find(
|
|
1553
|
-
(m) => m.gvids && m.gvids.includes(variantId)
|
|
1554
|
-
);
|
|
1555
|
-
if (mockupForVariant) {
|
|
1556
|
-
return mockupForVariant.id;
|
|
1557
|
-
}
|
|
1558
|
-
}
|
|
1559
|
-
return context.product.mockups[0].id;
|
|
1578
|
+
return pictureForVariant(context.product.mockups, variantId)?.id ?? null;
|
|
1560
1579
|
}
|
|
1561
1580
|
return null;
|
|
1562
1581
|
}
|
|
@@ -5211,6 +5230,7 @@ export {
|
|
|
5211
5230
|
REALTIME_WS_URL,
|
|
5212
5231
|
RealtimeMockupService,
|
|
5213
5232
|
RenderSession,
|
|
5233
|
+
SIZE_PICTURE,
|
|
5214
5234
|
SnowconeSdkError,
|
|
5215
5235
|
StandardComponents,
|
|
5216
5236
|
StandardEvents,
|
|
@@ -5266,6 +5286,7 @@ export {
|
|
|
5266
5286
|
findVariantForSelection,
|
|
5267
5287
|
formatPrice,
|
|
5268
5288
|
formatValidationErrors,
|
|
5289
|
+
gallerySizePicture,
|
|
5269
5290
|
getBuyUrl,
|
|
5270
5291
|
getDefaultVariantId,
|
|
5271
5292
|
getEffectiveAlignment,
|
|
@@ -5287,9 +5308,13 @@ export {
|
|
|
5287
5308
|
isValidTileCount,
|
|
5288
5309
|
listProducts,
|
|
5289
5310
|
mintRealtimeGrant,
|
|
5311
|
+
mockupRole,
|
|
5290
5312
|
mockupUrl,
|
|
5291
5313
|
normalizeChoice,
|
|
5314
|
+
ordinaryMockups,
|
|
5315
|
+
pictureForVariant,
|
|
5292
5316
|
prepareOptionRenderData,
|
|
5317
|
+
primaryMockup,
|
|
5293
5318
|
registerStandardComponents,
|
|
5294
5319
|
resolveBestCombination,
|
|
5295
5320
|
resolveMockupId,
|
package/dist/react.cjs
CHANGED
|
@@ -122,6 +122,15 @@ var RealtimeMockupService = class {
|
|
|
122
122
|
pendingFrames = /* @__PURE__ */ new Map();
|
|
123
123
|
// Last object URL handed out per mockup — revoked when replaced.
|
|
124
124
|
liveObjectUrls = /* @__PURE__ */ new Map();
|
|
125
|
+
// Frame flow control (negotiated per config): window, acked/newest seq per mockup, acks waiting for the next flush.
|
|
126
|
+
acks = null;
|
|
127
|
+
ackedSeq = /* @__PURE__ */ new Map();
|
|
128
|
+
newestSeq = /* @__PURE__ */ new Map();
|
|
129
|
+
pendingAcks = /* @__PURE__ */ new Map();
|
|
130
|
+
ackFlushScheduled = false;
|
|
131
|
+
// Live frames a newer frame for the same mockup has replaced (and revoked), newest last, bounded. Lets a consumer
|
|
132
|
+
// still loading an old frame tell "superseded" from "broken" the moment it fails (isFrameSuperseded).
|
|
133
|
+
supersededFrameUrls = /* @__PURE__ */ new Set();
|
|
125
134
|
renewTimer = null;
|
|
126
135
|
isConnecting = false;
|
|
127
136
|
connectAttempt = 0;
|
|
@@ -134,6 +143,7 @@ var RealtimeMockupService = class {
|
|
|
134
143
|
}
|
|
135
144
|
getState() {
|
|
136
145
|
return {
|
|
146
|
+
acks: this.acks ? { ...this.acks } : null,
|
|
137
147
|
isConnected: this.ws?.readyState === WebSocket.OPEN,
|
|
138
148
|
sessionId: this.sessionId,
|
|
139
149
|
box: this.box,
|
|
@@ -179,6 +189,10 @@ var RealtimeMockupService = class {
|
|
|
179
189
|
this.ws = new WebSocket(url);
|
|
180
190
|
this.ws.binaryType = "arraybuffer";
|
|
181
191
|
this.ws.onopen = () => {
|
|
192
|
+
this.acks = null;
|
|
193
|
+
this.ackedSeq.clear();
|
|
194
|
+
this.newestSeq.clear();
|
|
195
|
+
this.pendingAcks.clear();
|
|
182
196
|
console.log(`[WS] connection OPENED to ${this.wsUrl}`);
|
|
183
197
|
this.addLog("WebSocket connection opened");
|
|
184
198
|
this.status = "Connected";
|
|
@@ -259,6 +273,16 @@ var RealtimeMockupService = class {
|
|
|
259
273
|
break;
|
|
260
274
|
case "config_received":
|
|
261
275
|
case "configured":
|
|
276
|
+
if (this.config?.acks && data.acks && typeof data.acks.window === "number") {
|
|
277
|
+
this.acks = {
|
|
278
|
+
window: data.acks.window,
|
|
279
|
+
timeoutMs: typeof data.acks.timeoutMs === "number" ? data.acks.timeoutMs : 0,
|
|
280
|
+
timeouts: this.acks?.timeouts ?? 0,
|
|
281
|
+
badAcks: this.acks?.badAcks ?? 0
|
|
282
|
+
};
|
|
283
|
+
} else {
|
|
284
|
+
this.acks = null;
|
|
285
|
+
}
|
|
262
286
|
this.isConfigured = true;
|
|
263
287
|
this.status = "Configured";
|
|
264
288
|
this.addLog("\u2705 Configuration accepted! You can now send blobs.");
|
|
@@ -315,12 +339,20 @@ var RealtimeMockupService = class {
|
|
|
315
339
|
if (lastAccepted !== void 0 && responseVersion < lastAccepted) {
|
|
316
340
|
console.log(`[WS] STALE mockup dropped: v${responseVersion} for "${responsePlacement}" (already displayed: v${lastAccepted}, latest sent: v${this.latestSentVersionByPlacement[responsePlacement]})`);
|
|
317
341
|
this.addLog(`\u23ED\uFE0F Ignoring stale mockup v${responseVersion} for "${responsePlacement}" (displayed: v${lastAccepted})`);
|
|
342
|
+
if (typeof data.seq === "number") this.ackFrame(data.mockupId, data.seq);
|
|
318
343
|
break;
|
|
319
344
|
}
|
|
320
345
|
this.latestAcceptedVersionByPlacement[responsePlacement] = responseVersion;
|
|
321
346
|
}
|
|
347
|
+
if (typeof data.seq === "number") {
|
|
348
|
+
const prevSeq = this.newestSeq.get(data.mockupId);
|
|
349
|
+
if (prevSeq !== void 0 && prevSeq < data.seq) this.ackFrame(data.mockupId, prevSeq);
|
|
350
|
+
if (prevSeq === void 0 || prevSeq < data.seq) this.newestSeq.set(data.mockupId, data.seq);
|
|
351
|
+
}
|
|
322
352
|
const mockupResult = {
|
|
323
353
|
mockupId: data.mockupId,
|
|
354
|
+
...typeof data.seq === "number" ? { seq: data.seq } : {},
|
|
355
|
+
...typeof data.coalesced === "number" ? { coalesced: data.coalesced } : {},
|
|
324
356
|
imageUrl: data.imageUrl,
|
|
325
357
|
renderUrl: data.renderUrl || data.imageUrl,
|
|
326
358
|
imageSize: data.imageSize || 0,
|
|
@@ -372,7 +404,7 @@ var RealtimeMockupService = class {
|
|
|
372
404
|
}
|
|
373
405
|
return true;
|
|
374
406
|
});
|
|
375
|
-
|
|
407
|
+
const batch = freshMockups.map((mockup) => {
|
|
376
408
|
const existing = this.mockupResults.find(
|
|
377
409
|
(m) => m.mockupId === mockup.mockupId && (mockup.requestId === void 0 || m.requestId === mockup.requestId)
|
|
378
410
|
);
|
|
@@ -384,6 +416,11 @@ var RealtimeMockupService = class {
|
|
|
384
416
|
}
|
|
385
417
|
return merged;
|
|
386
418
|
});
|
|
419
|
+
const batchById = new Map(batch.map((m) => [m.mockupId, m]));
|
|
420
|
+
this.mockupResults = [
|
|
421
|
+
...this.mockupResults.map((m) => batchById.get(m.mockupId) ?? m),
|
|
422
|
+
...batch.filter((m) => !this.mockupResults.some((e) => e.mockupId === m.mockupId))
|
|
423
|
+
];
|
|
387
424
|
this.lastError = null;
|
|
388
425
|
this.renderError = null;
|
|
389
426
|
this.addLog(`\u{1F389} All mockups rendered: ${freshMockups.length} fresh (${data.mockups.length - freshMockups.length} stale filtered)`);
|
|
@@ -392,7 +429,23 @@ var RealtimeMockupService = class {
|
|
|
392
429
|
this.addLog(`\u26A0\uFE0F all_mockups_rendered message dropped: missing 'mockups' array. Full data keys: [${Object.keys(data).join(", ")}]`);
|
|
393
430
|
}
|
|
394
431
|
break;
|
|
432
|
+
case "ack_timeout": {
|
|
433
|
+
if (this.acks) this.acks.timeouts += 1;
|
|
434
|
+
const message = `E_RT_ACK_TIMEOUT: the box waited ${this.acks?.timeoutMs ?? "?"} ms for an ack of ${data.mockupId} seq ${data.seq}; fix: every frame must be acked once drawn, superseded, not shown or failed (ackFrame).`;
|
|
435
|
+
console.error(`[WS] ${message}`);
|
|
436
|
+
this.addLog(`\u23F1\uFE0F ${message}`);
|
|
437
|
+
this.callbacks.onAckFault?.({ code: "E_RT_ACK_TIMEOUT", mockupId: data.mockupId, seq: data.seq, message });
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
395
440
|
case "error": {
|
|
441
|
+
if (data.code === "E_RT_ACK_BAD") {
|
|
442
|
+
if (this.acks) this.acks.badAcks += 1;
|
|
443
|
+
const message = `E_RT_ACK_BAD (${data.reason ?? "?"}) for ${data.mockupId ?? "?"}: ${data.message ?? ""}`;
|
|
444
|
+
console.error(`[WS] ${message}`);
|
|
445
|
+
this.addLog(`\u274C ${message}`);
|
|
446
|
+
this.callbacks.onAckFault?.({ code: "E_RT_ACK_BAD", mockupId: data.mockupId, reason: data.reason, message });
|
|
447
|
+
break;
|
|
448
|
+
}
|
|
396
449
|
const errorMessage = data.message || "Unknown error occurred";
|
|
397
450
|
const renderError = {
|
|
398
451
|
code: data.code || "render_error",
|
|
@@ -445,7 +498,14 @@ var RealtimeMockupService = class {
|
|
|
445
498
|
if (!frame) return;
|
|
446
499
|
this.pendingFrames.delete(key);
|
|
447
500
|
const prevLive = this.liveObjectUrls.get(data.mockupId);
|
|
448
|
-
if (prevLive)
|
|
501
|
+
if (prevLive) {
|
|
502
|
+
URL.revokeObjectURL(prevLive);
|
|
503
|
+
this.supersededFrameUrls.add(prevLive);
|
|
504
|
+
if (this.supersededFrameUrls.size > 512) {
|
|
505
|
+
const oldest = this.supersededFrameUrls.values().next().value;
|
|
506
|
+
if (oldest) this.supersededFrameUrls.delete(oldest);
|
|
507
|
+
}
|
|
508
|
+
}
|
|
449
509
|
this.liveObjectUrls.set(data.mockupId, frame.objectUrl);
|
|
450
510
|
data.imageUrl = frame.objectUrl;
|
|
451
511
|
}
|
|
@@ -811,6 +871,47 @@ ${versionToSend}
|
|
|
811
871
|
* E_RERENDER_INCOMPLETE | E_RERENDER_RATE_LIMITED). Never changes the
|
|
812
872
|
* session's mockupIds.
|
|
813
873
|
*/
|
|
874
|
+
/**
|
|
875
|
+
* True when `url` was a ws-delivered frame for a mockup and a newer frame for that mockup has since arrived (the SDK
|
|
876
|
+
* revoked the old one). A consumer whose load of `url` failed uses this to tell supersession (the newer frame is
|
|
877
|
+
* already here; it reaches the results with its batch's all_mockups_rendered) from a real failure.
|
|
878
|
+
*/
|
|
879
|
+
isFrameSuperseded(url) {
|
|
880
|
+
return this.supersededFrameUrls.has(url);
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* The client is done with frame `seq` of `mockupId`: drawn on screen, superseded, not shown by any element, or
|
|
884
|
+
* failed. Cumulative per mockup. A no-op unless flow control was negotiated (see WebSocketConfig.acks). Acks are
|
|
885
|
+
* batched into one frame_ack message per animation frame.
|
|
886
|
+
*/
|
|
887
|
+
ackFrame(mockupId, seq) {
|
|
888
|
+
if (!this.acks || !(seq > 0)) return false;
|
|
889
|
+
if (seq <= (this.ackedSeq.get(mockupId) ?? 0) || seq <= (this.pendingAcks.get(mockupId) ?? 0)) return true;
|
|
890
|
+
this.pendingAcks.set(mockupId, seq);
|
|
891
|
+
if (!this.ackFlushScheduled) {
|
|
892
|
+
this.ackFlushScheduled = true;
|
|
893
|
+
const flush = () => this.flushAcks();
|
|
894
|
+
if (typeof requestAnimationFrame === "function") requestAnimationFrame(flush);
|
|
895
|
+
else setTimeout(flush, 16);
|
|
896
|
+
}
|
|
897
|
+
return true;
|
|
898
|
+
}
|
|
899
|
+
flushAcks() {
|
|
900
|
+
this.ackFlushScheduled = false;
|
|
901
|
+
if (!this.acks || this.pendingAcks.size === 0) {
|
|
902
|
+
this.pendingAcks.clear();
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;
|
|
906
|
+
const acks = [...this.pendingAcks].map(([mockupId, seq]) => ({ mockupId, seq }));
|
|
907
|
+
this.pendingAcks.clear();
|
|
908
|
+
acks.forEach(({ mockupId, seq }) => this.ackedSeq.set(mockupId, seq));
|
|
909
|
+
this.ws.send(JSON.stringify(acks.length === 1 ? { type: "frame_ack", ...acks[0] } : { type: "frame_ack", acks }));
|
|
910
|
+
}
|
|
911
|
+
/** Whether frame flow control is active on this session (negotiated with the box for the current config). */
|
|
912
|
+
isAcking() {
|
|
913
|
+
return this.acks !== null;
|
|
914
|
+
}
|
|
814
915
|
rerender(mockupIds) {
|
|
815
916
|
if (!this.ws || this.ws.readyState !== WebSocket.OPEN || !this.config || mockupIds.length === 0) return false;
|
|
816
917
|
const { requestId, traceparent } = newRenderCorrelation();
|
|
@@ -921,9 +1022,11 @@ var DEFAULT_REALTIME_WS_URL = "wss://cdn.snowcone.app/realtime";
|
|
|
921
1022
|
function useRealtimeMockup(options = {}) {
|
|
922
1023
|
const wsUrl = options.wsUrl ?? (options.getToken ? DEFAULT_REALTIME_WS_URL : void 0);
|
|
923
1024
|
const serviceRef = (0, import_react.useRef)(null);
|
|
1025
|
+
const stateFrameScheduledRef = (0, import_react.useRef)(false);
|
|
924
1026
|
const getTokenRef = (0, import_react.useRef)(options.getToken);
|
|
925
1027
|
getTokenRef.current = options.getToken;
|
|
926
1028
|
const [state, setState] = (0, import_react.useState)({
|
|
1029
|
+
acks: null,
|
|
927
1030
|
isConnected: false,
|
|
928
1031
|
sessionId: null,
|
|
929
1032
|
box: null,
|
|
@@ -957,7 +1060,15 @@ function useRealtimeMockup(options = {}) {
|
|
|
957
1060
|
options.onBlobSent?.(placement);
|
|
958
1061
|
},
|
|
959
1062
|
onMockupRendered: (result) => {
|
|
960
|
-
|
|
1063
|
+
if (service.isAcking() && !stateFrameScheduledRef.current) {
|
|
1064
|
+
stateFrameScheduledRef.current = true;
|
|
1065
|
+
const apply = () => {
|
|
1066
|
+
stateFrameScheduledRef.current = false;
|
|
1067
|
+
setState(service.getState());
|
|
1068
|
+
};
|
|
1069
|
+
if (typeof requestAnimationFrame === "function") requestAnimationFrame(apply);
|
|
1070
|
+
else setTimeout(apply, 16);
|
|
1071
|
+
}
|
|
961
1072
|
options.onMockupRendered?.(result);
|
|
962
1073
|
},
|
|
963
1074
|
onAllMockupsRendered: (results) => {
|
|
@@ -966,6 +1077,10 @@ function useRealtimeMockup(options = {}) {
|
|
|
966
1077
|
setState(newState);
|
|
967
1078
|
options.onAllMockupsRendered?.(results);
|
|
968
1079
|
},
|
|
1080
|
+
onAckFault: (fault) => {
|
|
1081
|
+
setState(service.getState());
|
|
1082
|
+
options.onAckFault?.(fault);
|
|
1083
|
+
},
|
|
969
1084
|
onError: (error, detail) => {
|
|
970
1085
|
setState(service.getState());
|
|
971
1086
|
options.onError?.(error, detail);
|
|
@@ -1036,6 +1151,12 @@ function useRealtimeMockup(options = {}) {
|
|
|
1036
1151
|
const rerender = (0, import_react.useCallback)((mockupIds) => {
|
|
1037
1152
|
return serviceRef.current?.rerender(mockupIds) ?? false;
|
|
1038
1153
|
}, []);
|
|
1154
|
+
const isFrameSuperseded = (0, import_react.useCallback)((url) => {
|
|
1155
|
+
return serviceRef.current?.isFrameSuperseded(url) ?? false;
|
|
1156
|
+
}, []);
|
|
1157
|
+
const ackFrame = (0, import_react.useCallback)((mockupId, seq) => {
|
|
1158
|
+
return serviceRef.current?.ackFrame(mockupId, seq) ?? false;
|
|
1159
|
+
}, []);
|
|
1039
1160
|
const getLastSentVersion = (0, import_react.useCallback)(() => {
|
|
1040
1161
|
return serviceRef.current?.getLastSentVersion() ?? 0;
|
|
1041
1162
|
}, []);
|
|
@@ -1059,7 +1180,9 @@ function useRealtimeMockup(options = {}) {
|
|
|
1059
1180
|
hasPendingBlobs,
|
|
1060
1181
|
getLastSentVersion,
|
|
1061
1182
|
getLatestSentVersions,
|
|
1062
|
-
rerender
|
|
1183
|
+
rerender,
|
|
1184
|
+
isFrameSuperseded,
|
|
1185
|
+
ackFrame
|
|
1063
1186
|
};
|
|
1064
1187
|
}
|
|
1065
1188
|
|
package/dist/react.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { M as MockupResult, R as RealtimeRenderError, W as WebSocketConfig, P as PlacementSettings, F as FrameworkAdapter, b as ComponentProps, d as ComponentState, e as ComponentContext, f as ComponentLifecycleHooks, E as EventHandler, c as ComponentDescriptor, g as FrameworkUtilities } from './websocket-
|
|
1
|
+
import { M as MockupResult, R as RealtimeRenderError, j as RealtimeMockupCallbacks, W as WebSocketConfig, P as PlacementSettings, w as RealtimeAcksState, F as FrameworkAdapter, b as ComponentProps, d as ComponentState, e as ComponentContext, f as ComponentLifecycleHooks, E as EventHandler, c as ComponentDescriptor, g as FrameworkUtilities } from './websocket-CvN0UU2j.cjs';
|
|
2
2
|
import { CSSProperties, ReactNode } from 'react';
|
|
3
3
|
|
|
4
4
|
interface UseRealtimeMockupOptions {
|
|
@@ -31,6 +31,8 @@ interface UseRealtimeMockupOptions {
|
|
|
31
31
|
* stale mockup) instead of only logging it.
|
|
32
32
|
*/
|
|
33
33
|
onError?: (error: string, detail: RealtimeRenderError) => void;
|
|
34
|
+
/** Flow-control fault (E_RT_ACK_TIMEOUT / E_RT_ACK_BAD): never a picture refusal; see RealtimeMockupCallbacks. */
|
|
35
|
+
onAckFault?: RealtimeMockupCallbacks['onAckFault'];
|
|
34
36
|
}
|
|
35
37
|
declare function useRealtimeMockup(options?: UseRealtimeMockupOptions): {
|
|
36
38
|
connect: () => void;
|
|
@@ -56,6 +58,9 @@ declare function useRealtimeMockup(options?: UseRealtimeMockupOptions): {
|
|
|
56
58
|
getLastSentVersion: () => number;
|
|
57
59
|
getLatestSentVersions: () => Record<string, number>;
|
|
58
60
|
rerender: (mockupIds: string[]) => boolean;
|
|
61
|
+
isFrameSuperseded: (url: string) => boolean;
|
|
62
|
+
ackFrame: (mockupId: string, seq: number) => boolean;
|
|
63
|
+
acks: RealtimeAcksState | null;
|
|
59
64
|
isConnected: boolean;
|
|
60
65
|
sessionId: string | null;
|
|
61
66
|
box: string | null;
|
package/dist/react.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { M as MockupResult, R as RealtimeRenderError, W as WebSocketConfig, P as PlacementSettings, F as FrameworkAdapter, b as ComponentProps, d as ComponentState, e as ComponentContext, f as ComponentLifecycleHooks, E as EventHandler, c as ComponentDescriptor, g as FrameworkUtilities } from './websocket-
|
|
1
|
+
import { M as MockupResult, R as RealtimeRenderError, j as RealtimeMockupCallbacks, W as WebSocketConfig, P as PlacementSettings, w as RealtimeAcksState, F as FrameworkAdapter, b as ComponentProps, d as ComponentState, e as ComponentContext, f as ComponentLifecycleHooks, E as EventHandler, c as ComponentDescriptor, g as FrameworkUtilities } from './websocket-CvN0UU2j.js';
|
|
2
2
|
import { CSSProperties, ReactNode } from 'react';
|
|
3
3
|
|
|
4
4
|
interface UseRealtimeMockupOptions {
|
|
@@ -31,6 +31,8 @@ interface UseRealtimeMockupOptions {
|
|
|
31
31
|
* stale mockup) instead of only logging it.
|
|
32
32
|
*/
|
|
33
33
|
onError?: (error: string, detail: RealtimeRenderError) => void;
|
|
34
|
+
/** Flow-control fault (E_RT_ACK_TIMEOUT / E_RT_ACK_BAD): never a picture refusal; see RealtimeMockupCallbacks. */
|
|
35
|
+
onAckFault?: RealtimeMockupCallbacks['onAckFault'];
|
|
34
36
|
}
|
|
35
37
|
declare function useRealtimeMockup(options?: UseRealtimeMockupOptions): {
|
|
36
38
|
connect: () => void;
|
|
@@ -56,6 +58,9 @@ declare function useRealtimeMockup(options?: UseRealtimeMockupOptions): {
|
|
|
56
58
|
getLastSentVersion: () => number;
|
|
57
59
|
getLatestSentVersions: () => Record<string, number>;
|
|
58
60
|
rerender: (mockupIds: string[]) => boolean;
|
|
61
|
+
isFrameSuperseded: (url: string) => boolean;
|
|
62
|
+
ackFrame: (mockupId: string, seq: number) => boolean;
|
|
63
|
+
acks: RealtimeAcksState | null;
|
|
59
64
|
isConnected: boolean;
|
|
60
65
|
sessionId: string | null;
|
|
61
66
|
box: string | null;
|
package/dist/react.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
RealtimeMockupService
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-IW7DXXGY.js";
|
|
4
4
|
|
|
5
5
|
// src/realtime/react.ts
|
|
6
6
|
import { useCallback, useEffect, useRef, useState } from "react";
|
|
@@ -8,9 +8,11 @@ var DEFAULT_REALTIME_WS_URL = "wss://cdn.snowcone.app/realtime";
|
|
|
8
8
|
function useRealtimeMockup(options = {}) {
|
|
9
9
|
const wsUrl = options.wsUrl ?? (options.getToken ? DEFAULT_REALTIME_WS_URL : void 0);
|
|
10
10
|
const serviceRef = useRef(null);
|
|
11
|
+
const stateFrameScheduledRef = useRef(false);
|
|
11
12
|
const getTokenRef = useRef(options.getToken);
|
|
12
13
|
getTokenRef.current = options.getToken;
|
|
13
14
|
const [state, setState] = useState({
|
|
15
|
+
acks: null,
|
|
14
16
|
isConnected: false,
|
|
15
17
|
sessionId: null,
|
|
16
18
|
box: null,
|
|
@@ -44,7 +46,15 @@ function useRealtimeMockup(options = {}) {
|
|
|
44
46
|
options.onBlobSent?.(placement);
|
|
45
47
|
},
|
|
46
48
|
onMockupRendered: (result) => {
|
|
47
|
-
|
|
49
|
+
if (service.isAcking() && !stateFrameScheduledRef.current) {
|
|
50
|
+
stateFrameScheduledRef.current = true;
|
|
51
|
+
const apply = () => {
|
|
52
|
+
stateFrameScheduledRef.current = false;
|
|
53
|
+
setState(service.getState());
|
|
54
|
+
};
|
|
55
|
+
if (typeof requestAnimationFrame === "function") requestAnimationFrame(apply);
|
|
56
|
+
else setTimeout(apply, 16);
|
|
57
|
+
}
|
|
48
58
|
options.onMockupRendered?.(result);
|
|
49
59
|
},
|
|
50
60
|
onAllMockupsRendered: (results) => {
|
|
@@ -53,6 +63,10 @@ function useRealtimeMockup(options = {}) {
|
|
|
53
63
|
setState(newState);
|
|
54
64
|
options.onAllMockupsRendered?.(results);
|
|
55
65
|
},
|
|
66
|
+
onAckFault: (fault) => {
|
|
67
|
+
setState(service.getState());
|
|
68
|
+
options.onAckFault?.(fault);
|
|
69
|
+
},
|
|
56
70
|
onError: (error, detail) => {
|
|
57
71
|
setState(service.getState());
|
|
58
72
|
options.onError?.(error, detail);
|
|
@@ -123,6 +137,12 @@ function useRealtimeMockup(options = {}) {
|
|
|
123
137
|
const rerender = useCallback((mockupIds) => {
|
|
124
138
|
return serviceRef.current?.rerender(mockupIds) ?? false;
|
|
125
139
|
}, []);
|
|
140
|
+
const isFrameSuperseded = useCallback((url) => {
|
|
141
|
+
return serviceRef.current?.isFrameSuperseded(url) ?? false;
|
|
142
|
+
}, []);
|
|
143
|
+
const ackFrame = useCallback((mockupId, seq) => {
|
|
144
|
+
return serviceRef.current?.ackFrame(mockupId, seq) ?? false;
|
|
145
|
+
}, []);
|
|
126
146
|
const getLastSentVersion = useCallback(() => {
|
|
127
147
|
return serviceRef.current?.getLastSentVersion() ?? 0;
|
|
128
148
|
}, []);
|
|
@@ -146,7 +166,9 @@ function useRealtimeMockup(options = {}) {
|
|
|
146
166
|
hasPendingBlobs,
|
|
147
167
|
getLastSentVersion,
|
|
148
168
|
getLatestSentVersions,
|
|
149
|
-
rerender
|
|
169
|
+
rerender,
|
|
170
|
+
isFrameSuperseded,
|
|
171
|
+
ackFrame
|
|
150
172
|
};
|
|
151
173
|
}
|
|
152
174
|
|