basklee-nuxt 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
@@ -201,7 +201,7 @@ Product details, saved items and the cart.
201
201
 
202
202
  | Component | Name | What it does |
203
203
  | --- | --- | --- |
204
- | **Product details** | `StorefrontProduct` | Loads and displays a published product or a secret-key preview with images, purchase choices, details and reviews. |
204
+ | **Product details** | `StorefrontProduct` | Loads and displays a published product or a secret-key preview with images and videos, purchase choices, details and reviews. |
205
205
  | **Page path** | `BaskleeBreadcrumbs` | Linked path from the storefront home page through parent categories to the current page. |
206
206
  | **Product characteristics** | `ProductSpecificationsDialog` | Every characteristic of the product in a dialog over the page. |
207
207
  | **Product reviews** | `ProductReviews` | Reviews, replies, ratings and the user’s submissions. |
@@ -725,9 +725,11 @@ HTTP `401` means the request has no signed-in session. When it arrives while
725
725
  `store.isAuthenticated` is `true`, the client calls the store's `endSession()`
726
726
  once: the profile, wallet, authenticated discovery, cart/wishlist counters and
727
727
  account values of known products are removed at once, then Application Load
728
- reloads for the guest session. The failed request is not repeated and no
729
- sign-in dialog opens; a guest `401`, `403`, CSRF rejection or network failure
730
- stays an ordinary request error.
728
+ reloads for the guest session. Every `401` (also a guest's) then opens
729
+ `/profile?locale=<locale>&redirect=<current page>`, which returns to the page
730
+ after sign-in; on `/profile` and `/logout` the page stays. The failed request
731
+ is not repeated; a `403`, CSRF rejection or network failure stays an ordinary
732
+ request error.
731
733
 
732
734
  See the [cookie lifecycle and browser example](https://docs.basklee.com/en/sandbox/appload/nuxt#session-cookies)
733
735
  for exact source references and a copyable component.
@@ -1100,7 +1102,9 @@ heart, an availability notification, Checkout in the cart, a plan's Subscribe
1100
1102
  or Try, an event) opens `/profile?locale=<locale>&redirect=<current page>` at
1101
1103
  once through `useBaskleeSignIn().requireSignIn()` in
1102
1104
  `app/composables/useBaskleeSignIn.ts`, with no separate sign-in notice.
1103
- Background requests and an ended session never navigate.
1105
+ A request that answers HTTP 401 opens the same address: the shared API client
1106
+ ends a signed-in session first (the guest storefront shows at once), and the
1107
+ sign-in page returns to the page afterwards; `/profile` and `/logout` stay put.
1104
1108
  Account pages (`/orders`, `/wallet`, `/addresses`, `/subscriptions`, `/tickets`,
1105
1109
  `/activity`, `/wishlist`) declare the `basklee-account` route middleware in
1106
1110
  `app/middleware/basklee-account.ts`: after Application Load confirms a guest
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "basklee-nuxt",
3
- "version": "0.9.9",
3
+ "version": "0.9.11",
4
4
  "description": "Nuxt 4 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",
@@ -93,7 +93,9 @@ heart, an availability notification, Checkout in the cart, a plan's Subscribe
93
93
  or Try, an event) opens \`/profile?locale=<locale>&redirect=<current page>\` at
94
94
  once through \`useBaskleeSignIn().requireSignIn()\` in
95
95
  \`app/composables/useBaskleeSignIn.ts\`, with no separate sign-in notice.
96
- Background requests and an ended session never navigate.
96
+ A request that answers HTTP 401 opens the same address: the shared API client
97
+ ends a signed-in session first (the guest storefront shows at once), and the
98
+ sign-in page returns to the page afterwards; \`/profile\` and \`/logout\` stay put.
97
99
  Account pages (\`/orders\`, \`/wallet\`, \`/addresses\`, \`/subscriptions\`, \`/tickets\`,
98
100
  \`/activity\`, \`/wishlist\`) declare the \`basklee-account\` route middleware in
99
101
  \`app/middleware/basklee-account.ts\`: after Application Load confirms a guest
@@ -409,9 +411,11 @@ HTTP \`401\` means the request has no signed-in session. When it arrives while
409
411
  \`store.isAuthenticated\` is \`true\`, the client calls the store's \`endSession()\`
410
412
  once: the profile, wallet, authenticated discovery, cart/wishlist counters and
411
413
  account values of known products are removed at once, then Application Load
412
- reloads for the guest session. The failed request is not repeated and no
413
- sign-in dialog opens; a guest \`401\`, \`403\`, CSRF rejection or network failure
414
- stays an ordinary request error.
414
+ reloads for the guest session. Every \`401\` (also a guest's) then opens
415
+ \`/profile?locale=<locale>&redirect=<current page>\`, which returns to the page
416
+ after sign-in; on \`/profile\` and \`/logout\` the page stays. The failed request
417
+ is not repeated; a \`403\`, CSRF rejection or network failure stays an ordinary
418
+ request error.
415
419
 
416
420
  [Cookie lifecycle and browser request example](https://docs.basklee.com/en/sandbox/appload/nuxt#session-cookies)
417
421
 
@@ -14,7 +14,7 @@ This is the only navigation on an account page: the components rendered in the s
14
14
 
15
15
  The component never renders a sign-in form. Account pages declare the `basklee-account` route middleware (`app/middleware/basklee-account.ts`); after Application Load confirms a guest session, it replaces the page with `/profile?locale=<locale>&redirect=<current page>`. The sign-in form on `/profile` returns to that page after the refreshed Application Load confirms the session. A pending or failed Application Load does not redirect.
16
16
 
17
- If the session ends while an account page is open, for example when a request answers HTTP 401, the component shows a short message that the section needs sign-in instead of the section content, and the page does not navigate on its own; the header shows Login. The shared API client removes the signed-in data from the store at once and reloads Application Load for the guest session; no dialog opens. After a failed Application Load it shows an error with Retry, which repeats Application Load.
17
+ If the session ends while an account page is open, for example when a request answers HTTP 401, the component shows a short message that the section needs sign-in instead of the section content, and the header shows Login. The shared API client removes the signed-in data from the store at once, reloads Application Load for the guest session and opens `/profile?locale=<locale>&redirect=<current page>`, which returns to the page after sign-in. After a failed Application Load it shows an error with Retry, which repeats Application Load.
18
18
 
19
19
  The guide describes its inputs and events. Source is maintained in
20
20
  `app/components/basklee/account/AccountSection.vue`; it has no separate interface file.
@@ -20,9 +20,9 @@
20
20
  const sections = computed(() => Object.entries(labels.value.navigation));
21
21
 
22
22
  // The basklee-account middleware opens /profile before a guest reaches
23
- // this page. When the session ends while the page is open, the page stays
24
- // and explains that the account content needs sign-in; it never navigates
25
- // on its own, and the header offers Login. A failed Application Load is
23
+ // this page. When the session ends while the page is open, the section
24
+ // explains that the account content needs sign-in while the shared API
25
+ // client opens the sign-in page, which returns here afterwards. A failed Application Load is
26
26
  // not a guest session: it offers Retry instead.
27
27
  </script>
28
28
 
@@ -20,6 +20,8 @@ Above the gallery and the purchase column, `BaskleeBreadcrumbs` shows the path t
20
20
 
21
21
  The gallery uses `product.images.full`, falling back to `product.images.small` when empty. On wide screens the thumbnails form a column as tall as the main image beside it; on narrow screens they form a row below it. The strip has no scrollbar: when more thumbnails exist than fit, arrow buttons at its ends move it by one thumbnail, and each button disappears at the first or last position. The selected thumbnail has a dark border and scrolls into view when the photo changes. The thumbnails are one keyboard stop: arrow keys select the previous or next photo, Home and End the first and last. The previous and next buttons over the main image cycle through the photos. A tap, click or Enter on the main image opens the photos in `ProductReviewImageViewer`; the photo chosen there stays selected on the page.
22
22
 
23
+ The product's videos (`product.videos`, uploaded on the Video tab of the panel) follow the photos in the same gallery, in the order the backend sends them; a video without a file is left out. A video's thumbnail shows its `preview` frame under a round play mark and is labelled Product video. Choosing it puts a `<video>` with the browser's controls in the main image's place (`preload="metadata"`, `playsinline`, the preview as the poster, never playing by itself); choosing another item stops it. The previous and next buttons, swipes and thumbnail keys go through photos and videos alike; the full-screen viewer shows the photos only. A product with a video and no photo shows the gallery with that video.
24
+
23
25
  On wide screens the gallery and the purchase column end at the same height: the taller of the two sets it, and the photo area takes the whole height with the photo centred in it at its own proportions, never stretched or cropped. When the purchase column is short, the photo area keeps a height that still shows the photo.
24
26
 
25
27
  Beside the gallery, the purchase column keeps its place in the layout and scrolls with the page. It shows the product name and, when `feedback_stat.c_feedbacks` is positive, the average `feedback_stat.avg_raiting` with the review count as a link to the reviews section. Below it, `ProductCard` in `details` mode shows the badges and price, then About this product and Characteristics, then the selected main variant as “variant name: value”, the variant choices, the stock notice and the actions. Changing the variant updates the gallery, heading, description, characteristics and reviews.
@@ -32,6 +34,8 @@ The manufacturer card shows the logo from `manufacture.small_image`, or `manufac
32
34
 
