basklee-svelte 0.9.9 → 0.9.11

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/README.md CHANGED
@@ -206,7 +206,7 @@ Product details, saved items and the cart.
206
206
 
207
207
  | Component | Name | What it does |
208
208
  | --- | --- | --- |
209
- | **Product details** | `StorefrontProduct` | Loads and displays a published product or a secret-key preview with images, purchase choices, details and reviews. |
209
+ | **Product details** | `StorefrontProduct` | Loads and displays a published product or a secret-key preview with images and videos, purchase choices, details and reviews. |
210
210
  | **Page path** | `BaskleeBreadcrumbs` | Linked path from the storefront home page through parent categories to the current page. |
211
211
  | **Product characteristics** | `ProductSpecificationsDialog` | Every characteristic of the product in a dialog over the page. |
212
212
  | **Product reviews** | `ProductReviews` | Reviews, replies, ratings and the user’s submissions. |
@@ -574,7 +574,9 @@ When a request returns HTTP `401` while the store is signed in, the shared API
574
574
  client clears profile, wallet, authenticated discovery, cart and wishlist counters
575
575
  and account fields of cached products, then reloads Application Load as a guest.
576
576
  Public data and the current selections remain available during that refresh.
577
- The failed request is not repeated and no sign-in dialog opens automatically.
577
+ Every `401` (also a guest's) then opens `/profile?locale=<locale>&redirect=<current page>`,
578
+ which returns to the page after sign-in; on `/profile` and `/logout` the page
579
+ stays. The failed request is not repeated.
578
580
 
579
581
  ## Update an existing project
580
582
 
@@ -646,8 +648,8 @@ Component source lives in `src/lib/components/basklee/`; controllers live in
646
648
  `src/lib/composables/`. `basklee/COMPONENTS.md` describes the component catalog.
647
649
  The store is scoped to one render on the server and the root layout in the
648
650
  browser. It preserves valid selections when Application Load refreshes. HTTP
649
- 401 clears account data and refreshes the guest session without repeating the
650
- failed mutation. API validation errors remain beside the affected form.
651
+ 401 clears account data, refreshes the guest session and opens the sign-in page
652
+ without repeating the failed mutation. API validation errors remain beside the affected form.
651
653
 
652
654
  ---
653
655
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "basklee-svelte",
3
- "version": "0.9.9",
3
+ "version": "0.9.11",
4
4
  "description": "SvelteKit 2 storefront for your Basklee marketplace: setup CLI, server API gateway, typed store and ready-made catalog, cart, checkout and account components in English, Russian and Spanish, plus an Android app build. Powered by Basklee: https://basklee.com",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -269,7 +269,8 @@ client navigation and the selected language.
269
269
 
270
270
  A signed-in request that receives HTTP \`401\` removes private account values and
271
271
  refreshes Application Load as a guest while retaining public data and selections.
272
- The failed request is not repeated and no sign-in dialog opens automatically.
272
+ Every \`401\` then opens the \`/profile\` sign-in page, which returns to the current
273
+ page after sign-in. The failed request is not repeated.
273
274
 
274
275
  ### Session and CSRF cookies
275
276
 
@@ -37,9 +37,9 @@
37
37
  const sections = computed(() => Object.entries(labels.value.navigation));
38
38
 
39
39
  // The basklee-account middleware opens /profile before a guest reaches
40
- // this page. When the session ends while the page is open, the page stays
41
- // and explains that the account content needs sign-in; it never navigates
42
- // on its own, and the header offers Login. A failed Application Load is
40
+ // this page. When the session ends while the page is open, the section
41
+ // explains that the account content needs sign-in while the shared API
42
+ // client opens the sign-in page, which returns here afterwards. A failed Application Load is
43
43
  // not a guest session: it offers Retry instead.
44
44
  </script>
45
45
 
@@ -8,6 +8,20 @@ preview address with `?key=` uses `products_preview`, so anyone with the complet
8
8
  preview address can view it without signing in. The request also runs during server
9
9
  rendering so the product is present in the HTML.
10
10
 
11
+ The media are the photos, then the product's videos (`product.videos`, from the Video
12
+ tab of the panel; a video without a file is left out). A video's thumbnail shows its
13
+ `preview` frame under a round play mark; choosing it plays the video with the browser's
14
+ controls in the main image's place, never by itself. The full-screen viewer shows the
15
+ photos only.
16
+
17
+ Under the reviews, “You may also like” shows the products attached to this product on
18
+ the panel's Relevant Products tab (`related.data`, without the product itself, up to
19
+ eight). Only a product without attached products shows up to eight more products of its
20
+ `main_category` from `products_search`, with a link to the category page; without either
21
+ the row is not shown. The logic is in
22
+ `src/lib/composables/useBaskleeRelatedProducts.svelte.ts` and
23
+ `src/lib/utils/basklee/relatedProducts.ts`.
24
+
11
25
  Source: `src/lib/components/basklee/products/StorefrontProduct.svelte`.
12
26
 
13
27
  ## Inputs
@@ -1,5 +1,5 @@
1
1
  <script lang="ts">
2
- import { routeHref } from '@/lib/basklee/navigation.svelte';
2
+ import { navigateTo, routeHref } from '@/lib/basklee/navigation.svelte';
3
3
  import {
4
4
  computed,
5
5
  nextTick,
@@ -18,6 +18,8 @@
18
18
  } from '@/lib/composables/useBaskleeFeature.svelte';
19
19
  import { useBaskleeProductActions } from '@/lib/composables/useBaskleeProductActions.svelte';
20
20
  import { useBaskleeProductVariants } from '@/lib/composables/useBaskleeProductVariants.svelte';
21
+ import { useBaskleeRelatedProducts } from '@/lib/composables/useBaskleeRelatedProducts.svelte';
22
+ import { relatedProductsLabels } from '@/lib/utils/basklee/relatedProducts';
21
23
  import { reviewLabels } from '@/lib/utils/basklee/reviewLabels';
22
24
  import { featureLabels } from '@/lib/utils/basklee/featureLabels';
23
25
  import { productLabels } from '@/lib/utils/basklee/productLabels';
@@ -31,6 +33,7 @@
31
33
  import { safeArticleHtml } from '@/lib/utils/basklee/richText';
32
34
  import { htmlTextParagraphs } from '@/lib/utils/basklee/htmlText';
33
35
  import {
36
+ productMediaItems,
34
37
  thumbnailKeyTarget,
35
38
  thumbnailRailEdges,
36
39
  thumbnailScrollTarget,
@@ -54,6 +57,7 @@
54
57
  IProductSpecificationRow,
55
58
  } from '@/lib/interfaces/basklee/products/IProductSpecification';
56
59
  import ProductCard from '@/lib/components/basklee/products/ProductCard.svelte';
60
+ import ProductGroup from '@/lib/components/basklee/products/ProductGroup.svelte';
57
61
  import ProductReviews from '@/lib/components/basklee/products/ProductReviews.svelte';
58
62
  import ProductPreorderDialog from '@/lib/components/basklee/products/ProductPreorderDialog.svelte';
59
63
  import ProductSpecificationsDialog from '@/lib/components/basklee/products/ProductSpecificationsDialog.svelte';
@@ -200,6 +204,13 @@
200
204
  const images = product.value?.images;
201
205
  return images?.full?.length ? images.full : (images?.small ?? []);
202
206
  });
207
+ // The gallery: the photos, then the product's videos (Video tab of the
208
+ // panel). A video plays in the large photo's place; the full-screen viewer
209
+ // keeps to the photos, which come first, so their numbers are the same.
210
+ const media = computed(() => productMediaItems(product.value));
211
+ const current = computed(
212
+ () => media.value[image.value] ?? media.value[0],
213
+ );
203
214
  // The first request in the browser shows a placeholder with the page
204
215
  // layout; a later retry after an error shows it again. A product loaded
205
216
  // during the server render is shown at once.
@@ -525,7 +536,7 @@
525
536
  }
526
537
 
527
538
  function showImage(index: number) {
528
- const count = photos.value.length;
539
+ const count = media.value.length;
529
540
  image.value = (index + count) % count;
530
541
  }
531
542
 
@@ -552,7 +563,7 @@
552
563
  showImage(
553
564
  productPhotoAfterSwipe(
554
565
  image.value,
555
- photos.value.length,
566
+ media.value.length,
556
567
  touch.clientX - start.x,
557
568
  touch.clientY - start.y,
558
569
  ),
@@ -663,7 +674,7 @@
663
674
 
664
675
  // Arrow keys, Home and End move between thumbnails, which form one tab stop.
665
676
  function thumbnailKeydown(event: KeyboardEvent, index: number) {
666
- const target = thumbnailKeyTarget(event.key, index, photos.value.length);
677
+ const target = thumbnailKeyTarget(event.key, index, media.value.length);
667
678
 
668
679
  if (target === undefined) {
669
680
  return;
@@ -723,6 +734,18 @@
723
734
  currentId.value = selection.variant.product.id;
724
735
  image.value = 0;
725
736
  }
737
+ // The row under the product: the products attached on the panel's
738
+ // «Relevant Products» tab first, else more of the product's category.
739
+ const related = useBaskleeRelatedProducts({ api, product });
740
+ const relatedLabels = computed(() =>
741
+ relatedProductsLabels(selectionStore.localeCode),
742
+ );
743
+ function openRelated(item: IProduct) {
744
+ void navigateTo({
745
+ path: `/product/${item.id}`,
746
+ query: { locale: selectionStore.localeCode },
747
+ });
748
+ }
726
749
  onMounted(() => {
727
750
  mounted.value = true;
728
751
  if (!confirmed.value) {
@@ -794,7 +817,7 @@
794
817
  revealThumbnail(index);
795
818
  });
796
819
  // Another variant's photos start from the first thumbnail.
797
- watch(photos, async () => {
820
+ watch(media, async () => {
798
821
  await nextTick();
799
822
 
800
823
  if (rail.value) {
@@ -862,7 +885,7 @@
862
885
  `,
863
886
  ]}
