@depict-ai/portal-components 2.7.5 → 2.7.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,997 @@
1
+ import {
2
+ ImageContainer,
3
+ ImagePlaceholder,
4
+ media_query_to_accessor,
5
+ ModernDisplayWithPageUrl,
6
+ SDKRenderingInfo,
7
+ ShopifyContainedImage,
8
+ SlidableItems,
9
+ TextPlaceholder,
10
+ useProductCardIndex,
11
+ useProductCardIsVisible,
12
+ useSlidableInformation,
13
+ useVisibilityState,
14
+ } from "@depict-ai/ui/latest";
15
+ import { catchify, dlog, dwarn } from "@depict-ai/utilishared/latest";
16
+ import {
17
+ type Accessor,
18
+ children,
19
+ createContext,
20
+ createEffect,
21
+ createMemo,
22
+ createRenderEffect,
23
+ createResource,
24
+ createSignal,
25
+ For,
26
+ type JSX,
27
+ on,
28
+ onCleanup,
29
+ type Resource,
30
+ type Setter,
31
+ Show,
32
+ type Signal,
33
+ Suspense,
34
+ untrack,
35
+ useContext,
36
+ } from "solid-js";
37
+ import { classList, createComponent } from "solid-js/web";
38
+ // You can import from the solid-js library here and leverage its reactivity to create an interactive UI.
39
+ // Also, Depict packages can be imported (you must import /latest from those).
40
+
41
+ type TextOptions = {
42
+ /** Enabled */
43
+ enabled: boolean;
44
+ /** Bold */
45
+ bold: boolean;
46
+ /** Italic */
47
+ italic: boolean;
48
+ /** Font Size Rem */
49
+ font_size_rem: number;
50
+ /** Color */
51
+ color: string;
52
+ /** Bg Color */
53
+ bg_color?: string;
54
+ };
55
+
56
+ export type ProductCardSchema = {
57
+ /**
58
+ * Image Radius
59
+ * @enum {string}
60
+ */
61
+ image_radius: "none" | "sm" | "md" | "lg";
62
+ /**
63
+ * Alignment
64
+ * @enum {string}
65
+ */
66
+ alignment: "left" | "center" | "right";
67
+ title: TextOptions;
68
+ price: TextOptions;
69
+ original_price: TextOptions;
70
+ smart_labels: TextOptions;
71
+ /** Color Options */
72
+ color_options: boolean;
73
+ /** Sizes */
74
+ sizes: boolean;
75
+ /** Use Hover Image */
76
+ use_hover_image: boolean;
77
+ /** Image Carousel */
78
+ image_carousel: boolean;
79
+ image_aspect_ratio: number;
80
+ };
81
+
82
+ const sizeOrder = [
83
+ "XXS",
84
+ "XS",
85
+ "XS/S",
86
+ "S",
87
+ "S/M",
88
+ "M",
89
+ "M/L",
90
+ "L",
91
+ "L/XL",
92
+ "XL",
93
+ "XL/XXL",
94
+ "XXL",
95
+ "One Size",
96
+ "Onesize",
97
+ ];
98
+ const ContainsColorSwatchesContext = /*@__PURE__*/ createContext<Signal<boolean>>();
99
+ let colorCanvasContext: CanvasRenderingContext2D | undefined | null;
100
+
101
+ // Remove weird spaces around swatches
102
+
103
+ /**
104
+ * ProductCard built according to this excerpt of our SDK docs https://docs.depict.ai/js-ui-guide/setup/product-card
105
+ */
106
+ export function DefaultSolidProductCard(
107
+ display: Accessor<null | ModernDisplayWithPageUrl<YourDisplay>>,
108
+ info?: SDKRenderingInfo & {
109
+ // depictCardsDataset is the dataset of the #depict-cards HTML element. It is empty in the development environment.
110
+ depictCardsDataset?: Record<string, string>;
111
+ // formatPrice takes a price as number (`price` is NOT in cents but the actual price, as returned from Depict) and returns a formatted string. It will use the same currency formatting that the shopify store is configured to use.
112
+ // In development (product card editor), a fallback formatting will be used.
113
+ formatPrice: <T extends number | undefined>(price: T) => T extends undefined ? undefined : string;
114
+ },
115
+ configuredOptions_: Accessor<ProductCardSchema> = () => ({
116
+ image_radius: "md",
117
+ alignment: "left",
118
+ sizes: true,
119
+ smart_labels: {
120
+ font_size_rem: 0.5,
121
+ enabled: true,
122
+ bold: false,
123
+ italic: false,
124
+ color: "red",
125
+ bg_color: "yellow",
126
+ },
127
+ title: {
128
+ font_size_rem: 1.6,
129
+ enabled: true,
130
+ bold: false,
131
+ italic: false,
132
+ color: "black",
133
+ },
134
+ price: {
135
+ font_size_rem: 1.5,
136
+ enabled: true,
137
+ bold: false,
138
+ italic: false,
139
+ color: "black",
140
+ },
141
+ original_price: {
142
+ font_size_rem: 0.9,
143
+ enabled: true,
144
+ bold: false,
145
+ italic: false,
146
+ color: "black",
147
+ },
148
+ use_hover_image: true,
149
+ image_carousel: true,
150
+ color_options: true,
151
+ image_aspect_ratio: 1,
152
+ })
153
+ ) {
154
+ const variantDisplays = createMemo(() => display()?.variant_displays);
155
+ const defaultVariantIndex = createMemo(() => display()?.variant_index);
156
+ const [showVariantIndex, setShowVariantIndex] = createSignal<number | undefined>(untrack(defaultVariantIndex));
157
+ const [cardIsHovered, setCardIsHovered] = createSignal(false);
158
+ const variantToShow = createMemo(() => variantDisplays()?.[showVariantIndex() as number]);
159
+ const noHoverSupport_ = media_query_to_accessor("(hover: none)");
160
+ const [salePrice] = createResource(variantToShow, v => v?.sale_price);
161
+ const [originalPrice] = createResource(variantToShow, v => v?.original_price);
162
+ const onSale = createMemo(() => <Suspense>{originalPrice() !== salePrice()}</Suspense>);
163
+ const aspectRatio_ = createMemo(() => configuredOptions_().image_aspect_ratio);
164
+ const sizesInStock_ = createMemo(
165
+ () =>
166
+ new Map(
167
+ variantDisplays()
168
+ ?.map(d => [d.size_name, d.in_stock] as const)
169
+ .filter(([name]) => name) as [string, boolean][]
170
+ )
171
+ );
172
+ const titleOptions = createMemo(() => configuredOptions_().title);
173
+ const colorMap = createMemo(
174
+ () =>
175
+ new Map(
176
+ variantDisplays()
177
+ ?.map(
178
+ (variant, index) =>
179
+ [
180
+ variant.color_name,
181
+ {
182
+ hexColor_: variant.color_name,
183
+ pageUrl_: variant.page_url,
184
+ variantIndex_: index,
185
+ },
186
+ ] as const
187
+ )
188
+ .filter(([colorName]) => colorName) // in case color_name is null
189
+ )
190
+ );
191
+ const swatchContainerHeight = createMemo(() => {
192
+ // To avoid the product cards switching around as one hovers and price switches to the swatches, we have to make the swatches container have the same height as the price one
193
+ let considerSize: number[] = [];
194
+ const { original_price, price } = configuredOptions_();
195
+ const isOnSale = (onSale as any)?.()?.(); // Hack for getting if we're on sale without triggering <Suspense> above us
196
+ if (price.enabled) {
197
+ considerSize.push(price.font_size_rem);
198
+ }
199
+ if (original_price.enabled && isOnSale) {
200
+ considerSize.push(original_price.font_size_rem);
201
+ }
202
+ if (!considerSize.length) return;
203
+ return Math.max(...considerSize);
204
+ });
205
+
206
+ const LinkWrapped = (props: { children: JSX.Element; class?: string; ref?: (el: HTMLAnchorElement) => void }) => (
207
+ <a
208
+ class={props.class}
209
+ href={variantToShow()?.page_url || "#"}
210
+ // Work around https://github.com/solidjs/solid/issues/2137
211
+ ref={el => props?.ref?.(el)}
212
+ onClick={catchify(e => {
213
+ const { target } = e;
214
+ const navbuttonSelector = ".d-navbutton";
215
+ if (target.matches(navbuttonSelector) || target.closest(navbuttonSelector)) {
216
+ // Don't navigate if optional slider button that can be shown using css was clicked
217
+ e.preventDefault();
218
+ }
219
+ })}
220
+ >
221
+ {props.children}
222
+ </a>
223
+ );
224
+ const Title = (props: { ref_?: (el: HTMLDivElement) => void }) => (
225
+ <div
226
+ class="d-title line-clamp"
227
+ title={variantToShow()?.title}
228
+ ref={el => {
229
+ props.ref_?.(el);
230
+ setStyleForTextOptions(el, titleOptions);
231
+ }}
232
+ >
233
+ {variantToShow()?.title ?? (
234
+ <>
235
+ <TextPlaceholder height="1em" width="20ch" />
236
+ <TextPlaceholder height="1em" width="20ch" />
237
+ </>
238
+ )}
239
+ </div>
240
+ );
241
+ const mainStyle = () => {
242
+ const { alignment } = configuredOptions_();
243
+ const flexAlignment = alignment === "center" ? alignment : "flex-" + alignment;
244
+ return { "--flex-alignment": flexAlignment, "--alignment": alignment };
245
+ };
246
+
247
+ createEffect(() => dlog("Got passed options", JSON.parse(JSON.stringify(configuredOptions_()))));
248
+ createEffect(() => dlog("Got passed display", JSON.parse(JSON.stringify(display()))));
249
+
250
+ createEffect(() => noHoverSupport_() && setCardIsHovered(false));
251
+
252
+ return (
253
+ <ContainsColorSwatchesProvider>
254
+ <div
255
+ class={`d-product-card`}
256
+ style={mainStyle()}
257
+ onMouseEnter={catchify(() => !noHoverSupport_() && setCardIsHovered(true))}
258
+ onMouseLeave={catchify(() => !noHoverSupport_() && setCardIsHovered(false))}
259
+ >
260
+ <LinkWrapped class="upper">
261
+ <ImagesAndVideos
262
+ image_urls_={() => variantToShow()?.image_urls}
263
+ video_={() => variantToShow()?.videos?.[0]}
264
+ configuredOptions_={configuredOptions_}
265
+ cardIsHovered_={() => showVariantIndex() === display()?.variant_index && cardIsHovered()}
266
+ aspectRatio_={aspectRatio_}
267
+ />
268
+ </LinkWrapped>
269
+ <Show
270
+ when={
271
+ titleOptions().enabled ||
272
+ configuredOptions_().price.enabled ||
273
+ configuredOptions_().sizes ||
274
+ configuredOptions_().color_options
275
+ }
276
+ >
277
+ {(() => {
278
+ // We want the whole product card to be a link, except for the color swatches
279
+ const [containsColorSwatches] = useContainsColorSwatches();
280
+ const LinkWrappedIfHaveSwatches = (props: { children: JSX.Element }) => {
281
+ const resolved = children(() => props.children);
282
+ return (
283
+ <Show when={containsColorSwatches()} fallback={resolved()}>
284
+ <LinkWrapped>{resolved()}</LinkWrapped>
285
+ </Show>
286
+ );
287
+ };
288
+
289
+ return (
290
+ <InComponentOrDiv component_={!containsColorSwatches() && LinkWrapped} class_="text-container">
291
+ <Show
292
+ when={titleOptions().enabled}
293
+ fallback={
294
+ <Show when={configuredOptions_().sizes}>
295
+ <LinkWrappedIfHaveSwatches>
296
+ <Sizes sizesInStock_={sizesInStock_} fontSizeRem_={() => titleOptions().font_size_rem} />
297
+ </LinkWrappedIfHaveSwatches>
298
+ </Show>
299
+ }
300
+ >
301
+ <Show
302
+ when={configuredOptions_().sizes && sizesInStock_().size > 1}
303
+ fallback={
304
+ <LinkWrappedIfHaveSwatches>
305
+ <Title />
306
+ </LinkWrappedIfHaveSwatches>
307
+ }
308
+ >
309
+ <AnimatedRowSwitch
310
+ DefaultComponent_={Title}
311
+ HoveredComponent_={({ ref_ }) => (
312
+ <Sizes
313
+ sizesInStock_={sizesInStock_}
314
+ fontSizeRem_={() => titleOptions().font_size_rem}
315
+ ref_={ref_}
316
+ />
317
+ )}
318
+ cardIsHovered_={cardIsHovered}
319
+ containerComponent_={() => containsColorSwatches() && LinkWrapped}
320
+ />
321
+ </Show>
322
+ </Show>
323
+ <Show
324
+ when={configuredOptions_().price.enabled}
325
+ fallback={
326
+ configuredOptions_().color_options && (
327
+ <ColorSwatches
328
+ colorMap_={colorMap}
329
+ showVariantIndex_={showVariantIndex}
330
+ setShowVariantIndex_={setShowVariantIndex}
331
+ colorsAtIndex_={() => variantDisplays()?.map(variant => variant.color_name)}
332
+ wantedContainerHeightRem_={swatchContainerHeight}
333
+ defaultVariantIndex_={defaultVariantIndex}
334
+ />
335
+ )
336
+ }
337
+ >
338
+ <Show
339
+ when={configuredOptions_().color_options && colorMap().size > 1}
340
+ fallback={
341
+ <Prices
342
+ variantToShow_={variantToShow}
343
+ formatPrice_={info?.formatPrice}
344
+ configuredOptions_={configuredOptions_}
345
+ salePrice_={salePrice}
346
+ originalPrice_={originalPrice}
347
+ wrapperComponent_={() => containsColorSwatches() && LinkWrapped}
348
+ />
349
+ }
350
+ >
351
+ <AnimatedRowSwitch
352
+ containerComponent_={() => !containsColorSwatches() && LinkWrapped}
353
+ DefaultComponent_={({ ref_ }) => (
354
+ <Prices
355
+ variantToShow_={variantToShow}
356
+ formatPrice_={info?.formatPrice}
357
+ salePrice_={salePrice}
358
+ originalPrice_={originalPrice}
359
+ configuredOptions_={configuredOptions_}
360
+ wrapperComponent_={() => containsColorSwatches() && LinkWrapped}
361
+ ref_={ref_}
362
+ />
363
+ )}
364
+ HoveredComponent_={({ ref_ }) => (
365
+ <ColorSwatches
366
+ colorMap_={colorMap}
367
+ showVariantIndex_={showVariantIndex}
368
+ setShowVariantIndex_={setShowVariantIndex}
369
+ colorsAtIndex_={() => variantDisplays()?.map(variant => variant.color_name)}
370
+ ref_={ref_}
371
+ wantedContainerHeightRem_={swatchContainerHeight}
372
+ defaultVariantIndex_={defaultVariantIndex}
373
+ />
374
+ )}
375
+ cardIsHovered_={cardIsHovered}
376
+ />
377
+ </Show>
378
+ </Show>
379
+ </InComponentOrDiv>
380
+ );
381
+ })()}
382
+ </Show>
383
+ </div>
384
+ </ContainsColorSwatchesProvider>
385
+ );
386
+ }
387
+
388
+ /**
389
+ * Transitions between DefaultComponent_ and HoveredComponent_ when cardIsHovered_ changes in both height and opacity.
390
+ */
391
+ function AnimatedRowSwitch({
392
+ DefaultComponent_,
393
+ HoveredComponent_,
394
+ cardIsHovered_,
395
+ containerComponent_,
396
+ }: {
397
+ DefaultComponent_: (props: { ref_: (el: HTMLElement) => void }) => JSX.Element;
398
+ HoveredComponent_: (props: { ref_: (el: HTMLElement) => void }) => JSX.Element;
399
+ cardIsHovered_: Accessor<boolean>;
400
+ containerComponent_: Accessor<
401
+ false | ((props: { ref?: (el: HTMLElement) => void; class: string; children: JSX.Element }) => JSX.Element)
402
+ >;
403
+ }) {
404
+ let defaultElement: HTMLElement;
405
+ let hoveredElement: HTMLElement;
406
+ let containerElement: HTMLElement;
407
+ let defaultElementAnimation: Animation | undefined;
408
+ let hoveredElementAnimation: Animation | undefined;
409
+ let containerAnimation: Animation | undefined;
410
+ const fadeInKeyframes = [
411
+ { opacity: 0, pointerEvents: "none", cursor: "default" },
412
+ { opacity: 1, pointerEvents: "auto", cursor: "unset" },
413
+ ];
414
+ const fadeOutKeyframes = [...fadeInKeyframes].reverse();
415
+
416
+ createEffect(firstRun => {
417
+ const isHovered = cardIsHovered_();
418
+ if (!hoveredElement || !defaultElement) return; // Got no sizes probably, can't switch to anything
419
+
420
+ const hoveredStyle = hoveredElement.style;
421
+ const defaultStyle = defaultElement.style;
422
+ const containerStyle = containerElement.style;
423
+ const duration = 200;
424
+ const easing = "ease-in-out";
425
+
426
+ hoveredStyle.position = "absolute";
427
+
428
+ if (firstRun) {
429
+ Object.assign(hoveredStyle, fadeInKeyframes[0]);
430
+ return;
431
+ }
432
+
433
+ defaultStyle.position = "absolute";
434
+
435
+ // These animations we can let live forever, since opacity always goes between 0 and 1
436
+ hoveredElementAnimation ||= hoveredElement.animate(fadeInKeyframes, {
437
+ duration,
438
+ fill: "both",
439
+ easing,
440
+ });
441
+ defaultElementAnimation ||= defaultElement.animate(fadeOutKeyframes, {
442
+ duration,
443
+ fill: "both",
444
+ easing,
445
+ });
446
+
447
+ if (!containerAnimation) {
448
+ const containerKeyframes = [
449
+ { height: defaultElement.getBoundingClientRect().height + "px" },
450
+ { height: hoveredElement.getBoundingClientRect().height + "px" },
451
+ ];
452
+ containerAnimation = containerElement.animate(containerKeyframes, { duration, easing });
453
+ containerAnimation.finished.then(() => {
454
+ containerAnimation?.cancel();
455
+ containerAnimation = undefined;
456
+ // Animation can survive direction change so need to get current hovered state when it finishes
457
+ const hoveredNow = untrack(cardIsHovered_);
458
+ containerStyle.height = "";
459
+ if (hoveredNow) {
460
+ hoveredStyle.position = "";
461
+ } else {
462
+ defaultStyle.position = "";
463
+ }
464
+ });
465
+ if (!isHovered) {
466
+ // When starting the animation in reverse we need to set the current time to the end of the animation
467
+ containerAnimation.currentTime = containerAnimation.effect!.getComputedTiming().endTime!;
468
+ }
469
+ // Remove this animation once it has finished and re-create it later since the size of the elements containing texts might change, i.e. when the window is resized of zoom level adjusted
470
+ }
471
+
472
+ const animationDirection = isHovered ? 1 : -1;
473
+ defaultElementAnimation.updatePlaybackRate(animationDirection);
474
+ defaultElementAnimation.play();
475
+ hoveredElementAnimation!.updatePlaybackRate(animationDirection);
476
+ hoveredElementAnimation.play();
477
+ containerAnimation!.updatePlaybackRate(animationDirection);
478
+ }, true);
479
+
480
+ return (
481
+ <InComponentOrDiv
482
+ component_={containerComponent_()}
483
+ class_="animated-row-switch"
484
+ ref_={(el: HTMLElement) => (containerElement = el)}
485
+ >
486
+ <DefaultComponent_ ref_={el => (defaultElement = el)} />
487
+ <HoveredComponent_ ref_={el => (hoveredElement = el)} />
488
+ </InComponentOrDiv>
489
+ );
490
+ }
491
+
492
+ function ColorSwatches({
493
+ colorMap_,
494
+ setShowVariantIndex_,
495
+ showVariantIndex_,
496
+ colorsAtIndex_,
497
+ wantedContainerHeightRem_,
498
+ defaultVariantIndex_,
499
+ ref_,
500
+ }: {
501
+ colorMap_: Accessor<Map<string, { hexColor_: string; pageUrl_: string; variantIndex_: number }>>;
502
+ setShowVariantIndex_: Setter<number | undefined>;
503
+ showVariantIndex_: Accessor<number | undefined>;
504
+ colorsAtIndex_: Accessor<string[] | undefined>;
505
+ wantedContainerHeightRem_: Accessor<number | undefined>;
506
+ defaultVariantIndex_: Accessor<number | undefined>;
507
+ ref_?: (el: HTMLDivElement) => void;
508
+ }) {
509
+ let unHoverDebouncedTimeout: ReturnType<typeof setTimeout> | undefined;
510
+ const entriesToShow = () => [...colorMap_().entries()].slice(0, 12);
511
+ const [, setContainsColorSwatches] = useContainsColorSwatches();
512
+
513
+ return (
514
+ <Show when={entriesToShow().length > 1}>
515
+ {(() => {
516
+ setContainsColorSwatches(true);
517
+ onCleanup(() => setContainsColorSwatches(false));
518
+
519
+ return (
520
+ <div
521
+ class="d-swatches"
522
+ ref={el => {
523
+ ref_?.(el);
524
+ // Do like this so we don't override other styles set by AnimateRowSwitch
525
+ createEffect(() =>
526
+ setPropertyIfExists(
527
+ el.style,
528
+ "--swatch-container-height",
529
+ wantedContainerHeightRem_() && wantedContainerHeightRem_() + "rem"
530
+ )
531
+ );
532
+ }}
533
+ >
534
+ <For each={entriesToShow()}>
535
+ {([colorName, { pageUrl_, hexColor_, variantIndex_ }]) => {
536
+ const thisColorIsDefaultColor = createMemo(
537
+ () => colorsAtIndex_()?.[defaultVariantIndex_() as number] === colorName
538
+ );
539
+ // Since we don't have actual colors right now and rely on color names working as css colors
540
+ // We need a default fallback for it being usable
541
+ const [invalidColor, setInvalidColor] = createSignal(false);
542
+
543
+ return (
544
+ <a
545
+ onPointerEnter={catchify(e => {
546
+ clearTimeout(unHoverDebouncedTimeout);
547
+ setShowVariantIndex_(thisColorIsDefaultColor() ? defaultVariantIndex_() : variantIndex_);
548
+ })}
549
+ onPointerLeave={catchify(e => {
550
+ clearTimeout(unHoverDebouncedTimeout);
551
+ unHoverDebouncedTimeout = setTimeout(
552
+ catchify(() => setShowVariantIndex_(defaultVariantIndex_())),
553
+ 500
554
+ );
555
+ })}
556
+ href={pageUrl_}
557
+ class="d-swatch"
558
+ ref={element =>
559
+ requestAnimationFrame(
560
+ // After one frame we're usually in the DOM, if we're not boxShadow is ""
561
+ // If it's none, the color was invalid - so just show this swatch as a white swatch which is the prettiest
562
+ catchify(() => getComputedStyle(element).boxShadow === "none" && setInvalidColor(true))
563
+ )
564
+ }
565
+ title={colorName}
566
+ // Value first take canvas color because it's more likely to exist for for example Aubergine
567
+ style={`--background:${invalidColor() ? "white" : hexColor_}`}
568
+ classList={{
569
+ selected: colorsAtIndex_()?.[showVariantIndex_()!] === colorName,
570
+ first: thisColorIsDefaultColor(),
571
+ "light-colored": isLightColor(hexColor_) || invalidColor(),
572
+ }}
573
+ />
574
+ );
575
+ }}
576
+ </For>
577
+ <Show when={entriesToShow().length !== colorMap_().size}>
578
+ <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" class="more">
579
+ <path d="M10.8 6c0 .153-.061.299-.169.407s-.255.169-.407.169H6.576v3.648c0 .153-.061.299-.169.407S6.153 10.8 6 10.8s-.299-.061-.407-.169-.169-.255-.169-.407V6.576H1.776c-.153 0-.299-.061-.407-.169S1.2 6.153 1.2 6s.061-.299.169-.407.255-.169.407-.169h3.648V1.776c0-.153.061-.299.169-.407S5.847 1.2 6 1.2s.299.061.407.169.169.255.169.407v3.648h3.648c.153 0 .299.061.407.169s.169.255.169.407z" />
580
+ </svg>
581
+ </Show>
582
+ </div>
583
+ );
584
+ })()}
585
+ </Show>
586
+ );
587
+ }
588
+
589
+ function Sizes({
590
+ sizesInStock_,
591
+ ref_,
592
+ fontSizeRem_,
593
+ }: {
594
+ sizesInStock_: Accessor<Map<string, boolean>>;
595
+ ref_?: (el: HTMLDivElement) => void;
596
+ fontSizeRem_: Accessor<number>;
597
+ }) {
598
+ const keys = () => [...sizesInStock_().keys()];
599
+ const keysToShow = () => keys().slice(0, 7);
600
+ const hidden = () => keys().length - keysToShow().length;
601
+
602
+ return (
603
+ <Show when={keysToShow().length > 1}>
604
+ <div
605
+ class="sizes"
606
+ ref={el => {
607
+ ref_?.(el);
608
+ // Do like this so we don't override other styles set by AnimateRowSwitch
609
+ createEffect(() => el.style.setProperty("--font-size-rem", fontSizeRem_() + "rem"));
610
+ }}
611
+ >
612
+ <For each={sortSizes(keysToShow())}>
613
+ {size => (
614
+ <Show when={sizesInStock_().get(size)} fallback={<s>{size}</s>}>
615
+ <span>{size}</span>
616
+ </Show>
617
+ )}
618
+ </For>
619
+ <Show when={hidden() > 0}>
620
+ <span class="more">+ {hidden()} more</span>
621
+ </Show>
622
+ </div>
623
+ </Show>
624
+ );
625
+ }
626
+
627
+ function setPropertyIfExists(style: CSSStyleDeclaration, property: string, value?: string | false | 0) {
628
+ if (value) {
629
+ style.setProperty(property, value);
630
+ } else {
631
+ style.removeProperty(property);
632
+ }
633
+ }
634
+
635
+ function setStyleForTextOptions({ style }: HTMLElement, options: Accessor<TextOptions>) {
636
+ // Doing this instead of just using style={} because AnimatedRowSwitch needs to be able to set inline styling without it being overridden
637
+ createEffect(() => setPropertyIfExists(style, "--font-size-rem", options().font_size_rem + "rem"));
638
+ createEffect(() => setPropertyIfExists(style, "--font-weight", options().bold && "bold"));
639
+ createEffect(() => setPropertyIfExists(style, "--font-style", options().italic && "italic"));
640
+ createEffect(() => setPropertyIfExists(style, "--color", options().color));
641
+ createEffect(() => setPropertyIfExists(style, "--background", options().bg_color));
642
+ }
643
+
644
+ function ImagesAndVideos({
645
+ image_urls_,
646
+ video_,
647
+ configuredOptions_,
648
+ cardIsHovered_,
649
+ aspectRatio_,
650
+ }: {
651
+ image_urls_: Accessor<undefined | string[]>;
652
+ video_: Accessor<undefined | { preview_image_url: string; video_urls: string[] }>;
653
+ configuredOptions_: Accessor<ProductCardSchema>;
654
+ cardIsHovered_: Accessor<boolean>;
655
+ aspectRatio_: Accessor<number>;
656
+ }) {
657
+ const isAlreadyInSlider = !!useSlidableInformation();
658
+ const containerClasses = () => ["image-video", "border-radius-" + configuredOptions_().image_radius] as const;
659
+ // Don't make cards swipable inside of sliders (PLP slider or recs slider)
660
+ const slidable = createMemo(() => !isAlreadyInSlider && configuredOptions_().image_carousel);
661
+ const hoverImageDisabled = createMemo(() => !configuredOptions_().use_hover_image);
662
+ const video_urls = () => video_()?.video_urls;
663
+
664
+ const Container = (props: { children: JSX.Element }) => {
665
+ const resolved = children(() => props.children);
666
+ return (
667
+ <Show when={slidable()} fallback={<div class={containerClasses().join(" ")}>{resolved()}</div>}>
668
+ <SlidableItems
669
+ arrow_height_={25}
670
+ arrow_width_={12.5}
671
+ disable_fading_={true}
672
+ slider_ref_={slider => {
673
+ const { container, insert_here } = slider;
674
+ slider.stepstoslide = 1; // In case anyone enables the hidden buttons using css
675
+
676
+ createRenderEffect<{ [k: string]: boolean } | undefined>(previous =>
677
+ classList(
678
+ container,
679
+ { products: true, ...Object.fromEntries(containerClasses().map(cls => [cls, true])) },
680
+ previous
681
+ )
682
+ );
683
+
684
+ // Scroll to beginning when changing what variant we're showing
685
+ createEffect(on(image_urls_, () => insert_here.scrollTo({ left: 0, behavior: "auto" }), { defer: true }));
686
+ }}
687
+ >
688
+ {resolved()}
689
+ </SlidableItems>
690
+ </Show>
691
+ );
692
+ };
693
+
694
+ return (
695
+ <Show when={image_urls_()} fallback={<ImagePlaceholder aspectRatio={aspectRatio_()} />}>
696
+ <Container>
697
+ <Show when={video_urls()?.length}>
698
+ <div class="media-item video">
699
+ <ImageContainer aspectRatio={aspectRatio_()}>
700
+ <Video
701
+ video_sources_={video_urls() as [string, ...string[]]}
702
+ poster_={video_()?.preview_image_url || image_urls_()?.[0]}
703
+ />
704
+ </ImageContainer>
705
+ </div>
706
+ </Show>
707
+ <Show when={!video_urls()?.length || slidable()}>
708
+ <For each={slidable() ? image_urls_() : image_urls_()?.slice(0, 1)}>
709
+ {(image_url, index) => (
710
+ <Show when={hoverImageDisabled() || index() !== 1}>
711
+ {/* The image with index 1 will already be shown as hover image if hover is supported, so hide it in the slider
712
+ (We assume people don't discover the slider can be slided on desktop) */}
713
+ <div class="media-item image">
714
+ {/* Hover to see JSDOc for ShopifyContainedImage */}
715
+ <ShopifyContainedImage
716
+ src={image_url}
717
+ aspectRatio={aspectRatio_()}
718
+ imgProps={{ alt: "Product image" }}
719
+ />
720
+ <Show when={!index() && image_urls_()?.[1] && !hoverImageDisabled()}>
721
+ <ShopifyContainedImage
722
+ src={image_urls_()![1]}
723
+ aspectRatio={aspectRatio_()}
724
+ imgProps={{ alt: "Product image" }}
725
+ class={`hover${cardIsHovered_() ? " visible" : ""}`}
726
+ />
727
+ </Show>
728
+ </div>
729
+ </Show>
730
+ )}
731
+ </For>
732
+ </Show>
733
+ </Container>
734
+ </Show>
735
+ );
736
+ }
737
+
738
+ function Video(props: { video_sources_: [string, ...string[]]; poster_?: string }) {
739
+ // Making some assumptions for shopify here rn, change those if wanting to support other browsers too
740
+
741
+ const tabIsVisible = useVisibilityState();
742
+ const hlsSource = createMemo(() => props.video_sources_.find(src => src.endsWith(".m3u8"))); // Prefer HLS when given by backend and browser supported
743
+ // This is because HLS automatically lets the browser choose both a fitting resolution and quality, depending on video dimensions and network conditions
744
+ const nonHLSSources = createMemo(() => {
745
+ const sources = props.video_sources_?.filter(src => !src.endsWith(".m3u8"));
746
+ try {
747
+ sortVideoUrlsByQuality(sources);
748
+ } catch (e) {
749
+ dlog("Sorting by quality failed", e);
750
+ }
751
+ return sources;
752
+ });
753
+ const productCardIndexAccessor = useProductCardIndex();
754
+ const isVisible = useProductCardIsVisible();
755
+ const slidableInformation = useSlidableInformation();
756
+ const hiddenInImageCarousel = createMemo(() => {
757
+ // Pause video when swiping to the next image
758
+ slidableInformation?.intersectionEntries_(); // Re-check when intersecting entries change
759
+ const intersectingsObject = slidableInformation?.slider_.intersecting_items_object;
760
+ // If intersection observers haven't started yet or we aren't in a slider, we count as visible for faster playback
761
+ if (!intersectingsObject || !Object.keys(intersectingsObject).length) return false;
762
+ // Video is always the first card in the slider
763
+ const ratio = intersectingsObject?.[0]?.intersectionRatio;
764
+ return !ratio;
765
+ });
766
+
767
+ return (
768
+ <video
769
+ class="s-responsive-image"
770
+ controls={false}
771
+ playsinline={true}
772
+ poster={props.poster_}
773
+ loop={true}
774
+ muted={true}
775
+ crossOrigin="anonymous"
776
+ ref={element => {
777
+ element.disablePictureInPicture = true;
778
+ createEffect(() => {
779
+ if (isVisible() && tabIsVisible() && !hiddenInImageCarousel()) {
780
+ element.play().catch(e => dwarn("Error playing video", e));
781
+ } else {
782
+ element.pause();
783
+ }
784
+ });
785
+ }}
786
+ // Preload videos that are probably above the fold
787
+ {...((productCardIndexAccessor?.() as number) < 8 && { preload: "auto" })}
788
+ >
789
+ <Show when={hlsSource()}>
790
+ <source src={hlsSource()} type="application/x-mpegURL" />
791
+ </Show>
792
+ <For each={nonHLSSources()}>{source => <source src={source} />}</For>
793
+ </video>
794
+ );
795
+ }
796
+
797
+ // ChatGPT written
798
+ function sortVideoUrlsByQuality(urls: string[]): string[] {
799
+ // Function to extract resolution from a URL, assuming format consistency
800
+ function getResolution(url: string): number {
801
+ const match = url.match(/(\d+)p/);
802
+ return match ? parseInt(match[1], 10) : 0;
803
+ }
804
+
805
+ // Sort the URLs based on the resolution extracted
806
+ return urls.sort((a, b) => {
807
+ const resolutionA = getResolution(a);
808
+ const resolutionB = getResolution(b);
809
+
810
+ // For descending order, compare B to A
811
+ return resolutionB - resolutionA;
812
+ });
813
+ }
814
+
815
+ function Prices({
816
+ formatPrice_,
817
+ configuredOptions_,
818
+ salePrice_,
819
+ originalPrice_,
820
+ ref_,
821
+ variantToShow_,
822
+ wrapperComponent_,
823
+ }: {
824
+ variantToShow_: Accessor<(YourVariantDisplay & { page_url: string }) | undefined>;
825
+ formatPrice_: undefined | (<T extends number | undefined>(price: T) => T extends undefined ? undefined : string);
826
+ configuredOptions_: Accessor<ProductCardSchema>;
827
+ salePrice_: Resource<number | undefined>;
828
+ originalPrice_: Resource<number | undefined>;
829
+ wrapperComponent_: Accessor<
830
+ | false
831
+ | ((props: { class: string; children: JSX.Element; ref?: (el: HTMLElement) => void | undefined }) => JSX.Element)
832
+ >;
833
+ ref_?: (el: HTMLElement) => void;
834
+ }) {
835
+ // Depict is fetching the prices from Shopify's storefront API on the frontend. This is because getting all prices in all currencies from Shopify be too computationally intensive (~1 million prices for some customers that can change at any time depending on exchange rate).
836
+ // This is why the prices are wrapped in a Promise (we want to render product cards without having to wait for the price request).
837
+ const priceOptions = () => configuredOptions_().price;
838
+ const originalPriceOptions = () => configuredOptions_().original_price;
839
+
840
+ return (
841
+ <Show when={priceOptions().enabled}>
842
+ <InComponentOrDiv component_={wrapperComponent_()} class_="price-container" ref_={ref_}>
843
+ <span class="price" ref={el => setStyleForTextOptions(el, priceOptions)}>
844
+ <Show
845
+ when={variantToShow_()}
846
+ fallback={
847
+ // When depict API request not completed (display is null), always show a placeholder for the price
848
+ <TextPlaceholder height="1em" width="5ch" />
849
+ }
850
+ >
851
+ {/* If we are not rendering a pure placeholder card, show a placeholder for the price, while it's loading - and then show the price (or nothing if it failed to load) */}
852
+ <Suspense fallback={<TextPlaceholder height="1em" width="5ch" />}>{formatPrice_?.(salePrice_())}</Suspense>
853
+ </Show>
854
+ </span>
855
+ {/* Suspense renders its fallback until all resources read within it have resolved.
856
+ Depict renders the `ProductCard` component itself inside a <Suspense>.
857
+ Therefore, we have to wrap our resource accesses here (and above) in <Suspense>, because we want to show the rest of the product card already while the prices are loading */}
858
+ <Suspense>
859
+ {/* Only show original price if it exists and deviates from the salePrice */}
860
+ <Show when={originalPrice_() !== salePrice_() && originalPriceOptions().enabled}>
861
+ {" "}
862
+ <span class="original-price" ref={el => setStyleForTextOptions(el, originalPriceOptions)}>
863
+ {formatPrice_?.(originalPrice_())}
864
+ </span>
865
+ </Show>
866
+ </Suspense>
867
+ </InComponentOrDiv>
868
+ </Show>
869
+ );
870
+ }
871
+
872
+ function isLightColor(anyCssColor: string) {
873
+ // Source: https://stackoverflow.com/a/47355187
874
+ colorCanvasContext ||= document.createElement("canvas").getContext("2d");
875
+ colorCanvasContext!.fillStyle = anyCssColor;
876
+ const asHex = colorCanvasContext!.fillStyle;
877
+
878
+ // Source: https://stackoverflow.com/a/12043228
879
+ const stripped = asHex.substring(1); // strip #
880
+ const rgb = parseInt(stripped, 16); // convert rrggbb to decimal
881
+ const r = (rgb >> 16) & 0xff; // extract red
882
+ const g = (rgb >> 8) & 0xff; // extract green
883
+ const b = (rgb >> 0) & 0xff; // extract blue
884
+
885
+ const luma = 0.2126 * r + 0.7152 * g + 0.0722 * b; // per ITU-R BT.709, apparently between 0 and 255
886
+
887
+ return luma > 200;
888
+ }
889
+
890
+ // Mostly written by chatGPT
891
+ function sortSizes(sizesToSort: string[]): string[] {
892
+ const sizeEntries: {
893
+ size: string;
894
+ numericValue?: number;
895
+ }[] = sizesToSort.map(size => {
896
+ const numericMatch = size.match(/^(\d+)(?:\/\d+)?$/);
897
+ if (numericMatch) {
898
+ // It's a numeric size or a range like "44/46", we sort by the first number.
899
+ return { size, numericValue: parseInt(numericMatch[1], 10) };
900
+ }
901
+ return { size };
902
+ });
903
+
904
+ sizeEntries.sort((a, b) => {
905
+ const indexA = sizeOrder.indexOf(a.size);
906
+ const indexB = sizeOrder.indexOf(b.size);
907
+
908
+ // Both sizes are in the predefined list
909
+ if (indexA !== -1 && indexB !== -1) {
910
+ return indexA - indexB;
911
+ }
912
+ // Handle numeric and mixed sorting
913
+ if (a.numericValue != null && b.numericValue != null) {
914
+ return a.numericValue - b.numericValue;
915
+ }
916
+ if (a.numericValue != null && indexB === -1) {
917
+ return -1; // numeric values come before unknown text
918
+ }
919
+ if (b.numericValue != null && indexA === -1) {
920
+ return 1; // numeric values come before unknown text
921
+ }
922
+ // Fallback if both are unrecognized, sort alphabetically
923
+ return a.size.localeCompare(b.size);
924
+ });
925
+
926
+ return sizeEntries.map(entry => entry.size);
927
+ }
928
+
929
+ function ContainsColorSwatchesProvider(props: { children: JSX.Element }) {
930
+ const containsSignal = createSignal(false);
931
+ return (
932
+ <ContainsColorSwatchesContext.Provider value={containsSignal}>
933
+ {props.children}
934
+ </ContainsColorSwatchesContext.Provider>
935
+ );
936
+ }
937
+
938
+ function useContainsColorSwatches() {
939
+ return useContext(ContainsColorSwatchesContext)!;
940
+ }
941
+
942
+ // Work around https://github.com/solidjs/solid/issues/2136 and random shit I thought was an issue before I found https://github.com/solidjs/solid/issues/2137
943
+ function InComponentOrDiv(props: {
944
+ component_:
945
+ | undefined
946
+ | false
947
+ | ((componentProps: { children: JSX.Element; ref?: (el: HTMLElement) => void; class: string }) => JSX.Element);
948
+ children: JSX.Element;
949
+ class_: string;
950
+ ref_?: (el: HTMLElement) => void;
951
+ }) {
952
+ const resolved = children(() => props.children);
953
+ return createMemo(() => {
954
+ const Component = props.component_;
955
+ if (Component) {
956
+ // Written like this because the JSX transform mutates our props object: https://github.com/ryansolid/dom-expressions/pull/316#issuecomment-2066925544
957
+ return createComponent(Component, {
958
+ get class() {
959
+ return props.class_;
960
+ },
961
+ get ref() {
962
+ return props.ref_;
963
+ },
964
+ children: resolved as unknown as JSX.Element,
965
+ });
966
+ }
967
+ return (
968
+ <div class={props.class_} ref={el => props?.ref_?.(el)}>
969
+ {resolved()}
970
+ </div>
971
+ );
972
+ }) as unknown as JSX.Element;
973
+ }
974
+
975
+ interface YourDisplay {
976
+ variant_index: number;
977
+ variant_displays: YourVariantDisplay[];
978
+ search_result_id: string;
979
+ /** SKUs of the different variants, slated for removal */
980
+ variant_skus: string[];
981
+ /** Product of the different variants, slated for removal */
982
+ variant_product_ids: string[];
983
+ }
984
+
985
+ type YourVariantDisplay = {
986
+ // !!!! Please ask Depict for the type definition to put here, or create them yourself from a sample response with https://app.quicktype.io/ !!!!
987
+ title: string;
988
+ image_urls: string[];
989
+ videos?: { preview_image_url: string; video_urls: string[] }[];
990
+ page_url: string;
991
+ color_name: string;
992
+ size_name: string | null;
993
+ in_stock: boolean;
994
+ } & (
995
+ | { sale_price: Promise<number>; original_price: Promise<number> }
996
+ | { sale_price: Promise<undefined>; original_price: Promise<undefined> }
997
+ );