33
35
  The seller card shows `seller.avatar`, `seller.name` and a positive `seller.raiting`. Its link points to `/sellers?seller=` with `seller.id`; selecting it emits `seller`, and the supplied page opens that address. The card is hidden when `init.visual_settings.single_seller_mode` is on.
34
36
 
37
+ Under the reviews, a row of other products, “You may also like”: the products attached to this product on the panel's Relevant Products tab (`related.data` of the returned product, without the product itself, up to eight), in their order. Only a product without attached products shows up to eight more products of its `main_category` (with its public subcategories), asked from `products_search`, and a link to that category's page. Without attached products and without other products of the category the row is not shown; a failed category request leaves it off the page. The row's cards use the same purchase, wishlist, availability and preorder actions as the product; selecting a card opens that product's page. The logic is in `app/composables/useBaskleeRelatedProducts.ts` and `app/utils/basklee/relatedProducts.ts`.
38
+
35
39
  After client-side navigation, until the product arrives, the component shows a placeholder with the page layout: gallery frame, thumbnails, name, price, description, characteristics, variants and button. The page keeps its height, the section has `aria-busy` and a hidden status announces loading. A failed request replaces the placeholder with the error notice and Retry.
36
40
 
37
41
  When the selected product endpoint succeeds but returns no product with this ID, the server render of the supplied page answers HTTP 404; after client-side navigation the component emits `missing` and shows the unavailable state. `products_search` returns an empty list both for an unknown ID and for a product that is not published. A failed request, including an invalid preview key, is not a missing product: the error notice keeps Retry. The supplied `app/pages/product/[id].vue` opens the storefront 404 page on `missing` through `useBaskleeMissingPage()`.
