basklee-react 0.9.8 → 0.9.10

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
@@ -521,6 +521,7 @@ server render. Public product, article and tariff details load through the
521
521
  maintained API client. Page metadata uses those returned records and follows
522
522
  client navigation and language selection. Home-page event clicks open enrollment
523
523
  for the returned event, preserving its return path through sign-in.
524
+ A product page takes the product's SEO tab: its heading is the page title (the product name without one), its meta description and keywords fill their tags, and its own Open Graph and Twitter Cards tags are added in the page's language only, replacing a default tag of the same name.
524
525
  Pages with a canonical address also link the same page in the other storefront languages (`hreflang`) and set `og:type` and `og:locale`; a journal article adds its publication date (`article:published_time`) and schema.org `BlogPosting` data. The store icon (`logos.ico`) is the page's `<link rel="icon">`. An unknown `?locale` opens the default language.
525
526
 
526
527
  List pages (journal, categories, stores) link their previous and next pages as real links (`?page=2`). Each later page has its own canonical address and a title with its page number; a journal page past the last one answers 404.
@@ -568,7 +569,9 @@ When a request returns HTTP `401` while the store is signed in, the shared API
568
569
  client clears profile, wallet, authenticated discovery, cart and wishlist counters
569
570
  and account fields of cached products, then reloads Application Load as a guest.
570
571
  Public data and the current selections remain available during that refresh.
571
- 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.
572
575
 
573
576
  ## Update an existing project
574
577
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "basklee-react",
3
- "version": "0.9.8",
3
+ "version": "0.9.10",
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
  }
@@ -37,6 +37,14 @@ groups. The current weight and length selections choose the displayed units.
37
37
  A list that exceeds its reserved space opens every row in
38
38
  `ProductSpecificationsDialog`.
39
39
 
40
+ Under the reviews, `relatedProductIds` shows the row “You may also like” with
41
+ the same card events; `relatedCategoryHref` adds a link to the category page
42
+ and `productHref` gives the cards their links. `useBaskleeRelatedProducts` in
43
+ `hooks/useBaskleeRelatedProducts.ts` gives both values: the products attached
44
+ on the panel's Relevant Products tab (`related.data`, without the product
45
+ itself, up to eight), and only without them up to eight more products of the
46
+ product's `main_category` from `products_search`. An empty list hides the row.
47
+
40
48
  The details card forwards cart, wishlist, availability and variant events
41
49
  through the matching `onAdd`, `onRemove`, `onToggleFavorite`, `onSubscribe`,
42
50
  `onUnsubscribe`, `onRequestSecondaryVariants`, `onSelectVariant` and
@@ -81,6 +89,9 @@ contract is in `interfaces/basklee/products/IProduct.ts`.
81
89
  | `needsRefresh?: boolean` | Shows that the surrounding data must be loaded again. |
82
90
  | `profileHref?: string` | Destination used by the profile link. |
83
91
  | `reviewProps?: Omit<ProductReviewsProps, "productId">` | Props forwarded to the review child component. |