864
887
  >
865
- {#if photos.value.length}
888
+ {#if media.value.length}
866
889
  <section
867
890
  aria-label={labels.value.gallery}
868
891
  data-product-gallery
@@ -882,40 +905,64 @@
882
905
  relative min-w-0 @min-[560px]/product:col-start-2
883
906
  @min-[560px]/product:row-start-1 @min-[960px]/product:min-h-96
884
907
  `,
885
- photos.value.length > 1 && 'touch-pan-y',
908
+ media.value.length > 1 && 'touch-pan-y',
886
909
  ]}
887
910
  ontouchstart={startSwipe}
888
911
  ontouchend={endSwipe}
889
912
  >
890
- <BaskleeImage
891
- src={photos.value[image.value]}
892
- alt={title.value}
893
- width={800}
894
- height={1000}
895
- loading="eager"
896
- role="button"
897
- tabindex="0"
898
- aria-label={labels.value.openProductPhoto}
899
- data-product-photo-open
900
- onclick={() => {
901
- viewerOpen.value = true;
902
- }}
903
- onkeydown={openViewerKey}
904
- class={[
905
- `
906
- box-border aspect-square h-auto max-h-[70vh] w-full bg-basklee-surface
907
- cursor-zoom-in outline-none focus-visible:outline-1
908
- focus-visible:outline-solid focus-visible:outline-basklee-text
909
- object-contain @min-[560px]/product:aspect-[4/5]
910
- @min-[960px]/product:absolute @min-[960px]/product:inset-0
911
- @min-[960px]/product:m-auto @min-[960px]/product:aspect-auto
912
- @min-[960px]/product:h-full
913
- @min-[960px]/product:max-h-[calc(100vh-12rem)]
914
- `,
915
- ]}
916
- />
913
+ {#if current.value?.kind === 'video'}
914
+ {#key current.value.key}
915
+ <video
916
+ src={current.value.src}
917
+ poster={current.value.preview || undefined}
918
+ aria-label={labels.value.productVideo}
919
+ controls
920
+ playsinline
921
+ preload="metadata"
922
+ data-product-video
923
+ class={[
924
+ `
925
+ box-border aspect-square h-auto max-h-[70vh] w-full bg-basklee-surface
926
+ object-contain @min-[560px]/product:aspect-[4/5]
927
+ @min-[960px]/product:absolute @min-[960px]/product:inset-0
928
+ @min-[960px]/product:m-auto @min-[960px]/product:aspect-auto
929
+ @min-[960px]/product:h-full
930
+ @min-[960px]/product:max-h-[calc(100vh-12rem)]
931
+ `,
932
+ ]}
933
+ ></video>
934
+ {/key}
935
+ {:else if current.value}
936
+ <BaskleeImage
937
+ src={current.value.src}
938
+ alt={title.value}
939
+ width={800}
940
+ height={1000}
941
+ loading="eager"
942
+ role="button"
943
+ tabindex="0"
944
+ aria-label={labels.value.openProductPhoto}
945
+ data-product-photo-open
946
+ onclick={() => {
947
+ viewerOpen.value = true;
948
+ }}
949
+ onkeydown={openViewerKey}
950
+ class={[
951
+ `
952
+ box-border aspect-square h-auto max-h-[70vh] w-full bg-basklee-surface
953
+ cursor-zoom-in outline-none focus-visible:outline-1
954
+ focus-visible:outline-solid focus-visible:outline-basklee-text
955
+ object-contain @min-[560px]/product:aspect-[4/5]
956
+ @min-[960px]/product:absolute @min-[960px]/product:inset-0
957
+ @min-[960px]/product:m-auto @min-[960px]/product:aspect-auto
958
+ @min-[960px]/product:h-full
959
+ @min-[960px]/product:max-h-[calc(100vh-12rem)]
960
+ `,
961
+ ]}
962
+ />
963
+ {/if}
917
964
 
918
- {#if photos.value.length > 1}
965
+ {#if media.value.length > 1}
919
966
  <button
920
967
  type="button"
921
968
  aria-label={labels.value.previousImage}
@@ -975,7 +1022,7 @@
975
1022
  {/if}
976
1023
  </div>
977
1024
 
978
- {#if photos.value.length > 1}
1025
+ {#if media.value.length > 1}
979
1026
  <div
980
1027
  data-product-thumbnail-rail
981
1028
  class={[
@@ -999,13 +1046,14 @@
999
1046
  `,
1000
1047
  ]}
