basklee-react 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
@@ -199,7 +199,7 @@ Product details, saved items and the cart.
199
199
 
200
200
  | Component | Name | What it does |
201
201
  | --- | --- | --- |
202
- | **Product details** | `StorefrontProduct` | Loads and displays a published product or a secret-key preview with images, purchase choices, details and reviews. |
202
+ | **Product details** | `StorefrontProduct` | Loads and displays a published product or a secret-key preview with images and videos, purchase choices, details and reviews. |
203
203
  | **Page path** | `BaskleeBreadcrumbs` | Linked path from the storefront home page through parent categories to the current page. |
204
204
  | **Product characteristics** | `ProductSpecificationsDialog` | Every characteristic of the product in a dialog over the page. |
205
205
  | **Product reviews** | `ProductReviews` | Reviews, replies, ratings and the user’s submissions. |
@@ -569,7 +569,9 @@ When a request returns HTTP `401` while the store is signed in, the shared API
569
569
  client clears profile, wallet, authenticated discovery, cart and wishlist counters
570
570
  and account fields of cached products, then reloads Application Load as a guest.
571
571
  Public data and the current selections remain available during that refresh.
572
- The failed request is not repeated and no sign-in dialog opens automatically.
572
+ Every `401` (also a guest's) then opens `/profile?locale=<locale>&redirect=<current page>`,
573
+ which returns to the page after sign-in; on `/profile` and `/logout` the page
574
+ stays. The failed request is not repeated.
573
575
 
574
576
  ## Update an existing project
575
577
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "basklee-react",
3
- "version": "0.9.9",
3
+ "version": "0.9.11",
4
4
  "description": "Next.js 16 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",
@@ -272,7 +272,8 @@ client navigation and the selected language.
272
272
 
273
273
  A signed-in request that receives HTTP \`401\` removes private account values and
274
274
  refreshes Application Load as a guest while retaining public data and selections.
275
- The failed request is not repeated and no sign-in dialog opens automatically.
275
+ Every \`401\` then opens the \`/profile\` sign-in page, which returns to the current
276
+ page after sign-in. The failed request is not repeated.
276
277
 
277
278
  ### Session and CSRF cookies
278
279
 
@@ -11,6 +11,7 @@ import { selectInit } from '@/stores/basklee';
11
11
  import { useBaskleeApi } from '@/hooks/useBaskleeApi';
12
12
  import { useBaskleeStorefront } from '@/hooks/useBaskleeStorefront';
13
13
  import { useBaskleeReviews } from '@/hooks/useBaskleeReviews';
14
+ import { useBaskleeRelatedProducts } from '@/hooks/useBaskleeRelatedProducts';
14
15
  import { requestProductPage } from '@/lib/basklee/productPage';
15
16
  import { useStorefrontNavigation } from '@/app/_storefront/useStorefrontNavigation';
16
17
  import styles from '@/app/storefront.module.css';
@@ -42,6 +43,8 @@ export function ProductPage({
42
43
  });
43
44
  const [metadataProduct, setMetadataProduct] = useState(initialProduct);
44
45
  const [missing, setMissing] = useState(false);
46
+ // The row under the product: attached products first, else its category.
47
+ const related = useBaskleeRelatedProducts(metadataProduct);
45
48
  useEffect(() => {
46
49
  setMetadataProduct(initialProduct);
47
50
  setMissing(false);
@@ -71,6 +74,13 @@ export function ProductPage({
71
74
  actionPending={controls.productActionsDisabled}
72
75
  profileHref={navigation.href('/profile')}
73
76
  reviewProps={reviews}
77
+ relatedProductIds={related.productIds}
78
+ relatedCategoryHref={
79
+ related.categoryId
80
+ ? navigation.href(`/category/${related.categoryId}`)
81
+ : undefined
82
+ }
83
+ productHref={(id) => navigation.href(`/product/${id}`)}
74
84
  onLoad={(action) =>
75
85
  requestProductPage(api, productId, previewKey, action.signal)
76
86
  }
@@ -29,6 +29,16 @@ select the first and last. A tap, click or Enter on the main image opens the
29
29
  photos in `ProductReviewImageViewer`; the photo chosen there stays selected.
30
30
  Every image reserves display space while it loads.
31
31
 
32
+ The product's videos (`product.videos`, uploaded on the Video tab of the
33
+ panel) follow the photos in the same gallery, in the order the backend sends
34
+ them; a video without a file is left out. A video's thumbnail shows its
35
+ `preview` frame under a round play mark and is labelled Product video.
36
+ Choosing it puts a `<video>` with the browser's controls in the main image's
37
+ place (`preload="metadata"`, `playsInline`, the preview as the poster, never
38
+ playing by itself); choosing another item stops it. The previous and next
39
+ controls, swipes and thumbnail keys go through photos and videos alike; the
40
+ full-screen viewer shows the photos only.
41
+
32
42
  The localized product description is rendered as safe plain paragraphs on the
33
43
  server and sanitized editor HTML in the browser. Long descriptions collapse
34
44
  behind More. Characteristics include the manufacturer, positive weight, all
@@ -37,6 +47,14 @@ groups. The current weight and length selections choose the displayed units.
37
47
  A list that exceeds its reserved space opens every row in
38
48
  `ProductSpecificationsDialog`.
39
49
 
50
+ Under the reviews, `relatedProductIds` shows the row “You may also like” with
51
+ the same card events; `relatedCategoryHref` adds a link to the category page
52
+ and `productHref` gives the cards their links. `useBaskleeRelatedProducts` in
53
+ `hooks/useBaskleeRelatedProducts.ts` gives both values: the products attached
54
+ on the panel's Relevant Products tab (`related.data`, without the product
55
+ itself, up to eight), and only without them up to eight more products of the
56
+ product's `main_category` from `products_search`. An empty list hides the row.
57
+
40
58
  The details card forwards cart, wishlist, availability and variant events
41
59
  through the matching `onAdd`, `onRemove`, `onToggleFavorite`, `onSubscribe`,
42
60
  `onUnsubscribe`, `onRequestSecondaryVariants`, `onSelectVariant` and
@@ -81,6 +99,9 @@ contract is in `interfaces/basklee/products/IProduct.ts`.
81
99
  | `needsRefresh?: boolean` | Shows that the surrounding data must be loaded again. |
82
100
  | `profileHref?: string` | Destination used by the profile link. |
83
101
  | `reviewProps?: Omit<ProductReviewsProps, "productId">` | Props forwarded to the review child component. |
102
+ | `relatedProductIds?: number[]` | Products of the row under the reviews; empty hides it. |
103
+ | `relatedCategoryHref?: string` | Category page linked from that row. |
104
+ | `productHref?: ProductCardProps["productHref"]` | Address of a product of that row. |
84
105
  | `onLoad?: (action: ProductPageLoadAction) => Promise<IProduct \| undefined> \| IProduct \| undefined` | Called when the component needs its primary data. The callback payload is shown in its type. |
85
106
  | `onLoaded?: (product: IProduct) => void` | Called when the requested data loads successfully. The callback payload is shown in its type. |
86
107
  | `onMissing?: () => void` | Called when the requested public record does not exist. The callback has no payload. |
@@ -119,6 +140,14 @@ contract is in `interfaces/basklee/products/IProduct.ts`.
119
140
  а «Повторить» отправляет тот же запрос. `onLoaded` получает показанный товар,
120
141
  включая загруженный вариант.
121
142
 
143
+ Под отзывами `relatedProductIds` показывает ряд «Вам может понравиться» с теми же
144
+ событиями карточек; `relatedCategoryHref` добавляет ссылку на страницу
145
+ категории, а `productHref` даёт карточкам ссылки. Оба значения даёт
146
+ `useBaskleeRelatedProducts` из `hooks/useBaskleeRelatedProducts.ts`: товары,
147
+ прикреплённые на вкладке «Релевантные товары» панели (`related.data`, без самого
148
+ товара, до восьми), и только без них — до восьми других товаров его
149
+ `main_category` из `products_search`. Пустой список скрывает ряд.
150
+
122
151
  Галерея использует полные изображения, а при их отсутствии — малые. Кнопки
123
152
  вперёд и назад переходят по кругу. Лента миниатюр прокручивается только тогда,
124
153
  когда изображения не помещаются. Клавиши со стрелками выбирают соседнее фото,
@@ -181,6 +210,9 @@ Home и End — первое и последнее. Нажатие, щелчок
181
210
  | `needsRefresh?: boolean` | Показывает, что внешние данные нужно загрузить заново. |
182
211
  | `profileHref?: string` | Адрес ссылки профиля. |
183
212
  | `reviewProps?: Omit<ProductReviewsProps, "productId">` | Свойства, передаваемые дочернему компоненту отзывов. |
213
+ | `relatedProductIds?: number[]` | Товары ряда под отзывами; пустой список скрывает его. |
214
+ | `relatedCategoryHref?: string` | Страница категории, на которую ведёт ряд. |
215
+ | `productHref?: ProductCardProps["productHref"]` | Адрес товара этого ряда. |
184
216
  | `onLoad?: (action: ProductPageLoadAction) => Promise<IProduct \| undefined> \| IProduct \| undefined` | Вызывается, когда компоненту нужны основные данные. Данные обработчика указаны в его типе. |
185
217
  | `onLoaded?: (product: IProduct) => void` | Вызывается, когда запрошенные данные успешно загружены. Данные обработчика указаны в его типе. |
186
218
  | `onMissing?: () => void` | Вызывается, когда запрошенная общедоступная запись не существует. Обработчик не получает данные. |
@@ -204,6 +204,7 @@
204
204
  }
205
205
 
206
206
  .thumbnail {
207
+ position: relative;
207
208
  box-sizing: border-box;
208
209
  flex: 0 0 56px;
209
210
  width: 56px;
@@ -239,6 +240,35 @@
239
240
  object-fit: contain;
240
241
  }
241
242
 
243
+ /* A product video: it plays in the large photo's place, its thumbnail shows
244
+ the preview frame under a round play mark. */
245
+ .mainVideo {
246
+ cursor: auto;
247
+ }
248
+
249
+ .thumbnailPreview {
250
+ object-fit: cover;
251
+ }
252
+
253
+ .videoMark {
254
+ position: absolute;
255
+ inset: 0;
256
+ display: grid;
257
+ width: 28px;
258
+ height: 28px;
259
+ margin: auto;
260
+ place-items: center;
261
+ border-radius: 9999px;
262
+ background: color-mix(in srgb, var(--basklee-text) 80%, transparent);
263
+ color: var(--basklee-surface);
264
+ }
265
+
266
+ .videoMark svg {
267
+ width: 14px;
268
+ height: 14px;
269
+ margin-left: 2px;
270
+ }
271
+
242
272
  .railArrow {
243
273
  position: absolute;
244
274
  top: 50%;
@@ -765,3 +795,41 @@
765
795
  animation: none;
766
796
  }
767
797
  }
798
+
799
+ /* The row under the reviews: «You may also like». */
800
+ .related {
801
+ margin-top: 56px;
802
+ padding-top: 40px;
803
+ border-top: 1px solid var(--basklee-border);
804
+ }
805
+
806
+ .relatedHead {
807
+ display: flex;
808
+ flex-wrap: wrap;
809
+ align-items: baseline;
810
+ justify-content: space-between;
811
+ gap: 8px 24px;
812
+ margin-bottom: 24px;
813
+ }
814
+
815
+ .relatedHead h2 {
816
+ margin: 0;
817
+ color: var(--basklee-text);
818
+ font-size: 1.25rem;
819
+ line-height: 1.75rem;
820
+ font-weight: 600;
821
+ }
822
+
823
+ .relatedHead a {
824
+ color: var(--basklee-text);
825
+ font-size: 0.875rem;
826
+ line-height: 1.25rem;
827
+ text-decoration: underline;
828
+ text-underline-offset: 4px;
829
+ }
830
+
831
+ @container product (min-width: 592px) {
832
+ .related {
833
+ margin-top: 80px;
834
+ }
835
+ }
@@ -33,6 +33,7 @@ import { featureLabels } from '@/lib/basklee/featureLabels';
33
33
  import { htmlTextParagraphs } from '@/lib/basklee/htmlText';
34
34
  import { productActionLabels } from '@/lib/basklee/productActionLabels';
35
35
  import {
36
+ productMediaItems,
36
37
  productThumbnailKeyTarget,
37
38
  productThumbnailRailEdges,
38
39
  productThumbnailScrollTarget,
@@ -58,6 +59,8 @@ import { BaskleeBreadcrumbs } from '@/components/basklee/shared/BaskleeBreadcrum
58
59
  import { BaskleeEmptyState } from '@/components/basklee/shared/BaskleeEmptyState';
59
60
  import { BaskleeImage } from '@/components/basklee/shared/BaskleeImage';
60
61
  import { ProductCard, type ProductCardProps } from './ProductCard';
62
+ import { ProductGroup } from './ProductGroup';
63
+ import { relatedProductsLabels } from '@/lib/basklee/relatedProducts';
61
64
  import {
62
65
  ProductPreorderDialog,
63
66
  type ProductPreorderSelection,
@@ -115,6 +118,16 @@ export interface StorefrontProductProps extends CardCallbacks {
115
118
  needsRefresh?: boolean;
116
119
  profileHref?: string;
117
120
  reviewProps?: Omit<ProductReviewsProps, 'productId'>;
121
+ /**
122
+ * The row under the reviews, «You may also like»: the products attached on
123
+ * the panel's Relevant Products tab, else more of the product's category
124
+ * (`useBaskleeRelatedProducts` in hooks/useBaskleeRelatedProducts.ts).
125
+ */
126
+ relatedProductIds?: number[];
127
+ /** The category page of that row; only when the row comes from it. */
128
+ relatedCategoryHref?: string;
129
+ /** The address of a product of that row. */
130
+ productHref?: ProductCardProps['productHref'];
118
131
  onLoad?: (
119
132
  action: ProductPageLoadAction,
120
133
  ) => Promise<IProduct | undefined> | IProduct | undefined;
@@ -163,6 +176,9 @@ export function StorefrontProduct({
163
176
  needsRefresh = false,
164
177
  profileHref,
165
178
  reviewProps,
179
+ relatedProductIds = [],
180
+ relatedCategoryHref,
181
+ productHref,
166
182
  variantProductIds,
167
183
  onLoad,
168
184
  onLoaded,
@@ -244,6 +260,7 @@ export function StorefrontProduct({
244
260
  const labels = reviewLabels(locale);
245
261
  const common = featureLabels(locale);
246
262
  const cardLabels = productLabels(locale);
263
+ const relatedLabels = relatedProductsLabels(locale);
247
264
  const actionLabels = productActionLabels(locale);
248
265
  const categoryNames = categoryLabels(locale);
249
266
  const product = confirmed
@@ -274,6 +291,11 @@ export function StorefrontProduct({
274
291
  ? Boolean(descriptionHtml)
275
292
  : descriptionText.length > 0;
276
293
  const photos = useMemo(() => productPagePhotos(product), [product]);
294
+ // The gallery: the photos, then the product's videos (Video tab of the
295
+ // panel). A video plays in the large photo's place; the full-screen viewer
296
+ // keeps to the photos, which come first, so their numbers are the same.
297
+ const media = useMemo(() => productMediaItems(product), [product]);
298
+ const current = media[image] ?? media[0];
277
299
  const manufacturer = useMemo(
278
300
  () => productPageManufacturer(product, locale),
279
301
  [product, locale],
@@ -498,7 +520,7 @@ export function StorefrontProduct({
498
520
  updateRail();
499
521
 
500
522
  return () => observer?.disconnect();
501
- }, [photos, updateRail]);
523
+ }, [media, updateRail]);
502
524
 
503
525
  useEffect(() => {
504
526
  const element = descriptionBody.current;
@@ -562,7 +584,7 @@ export function StorefrontProduct({
562
584
  rail.current.scrollLeft = 0;
563
585
  }
564
586
  updateRail();
565
- }, [photos, updateRail]);
587
+ }, [media, updateRail]);
566
588
 
567
589
  const viewerPhotos = useMemo(
568
590
  () => photos.map((photo, id) => ({ id, image: photo })),
@@ -577,8 +599,8 @@ export function StorefrontProduct({
577
599
  }
578
600
 
579
601
  function showImage(index: number) {
580
- if (photos.length) {
581
- setImage((index + photos.length) % photos.length);
602
+ if (media.length) {
603
+ setImage((index + media.length) % media.length);
582
604
  }
583
605
  }
584
606
 
@@ -603,7 +625,7 @@ export function StorefrontProduct({
603
625
  showImage(
604
626
  productPhotoAfterSwipe(
605
627
  image,
606
- photos.length,
628
+ media.length,
607
629
  touch.clientX - start.x,
608
630
  touch.clientY - start.y,
609
631
  ),
@@ -639,7 +661,7 @@ export function StorefrontProduct({
639
661
  event: KeyboardEvent<HTMLButtonElement>,
640
662
  index: number,
641
663
  ) {
642
- const target = productThumbnailKeyTarget(event.key, index, photos.length);
664
+ const target = productThumbnailKeyTarget(event.key, index, media.length);
643
665
  if (target === undefined) {
644
666
  return;
645
667
  }
@@ -886,7 +908,7 @@ export function StorefrontProduct({
886
908
  {product ? (
887
909
  <>
888
910
  <div className={styles.layout}>
889
- {photos.length ? (
911
+ {media.length ? (
890
912
  <section
891
913
  className={styles.gallery}
892
914
  aria-label={labels.gallery}
@@ -894,7 +916,7 @@ export function StorefrontProduct({
894
916
  >
895
917
  <div
896
918
  className={
897
- photos.length > 1
919
+ media.length > 1
898
920
  ? `${styles.mainImage} ${styles.mainImageSwipe}`
899
921
  : styles.mainImage
900
922
  }
@@ -902,21 +924,35 @@ export function StorefrontProduct({
902
924
  onTouchStart={startSwipe}
903
925
  onTouchEnd={endSwipe}
904
926
  >
905
- <BaskleeImage
906
- src={photos[image]}
907
- alt={title}
908
- width={800}
909
- height={1000}
910
- loading="eager"
911
- role="button"
912
- tabIndex={0}
913
- aria-label={labels.openProductPhoto}
914
- data-product-photo-open
915
- onClick={() => setViewerOpen(true)}
916
- onKeyDown={openViewerKey}
917
- className={styles.mainImageAsset}
918
- />
919
- {photos.length > 1 ? (
927
+ {current?.kind === 'video' ? (
928
+ <video
929
+ key={current.key}
930
+ src={current.src}
931
+ poster={current.preview || undefined}
932
+ aria-label={labels.productVideo}
933
+ controls
934
+ playsInline
935
+ preload="metadata"
936
+ data-product-video
937
+ className={`${styles.mainImageAsset} ${styles.mainVideo}`}
938
+ />
939
+ ) : current ? (
940
+ <BaskleeImage
941
+ src={current.src}
942
+ alt={title}
943
+ width={800}
944
+ height={1000}
945
+ loading="eager"
946
+ role="button"
947
+ tabIndex={0}
948
+ aria-label={labels.openProductPhoto}
949
+ data-product-photo-open
950
+ onClick={() => setViewerOpen(true)}
951
+ onKeyDown={openViewerKey}
952
+ className={styles.mainImageAsset}
953
+ />
954
+ ) : null}
955
+ {media.length > 1 ? (
920
956
  <>
921
957
  <button
922
958
  type="button"
@@ -955,7 +991,7 @@ export function StorefrontProduct({
955
991
  </>
956
992
  ) : null}
957
993
  </div>
958
- {photos.length > 1 ? (
994
+ {media.length > 1 ? (
959
995
  <div
960
996
  className={styles.thumbnailRail}
961
997
  data-product-thumbnail-rail
@@ -966,27 +1002,59 @@ export function StorefrontProduct({
966
1002
  data-product-thumbnails
967
1003
  onScroll={updateRail}
968
1004
  >
969
- {photos.map((photo, index) => (
1005
+ {media.map((item, index) => (
970
1006
  <button
971
- key={`${photo}:${index}`}
1007
+ key={item.key}
972
1008
  type="button"
973
1009
  className={`${styles.thumbnail} ${
974
1010
  index === image ? styles.thumbnailSelected : ''
975
1011
  }`}
976
- aria-label={`${labels.gallery} ${index + 1}`}
1012
+ aria-label={`${
1013
+ item.kind === 'video'
1014
+ ? labels.productVideo
1015
+ : labels.gallery
1016
+ } ${index + 1}`}
977
1017
  aria-pressed={index === image}
978
1018
  tabIndex={index === image ? 0 : -1}
979
1019
  data-product-thumbnail={index}
1020
+ data-product-thumbnail-video={
1021
+ item.kind === 'video' || undefined
1022
+ }
980
1023
  onClick={() => setImage(index)}
981
1024
  onKeyDown={(event) => thumbnailKeydown(event, index)}
982
1025
  >
983
- <BaskleeImage
984
- src={photo}
985
- alt=""
986
- width={72}
987
- height={90}
988
- className={styles.thumbnailImage}
989
- />
1026
+ {item.kind === 'image' || item.preview ? (
1027
+ <BaskleeImage
1028
+ src={
1029
+ item.kind === 'image'
1030
+ ? item.src
1031
+ : (item.preview as string)
1032
+ }
1033
+ alt=""
1034
+ width={72}
1035
+ height={90}
1036
+ className={
1037
+ item.kind === 'image'
1038
+ ? styles.thumbnailImage
1039
+ : `${styles.thumbnailImage} ${styles.thumbnailPreview}`
1040
+ }
1041
+ />
1042
+ ) : null}
1043
+ {item.kind === 'video' ? (
1044
+ <span
1045
+ className={styles.videoMark}
1046
+ aria-hidden="true"
1047
+ data-product-video-mark
1048
+ >
1049
+ <svg
1050
+ viewBox="0 0 24 24"
1051
+ fill="currentColor"
1052
+ aria-hidden="true"
1053
+ >
1054
+ <path d="M8 5v14l11-7z" />
1055
+ </svg>
1056
+ </span>
1057
+ ) : null}
990
1058
  </button>
991
1059
  ))}
992
1060
  </div>
@@ -1254,6 +1322,39 @@ export function StorefrontProduct({
1254
1322
  productId={currentId}
1255
1323
  />
1256
1324
  </div>
1325
+ {relatedProductIds.length ? (
1326
+ <section
1327
+ className={styles.related}
1328
+ aria-label={relatedLabels.title}
1329
+ data-product-related
1330
+ >
1331
+ <header className={styles.relatedHead}>
1332
+ <h2>{relatedLabels.title}</h2>
1333
+ {relatedCategoryHref ? (
1334
+ <Link
1335
+ href={relatedCategoryHref}
1336
+ data-product-related-category
1337
+ >
1338
+ {relatedLabels.category}
1339
+ </Link>
1340
+ ) : null}
1341
+ </header>
1342
+ <ProductGroup
1343
+ productIds={relatedProductIds}
1344
+ disabled={actionPending || needsRefresh}
1345
+ productHref={productHref}
1346
+ onSelectSeller={onSelectSeller}
1347
+ onSelectVariant={onSelectVariant}
1348
+ onRequestSecondaryVariants={onRequestSecondaryVariants}
1349
+ onToggleFavorite={onToggleFavorite}
1350
+ onAdd={onAdd}
1351
+ onRemove={onRemove}
1352
+ onSubscribe={onSubscribe}
1353
+ onUnsubscribe={onUnsubscribe}
1354
+ onPreorder={openPreorder}
1355
+ />
1356
+ </section>
1357
+ ) : null}
1257
1358
  {preorderId !== undefined ? (
1258
1359
  <ProductPreorderDialog
1259
1360
  productId={preorderId}
@@ -6,6 +6,8 @@ import {
6
6
  useBaskleeStore,
7
7
  } from '@/providers/BaskleeProvider';
8
8
  import { requestBrowserAppLoad } from '@/lib/basklee/appLoadClient';
9
+ import { openAppAddress } from '@/lib/basklee/navigation';
10
+ import { signInPageLocation } from '@/lib/basklee/signInReturn';
9
11
  import {
10
12
  BaskleeApi,
11
13
  type BaskleeApiRequest,
@@ -69,6 +71,30 @@ export async function transport(
69
71
  };
70
72
  }
71
73
 
74
+ /*
75
+ * After HTTP 401 the visitor goes to the /profile sign-in page with this page
76
+ * in `redirect`, for example `/profile?locale=en&redirect=/orders?locale=en`.
77
+ * The sign-in page itself and /logout stay where they are: /profile already
78
+ * shows the form, and logging out should not ask for sign-in. The website
79
+ * opens the sign-in page as a new page load; the app changes its address.
80
+ */
81
+ function openSignInAfterUnauthorized(locale: string) {
82
+ if (typeof window === 'undefined') {
83
+ return;
84
+ }
85
+ const { pathname, search, hash } = window.location;
86
+ if (pathname === '/profile' || pathname === '/logout') {
87
+ return;
88
+ }
89
+ const target = signInPageLocation(pathname + search + hash, locale);
90
+ const href = `${target.path}?${new URLSearchParams(target.query)}`;
91
+ if (APP_ORIGIN) {
92
+ openAppAddress(href);
93
+ return;
94
+ }
95
+ window.location.assign(href);
96
+ }
97
+
72
98
  export function useBaskleeApi() {
73
99
  const store = useBaskleeStore();
74
100
  const selections = useBaskleeSelectionsStore();
@@ -86,11 +112,18 @@ export function useBaskleeApi() {
86
112
  Boolean(
87
113
  store.getState().result?.response.page_data.init.is_authenticated,
88
114
  ),
89
- onSessionEnded: async () => {
115
+ // HTTP 401: the request needs a signed-in customer. An ended session
116
+ // shows the guest storefront at once; then the sign-in page opens and
117
+ // returns to this page afterwards. The failed request is not repeated.
118
+ onUnauthorized: async (signedIn) => {
90
119
  const locale = selections.getState().localeCode;
91
- await store
92
- .getState()
93
- .endSession((signal) => requestBrowserAppLoad(signal, locale));
120
+ const ending = signedIn
121
+ ? store
122
+ .getState()
123
+ .endSession((signal) => requestBrowserAppLoad(signal, locale))
124
+ : undefined;
125
+ openSignInAfterUnauthorized(locale);
126
+ await ending;
94
127
  },
95
128
  }),
96
129
  [selections, store],
@@ -0,0 +1,92 @@
1
+ 'use client';
2
+
3
+ import { useEffect, useMemo, useState } from 'react';
4
+ import {
5
+ useBaskleeCatalog,
6
+ useBaskleeProductsStore,
7
+ } from '@/providers/BaskleeProvider';
8
+ import { useBaskleeApi } from '@/hooks/useBaskleeApi';
9
+ import {
10
+ attachedRelatedProducts,
11
+ relatedCategoryId,
12
+ relatedCategoryProducts,
13
+ relatedCategoryRequest,
14
+ } from '@/lib/basklee/relatedProducts';
15
+ import type {
16
+ IProduct,
17
+ IProductSearchSeller,
18
+ } from '@/interfaces/basklee/products/IProduct';
19
+
20
+ /*
21
+ * The products of the row under a product page (lib/basklee/relatedProducts.ts):
22
+ * the products attached on the panel's «Relevant Products» tab first, else
23
+ * more of the product's main category. The products go into the product
24
+ * store, so the row's cards read them like every other card. A failed
25
+ * category request leaves the row off the page.
26
+ */
27
+ export function useBaskleeRelatedProducts(product: IProduct | undefined) {
28
+ const api = useBaskleeApi();
29
+ const products = useBaskleeProductsStore();
30
+ const catalog = useBaskleeCatalog((state) => state.catalog);
31
+ const attached = useMemo(
32
+ () => attachedRelatedProducts(product),
33
+ [product],
34
+ );
35
+ const categoryId = relatedCategoryId(product);
36
+ const productId = product?.id ?? 0;
37
+ const key = `${categoryId}:${productId}`;
38
+ const [fromCategory, setCategory] = useState({ key: '', ids: [] as number[] });
39
+
40
+ useEffect(() => {
41
+ for (const item of attached) {
42
+ if (!products.getState().getProduct(item.id)) {
43
+ products.getState().setProduct(item, 'products');
44
+ }
45
+ }
46
+ }, [attached, products]);
47
+
48
+ useEffect(() => {
49
+ if (!categoryId) {
50
+ return;
51
+ }
52
+ const controller = new AbortController();
53
+ api
54
+ .request<{
55
+ products?: { data?: IProduct[] };
56
+ selects?: { sellers?: IProductSearchSeller[] };
57
+ }>(
58
+ 'products_search',
59
+ relatedCategoryRequest(categoryId, catalog ?? []),
60
+ controller.signal,
61
+ )
62
+ .then((data) => {
63
+ if (controller.signal.aborted) {
64
+ return;
65
+ }
66
+ const items = relatedCategoryProducts(data.products?.data, productId);
67
+ for (const item of items) {
68
+ products
69
+ .getState()
70
+ .setProduct(item, 'products', data.selects?.sellers ?? []);
71
+ }
72
+ setCategory({ key, ids: items.map((item) => item.id) });
73
+ })
74
+ .catch(() => {
75
+ // The row stays off the page; the next visit of the page asks again.
76
+ });
77
+ return () => controller.abort();
78
+ // The catalog only narrows the request; a new catalog does not ask again.
79
+ }, [api, categoryId, productId, key, products]);
80
+
81
+ const productIds = attached.length
82
+ ? attached.map((item) => item.id)
83
+ : fromCategory.key === key
84
+ ? fromCategory.ids
85
+ : [];
86
+
87
+ return {
88
+ productIds,
89
+ /** The category the row comes from, or 0 for attached products. */
90
+ categoryId: attached.length ? 0 : categoryId,
91
+ };
92
+ }
@@ -100,7 +100,7 @@ export class BaskleeApi {
100
100
  private readonly canRequest: () => boolean;
101
101
  private readonly isSignedIn: () => boolean;
102
102
  private readonly currency: () => string | number | undefined;
103
- private readonly onSessionEnded?: () => unknown;
103
+ private readonly onUnauthorized?: (signedIn: boolean) => unknown;
104
104
 
105
105
  constructor(options: {
106
106
  transport: BaskleeTransport;
@@ -110,7 +110,7 @@ export class BaskleeApi {
110
110
  canRequest?: () => boolean;
111
111
  isSignedIn?: () => boolean;
112
112
  currency?: () => string | number | undefined;
113
- onSessionEnded?: () => unknown;
113
+ onUnauthorized?: (signedIn: boolean) => unknown;
114
114
  }) {
115
115
  this.transport = options.transport;
116
116
  this.endpoints = options.endpoints;
@@ -119,7 +119,7 @@ export class BaskleeApi {
119
119
  this.canRequest = options.canRequest ?? (() => true);
120
120
  this.isSignedIn = options.isSignedIn ?? (() => false);
121
121
  this.currency = options.currency ?? (() => undefined);
122
- this.onSessionEnded = options.onSessionEnded;
122
+ this.onUnauthorized = options.onUnauthorized;
123
123
  }
124
124
 
125
125
  get sessionEnd() {
@@ -205,27 +205,42 @@ export class BaskleeApi {
205
205
  signal?.throwIfAborted();
206
206
  }
207
207
 
208
- this.detectSessionEnd(response);
208
+ this.detectUnauthorized(response, name);
209
209
  signal?.throwIfAborted();
210
210
  return response;
211
211
  }
212
212
 
213
- private detectSessionEnd(response: BaskleeApiResponse) {
213
+ /*
214
+ * The backend answers HTTP 401 when the request has no signed-in session:
215
+ * an authentication-required endpoint without a customer ({ auth: false }),
216
+ * or a session the backend rejected and whose cookies it deleted.
217
+ * Every such answer goes to `onUnauthorized`, which opens sign-in. With
218
+ * `signedIn` true the application still shows a customer, so the session
219
+ * has ended and the handler first removes the account data. One handler
220
+ * call serves concurrent failures. The 401 of `profile_logout` only says
221
+ * that the session had already ended, so it is not passed on; 403 and CSRF
222
+ * rejection are ordinary request errors.
223
+ */
224
+ private detectUnauthorized(response: BaskleeApiResponse, name = '') {
214
225
  if (
215
226
  response.status !== 401 ||
227
+ name === 'profile_logout' ||
216
228
  this.sessionEnding ||
217
- !this.onSessionEnded ||
218
- !this.isSignedIn()
229
+ !this.onUnauthorized
219
230
  ) {
220
231
  return;
221
232
  }
222
233
 
223
234
  let ending: Promise<void>;
224
235
  try {
225
- ending = Promise.resolve(this.onSessionEnded()).then(() => undefined);
236
+ ending = Promise.resolve(this.onUnauthorized(this.isSignedIn())).then(
237
+ () => undefined,
238
+ );
226
239
  } catch (error) {
227
240
  ending = Promise.reject(error);
228
241
  }
242
+
243
+ // The failed request reports its own error; the refresh has its own state.
229
244
  this.sessionEnding = ending
230
245
  .catch(() => undefined)
231
246
  .finally(() => {
@@ -250,7 +265,7 @@ export class BaskleeApi {
250
265
  if (!this.renewal) {
251
266
  this.renewal = this.send('/api/csrf_renew', 'POST', {})
252
267
  .then((response) => {
253
- this.detectSessionEnd(response);
268
+ this.detectUnauthorized(response);
254
269
  this.successData(response);
255
270
  if (!this.csrfToken()) {
256
271
  throw new BaskleeApiError('failed');
@@ -62,3 +62,40 @@ export function productThumbnailKeyTarget(
62
62
 
63
63
  return undefined;
64
64
  }
65
+
66
+ export type ProductMediaItem =
67
+ | { kind: 'image'; key: string; src: string }
68
+ | { kind: 'video'; key: string; src: string; preview: string | null };
69
+
70
+ export interface ProductMediaSources {
71
+ images?: { full?: string[] | null; small?: string[] | null } | null;
72
+ videos?:
73
+ | { id: number; product_video: string | null; preview: string | null }[]
74
+ | null;
75
+ }
76
+
77
+ // The pictures and videos of a product in the order its gallery shows them:
78
+ // the full images first (the small copies when it has none), then the videos
79
+ // in the order the backend sends them. A video without a file is left out.
80
+ export function productMediaItems(
81
+ product: ProductMediaSources | null | undefined,
82
+ ): ProductMediaItem[] {
83
+ const images = product?.images;
84
+ const photos = images?.full?.length ? images.full : (images?.small ?? []);
85
+ const items = photos.map(
86
+ (src, index): ProductMediaItem => ({ kind: 'image', key: `image-${index}`, src }),
87
+ );
88
+
89
+ for (const video of product?.videos ?? []) {
90
+ if (video.product_video) {
91
+ items.push({
92
+ kind: 'video',
93
+ key: `video-${video.id}`,
94
+ src: video.product_video,
95
+ preview: video.preview,
96
+ });
97
+ }
98
+ }
99
+
100
+ return items;
101
+ }
@@ -0,0 +1,101 @@
1
+ import { catalogBranchIds } from '@/lib/basklee/catalog';
2
+ import type { ICategory, IProduct } from '@/interfaces/basklee';
3
+
4
+ /*
5
+ * The row of other products under a product page.
6
+ *
7
+ * The products the seller attached to this product on the panel's «Relevant
8
+ * Products» tab come first: they arrive with the product (`related.data`),
9
+ * so they need no request. Only a product without them shows more products
10
+ * of its own main category, asked from `products_search` the way the
11
+ * category page asks (the category with its subcategories), one more than
12
+ * shown because the product itself may be among them.
13
+ */
14
+
15
+ /** How many products the row shows. */
16
+ export const RELATED_PRODUCTS_LIMIT = 8;
17
+
18
+ /** The attached products of `product`, without the product itself. */
19
+ export function attachedRelatedProducts(
20
+ product: IProduct | undefined,
21
+ limit = RELATED_PRODUCTS_LIMIT,
22
+ ): IProduct[] {
23
+ const items = product?.related?.data;
24
+
25
+ if (!product || !Array.isArray(items)) {
26
+ return [];
27
+ }
28
+
29
+ return items
30
+ .filter(
31
+ (item) =>
32
+ Number.isInteger(item?.id) && item.id > 0 && item.id !== product.id,
33
+ )
34
+ .slice(0, limit);
35
+ }
36
+
37
+ /**
38
+ * The category whose products fill the row when nothing is attached: the
39
+ * product's main category, or 0 when the row needs none.
40
+ */
41
+ export function relatedCategoryId(product: IProduct | undefined): number {
42
+ const category = product?.main_category;
43
+
44
+ if (
45
+ !product ||
46
+ attachedRelatedProducts(product).length ||
47
+ typeof category !== 'number' ||
48
+ !Number.isInteger(category) ||
49
+ category <= 0
50
+ ) {
51
+ return 0;
52
+ }
53
+
54
+ return category;
55
+ }
56
+
57
+ /**
58
+ * The `products_search` body for that category: the category with its public
59
+ * subcategories when the catalog tree knows it, otherwise the category alone.
60
+ */
61
+ export function relatedCategoryRequest(
62
+ categoryId: number,
63
+ catalog: ICategory[],
64
+ limit = RELATED_PRODUCTS_LIMIT,
65
+ ) {
66
+ return {
67
+ filters: { categories: catalogBranchIds(catalog, categoryId) },
68
+ paginate: { page: 1, pp_items: limit + 1 },
69
+ };
70
+ }
71
+
72
+ /** The products of the category answer that the row shows. */
73
+ export function relatedCategoryProducts(
74
+ items: IProduct[] | undefined,
75
+ productId: number,
76
+ limit = RELATED_PRODUCTS_LIMIT,
77
+ ): IProduct[] {
78
+ return (Array.isArray(items) ? items : [])
79
+ .filter((item) => Number.isInteger(item?.id) && item.id !== productId)
80
+ .slice(0, limit);
81
+ }
82
+
83
+ const RELATED_EN = {
84
+ title: 'You may also like',
85
+ category: 'All products of the category',
86
+ };
87
+ const RELATED_TITLES: Record<string, { title: string; category: string }> = {
88
+ en: RELATED_EN,
89
+ ru: { title: 'Вам может понравиться', category: 'Все товары категории' },
90
+ es: {
91
+ title: 'También te puede gustar',
92
+ category: 'Todos los productos de la categoría',
93
+ },
94
+ };
95
+
96
+ /** The row's heading and the link to its category, in the given language. */
97
+ export function relatedProductsLabels(locale: string) {
98
+ return (
99
+ RELATED_TITLES[String(locale || '').toLowerCase().slice(0, 2)] ?? RELATED_EN
100
+ );
101
+ }
@@ -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',