92
+ | `relatedProductIds?: number[]` | Products of the row under the reviews; empty hides it. |
93
+ | `relatedCategoryHref?: string` | Category page linked from that row. |
94
+ | `productHref?: ProductCardProps["productHref"]` | Address of a product of that row. |
84
95
  | `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
96
  | `onLoaded?: (product: IProduct) => void` | Called when the requested data loads successfully. The callback payload is shown in its type. |
86
97
  | `onMissing?: () => void` | Called when the requested public record does not exist. The callback has no payload. |
@@ -119,6 +130,14 @@ contract is in `interfaces/basklee/products/IProduct.ts`.
119
130
  а «Повторить» отправляет тот же запрос. `onLoaded` получает показанный товар,
120
131
  включая загруженный вариант.
121
132
 
133
+ Под отзывами `relatedProductIds` показывает ряд «Вам может понравиться» с теми же
134
+ событиями карточек; `relatedCategoryHref` добавляет ссылку на страницу
135
+ категории, а `productHref` даёт карточкам ссылки. Оба значения даёт
136
+ `useBaskleeRelatedProducts` из `hooks/useBaskleeRelatedProducts.ts`: товары,
137
+ прикреплённые на вкладке «Релевантные товары» панели (`related.data`, без самого
138
+ товара, до восьми), и только без них — до восьми других товаров его
139
+ `main_category` из `products_search`. Пустой список скрывает ряд.
140
+
122
141
  Галерея использует полные изображения, а при их отсутствии — малые. Кнопки
123
142
  вперёд и назад переходят по кругу. Лента миниатюр прокручивается только тогда,
124
143
  когда изображения не помещаются. Клавиши со стрелками выбирают соседнее фото,
@@ -181,6 +200,9 @@ Home и End — первое и последнее. Нажатие, щелчок
181
200
  | `needsRefresh?: boolean` | Показывает, что внешние данные нужно загрузить заново. |
182
201
  | `profileHref?: string` | Адрес ссылки профиля. |
183
202
  | `reviewProps?: Omit<ProductReviewsProps, "productId">` | Свойства, передаваемые дочернему компоненту отзывов. |
203
+ | `relatedProductIds?: number[]` | Товары ряда под отзывами; пустой список скрывает его. |
204
+ | `relatedCategoryHref?: string` | Страница категории, на которую ведёт ряд. |
205
+ | `productHref?: ProductCardProps["productHref"]` | Адрес товара этого ряда. |
184
206
  | `onLoad?: (action: ProductPageLoadAction) => Promise<IProduct \| undefined> \| IProduct \| undefined` | Вызывается, когда компоненту нужны основные данные. Данные обработчика указаны в его типе. |
185
207
  | `onLoaded?: (product: IProduct) => void` | Вызывается, когда запрошенные данные успешно загружены. Данные обработчика указаны в его типе. |
186
208
  | `onMissing?: () => void` | Вызывается, когда запрошенная общедоступная запись не существует. Обработчик не получает данные. |
@@ -765,3 +765,41 @@
765
765
  animation: none;
766
766
  }
767
767
  }
768
+
769
+ /* The row under the reviews: «You may also like». */
770
+ .related {
771
+ margin-top: 56px;
772
+ padding-top: 40px;
773
+ border-top: 1px solid var(--basklee-border);
774
+ }
775
+
776
+ .relatedHead {
777
+ display: flex;
778
+ flex-wrap: wrap;
779
+ align-items: baseline;
780
+ justify-content: space-between;
781
+ gap: 8px 24px;
782
+ margin-bottom: 24px;
783
+ }
784
+
785
+ .relatedHead h2 {
786
+ margin: 0;
787
+ color: var(--basklee-text);
788
+ font-size: 1.25rem;
789
+ line-height: 1.75rem;
790
+ font-weight: 600;
791
+ }
792
+
793
+ .relatedHead a {
794
+ color: var(--basklee-text);
795
+ font-size: 0.875rem;
796
+ line-height: 1.25rem;
797
+ text-decoration: underline;
798
+ text-underline-offset: 4px;
799
+ }
800
+
801
+ @container product (min-width: 592px) {
802
+ .related {
803
+ margin-top: 80px;
804
+ }
805
+ }
@@ -58,6 +58,8 @@ import { BaskleeBreadcrumbs } from '@/components/basklee/shared/BaskleeBreadcrum
58
58
  import { BaskleeEmptyState } from '@/components/basklee/shared/BaskleeEmptyState';
59
59
  import { BaskleeImage } from '@/components/basklee/shared/BaskleeImage';
60
60
  import { ProductCard, type ProductCardProps } from './ProductCard';
61
+ import { ProductGroup } from './ProductGroup';
62
+ import { relatedProductsLabels } from '@/lib/basklee/relatedProducts';
61
63
  import {
62
64
  ProductPreorderDialog,
63
65
  type ProductPreorderSelection,
@@ -115,6 +117,16 @@ export interface StorefrontProductProps extends CardCallbacks {
115
117
  needsRefresh?: boolean;
116
118
  profileHref?: string;
117
119
  reviewProps?: Omit<ProductReviewsProps, 'productId'>;
120
+ /**
121
+ * The row under the reviews, «You may also like»: the products attached on
122
+ * the panel's Relevant Products tab, else more of the product's category
123
+ * (`useBaskleeRelatedProducts` in hooks/useBaskleeRelatedProducts.ts).
124
+ */
125
+ relatedProductIds?: number[];
126
+ /** The category page of that row; only when the row comes from it. */
127
+ relatedCategoryHref?: string;
128
+ /** The address of a product of that row. */
129
+ productHref?: ProductCardProps['productHref'];
118
130
  onLoad?: (
119
131
  action: ProductPageLoadAction,
120
132
  ) => Promise<IProduct | undefined> | IProduct | undefined;
@@ -163,6 +175,9 @@ export function StorefrontProduct({
163
175
  needsRefresh = false,
164
176
  profileHref,
165
177
  reviewProps,
178
+ relatedProductIds = [],
179
+ relatedCategoryHref,
180
+ productHref,
166
181
  variantProductIds,
167
182
  onLoad,
168
183
  onLoaded,
@@ -244,6 +259,7 @@ export function StorefrontProduct({
244
259
  const labels = reviewLabels(locale);
245
260
  const common = featureLabels(locale);
246
261
  const cardLabels = productLabels(locale);
262
+ const relatedLabels = relatedProductsLabels(locale);
247
263
  const actionLabels = productActionLabels(locale);
248
264
  const categoryNames = categoryLabels(locale);
249
265
  const product = confirmed
@@ -1254,6 +1270,39 @@ export function StorefrontProduct({
1254
1270
  productId={currentId}
1255
1271
  />
1256
1272
  </div>
1273
+ {relatedProductIds.length ? (
1274
+ <section
1275
+ className={styles.related}
1276
+ aria-label={relatedLabels.title}
1277
+ data-product-related
1278
+ >
1279
+ <header className={styles.relatedHead}>
1280
+ <h2>{relatedLabels.title}</h2>
1281
+ {relatedCategoryHref ? (
1282
+ <Link
1283
+ href={relatedCategoryHref}
1284
+ data-product-related-category
1285
+ >
1286
+ {relatedLabels.category}
1287
+ </Link>
1288
+ ) : null}
1289
+ </header>
1290
+ <ProductGroup
1291
+ productIds={relatedProductIds}
1292
+ disabled={actionPending || needsRefresh}
1293
+ productHref={productHref}
1294
+ onSelectSeller={onSelectSeller}
1295
+ onSelectVariant={onSelectVariant}
1296
+ onRequestSecondaryVariants={onRequestSecondaryVariants}
1297
+ onToggleFavorite={onToggleFavorite}
1298
+ onAdd={onAdd}
1299
+ onRemove={onRemove}
1300
+ onSubscribe={onSubscribe}
1301
+ onUnsubscribe={onUnsubscribe}
1302
+ onPreorder={openPreorder}
1303
+ />
1304
+ </section>
1305
+ ) : null}
1257
1306
  {preorderId !== undefined ? (
1258
1307
  <ProductPreorderDialog
1259
1308
  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
+ }
@@ -1,6 +1,13 @@
1
+ import type {
2
+ IDomainSeoOg,
3
+ IDomainSeoTwitter,
4
+ } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonSEO';
1
5
  import type { ITransformValue } from '@/interfaces/basklee/shared/ITransformValue';
2
6
 
3
7
  export interface IProduct {
8
+ /** The product's own Open Graph / Twitter Cards tags (single product only). */
9
+ og?: IDomainSeoOg[];
10
+ twitter?: IDomainSeoTwitter[];
4
11
  id: number;
5
12
  product_group_id: number;
6
13
  whishlist_id?: number | null;
@@ -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');
@@ -26,7 +26,7 @@ import {
26
26
  type StorefrontSeoPage,
27
27
  } from '@/lib/basklee/pageSeo';
28
28
  import { structuredDataJson } from '@/lib/basklee/productStructuredData';
29
- import { getStorefrontSeo } from '@/lib/basklee/seo';
29
+ import { getProductSocialMeta, getStorefrontSeo } from '@/lib/basklee/seo';
30
30
  import { findCatalogCategory } from '@/lib/basklee/catalog';
31
31
  import { blogPostCover } from '@/lib/basklee/blogPresentation';
32
32
  import { browseLabels } from '@/lib/basklee/browseLabels';
@@ -135,6 +135,9 @@ export function storefrontMetadata(
135
135
  }
136
136
  const values: MetadataValues = {};
137
137
  let image: string | undefined;
138
+ // A product's own og:title / og:description (the panel's SEO tab) replace
139
+ // the link preview's title and description; its other tags are said as is.
140
+ let ownOg: { title?: string; description?: string } = {};
138
141
  let published: string | undefined;
139
142
  let modified: string | undefined;
140
143
  const tags: MetaTags = [];
@@ -192,11 +195,27 @@ export function storefrontMetadata(
192
195
  const product = records.product;
193
196
  const field = <Key extends keyof IProductLocale>(name: Key) =>
194
197
  getAvailableNestedValueFromObject(product.locale, locale, name);
195
- values.title = field('product_name');
198
+ // The panel's SEO tab: its heading is the page title and its keywords the
199
+ // keywords tag; without them the product's name and the page's own words.
200
+ values.title = plainText(field('product_title') ?? '') || field('product_name');
196
201
  values.description = plainText(
197
202
  field('meta_description') || field('short_description'),
198
203
  ).slice(0, 160);
204
+ values.keywords = plainText(field('meta_keywords') ?? '') || undefined;
199
205
  image = product.images?.full?.[0] ?? product.images?.small?.[0];
206
+ const own = getProductSocialMeta(product, locale);
207
+ const ownProperty = (name: string) =>
208
+ own.find((tag) => 'property' in tag && tag.property === name)?.content;
209
+ ownOg = {
210
+ title: ownProperty('og:title'),
211
+ description: ownProperty('og:description'),
212
+ };
213
+ tags.push(
214
+ ...own.filter(
215
+ (tag) =>
216
+ !('property' in tag && ['og:title', 'og:description'].includes(tag.property)),
217
+ ),
218
+ );
200
219
  } else if (page === 'publication' && records.post) {
201
220
  values.title = getAvailableNestedValueFromObject(
202
221
  records.post.locale,
@@ -284,8 +303,8 @@ export function storefrontMetadata(
284
303
  ...(icon ? { icons: { icon } } : {}),
285
304
  openGraph: {
286
305
  ...openGraph,
287
- title: content.title,
288
- description: content.description,
306
+ title: ownOg.title ?? content.title,
307
+ description: ownOg.description ?? content.description,
289
308
  ...(ogLocale ? { locale: ogLocale } : {}),
290
309
  ...(canonical ? { url: canonical } : {}),
291
310
  ...(image ? { images: [image] } : {}),
@@ -319,8 +338,8 @@ export function storefrontMetadata(
319
338
  description: content.description,
320
339
  keywords: content.keywords,
321
340
  robots,
322
- 'og:title': content.title,
323
- 'og:description': content.description,
341
+ 'og:title': ownOg.title ?? content.title,
342
+ 'og:description': ownOg.description ?? content.description,
324
343
  'og:image': image,
325
344
  'og:url': canonical,
326
345
  'og:type': ogType,
@@ -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
+ }
@@ -1,8 +1,9 @@
1
1
  import type { IAppLoadCommonSeo } from '@/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonSEO';
2
2
  import { getAvailableNestedValueFromObject } from '@/lib/basklee/presentation';
3
3
 
4
- type SeoMeta =
4
+ export type StorefrontSeoMeta =
5
5
  { name: string; content: string } | { property: string; content: string };
6
+ type SeoMeta = StorefrontSeoMeta;
6
7
 
7
8
  export function getStorefrontSeo(
8
9
  incomingData: IAppLoadCommonSeo[],
@@ -50,3 +51,28 @@ export function getStorefrontSeo(
50
51
  }
51
52
  return { title, meta };
52
53
  }
54
+
55
+ /**
56
+ * A product's own Open Graph and Twitter Cards tags (the panel's SEO tab) for
57
+ * its page head. Only the page's own language counts: a tag written in English
58
+ * is left out of the Russian page rather than replacing its Russian title.
59
+ */
60
+ export function getProductSocialMeta(
61
+ product: Partial<Pick<IAppLoadCommonSeo, 'og' | 'twitter'>> | undefined,
62
+ locale: string,
63
+ ): StorefrontSeoMeta[] {
64
+ const meta: StorefrontSeoMeta[] = [];
65
+ for (const tag of product?.og ?? []) {
66
+ const content = tag.locale?.[locale]?.og_content_value?.trim();
67
+ if (content) {
68
+ meta.push({ property: tag.og_property_name, content });
69
+ }
70
+ }
71
+ for (const tag of product?.twitter ?? []) {
72
+ const content = tag.locale?.[locale]?.extra_meta_content?.trim();
73
+ if (content) {
74
+ meta.push({ name: tag.extra_meta_name, content });
75
+ }
76
+ }
77
+ return meta;
78
+ }