basklee-svelte 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
@@ -527,6 +527,7 @@ data and actions; `basklee/COMPONENTS.md` lists their customer paths.
527
527
  Page titles, descriptions and link-preview metadata follow the current page
528
528
  and selected language, including client navigation. Public events and banner
529
529
  images come from Application Load.
530
+ 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.
530
531
  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.
531
532
 
532
533
  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.
@@ -573,7 +574,9 @@ When a request returns HTTP `401` while the store is signed in, the shared API
573
574
  client clears profile, wallet, authenticated discovery, cart and wishlist counters
574
575
  and account fields of cached products, then reloads Application Load as a guest.
575
576
  Public data and the current selections remain available during that refresh.
576
- The failed request is not repeated and no sign-in dialog opens automatically.
577
+ Every `401` (also a guest's) then opens `/profile?locale=<locale>&redirect=<current page>`,
578
+ which returns to the page after sign-in; on `/profile` and `/logout` the page
579
+ stays. The failed request is not repeated.
577
580
 
578
581
  ## Update an existing project
579
582
 
@@ -645,8 +648,8 @@ Component source lives in `src/lib/components/basklee/`; controllers live in
645
648
  `src/lib/composables/`. `basklee/COMPONENTS.md` describes the component catalog.
646
649
  The store is scoped to one render on the server and the root layout in the
647
650
  browser. It preserves valid selections when Application Load refreshes. HTTP
648
- 401 clears account data and refreshes the guest session without repeating the
649
- failed mutation. API validation errors remain beside the affected form.
651
+ 401 clears account data, refreshes the guest session and opens the sign-in page
652
+ without repeating the failed mutation. API validation errors remain beside the affected form.
650
653
 
651
654
  ---
652
655
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "basklee-svelte",
3
- "version": "0.9.8",
3
+ "version": "0.9.10",
4
4
  "description": "SvelteKit 2 storefront for your Basklee marketplace: setup CLI, server API gateway, typed store and ready-made catalog, cart, checkout and account components in English, Russian and Spanish, plus an Android app build. Powered by Basklee: https://basklee.com",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -269,7 +269,8 @@ client navigation and the selected language.
269
269
 
270
270
  A signed-in request that receives HTTP \`401\` removes private account values and
271
271
  refreshes Application Load as a guest while retaining public data and selections.
272
- The failed request is not repeated and no sign-in dialog opens automatically.
272
+ Every \`401\` then opens the \`/profile\` sign-in page, which returns to the current
273
+ page after sign-in. The failed request is not repeated.
273
274
 
274
275
  ### Session and CSRF cookies
275
276
 
@@ -37,9 +37,9 @@
37
37
  const sections = computed(() => Object.entries(labels.value.navigation));
38
38
 
39
39
  // The basklee-account middleware opens /profile before a guest reaches
40
- // this page. When the session ends while the page is open, the page stays
41
- // and explains that the account content needs sign-in; it never navigates
42
- // on its own, and the header offers Login. A failed Application Load is
40
+ // this page. When the session ends while the page is open, the section
41
+ // explains that the account content needs sign-in while the shared API
42
+ // client opens the sign-in page, which returns here afterwards. A failed Application Load is
43
43
  // not a guest session: it offers Retry instead.
44
44
  </script>
45
45
 
@@ -8,6 +8,14 @@ preview address with `?key=` uses `products_preview`, so anyone with the complet
8
8
  preview address can view it without signing in. The request also runs during server
9
9
  rendering so the product is present in the HTML.
10
10
 
11
+ Under the reviews, “You may also like” shows the products attached to this product on
12
+ the panel's Relevant Products tab (`related.data`, without the product itself, up to
13
+ eight). Only a product without attached products shows up to eight more products of its
14
+ `main_category` from `products_search`, with a link to the category page; without either
15
+ the row is not shown. The logic is in
16
+ `src/lib/composables/useBaskleeRelatedProducts.svelte.ts` and
17
+ `src/lib/utils/basklee/relatedProducts.ts`.
18
+
11
19
  Source: `src/lib/components/basklee/products/StorefrontProduct.svelte`.
12
20
 
13
21
  ## Inputs
@@ -1,5 +1,5 @@
1
1
  <script lang="ts">
2
- import { routeHref } from '@/lib/basklee/navigation.svelte';
2
+ import { navigateTo, routeHref } from '@/lib/basklee/navigation.svelte';
3
3
  import {
4
4
  computed,
5
5
  nextTick,
@@ -18,6 +18,8 @@
18
18
  } from '@/lib/composables/useBaskleeFeature.svelte';
19
19
  import { useBaskleeProductActions } from '@/lib/composables/useBaskleeProductActions.svelte';
20
20
  import { useBaskleeProductVariants } from '@/lib/composables/useBaskleeProductVariants.svelte';
21
+ import { useBaskleeRelatedProducts } from '@/lib/composables/useBaskleeRelatedProducts.svelte';
22
+ import { relatedProductsLabels } from '@/lib/utils/basklee/relatedProducts';
21
23
  import { reviewLabels } from '@/lib/utils/basklee/reviewLabels';
22
24
  import { featureLabels } from '@/lib/utils/basklee/featureLabels';
23
25
  import { productLabels } from '@/lib/utils/basklee/productLabels';
@@ -54,6 +56,7 @@
54
56
  IProductSpecificationRow,
55
57
  } from '@/lib/interfaces/basklee/products/IProductSpecification';
56
58
  import ProductCard from '@/lib/components/basklee/products/ProductCard.svelte';
59
+ import ProductGroup from '@/lib/components/basklee/products/ProductGroup.svelte';
57
60
  import ProductReviews from '@/lib/components/basklee/products/ProductReviews.svelte';
58
61
  import ProductPreorderDialog from '@/lib/components/basklee/products/ProductPreorderDialog.svelte';
59
62
  import ProductSpecificationsDialog from '@/lib/components/basklee/products/ProductSpecificationsDialog.svelte';
@@ -723,6 +726,18 @@
723
726
  currentId.value = selection.variant.product.id;
724
727
  image.value = 0;
725
728
  }
729
+ // The row under the product: the products attached on the panel's
730
+ // «Relevant Products» tab first, else more of the product's category.
731
+ const related = useBaskleeRelatedProducts({ api, product });
732
+ const relatedLabels = computed(() =>
733
+ relatedProductsLabels(selectionStore.localeCode),
734
+ );
735
+ function openRelated(item: IProduct) {
736
+ void navigateTo({
737
+ path: `/product/${item.id}`,
738
+ query: { locale: selectionStore.localeCode },
739
+ });
740
+ }
726
741
  onMounted(() => {
727
742
  mounted.value = true;
728
743
  if (!confirmed.value) {
@@ -1616,6 +1631,66 @@
1616
1631
  <ProductReviews productId={currentId.value} />
1617
1632
  {/key}
1618
1633
  </div>
1634
+ {#if related.productIds.value.length}
1635
+ <section
1636
+ class={[
1637
+ `
1638
+ mt-14 pt-10 border-0 border-t border-solid border-basklee-border
1639
+ @min-[592px]/product:mt-20
1640
+ `,
1641
+ ]}
1642
+ aria-label={relatedLabels.value.title}
1643
+ data-product-related
1644
+ >
1645
+ <header
1646
+ class={[
1647
+ 'mb-6 flex flex-wrap items-baseline justify-between gap-x-6 gap-y-2',
1648
+ ]}
1649
+ >
1650
+ <h2 class={['m-0 text-xl font-semibold text-basklee-text']}>
1651
+ {relatedLabels.value.title}
1652
+ </h2>
1653
+ {#if related.categoryId.value}
1654
+ <a
1655
+ href={routeHref({
1656
+ path: `/category/${related.categoryId.value}`,
1657
+ query: { locale: selectionStore.localeCode },
1658
+ })}
1659
+ class={['text-sm text-basklee-text underline underline-offset-4']}
1660
+ data-product-related-category
1661
+ >
1662
+ {relatedLabels.value.category}
1663
+ </a>
1664
+ {/if}
1665
+ </header>
1666
+ <ProductGroup
1667
+ productIds={related.productIds.value}
1668
+ disabled={actions.pending.value || actions.needsRefresh.value}
1669
+ onSelect={openRelated}
1670
+ onSelectSeller={($event) => {
1671
+ emit('seller', $event);
1672
+ }}
1673
+ onSelectVariant={variants.select}
1674
+ onRequestSecondaryVariants={variants.requestSecondary}
1675
+ onToggleFavorite={($event) => {
1676
+ actions.run('toggleFavorite', $event);
1677
+ }}
1678
+ onAdd={($event) => {
1679
+ actions.run('add', $event);
1680
+ }}
1681
+ onRemove={($event) => {
1682
+ actions.run('remove', $event);
1683
+ }}
1684
+ onSubscribe={($event) => {
1685
+ actions.run('subscribe', $event);
1686
+ }}
1687
+ onUnsubscribe={($event) => {
1688
+ actions.run('unsubscribe', $event);
1689
+ }}
1690
+ onPreorder={actions.openPreorder}
1691
+ />
1692
+ </section>
1693
+ {/if}
1619
1694
  <ProductPreorderDialog
1620
1695
  productId={actions.preorder.value}
1621
1696
  pending={actions.pending.value}
@@ -2,6 +2,8 @@ import { browser } from '$app/environment';
2
2
  import { getContext, setContext } from 'svelte';
3
3
  import { getBaskleeContext } from '@/lib/basklee/store.svelte';
4
4
  import { BaskleeApi } from '@/lib/utils/basklee/api';
5
+ import { navigateTo } from '@/lib/basklee/navigation.svelte';
6
+ import { signInPageLocation } from '@/lib/utils/basklee/signInReturn';
5
7
  import {
6
8
  APP_ORIGIN,
7
9
  nativeAppCookies,
@@ -14,6 +16,24 @@ import type {
14
16
  const clients = new WeakMap<object, BaskleeApi>();
15
17
  const apiKey = Symbol('basklee-api');
16
18
 
19
+ /*
20
+ * After HTTP 401 the visitor goes to the /profile sign-in page with this page
21
+ * in `redirect`, for example `/profile?locale=en&redirect=/orders?locale=en`.
22
+ * The sign-in page itself and /logout stay where they are: /profile already
23
+ * shows the form, and logging out should not ask for sign-in.
24
+ */
25
+ function openSignInAfterUnauthorized(locale: string) {
26
+ if (!browser) {
27
+ return;
28
+ }
29
+ const { pathname, search, hash } = window.location;
30
+ if (pathname === '/profile' || pathname === '/logout') {
31
+ return;
32
+ }
33
+
34
+ void navigateTo(signInPageLocation(pathname + search + hash, locale));
35
+ }
36
+
17
37
  export function provideBaskleeApi(api: BaskleeApi) {
18
38
  setContext(apiKey, api);
19
39
  }
@@ -99,12 +119,21 @@ export function useBaskleeApi() {
99
119
  isSignedIn: () => store.isAuthenticated,
100
120
  // The customer's currency for orders and plan purchases (CURRENCY_REQUESTS).
101
121
  currency: () => store.currencyId,
102
- onSessionEnded: () =>
103
- store.endSession((signal) =>
104
- import('@/lib/basklee/appLoadClient').then((module) =>
105
- module.requestBrowserAppLoad(signal, store.localeCode),
106
- ),
107
- ),
122
+ // HTTP 401: the request needs a signed-in customer. An ended session
123
+ // shows the guest storefront at once; then the sign-in page opens and
124
+ // returns to this page afterwards. The failed request is not repeated.
125
+ onUnauthorized: (signedIn) => {
126
+ const ending = signedIn
127
+ ? store.endSession((signal) =>
128
+ import('@/lib/basklee/appLoadClient').then((module) =>
129
+ module.requestBrowserAppLoad(signal, store.localeCode),
130
+ ),
131
+ )
132
+ : undefined;
133
+ openSignInAfterUnauthorized(store.localeCode);
134
+
135
+ return ending;
136
+ },
108
137
  });
109
138
  clients.set(store, api);
110
139
  return api;
@@ -15,6 +15,7 @@ import {
15
15
  storefrontPublicOrigin,
16
16
  } from '@/lib/utils/basklee/pageSeo';
17
17
  import type { StorefrontSeoPage } from '@/lib/utils/basklee/pageSeo';
18
+ import type { StorefrontSeoMeta } from '@/lib/utils/basklee/seo';
18
19
  import { structuredDataJson } from '@/lib/utils/basklee/productStructuredData';
19
20
 
20
21
  export function useBaskleePageSeo(
@@ -35,6 +36,12 @@ export function useBaskleePageSeo(
35
36
  * canonical address (preview, filtered, noindex) gets none.
36
37
  */
37
38
  structuredData?: (canonical: string, origin: string) => unknown;
39
+ /**
40
+ * The record's own tags (a product's Open Graph and Twitter Cards tags
41
+ * from the panel's SEO tab). They are said after the page's own tags,
42
+ * so a tag of the same name (og:title, og:description) replaces it.
43
+ */
44
+ meta?: MaybeRefOrGetter<StorefrontSeoMeta[] | undefined>;
38
45
  } = {},
39
46
  ) {
40
47
  const store = useBaskleeStore();
@@ -102,6 +109,7 @@ export function useBaskleePageSeo(
102
109
  : '',
103
110
  );
104
111
  useSeoMeta(seo);
112
+ useHead(() => ({ meta: toValue(values.meta) ?? [] }));
105
113
  useHead(() => ({
106
114
  link: canonical.value
107
115
  ? [
@@ -0,0 +1,132 @@
1
+ import { browser } from '$app/environment';
2
+ import {
3
+ computed,
4
+ onScopeDispose,
5
+ ref,
6
+ toValue,
7
+ watch,
8
+ } from '@/lib/basklee/reactivity.svelte';
9
+ import type { MaybeRefOrGetter } from '@/lib/basklee/reactivity.svelte';
10
+ import { useBaskleeProductsStore } from '@/lib/stores/baskleeProducts.svelte';
11
+ import { useBaskleeCatalogStore } from '@/lib/stores/baskleeCatalog.svelte';
12
+ import type { BaskleeApi } from '@/lib/utils/basklee/api';
13
+ import {
14
+ attachedRelatedProducts,
15
+ relatedCategoryId,
16
+ relatedCategoryProducts,
17
+ relatedCategoryRequest,
18
+ } from '@/lib/utils/basklee/relatedProducts';
19
+ import type {
20
+ IProduct,
21
+ IProductSearchSeller,
22
+ } from '@/lib/interfaces/basklee/products/IProduct';
23
+
24
+ /*
25
+ * The products of the row under a product page (lib/utils/basklee/relatedProducts.ts):
26
+ * the products attached on the panel's «Relevant Products» tab first, else
27
+ * more of the product's main category. The products go into the product
28
+ * store, so the row's cards read them like every other card. A failed
29
+ * category request leaves the row off the page.
30
+ */
31
+ export function useBaskleeRelatedProducts(options: {
32
+ api: Pick<BaskleeApi, 'request'>;
33
+ product: MaybeRefOrGetter<IProduct | undefined>;
34
+ }) {
35
+ const productStore = useBaskleeProductsStore();
36
+ const catalogStore = useBaskleeCatalogStore();
37
+ const categoryIds = ref<number[]>([]);
38
+ const pending = ref(false);
39
+ let request: AbortController | undefined;
40
+
41
+ const attached = computed(() =>
42
+ attachedRelatedProducts(toValue(options.product)),
43
+ );
44
+ const categoryId = computed(() =>
45
+ relatedCategoryId(toValue(options.product)),
46
+ );
47
+ const productIds = computed(() =>
48
+ attached.value.length
49
+ ? attached.value.map((item) => item.id)
50
+ : categoryIds.value,
51
+ );
52
+
53
+ function cancel() {
54
+ request?.abort();
55
+ request = undefined;
56
+ pending.value = false;
57
+ }
58
+
59
+ async function loadCategory(category: number, productId: number) {
60
+ cancel();
61
+ categoryIds.value = [];
62
+ if (!category) {
63
+ return;
64
+ }
65
+ const current = new AbortController();
66
+ request = current;
67
+ pending.value = true;
68
+ try {
69
+ const data = await options.api.request<{
70
+ products?: { data?: IProduct[] };
71
+ selects?: { sellers?: IProductSearchSeller[] };
72
+ }>(
73
+ 'products_search',
74
+ relatedCategoryRequest(category, catalogStore.catalog),
75
+ current.signal,
76
+ );
77
+ if (current.signal.aborted) {
78
+ return;
79
+ }
80
+ const items = relatedCategoryProducts(data.products?.data, productId);
81
+ for (const item of items) {
82
+ productStore.setProduct(item, 'products', data.selects?.sellers ?? []);
83
+ }
84
+ categoryIds.value = items.map((item) => item.id);
85
+ } catch {
86
+ // The row stays off the page; the next visit of the page asks again.
87
+ } finally {
88
+ if (request === current) {
89
+ request = undefined;
90
+ pending.value = false;
91
+ }
92
+ }
93
+ }
94
+
95
+ watch(
96
+ attached,
97
+ (items) => {
98
+ for (const item of items) {
99
+ if (!productStore.getProduct(item.id)) {
100
+ productStore.setProduct(item, 'products');
101
+ }
102
+ }
103
+ },
104
+ { immediate: true },
105
+ );
106
+ watch(
107
+ () => [categoryId.value, toValue(options.product)?.id ?? 0] as const,
108
+ ([category, productId], previous) => {
109
+ if (
110
+ previous &&
111
+ previous[0] === category &&
112
+ previous[1] === productId
113
+ ) {
114
+ return;
115
+ }
116
+ if (browser) {
117
+ void loadCategory(category, productId);
118
+ }
119
+ },
120
+ { immediate: true },
121
+ );
122
+ onScopeDispose(cancel);
123
+
124
+ return {
125
+ productIds,
126
+ /** The category the row comes from, or 0 for attached products. */
127
+ categoryId: computed(() =>
128
+ attached.value.length ? 0 : categoryId.value,
129
+ ),
130
+ pending,
131
+ };
132
+ }
@@ -28,8 +28,8 @@ export function provideBaskleeSignIn(handler: BaskleeSignInHandler) {
28
28
  * A guest who clicks an action that needs an account (a review, a reaction,
29
29
  * a favorite, a plan subscription) goes straight to the /profile sign-in page,
30
30
  * which returns to `redirect` afterwards. Call requireSignIn() only from the
31
- * visitor's own click: background requests and an ended session never
32
- * navigate.
31
+ * visitor's own click. A request that answers HTTP 401 opens the same page
32
+ * through the shared API client (see useBaskleeApi).
33
33
  */
34
34
  export function useBaskleeSignIn() {
35
35
  const store = useBaskleeStore();
@@ -1,6 +1,13 @@
1
+ import type {
2
+ IDomainSeoOg,
3
+ IDomainSeoTwitter,
4
+ } from '@/lib/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonSEO';
1
5
  import type { ITransformValue } from '@/lib/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;
@@ -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');
@@ -0,0 +1,106 @@
1
+ import { categoryBranchIds, categoryTrail } from '@/lib/utils/basklee/category';
2
+ import type { ICategory } from '@/lib/interfaces/basklee/category/ICategory';
3
+ import type { IProduct } from '@/lib/interfaces/basklee/products/IProduct';
4
+
5
+ /*
6
+ * The row of other products under a product page.
7
+ *
8
+ * The products the seller attached to this product on the panel's «Relevant
9
+ * Products» tab come first: they arrive with the product (`related.data`),
10
+ * so they need no request. Only a product without them shows more products
11
+ * of its own main category, asked from `products_search` the way the
12
+ * category page asks (the category with its subcategories), one more than
13
+ * shown because the product itself may be among them.
14
+ */
15
+
16
+ /** How many products the row shows. */
17
+ export const RELATED_PRODUCTS_LIMIT = 8;
18
+
19
+ /** The attached products of `product`, without the product itself. */
20
+ export function attachedRelatedProducts(
21
+ product: IProduct | undefined,
22
+ limit = RELATED_PRODUCTS_LIMIT,
23
+ ): IProduct[] {
24
+ const items = product?.related?.data;
25
+
26
+ if (!product || !Array.isArray(items)) {
27
+ return [];
28
+ }
29
+
30
+ return items
31
+ .filter(
32
+ (item) =>
33
+ Number.isInteger(item?.id) && item.id > 0 && item.id !== product.id,
34
+ )
35
+ .slice(0, limit);
36
+ }
37
+
38
+ /**
39
+ * The category whose products fill the row when nothing is attached: the
40
+ * product's main category, or 0 when the row needs none.
41
+ */
42
+ export function relatedCategoryId(product: IProduct | undefined): number {
43
+ const category = product?.main_category;
44
+
45
+ if (
46
+ !product ||
47
+ attachedRelatedProducts(product).length ||
48
+ typeof category !== 'number' ||
49
+ !Number.isInteger(category) ||
50
+ category <= 0
51
+ ) {
52
+ return 0;
53
+ }
54
+
55
+ return category;
56
+ }
57
+
58
+ /**
59
+ * The `products_search` body for that category: the category with its public
60
+ * subcategories when the catalog tree knows it, otherwise the category alone.
61
+ */
62
+ export function relatedCategoryRequest(
63
+ categoryId: number,
64
+ catalog: ICategory[],
65
+ limit = RELATED_PRODUCTS_LIMIT,
66
+ ) {
67
+ const category = categoryTrail(catalog, categoryId).at(-1);
68
+
69
+ return {
70
+ filters: {
71
+ categories: category ? categoryBranchIds(category) : [categoryId],
72
+ },
73
+ paginate: { page: 1, pp_items: limit + 1 },
74
+ };
75
+ }
76
+
77
+ /** The products of the category answer that the row shows. */
78
+ export function relatedCategoryProducts(
79
+ items: IProduct[] | undefined,
80
+ productId: number,
81
+ limit = RELATED_PRODUCTS_LIMIT,
82
+ ): IProduct[] {
83
+ return (Array.isArray(items) ? items : [])
84
+ .filter((item) => Number.isInteger(item?.id) && item.id !== productId)
85
+ .slice(0, limit);
86
+ }
87
+
88
+ const RELATED_EN = {
89
+ title: 'You may also like',
90
+ category: 'All products of the category',
91
+ };
92
+ const RELATED_TITLES: Record<string, { title: string; category: string }> = {
93
+ en: RELATED_EN,
94
+ ru: { title: 'Вам может понравиться', category: 'Все товары категории' },
95
+ es: {
96
+ title: 'También te puede gustar',
97
+ category: 'Todos los productos de la categoría',
98
+ },
99
+ };
100
+
101
+ /** The row's heading and the link to its category, in the given language. */
102
+ export function relatedProductsLabels(locale: string) {
103
+ return (
104
+ RELATED_TITLES[String(locale || '').toLowerCase().slice(0, 2)] ?? RELATED_EN
105
+ );
106
+ }
@@ -1,8 +1,9 @@
1
1
  import type { IAppLoadCommonSeo } from '@/lib/interfaces/basklee/appBase/appLoadCommon/IAppLoadCommonSEO';
2
2
  import { getAvailableNestedValueFromObject } from '@/lib/utils/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
+ }
@@ -3,6 +3,7 @@
3
3
  import { computed, ref, watch } from '@/lib/basklee/reactivity.svelte';
4
4
  import { navigateTo, useRoute } from '@/lib/basklee/navigation.svelte';
5
5
  import { useBaskleePageSeo } from '@/lib/composables/useBaskleePageSeo.svelte';
6
+ import { getProductSocialMeta } from '@/lib/utils/basklee/seo';
6
7
  import { useBaskleeMissingPage } from '@/lib/composables/useBaskleeMissingPage.svelte';
7
8
  import { useBaskleeServerData } from '@/lib/composables/useBaskleeServerData.svelte';
8
9
  import { requestProductPage } from '@/lib/utils/basklee/productPage';
@@ -100,9 +101,22 @@
100
101
  ).slice(0, 160),
101
102
  );
102
103
 
104
+ // The panel's SEO tab: its heading is the page title and its keywords the
105
+ // keywords tag; without them the product's name and the page's own words.
106
+ const productSeo = (key: 'product_title' | 'meta_keywords') =>
107
+ plainText(
108
+ getAvailableNestedValueFromObject(
109
+ product.value?.locale,
110
+ store.localeCode,
111
+ key,
112
+ ),
113
+ );
114
+
103
115
  useBaskleePageSeo('product', () => store.localeCode, {
104
- title: () => productName.value,
116
+ title: () => productSeo('product_title') || productName.value,
105
117
  description: () => productSummary.value,
118
+ keywords: () => productSeo('meta_keywords') || undefined,
119
+ meta: () => getProductSocialMeta(product.value, store.localeCode),
106
120
  image: () => image.value,
107
121
  robots: () => (previewKey.value ? 'noindex, nofollow' : undefined),
108
122
  structuredData: (canonical, origin) =>