@@ -8,6 +8,7 @@
8
8
  watch,
9
9
  } from 'vue';
10
10
  import { NuxtLink } from '#components';
11
+ import { navigateTo } from '#imports';
11
12
  import { useBaskleeStore } from '@/stores/basklee';
12
13
  import { useBaskleeProductsStore } from '@/stores/baskleeProducts';
13
14
  import { useBaskleeCatalogStore } from '@/stores/baskleeCatalog';
@@ -18,6 +19,8 @@
18
19
  } from '@/composables/useBaskleeFeature';
19
20
  import { useBaskleeProductActions } from '@/composables/useBaskleeProductActions';
20
21
  import { useBaskleeProductVariants } from '@/composables/useBaskleeProductVariants';
22
+ import { useBaskleeRelatedProducts } from '@/composables/useBaskleeRelatedProducts';
23
+ import { relatedProductsLabels } from '@/utils/basklee/relatedProducts';
21
24
  import { reviewLabels } from '@/utils/basklee/reviewLabels';
22
25
  import { featureLabels } from '@/utils/basklee/featureLabels';
23
26
  import { productLabels } from '@/utils/basklee/productLabels';
@@ -31,6 +34,7 @@
31
34
  import { safeArticleHtml } from '@/utils/basklee/richText';
32
35
  import { htmlTextParagraphs } from '@/utils/basklee/htmlText';
33
36
  import {
37
+ productMediaItems,
34
38
  thumbnailKeyTarget,
35
39
  thumbnailRailEdges,
36
40
  thumbnailScrollTarget,
@@ -54,6 +58,7 @@
54
58
  IProductSpecificationRow,
55
59
  } from '@/interfaces/basklee/products/IProductSpecification';