1001
1048
  >
1002
- {#each photos.value as photo, index (photo)}
1049
+ {#each media.value as item, index (item.key)}
1003
1050
  <button
1004
1051
  type="button"
1005
- aria-label={`${labels.value.gallery} ${index + 1}`}
1052
+ aria-label={`${item.kind === 'video' ? labels.value.productVideo : labels.value.gallery} ${index + 1}`}
1006
1053
  aria-pressed={index === image.value}
1007
1054
  tabindex={index === image.value ? 0 : -1}
1008
1055
  data-product-thumbnail={index}
1056
+ data-product-thumbnail-video={item.kind === 'video' || undefined}
1009
1057
  onclick={() => {
1010
1058
  image.value = index;
1011
1059
  }}
@@ -1014,7 +1062,7 @@
1014
1062
  }}
1015
1063
  class={[
1016
1064
  `
1017
- box-border h-[70px] w-14 shrink-0 p-1 @min-[560px]/product:h-[90px]
1065
+ relative box-border h-[70px] w-14 shrink-0 p-1 @min-[560px]/product:h-[90px]
1018
1066
  @min-[560px]/product:w-[72px] cursor-pointer border border-solid
1019
1067
  bg-basklee-surface outline-none transition-[opacity,border-color]
1020
1068
  motion-reduce:transition-none hover:opacity-100 focus-visible:border-2
@@ -1025,11 +1073,37 @@
1025
1073
  : 'border-transparent opacity-75',
1026
1074
  ]}
1027
1075
  >
1028
- <BaskleeImage
1029
- src={photo}
1030
- alt=""
1031
- class={['h-full w-full object-contain']}
1032
- />
1076
+ {#if item.kind === 'image' || item.preview}
1077
+ <BaskleeImage
1078
+ src={item.kind === 'image' ? item.src : (item.preview as string)}
1079
+ alt=""
1080
+ class={[
1081
+ 'h-full w-full',
1082
+ item.kind === 'image' ? 'object-contain' : 'object-cover',
1083
+ ]}
1084
+ />
1085
+ {/if}
1086
+ {#if item.kind === 'video'}
1087
+ <span
1088
+ aria-hidden="true"
1089
+ data-product-video-mark
1090
+ class={[
1091
+ `
1092
+ absolute inset-0 m-auto grid h-7 w-7 place-items-center rounded-full
1093
+ bg-basklee-text/80 text-basklee-surface
1094
+ `,
1095
+ ]}
1096
+ >
1097
+ <svg
1098
+ viewBox="0 0 24 24"
1099
+ class="ml-0.5 h-3.5 w-3.5"
1100
+ fill="currentColor"
1101
+ aria-hidden="true"
1102
+ >
1103
+ <path d="M8 5v14l11-7z" />
1104
+ </svg>
1105
+ </span>
1106
+ {/if}
1033
1107
  </button>
1034
1108
  {/each}
1035
1109
  </div>
@@ -1616,6 +1690,66 @@
1616
1690
  <ProductReviews productId={currentId.value} />
1617
1691
  {/key}
1618
1692
  </div>
1693
+ {#if related.productIds.value.length}
1694
+ <section
1695
+ class={[
1696
+ `
1697
+ mt-14 pt-10 border-0 border-t border-solid border-basklee-border
1698
+ @min-[592px]/product:mt-20
1699
+ `,
1700
+ ]}
1701
+ aria-label={relatedLabels.value.title}
1702
+ data-product-related
1703
+ >
1704
+ <header
1705
+ class={[
1706
+ 'mb-6 flex flex-wrap items-baseline justify-between gap-x-6 gap-y-2',
1707
+ ]}
1708
+ >
1709
+ <h2 class={['m-0 text-xl font-semibold text-basklee-text']}>
1710
+ {relatedLabels.value.title}
1711
+ </h2>
1712
+ {#if related.categoryId.value}
1713
+ <a
1714
+ href={routeHref({
1715
+ path: `/category/${related.categoryId.value}`,
1716
+ query: { locale: selectionStore.localeCode },
1717
+ })}
1718
+ class={['text-sm text-basklee-text underline underline-offset-4']}
1719
+ data-product-related-category
1720
+ >
1721
+ {relatedLabels.value.category}
1722
+ </a>
1723
+ {/if}
1724
+ </header>
1725
+ <ProductGroup
1726
+ productIds={related.productIds.value}
1727
+ disabled={actions.pending.value || actions.needsRefresh.value}
1728
+ onSelect={openRelated}
1729
+ onSelectSeller={($event) => {
1730
+ emit('seller', $event);
1731
+ }}
1732
+ onSelectVariant={variants.select}
1733
+ onRequestSecondaryVariants={variants.requestSecondary}
1734
+ onToggleFavorite={($event) => {
1735
+ actions.run('toggleFavorite', $event);
1736
+ }}
1737
+ onAdd={($event) => {
1738
+ actions.run('add', $event);
1739
+ }}
1740
+ onRemove={($event) => {
1741
+ actions.run('remove', $event);
1742
+ }}
1743
+ onSubscribe={($event) => {
1744
+ actions.run('subscribe', $event);
1745
+ }}
1746
+ onUnsubscribe={($event) => {
1747
+ actions.run('unsubscribe', $event);
1748
+ }}
1749
+ onPreorder={actions.openPreorder}
1750
+ />
1751
+ </section>
1752
+ {/if}
1619
1753
  <ProductPreorderDialog
1620
1754
  productId={actions.preorder.value}
1621
1755
  pending={actions.pending.value}
@@ -2,6 +2,8 @@ import { browser } from '$app/environment';
2
2
  import { getContext, setContext } from 'svelte';
3
3
  import { getBaskleeContext } from '@/lib/basklee/store.svelte';
4
4
  import { BaskleeApi } from '@/lib/utils/basklee/api';
5
+ import { navigateTo } from '@/lib/basklee/navigation.svelte';
6
+ import { signInPageLocation } from '@/lib/utils/basklee/signInReturn';
5
7
  import {
6
8
  APP_ORIGIN,
7
9
  nativeAppCookies,
@@ -14,6 +16,24 @@ import type {
14
16
  const clients = new WeakMap<object, BaskleeApi>();
15
17
  const apiKey = Symbol('basklee-api');
16
18
 
19
+ /*
20
+ * After HTTP 401 the visitor goes to the /profile sign-in page with this page
21
+ * in `redirect`, for example `/profile?locale=en&redirect=/orders?locale=en`.
22
+ * The sign-in page itself and /logout stay where they are: /profile already
23
+ * shows the form, and logging out should not ask for sign-in.
24
+ */
25
+ function openSignInAfterUnauthorized(locale: string) {
26
+ if (!browser) {
27
+ return;
28
+ }
29
+ const { pathname, search, hash } = window.location;
30
+ if (pathname === '/profile' || pathname === '/logout') {
31
+ return;
32
+ }
33
+
34
+ void navigateTo(signInPageLocation(pathname + search + hash, locale));
35
+ }
36
+
17
37
  export function provideBaskleeApi(api: BaskleeApi) {
18
38
  setContext(apiKey, api);
19
39
  }
@@ -99,12 +119,21 @@ export function useBaskleeApi() {
99
119
  isSignedIn: () => store.isAuthenticated,
100
120
  // The customer's currency for orders and plan purchases (CURRENCY_REQUESTS).
101
121
  currency: () => store.currencyId,
102
- onSessionEnded: () =>
103
- store.endSession((signal) =>
104
- import('@/lib/basklee/appLoadClient').then((module) =>
105
- module.requestBrowserAppLoad(signal, store.localeCode),
106
- ),
107
- ),
122
+ // HTTP 401: the request needs a signed-in customer. An ended session
123
+ // shows the guest storefront at once; then the sign-in page opens and
124
+ // returns to this page afterwards. The failed request is not repeated.
125
+ onUnauthorized: (signedIn) => {
126
+ const ending = signedIn
127
+ ? store.endSession((signal) =>
128
+ import('@/lib/basklee/appLoadClient').then((module) =>
129
+ module.requestBrowserAppLoad(signal, store.localeCode),
130
+ ),
131
+ )
132
+ : undefined;
133
+ openSignInAfterUnauthorized(store.localeCode);
134
+
135
+ return ending;
136
+ },
108
137
  });
109
138
  clients.set(store, api);
110
139
  return api;
@@ -0,0 +1,132 @@
1
+ import { browser } from '$app/environment';
2
+ import {
3
+ computed,
4
+ onScopeDispose,
5
+ ref,
6
+ toValue,
7
+ watch,
8
+ } from '@/lib/basklee/reactivity.svelte';
9
+ import type { MaybeRefOrGetter } from '@/lib/basklee/reactivity.svelte';
10
+ import { useBaskleeProductsStore } from '@/lib/stores/baskleeProducts.svelte';
11
+ import { useBaskleeCatalogStore } from '@/lib/stores/baskleeCatalog.svelte';
12
+ import type { BaskleeApi } from '@/lib/utils/basklee/api';
13
+ import {
14
+ attachedRelatedProducts,
15
+ relatedCategoryId,
16
+ relatedCategoryProducts,
17
+ relatedCategoryRequest,
18
+ } from '@/lib/utils/basklee/relatedProducts';
19
+ import type {
20
+ IProduct,
21
+ IProductSearchSeller,
22
+ } from '@/lib/interfaces/basklee/products/IProduct';
23
+
24
+ /*
25
+ * The products of the row under a product page (lib/utils/basklee/relatedProducts.ts):
26
+ * the products attached on the panel's «Relevant Products» tab first, else
27
+ * more of the product's main category. The products go into the product
28
+ * store, so the row's cards read them like every other card. A failed
29
+ * category request leaves the row off the page.
30
+ */
31
+ export function useBaskleeRelatedProducts(options: {
32
+ api: Pick<BaskleeApi, 'request'>;
33
+ product: MaybeRefOrGetter<IProduct | undefined>;
34
+ }) {
35
+ const productStore = useBaskleeProductsStore();
36
+ const catalogStore = useBaskleeCatalogStore();
37
+ const categoryIds = ref<number[]>([]);
38
+ const pending = ref(false);
39
+ let request: AbortController | undefined;
40
+
41
+ const attached = computed(() =>
42
+ attachedRelatedProducts(toValue(options.product)),
43
+ );
44
+ const categoryId = computed(() =>
45
+ relatedCategoryId(toValue(options.product)),
46
+ );
47
+ const productIds = computed(() =>
48
+ attached.value.length
49
+ ? attached.value.map((item) => item.id)
50
+ : categoryIds.value,
51
+ );
52
+
53
+ function cancel() {
54
+ request?.abort();
55
+ request = undefined;
56
+ pending.value = false;
57
+ }
58
+
59
+ async function loadCategory(category: number, productId: number) {
60
+ cancel();
61
+ categoryIds.value = [];
62
+ if (!category) {
63
+ return;
64
+ }
65
+ const current = new AbortController();
66
+ request = current;
67
+ pending.value = true;
68
+ try {
69
+ const data = await options.api.request<{
70
+ products?: { data?: IProduct[] };
71
+ selects?: { sellers?: IProductSearchSeller[] };
72
+ }>(
73
+ 'products_search',
74
+ relatedCategoryRequest(category, catalogStore.catalog),
75
+ current.signal,
76
+ );
77
+ if (current.signal.aborted) {
78
+ return;
79
+ }
80
+ const items = relatedCategoryProducts(data.products?.data, productId);
81
+ for (const item of items) {
82
+ productStore.setProduct(item, 'products', data.selects?.sellers ?? []);
83
+ }
84
+ categoryIds.value = items.map((item) => item.id);
85
+ } catch {
86
+ // The row stays off the page; the next visit of the page asks again.
87
+ } finally {
88
+ if (request === current) {
89
+ request = undefined;
90
+ pending.value = false;
91
+ }
92
+ }
93
+ }
94
+
95
+ watch(
96
+ attached,
97
+ (items) => {
98
+ for (const item of items) {
99
+ if (!productStore.getProduct(item.id)) {
100
+ productStore.setProduct(item, 'products');
101
+ }
102
+ }
103
+ },
104
+ { immediate: true },
105
+ );
106
+ watch(
107
+ () => [categoryId.value, toValue(options.product)?.id ?? 0] as const,
108
+ ([category, productId], previous) => {
109
+ if (
110
+ previous &&
111
+ previous[0] === category &&
112
+ previous[1] === productId
113
+ ) {
114
+ return;
115
+ }
116
+ if (browser) {
117
+ void loadCategory(category, productId);
118
+ }
119
+ },
120
+ { immediate: true },
121
+ );
122
+ onScopeDispose(cancel);
123
+
124
+ return {
125
+ productIds,
126
+ /** The category the row comes from, or 0 for attached products. */
127
+ categoryId: computed(() =>
128
+ attached.value.length ? 0 : categoryId.value,
129
+ ),
130
+ pending,
131
+ };
132
+ }
@@ -28,8 +28,8 @@ export function provideBaskleeSignIn(handler: BaskleeSignInHandler) {
28
28
  * A guest who clicks an action that needs an account (a review, a reaction,
29
29
  * a favorite, a plan subscription) goes straight to the /profile sign-in page,
30
30
  * which returns to `redirect` afterwards. Call requireSignIn() only from the
31
- * visitor's own click: background requests and an ended session never
32
- * navigate.
31
+ * visitor's own click. A request that answers HTTP 401 opens the same page
32
+ * through the shared API client (see useBaskleeApi).
33
33
  */
34
34
  export function useBaskleeSignIn() {
35
35
  const store = useBaskleeStore();
@@ -80,7 +80,7 @@ export class BaskleeApi {
80
80
  private canRequest: () => boolean;
81
81
  private isSignedIn: () => boolean;
82
82
  private currency: () => string | number | undefined;
83
- private onSessionEnded: (() => unknown) | undefined;
83
+ private onUnauthorized: ((signedIn: boolean) => unknown) | undefined;
84
84
 
85
85
  constructor(options: {
86
86
  transport: BaskleeTransport;
@@ -90,7 +90,7 @@ export class BaskleeApi {
90
90
  canRequest?: () => boolean;
91
91
  isSignedIn?: () => boolean;
92
92
  currency?: () => string | number | undefined;
93
- onSessionEnded?: () => unknown;
93
+ onUnauthorized?: (signedIn: boolean) => unknown;
94
94
  }) {
95
95
  this.transport = options.transport;
96
96
  this.endpoints = options.endpoints;
@@ -99,10 +99,10 @@ export class BaskleeApi {
99
99
  this.canRequest = options.canRequest ?? (() => true);
100
100
  this.isSignedIn = options.isSignedIn ?? (() => false);
101
101
  this.currency = options.currency ?? (() => undefined);
102
- this.onSessionEnded = options.onSessionEnded;
102
+ this.onUnauthorized = options.onUnauthorized;
103
103
  }
104
104
 
105
- /** The guest refresh started by the latest HTTP 401, while it runs. */
105
+ /** The handling of the latest HTTP 401 (guest refresh, sign-in), while it runs. */
106
106
  get sessionEnd() {
107
107
  return this.sessionEnding;
108
108
  }
@@ -201,7 +201,7 @@ export class BaskleeApi {
201
201
  signal?.throwIfAborted();
202
202
  }
203
203
 
204
- this.detectSessionEnd(response);
204
+ this.detectUnauthorized(response, name);
205
205
  signal?.throwIfAborted();
206
206
  return response;
207
207
  }
@@ -210,23 +210,28 @@ export class BaskleeApi {
210
210
  * The backend answers HTTP 401 when the request has no signed-in session:
211
211
  * an authentication-required endpoint without a customer ({ auth: false }),
212
212
  * or a session the backend rejected and whose cookies it deleted.
213
- * A 401 while the application still shows a customer means the session
214
- * ended. One handler call serves concurrent failures; a guest 401, 403 and
215
- * CSRF rejection are ordinary request errors.
213
+ * Every such answer goes to `onUnauthorized`, which opens sign-in. With
214
+ * `signedIn` true the application still shows a customer, so the session
215
+ * has ended and the handler first removes the account data. One handler
216
+ * call serves concurrent failures. The 401 of `profile_logout` only says
217
+ * that the session had already ended, so it is not passed on; 403 and CSRF
218
+ * rejection are ordinary request errors.
216
219
  */
217
- private detectSessionEnd(response: BaskleeApiResponse) {
220
+ private detectUnauthorized(response: BaskleeApiResponse, name = '') {
218
221
  if (
219
222
  response.status !== 401 ||
223
+ name === 'profile_logout' ||
220
224
  this.sessionEnding ||
221
- !this.onSessionEnded ||
222
- !this.isSignedIn()
225
+ !this.onUnauthorized
223
226
  ) {
224
227
  return;
225
228
  }
226
229
 
227
230
  let ending: Promise<void>;
228
231
  try {
229
- ending = Promise.resolve(this.onSessionEnded()).then(() => undefined);
232
+ ending = Promise.resolve(this.onUnauthorized(this.isSignedIn())).then(
233
+ () => undefined,
234
+ );
230
235
  } catch (error) {
231
236
  ending = Promise.reject(error);
232
237
  }
@@ -239,6 +244,7 @@ export class BaskleeApi {
239
244
  });
240
245
  }
241
246
 
247
+
242
248
  private csrfToken() {
243
249
  return this.cookies().match(/(?:^|;\s*)csrftoken=([^;]*)/)?.[1] ?? '';
244
250
  }
@@ -257,7 +263,7 @@ export class BaskleeApi {
257
263
  if (!this.renewal) {
258
264
  this.renewal = this.send('/api/csrf_renew', 'POST', {})
259
265
  .then((response) => {
260
- this.detectSessionEnd(response);
266
+ this.detectUnauthorized(response);
261
267
  this.successData(response);
262
268
  if (!this.csrfToken()) {
263
269
  throw new BaskleeApiError('failed');
@@ -70,3 +70,40 @@ export function thumbnailKeyTarget(
70
70
 
71
71
  return undefined;
72
72
  }
73
+
74
+ export type ProductMediaItem =
75
+ | { kind: 'image'; key: string; src: string }
76
+ | { kind: 'video'; key: string; src: string; preview: string | null };
77
+
78
+ export interface IProductMediaSources {
79
+ images?: { full?: string[] | null; small?: string[] | null } | null;
80
+ videos?:
81
+ | { id: number; product_video: string | null; preview: string | null }[]
82
+ | null;
83
+ }
84
+
85
+ // The pictures and videos of a product in the order its gallery shows them:
86
+ // the full images first (the small copies when it has none), then the videos
87
+ // in the order the backend sends them. A video without a file is left out.
88
+ export function productMediaItems(
89
+ product: IProductMediaSources | null | undefined,
90
+ ): ProductMediaItem[] {
91
+ const images = product?.images;
92
+ const photos = images?.full?.length ? images.full : (images?.small ?? []);
93
+ const items = photos.map(
94
+ (src, index): ProductMediaItem => ({ kind: 'image', key: `image-${index}`, src }),
95
+ );
96
+
97
+ for (const video of product?.videos ?? []) {
98
+ if (video.product_video) {
99
+ items.push({
100
+ kind: 'video',
101
+ key: `video-${video.id}`,
102
+ src: video.product_video,
103
+ preview: video.preview,
104
+ });
105
+ }
106
+ }
107
+
108
+ return items;
109
+ }
@@ -0,0 +1,106 @@
1
+ import { categoryBranchIds, categoryTrail } from '@/lib/utils/basklee/category';
2
+ import type { ICategory } from '@/lib/interfaces/basklee/category/ICategory';
3
+ import type { IProduct } from '@/lib/interfaces/basklee/products/IProduct';
4
+
5
+ /*
6
+ * The row of other products under a product page.
7
+ *
8
+ * The products the seller attached to this product on the panel's «Relevant
9
+ * Products» tab come first: they arrive with the product (`related.data`),
10
+ * so they need no request. Only a product without them shows more products
11
+ * of its own main category, asked from `products_search` the way the
12
+ * category page asks (the category with its subcategories), one more than
13
+ * shown because the product itself may be among them.
14
+ */
15
+
16
+ /** How many products the row shows. */
17
+ export const RELATED_PRODUCTS_LIMIT = 8;
18
+
19
+ /** The attached products of `product`, without the product itself. */
20
+ export function attachedRelatedProducts(
21
+ product: IProduct | undefined,
22
+ limit = RELATED_PRODUCTS_LIMIT,
23
+ ): IProduct[] {
24
+ const items = product?.related?.data;
25
+
26
+ if (!product || !Array.isArray(items)) {
27
+ return [];
28
+ }
29
+
30
+ return items
31
+ .filter(
32
+ (item) =>
33
+ Number.isInteger(item?.id) && item.id > 0 && item.id !== product.id,
34
+ )
35
+ .slice(0, limit);
36
+ }
37
+
38
+ /**
39
+ * The category whose products fill the row when nothing is attached: the
40
+ * product's main category, or 0 when the row needs none.
41
+ */
42
+ export function relatedCategoryId(product: IProduct | undefined): number {
43
+ const category = product?.main_category;
44
+
45
+ if (
46
+ !product ||
47
+ attachedRelatedProducts(product).length ||
48
+ typeof category !== 'number' ||
49
+ !Number.isInteger(category) ||
50
+ category <= 0
51
+ ) {
52
+ return 0;
53
+ }
54
+
55
+ return category;
56
+ }
57
+
58
+ /**
59
+ * The `products_search` body for that category: the category with its public
60
+ * subcategories when the catalog tree knows it, otherwise the category alone.
61
+ */
62
+ export function relatedCategoryRequest(
63
+ categoryId: number,
64
+ catalog: ICategory[],
65
+ limit = RELATED_PRODUCTS_LIMIT,
66
+ ) {
67
+ const category = categoryTrail(catalog, categoryId).at(-1);
68
+
69
+ return {
70
+ filters: {
71
+ categories: category ? categoryBranchIds(category) : [categoryId],
72
+ },
73
+ paginate: { page: 1, pp_items: limit + 1 },
74
+ };
75
+ }
76
+
77
+ /** The products of the category answer that the row shows. */
78
+ export function relatedCategoryProducts(
79
+ items: IProduct[] | undefined,
80
+ productId: number,
81
+ limit = RELATED_PRODUCTS_LIMIT,
82
+ ): IProduct[] {
83
+ return (Array.isArray(items) ? items : [])
84
+ .filter((item) => Number.isInteger(item?.id) && item.id !== productId)
85
+ .slice(0, limit);
86
+ }
87
+
88
+ const RELATED_EN = {
89
+ title: 'You may also like',
90
+ category: 'All products of the category',
91
+ };
92
+ const RELATED_TITLES: Record<string, { title: string; category: string }> = {
93
+ en: RELATED_EN,
94
+ ru: { title: 'Вам может понравиться', category: 'Все товары категории' },
95
+ es: {
96
+ title: 'También te puede gustar',
97
+ category: 'Todos los productos de la categoría',
98
+ },
99
+ };
100
+
101
+ /** The row's heading and the link to its category, in the given language. */
102
+ export function relatedProductsLabels(locale: string) {
103
+ return (
104
+ RELATED_TITLES[String(locale || '').toLowerCase().slice(0, 2)] ?? RELATED_EN
105
+ );
106
+ }
@@ -52,6 +52,7 @@ const en = {
52
52
  zoomIn: 'Show at full size',
53
53
  zoomOut: 'Fit to screen',
54
54
  nextImage: 'Next image',
55
+ productVideo: 'Product video',
55
56
  thumbnailsBack: 'Show previous thumbnails',
56
57
  thumbnailsForward: 'Show next thumbnails',
57
58
  characteristics: 'Characteristics',
@@ -133,6 +134,7 @@ const ru: typeof en = {
133
134
  zoomIn: 'Показать в полный размер',
134
135
  zoomOut: 'Вписать в экран',
135
136
  nextImage: 'Следующая фотография',
137
+ productVideo: 'Видео товара',
136
138
  thumbnailsBack: 'Показать предыдущие миниатюры',
137
139
  thumbnailsForward: 'Показать следующие миниатюры',
138
140
  characteristics: 'Характеристики',
@@ -215,6 +217,7 @@ const es: typeof en = {
215
217
  zoomIn: 'Ver a tamaño completo',
216
218
  zoomOut: 'Ajustar a la pantalla',
217
219
  nextImage: 'Imagen siguiente',
220
+ productVideo: 'Vídeo del producto',
218
221
  thumbnailsBack: 'Ver miniaturas anteriores',
219
222
  thumbnailsForward: 'Ver miniaturas siguientes',
220
223
  characteristics: 'Características',