@depict-ai/portal-components 2.7.4 → 2.7.6

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