56
60
  import ProductCard from '@/components/basklee/products/ProductCard.vue';
61
+ import ProductGroup from '@/components/basklee/products/ProductGroup.vue';
57
62
  import ProductReviews from '@/components/basklee/products/ProductReviews.vue';
58
63
  import ProductPreorderDialog from '@/components/basklee/products/ProductPreorderDialog.vue';
59
64
  import ProductSpecificationsDialog from '@/components/basklee/products/ProductSpecificationsDialog.vue';
@@ -174,6 +179,13 @@
174
179
  const images = product.value?.images;
175
180
  return images?.full?.length ? images.full : (images?.small ?? []);
176
181
  });
182
+ // The gallery: the photos, then the product's videos (Video tab of the
183
+ // panel). A video plays in the large photo's place; the full-screen viewer
184
+ // keeps to the photos, which come first, so their numbers are the same.
185
+ const media = computed(() => productMediaItems(product.value));
186
+ const current = computed(
187
+ () => media.value[image.value] ?? media.value[0],
188
+ );
177
189
  // The first request in the browser shows a placeholder with the page
178
190
  // layout; a later retry after an error shows it again. A product loaded
179
191
  // during the server render is shown at once.
@@ -499,7 +511,7 @@
499
511
  }
500
512
 
501
513
  function showImage(index: number) {
502
- const count = photos.value.length;
514
+ const count = media.value.length;
503
515
  image.value = (index + count) % count;
504
516
  }
505
517
 
@@ -526,7 +538,7 @@
526
538
  showImage(
527
539
  productPhotoAfterSwipe(
528
540
  image.value,
529
- photos.value.length,
541
+ media.value.length,
530
542
  touch.clientX - start.x,
531
543
  touch.clientY - start.y,
532
544
  ),
@@ -637,7 +649,7 @@
637
649
 
638
650
  // Arrow keys, Home and End move between thumbnails, which form one tab stop.
639
651
  function thumbnailKeydown(event: KeyboardEvent, index: number) {
640
- const target = thumbnailKeyTarget(event.key, index, photos.value.length);
652
+ const target = thumbnailKeyTarget(event.key, index, media.value.length);
641
653
 
642
654
  if (target === undefined) {
643
655
  return;
@@ -697,6 +709,18 @@
697
709
  currentId.value = selection.variant.product.id;
698
710
  image.value = 0;
699
711
  }
712
+ // The row under the product: the products attached on the panel's
713
+ // «Relevant Products» tab first, else more of the product's category.
714
+ const related = useBaskleeRelatedProducts({ api, product });
715
+ const relatedLabels = computed(() =>
716
+ relatedProductsLabels(selectionStore.localeCode),
717
+ );
718
+ function openRelated(item: IProduct) {
719
+ void navigateTo({
720
+ path: `/product/${item.id}`,
721
+ query: { locale: selectionStore.localeCode },
722
+ });
723
+ }
700
724
  onMounted(() => {
701
725
  mounted.value = true;
702
726
  if (!confirmed.value) {
@@ -768,7 +792,7 @@
768
792
  revealThumbnail(index);
769
793
  });
770
794
  // Another variant's photos start from the first thumbnail.
771
- watch(photos, async () => {
795
+ watch(media, async () => {
772
796
  await nextTick();
773
797
 
774
798
  if (rail.value) {
@@ -824,20 +848,41 @@
824
848
  class="grid items-start gap-8 @min-[960px]/product:grid-cols-[minmax(0,7fr)_minmax(0,5fr)] @min-[960px]/product:items-stretch @min-[960px]/product:gap-x-12 @min-[1200px]/product:gap-x-20"
825
849
  >
826
850
  <section
827
- v-if="photos.length"
851
+ v-if="media.length"
828
852
  class="grid min-w-0 gap-3 @min-[560px]/product:grid-cols-[72px_minmax(0,1fr)] @min-[560px]/product:gap-4 @min-[960px]/product:col-start-1 @min-[960px]/product:row-start-1"
829
853
  :aria-label="labels.gallery"
830
854
  data-product-gallery
831
855
  >
832
856
  <div
833
857
  class="relative min-w-0 @min-[560px]/product:col-start-2 @min-[560px]/product:row-start-1 @min-[960px]/product:min-h-96"
834
- :class="{ 'touch-pan-y': photos.length > 1 }"
858
+ :class="{ 'touch-pan-y': media.length > 1 }"
835
859
  data-product-main-image
836
860
  @touchstart.passive="startSwipe"
837
861
  @touchend="endSwipe"
838
862
  >
863
+ <video
864
+ v-if="current?.kind === 'video'"
865
+ :key="current.key"
866
+ :src="current.src"
867
+ :poster="current.preview || undefined"
868
+ :aria-label="labels.productVideo"
869
+ controls
870
+ playsinline
871
+ preload="metadata"
872
+ data-product-video
873
+ class="
874
+ box-border aspect-square h-auto max-h-[70vh] w-full
875
+ bg-basklee-surface object-contain
876
+ @min-[560px]/product:aspect-[4/5]
877
+ @min-[960px]/product:absolute @min-[960px]/product:inset-0
878
+ @min-[960px]/product:m-auto @min-[960px]/product:aspect-auto
879
+ @min-[960px]/product:h-full
880
+ @min-[960px]/product:max-h-[calc(100vh-12rem)]
881
+ "
882
+ />
839
883
  <BaskleeImage
840
- :src="photos[image]"
884
+ v-else-if="current"
885
+ :src="current.src"
841
886
  :alt="title"
842
887
  :width="800"
843
888
  :height="1000"
@@ -861,7 +906,7 @@
861
906
  @min-[960px]/product:max-h-[calc(100vh-12rem)]
862
907
  "
863
908
  />
864
- <template v-if="photos.length > 1">
909
+ <template v-if="media.length > 1">
865
910
  <button
866
911
  type="button"
867
912
  class="absolute left-2 top-1/2 -translate-y-1/2 grid h-10 w-10 place-items-center rounded-full p-0 cursor-pointer border border-solid border-basklee-border bg-basklee-surface/90 text-basklee-text outline-none transition-colors motion-reduce:transition-none hover:border-basklee-text focus-visible:border-basklee-text"
@@ -901,7 +946,7 @@
901
946
  </template>
902
947
  </div>
903
948
  <div
904
- v-if="photos.length > 1"
949
+ v-if="media.length > 1"
905
950
  class="relative min-w-0 @min-[560px]/product:col-start-1 @min-[560px]/product:row-start-1 @min-[560px]/product:h-0 @min-[560px]/product:min-h-full"
906
951
  data-product-thumbnail-rail
907
952
  >
@@ -912,27 +957,45 @@
912
957
  @scroll.passive="updateRail"
913
958
  >
914
959
  <button
915
- v-for="(photo, index) in photos"
916
- :key="photo"
960
+ v-for="(item, index) in media"
961
+ :key="item.key"
917
962
  type="button"
918
- class="box-border h-[70px] w-14 shrink-0 p-1 @min-[560px]/product:h-[90px] @min-[560px]/product:w-[72px] cursor-pointer border border-solid bg-basklee-surface outline-none transition-[opacity,border-color] motion-reduce:transition-none hover:opacity-100 focus-visible:border-2 focus-visible:border-basklee-text"
963
+ class="relative box-border h-[70px] w-14 shrink-0 p-1 @min-[560px]/product:h-[90px] @min-[560px]/product:w-[72px] cursor-pointer border border-solid bg-basklee-surface outline-none transition-[opacity,border-color] motion-reduce:transition-none hover:opacity-100 focus-visible:border-2 focus-visible:border-basklee-text"
919
964
  :class="
920
965
  index === image
921
966
  ? 'border-basklee-text opacity-100'
922
967
  : 'border-transparent opacity-75'
923
968
  "
924
- :aria-label="`${labels.gallery} ${index + 1}`"
969
+ :aria-label="`${item.kind === 'video' ? labels.productVideo : labels.gallery} ${index + 1}`"
925
970
  :aria-pressed="index === image"
926
971
  :tabindex="index === image ? 0 : -1"
927
972
  :data-product-thumbnail="index"
973
+ :data-product-thumbnail-video="item.kind === 'video' || undefined"
928
974
  @click="image = index"
929
975
  @keydown="thumbnailKeydown($event, index)"
930
976
  >
931
977
  <BaskleeImage
932
- :src="photo"
978
+ v-if="item.kind === 'image' || item.preview"
979
+ :src="item.kind === 'image' ? item.src : (item.preview as string)"
933
980
  alt=""
934
- class="h-full w-full object-contain"
981
+ class="h-full w-full"
982
+ :class="item.kind === 'image' ? 'object-contain' : 'object-cover'"
935
983
  />
984
+ <span
985
+ v-if="item.kind === 'video'"
986
+ class="absolute inset-0 m-auto grid h-7 w-7 place-items-center rounded-full bg-basklee-text/80 text-basklee-surface"
987
+ aria-hidden="true"
988
+ data-product-video-mark
989
+ >
990
+ <svg
991
+ viewBox="0 0 24 24"
992
+ class="ml-0.5 h-3.5 w-3.5"
993
+ fill="currentColor"
994
+ aria-hidden="true"
995
+ >
996
+ <path d="M8 5v14l11-7z" />
997
+ </svg>
998
+ </span>
936
999
  </button>
937
1000
  </div>
938
1001
  <button
@@ -1334,6 +1397,43 @@
1334
1397
  :product-id="currentId"
1335
1398
  />
1336
1399
  </div>
1400
+ <section
1401
+ v-if="related.productIds.value.length"
1402
+ class="mt-14 pt-10 border-0 border-t border-solid border-basklee-border @min-[592px]/product:mt-20"
1403
+ :aria-label="relatedLabels.title"
1404
+ data-product-related
1405
+ >
1406
+ <header class="mb-6 flex flex-wrap items-baseline justify-between gap-x-6 gap-y-2">
1407
+ <h2 class="m-0 text-xl font-semibold text-basklee-text">
1408
+ {{ relatedLabels.title }}
1409
+ </h2>
1410
+ <NuxtLink
1411
+ v-if="related.categoryId.value"
1412
+ :to="{
1413
+ path: `/category/${related.categoryId.value}`,
1414
+ query: { locale: selectionStore.localeCode },
1415
+ }"
1416
+ class="text-sm text-basklee-text underline underline-offset-4"
1417
+ data-product-related-category
1418
+ >
1419
+ {{ relatedLabels.category }}
1420
+ </NuxtLink>
1421
+ </header>
1422
+ <ProductGroup
1423
+ :product-ids="related.productIds.value"
1424
+ :disabled="actions.pending.value || actions.needsRefresh.value"
1425
+ @select="openRelated"
1426
+ @select-seller="emit('seller', $event)"
1427
+ @select-variant="variants.select"
1428
+ @request-secondary-variants="variants.requestSecondary"
1429
+ @toggle-favorite="actions.run('toggleFavorite', $event)"
1430
+ @add="actions.run('add', $event)"
1431
+ @remove="actions.run('remove', $event)"
1432
+ @subscribe="actions.run('subscribe', $event)"
1433
+ @unsubscribe="actions.run('unsubscribe', $event)"
1434
+ @preorder="actions.openPreorder"
1435
+ />
1436
+ </section>
1337
1437
  <ProductPreorderDialog
1338
1438
  :product-id="actions.preorder.value"
1339
1439
  :pending="actions.pending.value"
@@ -25,7 +25,8 @@ After confirmed authentication changes, refresh Application Load to replace the
25
25
  session, profile, wallet and live endpoint discovery. When a request answers
26
26
  HTTP 401 during a signed-in session, the shared API client removes the profile
27
27
  and wallet from the store at once and reloads Application Load for the guest
28
- session; the button shows Login again and no dialog opens.
28
+ session; the button shows Login again, and the sign-in page opens with the
29
+ current page as its return address.
29
30
 
30
31
  The authenticated name comes from `store.profile`; missing names use Profile.
31
32
  The wallet reads only the selected currency's backend-converted amount. Zero
@@ -1,4 +1,5 @@
1
1
  import {
2
+ navigateTo,
2
3
  useNuxtApp,
3
4
  usePinia,
4
5
  useRequestFetch,
@@ -10,6 +11,7 @@ import { useBaskleeStore } from '@/stores/basklee';
10
11
  import { useBaskleeSelectionsStore } from '@/stores/baskleeSelections';
11
12
  import { useBaskleeAppLoad } from '@/composables/useBaskleeAppLoad';
12
13
  import { BaskleeApi } from '@/utils/basklee/api';
14
+ import { signInPageLocation } from '@/utils/basklee/signInReturn';
13
15
  import type {
14
16
  BaskleeApiRequest,
15
17
  BaskleeApiResponse,
@@ -149,10 +151,18 @@ function createClients(): BaskleeClients {
149
151
  browser: new BaskleeApi({
150
152
  ...shared,
151
153
  canRequest: () => import.meta.client,
152
- // HTTP 401 ended the customer's session: show the guest storefront.
153
- // This never opens sign-in and never repeats the failed request.
154
- onSessionEnded: () =>
155
- nuxt.runWithContext(() => useBaskleeAppLoad().endSession()),
154
+ // HTTP 401: the request needs a signed-in customer. An ended session
155
+ // shows the guest storefront at once; then the sign-in page opens and
156
+ // returns to this page afterwards. The failed request is not repeated.
157
+ onUnauthorized: (signedIn) =>
158
+ nuxt.runWithContext(() => {
159
+ const ending = signedIn
160
+ ? useBaskleeAppLoad().endSession()
161
+ : undefined;
162
+ openSignInAfterUnauthorized(nuxt, store.localeCode);
163
+
164
+ return ending;
165
+ }),
156
166
  }),
157
167
  // Page data that the server render awaits; see useBaskleeServerData.
158
168
  // A failed server request leaves the page to the browser, which loads
@@ -161,6 +171,24 @@ function createClients(): BaskleeClients {
161
171
  };
162
172
  }
163
173
 
174
+ /*
175
+ * After HTTP 401 the visitor goes to the /profile sign-in page with this page
176
+ * in `redirect`, for example `/profile?locale=en&redirect=/orders?locale=en`.
177
+ * The sign-in page itself and /logout stay where they are: /profile already
178
+ * shows the form, and logging out should not ask for sign-in.
179
+ */
180
+ function openSignInAfterUnauthorized(
181
+ nuxt: ReturnType<typeof useNuxtApp>,
182
+ locale: string,
183
+ ) {
184
+ const route = nuxt.$router.currentRoute.value;
185
+ if (route.path === '/profile' || route.path === '/logout') {
186
+ return;
187
+ }
188
+
189
+ void navigateTo(signInPageLocation(route.fullPath, locale));
190
+ }
191
+
164
192
  function useBaskleeClients() {
165
193
  const nuxt = useNuxtApp();
166
194
  const existing = clients.get(nuxt);
@@ -0,0 +1,125 @@
1
+ import { computed, onScopeDispose, ref, toValue, watch } from 'vue';
2
+ import type { MaybeRefOrGetter } from 'vue';
3
+ import { useBaskleeProductsStore } from '@/stores/baskleeProducts';
4
+ import { useBaskleeCatalogStore } from '@/stores/baskleeCatalog';
5
+ import type { BaskleeApi } from '@/utils/basklee/api';
6
+ import {
7
+ attachedRelatedProducts,
8
+ relatedCategoryId,
9
+ relatedCategoryProducts,
10
+ relatedCategoryRequest,
11
+ } from '@/utils/basklee/relatedProducts';
12
+ import type {
13
+ IProduct,
14
+ IProductSearchSeller,
15
+ } from '@/interfaces/basklee/products/IProduct';
16
+
17
+ /*
18
+ * The products of the row under a product page (utils/basklee/relatedProducts.ts):
19
+ * the products attached on the panel's «Relevant Products» tab first, else
20
+ * more of the product's main category. The products go into the product
21
+ * store, so the row's cards read them like every other card. A failed
22
+ * category request leaves the row off the page.
23
+ */
24
+ export function useBaskleeRelatedProducts(options: {
25
+ api: Pick<BaskleeApi, 'request'>;
26
+ product: MaybeRefOrGetter<IProduct | undefined>;
27
+ }) {
28
+ const productStore = useBaskleeProductsStore();
29
+ const catalogStore = useBaskleeCatalogStore();
30
+ const categoryIds = ref<number[]>([]);
31
+ const pending = ref(false);
32
+ let request: AbortController | undefined;
33
+
34
+ const attached = computed(() =>
35
+ attachedRelatedProducts(toValue(options.product)),
36
+ );
37
+ const categoryId = computed(() =>
38
+ relatedCategoryId(toValue(options.product)),
39
+ );
40
+ const productIds = computed(() =>
41
+ attached.value.length
42
+ ? attached.value.map((item) => item.id)
43
+ : categoryIds.value,
44
+ );
45
+
46
+ function cancel() {
47
+ request?.abort();
48
+ request = undefined;
49
+ pending.value = false;
50
+ }
51
+
52
+ async function loadCategory(category: number, productId: number) {
53
+ cancel();
54
+ categoryIds.value = [];
55
+ if (!category) {
56
+ return;
57
+ }
58
+ const current = new AbortController();
59
+ request = current;
60
+ pending.value = true;
61
+ try {
62
+ const data = await options.api.request<{
63
+ products?: { data?: IProduct[] };
64
+ selects?: { sellers?: IProductSearchSeller[] };
65
+ }>(
66
+ 'products_search',
67
+ relatedCategoryRequest(category, catalogStore.catalog),
68
+ current.signal,
69
+ );
70
+ if (current.signal.aborted) {
71
+ return;
72
+ }
73
+ const items = relatedCategoryProducts(data.products?.data, productId);
74
+ for (const item of items) {
75
+ productStore.setProduct(item, 'products', data.selects?.sellers ?? []);
76
+ }
77
+ categoryIds.value = items.map((item) => item.id);
78
+ } catch {
79
+ // The row stays off the page; the next visit of the page asks again.
80
+ } finally {
81
+ if (request === current) {
82
+ request = undefined;
83
+ pending.value = false;
84
+ }
85
+ }
86
+ }
87
+
88
+ watch(
89
+ attached,
90
+ (items) => {
91
+ for (const item of items) {
92
+ if (!productStore.getProduct(item.id)) {
93
+ productStore.setProduct(item, 'products');
94
+ }
95
+ }
96
+ },
97
+ { immediate: true },
98
+ );
99
+ watch(
100
+ () => [categoryId.value, toValue(options.product)?.id ?? 0] as const,
101
+ ([category, productId], previous) => {
102
+ if (
103
+ previous &&
104
+ previous[0] === category &&
105
+ previous[1] === productId
106
+ ) {
107
+ return;
108
+ }
109
+ if (import.meta.client) {
110
+ void loadCategory(category, productId);
111
+ }
112
+ },
113
+ { immediate: true },
114
+ );
115
+ onScopeDispose(cancel);
116
+
117
+ return {
118
+ productIds,
119
+ /** The category the row comes from, or 0 for attached products. */
120
+ categoryId: computed(() =>
121
+ attached.value.length ? 0 : categoryId.value,
122
+ ),
123
+ pending,
124
+ };
125
+ }
@@ -25,8 +25,8 @@ export function provideBaskleeSignIn(handler: BaskleeSignInHandler) {
25
25
  * A guest who clicks an action that needs an account (a review, a reaction,
26
26
  * a favorite, a plan subscription) goes straight to the /profile sign-in page,
27
27
  * which returns to `redirect` afterwards. Call requireSignIn() only from the
28
- * visitor's own click: background requests and an ended session never
29
- * navigate.
28
+ * visitor's own click. A request that answers HTTP 401 opens the same page
29
+ * through the shared API client (see useBaskleeApi).
30
30
  */
31
31
  export function useBaskleeSignIn() {
32
32
  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 '@/utils/basklee/category';
2
+ import type { ICategory } from '@/interfaces/basklee/category/ICategory';
3
+ import type { IProduct } from '@/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',
@@ -1480,7 +1480,9 @@ heart, an availability notification, Checkout in the cart, a plan's Subscribe
1480
1480
  or Try, an event) opens `/profile?locale=<locale>&redirect=<current page>` at
1481
1481
  once through `useBaskleeSignIn().requireSignIn()` in
1482
1482
  `app/composables/useBaskleeSignIn.ts`, with no separate sign-in notice.
1483
- Background requests and an ended session never navigate.
1483
+ A request that answers HTTP 401 opens the same address: the shared API client
1484
+ ends a signed-in session first (the guest storefront shows at once), and the
1485
+ sign-in page returns to the page afterwards; `/profile` and `/logout` stay put.
1484
1486
  Account pages (`/orders`, `/wallet`, `/addresses`, `/subscriptions`, `/tickets`,
1485
1487
  `/activity`, `/wishlist`) declare the `basklee-account` route middleware in
1486
1488
  `app/middleware/basklee-account.ts`: after Application Load confirms a guest