basklee-react 0.9.16 → 0.9.18

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
@@ -127,7 +127,7 @@ starting the application. Imports then work at any component directory depth.
127
127
  <!-- components:start (generated by scripts/generate-package-readme-components.mjs) -->
128
128
  ## Components
129
129
 
130
- The starter includes **126 storefront components**, copied into
130
+ The starter includes **127 storefront components**, copied into
131
131
  `components/basklee/` of your project. Each one has a README in English and Russian
132
132
  next to its source that describes its inputs, data and actions.
133
133
 
@@ -244,6 +244,7 @@ Profile, orders, addresses and account activity.
244
244
  | **Wallet top-up form** | `WalletTopUpForm` | Amount, currency and payment-method selection for a wallet top-up. |
245
245
  | **Payment panel** | `PaymentPanel` | Opens the payment link and lets the user refresh its status. |
246
246
  | **Pagination** | `StorefrontPagination` | Previous and next controls with the current page for a returned list. |
247
+ | **Payment result** | `PaymentReturnNotice` | Back from the payment system: the result of the payment, once, on the page the payment was made for. |
247
248
 
248
249
  ### Subscriptions and support
249
250
 
@@ -522,7 +523,7 @@ maintained API client. Page metadata uses those returned records and follows
522
523
  client navigation and language selection. Home-page event clicks open enrollment
523
524
  for the returned event, preserving its return path through sign-in.
524
525
  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.
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 language closest to the browser's, else the first one. A visit without `?locale` opens in the language and currency the customer picked in the selectors on an earlier visit (the `basklee_locale` and `basklee_currency` cookies, kept for a year; the privacy page and the cookie notice name them). Without a pick it opens in the storefront language closest to the browser's languages (`Accept-Language`; `navigator.languages` in the app build): the same code first, then the same language (`ru-RU` finds `ru`, `en` finds `en-GB`); the first available language when none of them is offered. A link with another `?locale` shows that language without replacing the pick: `setLocale(code, false)` and `setCurrency(id, false)` change the selection without keeping it.
526
+ 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, with every video of the post (YouTube players and uploaded videos of the text, then the post's own videos) as a `VideoObject`. YouTube players and uploaded videos stay in the server-rendered article, so search engines find them without scripts. A product page's `Product` data lists the product's videos as `VideoObject`s under `subjectOf` (preview, else the first photo, as the picture; the product's last change as the upload date). The store icon (`logos.ico`) is the page's `<link rel="icon">`. An unknown `?locale` opens the language closest to the browser's, else the first one. A visit without `?locale` opens in the language and currency the customer picked in the selectors on an earlier visit (the `basklee_locale` and `basklee_currency` cookies, kept for a year; the privacy page and the cookie notice name them). Without a pick it opens in the storefront language closest to the browser's languages (`Accept-Language`; `navigator.languages` in the app build): the same code first, then the same language (`ru-RU` finds `ru`, `en` finds `en-GB`); the first available language when none of them is offered. A link with another `?locale` shows that language without replacing the pick: `setLocale(code, false)` and `setCurrency(id, false)` change the selection without keeping it.
526
527
 
527
528
  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.
528
529
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "basklee-react",
3
- "version": "0.9.16",
3
+ "version": "0.9.18",
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",
@@ -0,0 +1,71 @@
1
+ /* The page covers the storefront's header and footer: in the payment frame only the way back shows. */
2
+ .page {
3
+ position: fixed;
4
+ z-index: 2147483000;
5
+ inset: 0;
6
+ display: flex;
7
+ box-sizing: border-box;
8
+ align-items: center;
9
+ justify-content: center;
10
+ padding: 1.5rem 1rem;
11
+ overflow: auto;
12
+ color: var(--basklee-text);
13
+ background: var(--basklee-surface);
14
+ }
15
+
16
+ .box {
17
+ display: grid;
18
+ justify-items: center;
19
+ gap: 1rem;
20
+ max-width: 22.5rem;
21
+ text-align: center;
22
+ }
23
+
24
+ .text {
25
+ margin: 0;
26
+ font-size: 1.125rem;
27
+ line-height: 1.375;
28
+ }
29
+
30
+ .link {
31
+ display: inline-flex;
32
+ align-items: center;
33
+ gap: 0.25rem;
34
+ padding-bottom: 0.125rem;
35
+ border-bottom: 1px solid currentColor;
36
+ color: var(--basklee-text);
37
+ font-size: 0.75rem;
38
+ line-height: 1rem;
39
+ text-decoration: none;
40
+ text-transform: uppercase;
41
+ letter-spacing: 0.08em;
42
+ }
43
+
44
+ @media (hover: hover) {
45
+ .link:hover {
46
+ opacity: 0.7;
47
+ }
48
+ }
49
+
50
+ .spinner {
51
+ display: block;
52
+ box-sizing: border-box;
53
+ width: 1.75rem;
54
+ height: 1.75rem;
55
+ border: 3px solid var(--basklee-border);
56
+ border-top-color: var(--basklee-accent);
57
+ border-radius: 50%;
58
+ animation: payment-return-spin 0.8s linear infinite;
59
+ }
60
+
61
+ @keyframes payment-return-spin {
62
+ to {
63
+ transform: rotate(360deg);
64
+ }
65
+ }
66
+
67
+ @media (prefers-reduced-motion: reduce) {
68
+ .spinner {
69
+ animation: none;
70
+ }
71
+ }
@@ -0,0 +1,59 @@
1
+ 'use client';
2
+
3
+ import { useEffect, useState } from 'react';
4
+ import { useBaskleeSelections } from '@/providers/BaskleeProvider';
5
+ import {
6
+ leavePaymentFrame,
7
+ parsePaymentReturnResult,
8
+ paymentReturnTarget,
9
+ rememberPaymentResult,
10
+ PAYMENT_RETURN_FALLBACK,
11
+ } from '@/lib/basklee/paymentReturn';
12
+ import { paymentReturnLabels } from '@/lib/basklee/paymentReturnLabels';
13
+ import styles from './PaymentReturnPage.module.css';
14
+
15
+ /*
16
+ * The gateway's return page, often opened inside the payment frame. It covers
17
+ * the header and the footer and only finds the way back out to the page the
18
+ * payment was made for, which shows the result once (PaymentReturnNotice).
19
+ */
20
+ export function PaymentReturnPage({ result }: { result?: string }) {
21
+ const locale = useBaskleeSelections((state) => state.localeCode);
22
+ const labels = paymentReturnLabels(locale);
23
+ const [target, setTarget] = useState(PAYMENT_RETURN_FALLBACK);
24
+
25
+ useEffect(() => {
26
+ const place = paymentReturnTarget();
27
+
28
+ setTarget(place);
29
+ rememberPaymentResult(parsePaymentReturnResult(result));
30
+ leavePaymentFrame(place, window);
31
+ }, [result]);
32
+
33
+ return (
34
+ <main
35
+ className={styles.page}
36
+ data-payment-return
37
+ >
38
+ <div className={styles.box}>
39
+ <span
40
+ className={styles.spinner}
41
+ aria-hidden="true"
42
+ />
43
+ <p
44
+ className={styles.text}
45
+ role="status"
46
+ >
47
+ {labels.wait}
48
+ </p>
49
+ <a
50
+ href={target}
51
+ target="_top"
52
+ className={styles.link}
53
+ >
54
+ {labels.open}
55
+ </a>
56
+ </div>
57
+ </main>
58
+ );
59
+ }
@@ -0,0 +1,19 @@
1
+ import { notFound } from 'next/navigation';
2
+ import { PaymentReturnPage } from '@/app/_storefront/PaymentReturnPage';
3
+
4
+ // The gateway's Success URL / Fail URL: …/accounts/orders/latest,
5
+ // …/latest/success and …/latest/failed (one part at most, like Nuxt's
6
+ // [[result]]), no query. The page leaves the payment frame.
7
+ export default async function Page({
8
+ params,
9
+ }: {
10
+ params?: Promise<{ result?: string[] }>;
11
+ }) {
12
+ const { result = [] } = (await params) ?? {};
13
+
14
+ if (result.length > 1) {
15
+ notFound();
16
+ }
17
+
18
+ return <PaymentReturnPage result={result[0]} />;
19
+ }
@@ -3,6 +3,7 @@ import type { ReactNode } from 'react';
3
3
  import { BaskleeProvider } from '@/providers/BaskleeProvider';
4
4
  import { getBaskleeAppLoad } from '@/lib/basklee/appLoadServer';
5
5
  import { StorefrontShell } from '@/app/StorefrontShell';
6
+ import { PaymentReturnNotice } from '@/components/basklee/payments/PaymentReturnNotice';
6
7
  import {
7
8
  getBaskleeSavedChoices,
8
9
  getBaskleeServerLocale,
@@ -63,7 +64,11 @@ export default async function RootLayout({
63
64
  locale={language}
64
65
  currency={currency}
65
66
  >
66
- <StorefrontShell>{children}</StorefrontShell>
67
+ <StorefrontShell>
68
+ {children}
69
+ {/* Back from a payment gateway: the result, once. */}
70
+ <PaymentReturnNotice />
71
+ </StorefrontShell>
67
72
  </BaskleeProvider>
68
73
  </body>
69
74
  </html>
@@ -29,6 +29,7 @@ import {
29
29
  } from '@/lib/basklee/blogArticle';
30
30
  import {
31
31
  blogArticleBlocks,
32
+ blogYoutubeAllow,
32
33
  removeLeadingDuplicateBlogHeading,
33
34
  safeBlogArticleHtml,
34
35
  type IBlogArticleInline,
@@ -599,6 +600,31 @@ function ArticleBlocks({ blocks }: { blocks: TBlogArticleBlock[] }) {
599
600
  {block.caption ? <figcaption>{block.caption}</figcaption> : null}
600
601
  </figure>
601
602
  );
603
+ case 'youtube':
604
+ return (
605
+ <iframe
606
+ key={index}
607
+ className="blog-post-editor-youtube"
608
+ src={block.src}
609
+ title={block.title}
610
+ allow={blogYoutubeAllow}
611
+ allowFullScreen
612
+ loading="lazy"
613
+ referrerPolicy="strict-origin-when-cross-origin"
614
+ />
615
+ );
616
+ case 'video':
617
+ return (
618
+ <video
619
+ key={index}
620
+ src={block.src}
621
+ poster={block.poster}
622
+ title={block.title || undefined}
623
+ controls
624
+ playsInline
625
+ preload="none"
626
+ />
627
+ );
602
628
  default:
603
629
  return <p key={index}><ArticleInline parts={block.inline} /></p>;
604
630
  }
@@ -33,6 +33,10 @@ import {
33
33
  type StorefrontCartData,
34
34
  } from '@/lib/basklee/cartController';
35
35
  import { cartSnapshotProducts } from '@/lib/basklee/cartSnapshot';
36
+ import {
37
+ orderPaymentPlace,
38
+ rememberPaymentPlace,
39
+ } from '@/lib/basklee/paymentReturn';
36
40
  import {
37
41
  cartShipmentOrigin,
38
42
  cartShipmentTitle,
@@ -382,6 +386,10 @@ export function StorefrontCart({
382
386
  });
383
387
  aborted(signal);
384
388
  const order = orderCreatedFromResponse(result);
389
+ // The gateway's return page comes back to the new order.
390
+ if (order.link) {
391
+ rememberPaymentPlace(orderPaymentPlace(order.order_id, locale));
392
+ }
385
393
  setCreated(order);
386
394
  setData(undefined);
387
395
  setPaymentOpen(true);
@@ -31,6 +31,10 @@ import { cartSnapshotProducts } from '@/lib/basklee/cartSnapshot';
31
31
  import { formatCurrency } from '@/lib/basklee/currency';
32
32
  import { featureLabels } from '@/lib/basklee/featureLabels';
33
33
  import { mergePagination } from '@/lib/basklee/featureData';
34
+ import {
35
+ orderPaymentPlace,
36
+ rememberPaymentPlace,
37
+ } from '@/lib/basklee/paymentReturn';
34
38
  import { orderItemCount, orderLabels } from '@/lib/basklee/orderLabels';
35
39
  import {
36
40
  hasOrderAmount,
@@ -409,6 +413,10 @@ export function StorefrontOrders({
409
413
  if (controller.signal.aborted || !result) {
410
414
  return;
411
415
  }
416
+ // The gateway's return page comes back to this order.
417
+ if (result.link) {
418
+ rememberPaymentPlace(orderPaymentPlace(paymentOrder, locale));
419
+ }
412
420
  setPayment(result);
413
421
  setPaymentOrder(undefined);
414
422
  setNeedsRefresh(true);
@@ -0,0 +1,72 @@
1
+ # PaymentReturnNotice · React
2
+
3
+ ## English
4
+
5
+ Shows the result of a payment once, after the payment system sends the
6
+ customer back to the shop.
7
+
8
+ ## Contract and dependencies
9
+
10
+ A payment system opens the shop's return page after payment: its Success URL
11
+ `/accounts/orders/latest/success` or its Fail URL
12
+ `/accounts/orders/latest/failed` (no query; `/accounts/orders/latest` alone
13
+ works too). The page answers GET and POST. Inside the payment frame it moves
14
+ the whole window out of the frame; on its own page it replaces itself. It goes
15
+ back to the page the payment was opened for: the order for an order payment
16
+ (cart or order list), the wallet for a top-up or an invoice paid again from
17
+ the wallet. Without a remembered page it opens the wallet, which lists every
18
+ payment.
19
+
20
+ The return page leaves the result in the tab's `sessionStorage`. On the next
21
+ page this window reads it once (a result older than 10 minutes is dropped)
22
+ and says «Payment received» or «Payment not completed»; Continue closes it.
23
+ The status of the payment itself always comes from the order or the wallet.
24
+
25
+ The root layout renders the component on every page, inside the storefront
26
+ shell; it makes no API request. Source:
27
+ `components/basklee/payments/PaymentReturnNotice.tsx`; the return page is
28
+ `app/accounts/orders/latest/[[...result]]/page.tsx`, the shared logic
29
+ `lib/basklee/paymentReturn.ts`.
30
+
31
+ ### Props
32
+
33
+ | Prop | Meaning |
34
+ | ----------------------------------- | ------------------------------------------------------------------------------ |
35
+ | `result?: 'success' \| 'failed'` | Shows this result instead of the one the return page left (previews, tests). |
36
+ | `modal?: boolean` | `false` keeps the window in the page instead of over it. Default: `true`. |
37
+
38
+ ## Русский
39
+
40
+ Один раз показывает результат оплаты после того, как платёжная система
41
+ вернула покупателя в магазин.
42
+
43
+ Платёжная система после оплаты открывает страницу возврата магазина: Success
44
+ URL `/accounts/orders/latest/success` или Fail URL
45
+ `/accounts/orders/latest/failed` (без параметров; подходит и просто
46
+ `/accounts/orders/latest`). Страница отвечает на GET и POST. Внутри окна
47
+ оплаты она выводит из него всю вкладку, на отдельной странице заменяет саму
48
+ себя. Возврат идёт на страницу, для которой открывалась оплата: к заказу при
49
+ оплате заказа (корзина или список заказов), в кошелёк при пополнении или
50
+ повторной оплате счёта из кошелька. Если страница не запомнена, открывается
51
+ кошелёк — в нём видны все платежи.
52
+
53
+ Результат страница возврата оставляет в `sessionStorage` вкладки. На
54
+ следующей странице это окно читает его один раз (результат старше 10 минут не
55
+ показывается) и сообщает «Оплата получена» или «Оплата не прошла»; кнопка
56
+ «Продолжить» закрывает его. Состояние самого платежа всегда берётся из заказа
57
+ или кошелька.
58
+
59
+ Корневой макет выводит компонент на каждой странице внутри оболочки магазина;
60
+ API-запросов он не делает. Исходный файл:
61
+ `components/basklee/payments/PaymentReturnNotice.tsx`; страница возврата —
62
+ `app/accounts/orders/latest/[[...result]]/page.tsx`, общая логика —
63
+ `lib/basklee/paymentReturn.ts`.
64
+
65
+ ### Свойства
66
+
67
+ | Свойство | Назначение |
68
+ | ----------------------------------- | --------------------------------------------------------------------------------------- |
69
+ | `result?: 'success' \| 'failed'` | Показывает этот результат вместо оставленного страницей возврата (превью, проверки). |
70
+ | `modal?: boolean` | `false` оставляет окно на странице, а не поверх неё. По умолчанию `true`. |
71
+
72
+ [English guide](https://docs.basklee.com/en/sandbox/components/react/payment-return-notice) · [Русский](https://docs.basklee.com/ru/sandbox/components/react/payment-return-notice)
@@ -0,0 +1,117 @@
1
+ .dialog {
2
+ box-sizing: border-box;
3
+ padding: 0;
4
+ border: 1px solid var(--basklee-border);
5
+ border-radius: 0;
6
+ color: var(--basklee-text);
7
+ background: var(--basklee-surface);
8
+ font: inherit;
9
+ }
10
+
11
+ .modal {
12
+ width: 420px;
13
+ max-width: calc(100vw - 32px);
14
+ margin: auto;
15
+ }
16
+
17
+ .inline {
18
+ position: relative;
19
+ width: 100%;
20
+ max-width: 420px;
21
+ margin: 0;
22
+ }
23
+
24
+ .dialog::backdrop {
25
+ background: rgb(0 0 0 / 35%);
26
+ backdrop-filter: blur(2px);
27
+ }
28
+
29
+ .body {
30
+ display: grid;
31
+ gap: 1.25rem;
32
+ padding: 1.5rem;
33
+ }
34
+
35
+ .title {
36
+ margin: 0;
37
+ font-size: 1.125rem;
38
+ line-height: 1.75rem;
39
+ text-transform: uppercase;
40
+ letter-spacing: 0.04em;
41
+ }
42
+
43
+ .notice {
44
+ position: relative;
45
+ box-sizing: border-box;
46
+ margin: 0;
47
+ padding: 0.75rem 1rem 0.75rem 44px;
48
+ border: 1px solid var(--basklee-border);
49
+ color: var(--basklee-text);
50
+ background: var(--basklee-muted-surface);
51
+ font-size: 0.875rem;
52
+ line-height: 1.5rem;
53
+ overflow-wrap: anywhere;
54
+ }
55
+
56
+ .notice::before {
57
+ position: absolute;
58
+ top: 0.875rem;
59
+ left: 0.875rem;
60
+ width: 1.25rem;
61
+ height: 1.25rem;
62
+ content: "";
63
+ background: currentColor;
64
+ -webkit-mask: var(--payment-return-icon) center / contain no-repeat;
65
+ mask: var(--payment-return-icon) center / contain no-repeat;
66
+ }
67
+
68
+ .success {
69
+ --payment-return-icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='12' cy='12' r='9'/%3E%3Cpath d='m8 12.5 2.5 2.5L16 9.5'/%3E%3C/svg%3E");
70
+ border-color: var(--basklee-success);
71
+ color: var(--basklee-success);
72
+ background: var(--basklee-success-surface);
73
+ }
74
+
75
+ .error {
76
+ --payment-return-icon: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='1.6' stroke-linecap='round'%3E%3Ccircle cx='12' cy='12' r='9'/%3E%3Cpath d='M12 7v6m0 4h.01'/%3E%3C/svg%3E");
77
+ border-color: var(--basklee-danger);
78
+ color: var(--basklee-danger);
79
+ background: var(--basklee-danger-surface);
80
+ }
81
+
82
+ .button {
83
+ display: inline-flex;
84
+ box-sizing: border-box;
85
+ justify-self: start;
86
+ align-items: center;
87
+ justify-content: center;
88
+ height: 2.75rem;
89
+ padding: 0 1.5rem;
90
+ border: 1px solid var(--basklee-accent);
91
+ color: var(--basklee-surface);
92
+ background: var(--basklee-accent);
93
+ font: inherit;
94
+ font-size: 0.75rem;
95
+ line-height: 1rem;
96
+ text-transform: uppercase;
97
+ letter-spacing: 0.08em;
98
+ cursor: pointer;
99
+ outline: none;
100
+ transition: opacity 150ms;
101
+ }
102
+
103
+ .button:focus-visible {
104
+ opacity: 0.85;
105
+ }
106
+
107
+ @media (hover: hover) {
108
+ .button:hover {
109
+ opacity: 0.85;
110
+ }
111
+ }
112
+
113
+ @media (prefers-reduced-motion: reduce) {
114
+ .button {
115
+ transition: none;
116
+ }
117
+ }
@@ -0,0 +1,136 @@
1
+ 'use client';
2
+
3
+ import '@/components/basklee/shared/dialogs.css';
4
+ import { useEffect, useId, useRef, useState } from 'react';
5
+ import type { MouseEvent } from 'react';
6
+ import { useBaskleeSelections } from '@/providers/BaskleeProvider';
7
+ import {
8
+ createPageScrollLock,
9
+ focusedElement,
10
+ restoreFocus,
11
+ } from '@/lib/basklee/modalWindow';
12
+ import {
13
+ isPaymentReturnPath,
14
+ takePaymentResult,
15
+ } from '@/lib/basklee/paymentReturn';
16
+ import type { TPaymentReturnResult } from '@/lib/basklee/paymentReturn';
17
+ import { paymentReturnLabels } from '@/lib/basklee/paymentReturnLabels';
18
+ import styles from './PaymentReturnNotice.module.css';
19
+
20
+ export interface PaymentReturnNoticeProps {
21
+ /** Shows this result instead of the one the return page left (documentation previews). */
22
+ result?: TPaymentReturnResult;
23
+ /** `false` keeps the window in the page instead of over it (documentation previews). */
24
+ modal?: boolean;
25
+ }
26
+
27
+ /*
28
+ * The result of a payment, once, on the page the gateway's return page
29
+ * (…/accounts/orders/latest/success|failed) came back to.
30
+ */
31
+ export function PaymentReturnNotice({
32
+ result,
33
+ modal = true,
34
+ }: PaymentReturnNoticeProps) {
35
+ const locale = useBaskleeSelections((state) => state.localeCode);
36
+ const labels = paymentReturnLabels(locale);
37
+ const id = useId();
38
+ const dialog = useRef<HTMLDialogElement>(null);
39
+ const opener = useRef<HTMLElement | undefined>(undefined);
40
+ const [pageScroll] = useState(() => createPageScrollLock());
41
+ const [shown, setShown] = useState<TPaymentReturnResult>();
42
+ const copy = shown === 'success' ? labels.success : labels.failed;
43
+
44
+ // The result is taken once: React's development mode runs effects twice.
45
+ const taken = useRef<{ result?: TPaymentReturnResult }>(undefined);
46
+
47
+ useEffect(() => {
48
+ if (!taken.current) {
49
+ taken.current = {
50
+ result: isPaymentReturnPath(window.location.pathname)
51
+ ? undefined
52
+ : takePaymentResult(),
53
+ };
54
+ }
55
+ setShown(result ?? taken.current.result);
56
+ }, [result]);
57
+
58
+ useEffect(() => {
59
+ const element = dialog.current;
60
+
61
+ if (!shown || !element || element.open) {
62
+ return;
63
+ }
64
+ if (!modal) {
65
+ // Opened by its attribute, not show(): the focus stays where it is.
66
+ element.setAttribute('open', '');
67
+ return;
68
+ }
69
+ opener.current = focusedElement();
70
+ pageScroll.lock();
71
+ element.showModal();
72
+
73
+ return () => pageScroll.unlock();
74
+ }, [modal, pageScroll, shown]);
75
+
76
+ function close() {
77
+ dialog.current?.close();
78
+ setShown(undefined);
79
+ if (pageScroll.locked) {
80
+ pageScroll.unlock();
81
+ restoreFocus(opener.current);
82
+ }
83
+ }
84
+
85
+ function backdrop(event: MouseEvent<HTMLDialogElement>) {
86
+ if (modal && event.target === dialog.current) {
87
+ close();
88
+ }
89
+ }
90
+
91
+ if (!shown) {
92
+ return null;
93
+ }
94
+
95
+ return (
96
+ <dialog
97
+ ref={dialog}
98
+ data-stable-modal="fit"
99
+ data-payment-return-notice={shown}
100
+ aria-labelledby={`${id}-title`}
101
+ aria-describedby={`${id}-text`}
102
+ className={`${styles.dialog} ${modal ? styles.modal : styles.inline}`}
103
+ onCancel={(event) => {
104
+ event.preventDefault();
105
+ close();
106
+ }}
107
+ onClick={backdrop}
108
+ >
109
+ <div className={styles.body}>
110
+ <h2
111
+ id={`${id}-title`}
112
+ className={styles.title}
113
+ >
114
+ {copy.title}
115
+ </h2>
116
+ <p
117
+ id={`${id}-text`}
118
+ className={`${styles.notice} ${
119
+ shown === 'success' ? styles.success : styles.error
120
+ }`}
121
+ role="status"
122
+ >
123
+ {copy.text}
124
+ </p>
125
+ <button
126
+ type="button"
127
+ className={styles.button}
128
+ data-payment-return-continue
129
+ onClick={close}
130
+ >
131
+ {labels.continue}
132
+ </button>
133
+ </div>
134
+ </dialog>
135
+ );
136
+ }
@@ -23,6 +23,10 @@ import type { ITransformValue } from '@/interfaces/basklee/shared/ITransformValu
23
23
  import { formatCurrency } from '@/lib/basklee/currency';
24
24
  import { featureLabels } from '@/lib/basklee/featureLabels';
25
25
  import { mergePagination } from '@/lib/basklee/featureData';
26
+ import {
27
+ rememberPaymentPlace,
28
+ walletPaymentPlace,
29
+ } from '@/lib/basklee/paymentReturn';
26
30
  import { getAvailableNestedValueFromObject } from '@/lib/basklee/presentation';
27
31
  import {
28
32
  walletComment,
@@ -218,6 +222,14 @@ export function StorefrontWallet({
218
222
  const [error, setError] = useState(initialError);
219
223
  const [fields, setFields] = useState<Record<string, string>>({});
220
224
 
225
+ // A top-up, or an unpaid invoice paid again from the list: the gateway's
226
+ // return page comes back to the wallet.
227
+ useEffect(() => {
228
+ if (payment?.link) {
229
+ rememberPaymentPlace(walletPaymentPlace(selections.localeCode));
230
+ }
231
+ }, [payment, selections.localeCode]);
232
+
221
233
  async function run(
222
234
  work: (controller: AbortController) => Promise<void>,
223
235
  withFields = false,
@@ -467,7 +467,12 @@ export type TBlogArticleBlock =
467
467
  | { kind: 'paragraph'; inline: IBlogArticleInline[] }
468
468
  | { kind: 'list'; ordered: boolean; items: IBlogArticleInline[][] }
469
469
  | { kind: 'quote'; blocks: TBlogArticleBlock[] }
470
- | { kind: 'image'; src: string; alt: string; caption: string; width?: number; height?: number };
470
+ | { kind: 'image'; src: string; alt: string; caption: string; width?: number; height?: number }
471
+ // A YouTube player (the privacy-enhanced address) and an uploaded video:
472
+ // the server render keeps them, so search engines find the video without
473
+ // scripts (Google: a video must be on the page without a click).
474
+ | { kind: 'youtube'; src: string; title: string }
475
+ | { kind: 'video'; src: string; poster?: string; title: string };
471
476
 
472
477
  const MAX_ARTICLE_BLOCKS = 600;
473
478
 
@@ -537,13 +542,143 @@ function blockImageSizeOf(figure: { width?: number; height?: number }) {
537
542
  return figure.width && figure.height ? { width: figure.width, height: figure.height } : {};
538
543
  }
539
544
 
545
+ /** A video of an article text: a YouTube player or an uploaded file. */
546
+ export interface IBlogArticleVideo {
547
+ kind: 'youtube' | 'file';
548
+ /** youtube: the privacy-enhanced player address; file: the file address. */
549
+ src: string;
550
+ /** youtube: the video ID. */
551
+ id?: string;
552
+ title: string;
553
+ poster?: string;
554
+ }
555
+
556
+ const articleMedia = /<(iframe|video)\b([^>]*)>([\s\S]*?)<\/\1\s*>/gi;
557
+
558
+ function articleMediaOf(
559
+ name: string,
560
+ attributes: string,
561
+ inner: string,
562
+ appOrigin: string,
563
+ ): IBlogArticleVideo | undefined {
564
+ const title = tagAttribute(attributes, 'title') || tagAttribute(attributes, 'aria-label');
565
+
566
+ if (name.toLowerCase() === 'iframe') {
567
+ const src = blogYoutubeEmbedSource(tagAttribute(attributes, 'src'));
568
+ const id = /\/embed\/([\w-]{11})/.exec(src)?.[1];
569
+
570
+ return src && id ? { kind: 'youtube', src, id, title } : undefined;
571
+ }
572
+
573
+ const own = tagAttribute(attributes, 'src') ||
574
+ tagAttribute(/<source\b([^>]*)>/i.exec(inner)?.[1] ?? '', 'src');
575
+ const src = blockImage(own, appOrigin);
576
+ const poster = blockImage(tagAttribute(attributes, 'poster'), appOrigin);
577
+
578
+ return src ? { kind: 'file', src, title, ...(poster ? { poster } : {}) } : undefined;
579
+ }
580
+
581
+ /** The YouTube players and uploaded videos of an article text, in order. */
582
+ export function blogArticleVideos(
583
+ value: string | undefined,
584
+ appOrigin = BLOCK_MEDIA_ORIGIN,
585
+ ): IBlogArticleVideo[] {
586
+ const found: IBlogArticleVideo[] = [];
587
+
588
+ for (const match of (value ?? '').replace(/<!--[\s\S]*?-->/g, ' ').matchAll(articleMedia)) {
589
+ const video = articleMediaOf(match[1]!, match[2] ?? '', match[3] ?? '', appOrigin);
590
+
591
+ if (video) {
592
+ found.push(video);
593
+ }
594
+ }
595
+
596
+ return found;
597
+ }
598
+
599
+ /**
600
+ * An article's videos for search engines (pageSeo storefrontVideoObject):
601
+ * the YouTube players and uploaded videos of its text, then the post's own
602
+ * videos. A YouTube video gets YouTube's own picture; an uploaded one its
603
+ * poster, else the article's cover. The article's date stands for the upload
604
+ * date. Each video once.
605
+ */
606
+ export function blogArticleVideoData(input: {
607
+ html: string | undefined;
608
+ /** The post's own videos (post.videos): file and poster addresses. */
609
+ uploaded?: { source?: string; poster?: string }[];
610
+ title: string;
611
+ description?: string;
612
+ cover?: string;
613
+ published?: string;
614
+ /** Makes an address complete (storefrontAbsoluteUrl). */
615
+ absoluteUrl: (value: string | undefined) => string | undefined;
616
+ }): {
617
+ name: string;
618
+ description?: string;
619
+ thumbnailUrl?: string;
620
+ uploadDate?: string;
621
+ embedUrl?: string;
622
+ contentUrl?: string;
623
+ }[] {
624
+ const seen = new Set<string>();
625
+ const named = (title: string) =>
626
+ title && !/^youtube video$/i.test(title) ? title : input.title;
627
+ const own = (input.uploaded ?? []).map((video): IBlogArticleVideo => ({
628
+ kind: 'file',
629
+ src: video.source ?? '',
630
+ title: '',
631
+ ...(video.poster ? { poster: video.poster } : {}),
632
+ }));
633
+
634
+ return [...blogArticleVideos(input.html, ''), ...own].flatMap((video) => {
635
+ const key = video.id ?? video.src;
636
+
637
+ if (!key || seen.has(key)) {
638
+ return [];
639
+ }
640
+ seen.add(key);
641
+ if (video.kind === 'youtube') {
642
+ return [{
643
+ name: named(video.title),
644
+ description: input.description,
645
+ thumbnailUrl: `https://i.ytimg.com/vi/${video.id}/hqdefault.jpg`,
646
+ uploadDate: input.published,
647
+ embedUrl: `https://www.youtube.com/embed/${video.id}`,
648
+ }];
649
+ }
650
+ const contentUrl = input.absoluteUrl(video.src);
651
+
652
+ return contentUrl
653
+ ? [{
654
+ name: named(video.title),
655
+ description: input.description,
656
+ thumbnailUrl: input.absoluteUrl(video.poster) || input.cover,
657
+ uploadDate: input.published,
658
+ contentUrl,
659
+ }]
660
+ : [];
661
+ });
662
+ }
663
+
540
664
  /** The article as plain blocks for the server render and the hydration. */
541
665
  export function blogArticleBlocks(
542
666
  value: string | undefined,
543
667
  appOrigin = BLOCK_MEDIA_ORIGIN,
544
668
  ): TBlogArticleBlock[] {
669
+ const media: IBlogArticleVideo[] = [];
545
670
  const html = (value ?? '')
546
671
  .replace(/<!--[\s\S]*?-->/g, ' ')
672
+ // Players and videos become markers before the other media are dropped.
673
+ .replace(articleMedia, (_, name: string, attributes: string, inner: string) => {
674
+ const video = articleMediaOf(name, attributes, inner, appOrigin);
675
+
676
+ if (!video) {
677
+ return ' ';
678
+ }
679
+ media.push(video);
680
+ return `<bkmedia i="${media.length - 1}"></bkmedia>`;
681
+ })
547
682
  .replace(skippedElements, ' ');
548
683
  const blocks: TBlogArticleBlock[] = [];
549
684
  const quotes: TBlogArticleBlock[][] = [];
@@ -686,6 +821,15 @@ export function blogArticleBlocks(
686
821
  flush();
687
822
  push({ kind: 'image', src, alt, caption: '', ...blockImageSize(attributes) });
688
823
  }
824
+ } else if (name === 'bkmedia') {
825
+ const video = media[Number(tagAttribute(attributes, 'i'))];
826
+
827
+ if (video) {
828
+ flush();
829
+ push(video.kind === 'youtube'
830
+ ? { kind: 'youtube', src: video.src, title: video.title || 'YouTube video' }
831
+ : { kind: 'video', src: video.src, title: video.title, ...(video.poster ? { poster: video.poster } : {}) });
832
+ }
689
833
  } else if (name === 'a') {
690
834
  link = blockLink(tagAttribute(attributes, 'href'));
691
835
  } else if (name === 'br' || name === 'td' || name === 'th') {
@@ -26,6 +26,7 @@ import {
26
26
  type StorefrontSeoPage,
27
27
  } from '@/lib/basklee/pageSeo';
28
28
  import { structuredDataJson } from '@/lib/basklee/productStructuredData';
29
+ import { isPaymentReturnPath } from '@/lib/basklee/paymentReturn';
29
30
  import { getProductSocialMeta, getStorefrontSeo } from '@/lib/basklee/seo';
30
31
  import { findCatalogCategory } from '@/lib/basklee/catalog';
31
32
  import { blogPostCover } from '@/lib/basklee/blogPresentation';
@@ -38,7 +39,9 @@ import {
38
39
  import {
39
40
  getAvailableNestedValueFromObject,
40
41
  plainText,
42
+ safePublicUrl,
41
43
  } from '@/lib/basklee/presentation';
44
+ import { blogArticleVideoData } from '@/lib/basklee/blogArticleHtml';
42
45
 
43
46
  const privatePages = new Set([
44
47
  'activity',
@@ -46,6 +49,7 @@ const privatePages = new Set([
46
49
  'cart',
47
50
  'logout',
48
51
  'orders',
52
+ 'paymentReturn',
49
53
  'profile',
50
54
  'subscriptions',
51
55
  'tickets',
@@ -90,6 +94,10 @@ export function storefrontSeoPage(pathname: string): StorefrontSeoPage {
90
94
  if (!section) {
91
95
  return 'home';
92
96
  }
97
+ // The gateway's return page: …/accounts/orders/latest[/<result>].
98
+ if (isPaymentReturnPath(pathname) && segments.length <= 4) {
99
+ return 'paymentReturn';
100
+ }
93
101
  if (segments.length === 1 && staticPages.has(section)) {
94
102
  return section as StorefrontSeoPage;
95
103
  }
@@ -327,6 +335,29 @@ export function storefrontMetadata(
327
335
  modified,
328
336
  locale,
329
337
  storeName: init?.contact?.company_name,
338
+ // The players and videos of the text, and the post's own videos.
339
+ videos: blogArticleVideoData({
340
+ html:
341
+ getAvailableNestedValueFromObject(
342
+ records.post.locale,
343
+ locale,
344
+ 'post_view_text',
345
+ ) ||
346
+ getAvailableNestedValueFromObject(
347
+ records.post.locale,
348
+ locale,
349
+ 'post_preview_text',
350
+ ),
351
+ uploaded: (records.post.videos ?? []).map((video) => ({
352
+ source: safePublicUrl(video.video_url),
353
+ poster: safePublicUrl(video.preview_url),
354
+ })),
355
+ title: content.title,
356
+ description: content.description,
357
+ cover: image,
358
+ published,
359
+ absoluteUrl: (value) => storefrontAbsoluteUrl(value, origin),
360
+ }),
330
361
  }),
331
362
  )
332
363
  : '';
@@ -117,6 +117,11 @@ const pageCopy = {
117
117
  'Завершение сеанса и возврат на главную страницу.',
118
118
  'аккаунт, выход, сеанс',
119
119
  ],
120
+ paymentReturn: [
121
+ 'Возврат после оплаты',
122
+ 'Возврат из платёжной системы в магазин.',
123
+ 'оплата, платёж, возврат',
124
+ ],
120
125
  notFound: [
121
126
  'Страница не найдена',
122
127
  'По этому адресу в магазине нет страницы.',
@@ -252,6 +257,11 @@ const pageCopy = {
252
257
  'End the current session and return to the homepage.',
253
258
  'account, sign out, session',
254
259
  ],
260
+ paymentReturn: [
261
+ 'Back from payment',
262
+ 'The return from the payment system to the shop.',
263
+ 'payment, checkout, return',
264
+ ],
255
265
  notFound: [
256
266
  'Page not found',
257
267
  'The store has no page at this address.',
@@ -387,6 +397,11 @@ const pageCopy = {
387
397
  'Fin de la sesión y vuelta a la página principal.',
388
398
  'cuenta, cerrar sesión, sesión',
389
399
  ],
400
+ paymentReturn: [
401
+ 'Vuelta del pago',
402
+ 'Regreso del sistema de pago a la tienda.',
403
+ 'pago, cobro, vuelta',
404
+ ],
390
405
  notFound: [
391
406
  'Página no encontrada',
392
407
  'No hay ninguna página de la tienda en esta dirección.',
@@ -611,9 +626,47 @@ export function storefrontIsoDate(
611
626
  return match ? `${match[3]}-${match[2]}-${match[1]}` : undefined;
612
627
  }
613
628
 
629
+ /** A video of a page, for search engines (blogArticleVideoData gives an article's). */
630
+ export interface IStorefrontVideo {
631
+ name: string;
632
+ description?: string;
633
+ /** Complete address of the video's picture. */
634
+ thumbnailUrl?: string;
635
+ /** ISO 8601 date. */
636
+ uploadDate?: string;
637
+ /** The player address (YouTube), or the file address. */
638
+ embedUrl?: string;
639
+ contentUrl?: string;
640
+ }
641
+
642
+ /**
643
+ * schema.org VideoObject (Google "Video" structured data). Google needs a
644
+ * name, a thumbnail and an upload date, and a player or file address; a video
645
+ * without them gives `undefined`.
646
+ */
647
+ export function storefrontVideoObject(
648
+ video: IStorefrontVideo,
649
+ ): Record<string, unknown> | undefined {
650
+ const name = video.name.trim();
651
+ if (!name || !video.thumbnailUrl || !video.uploadDate || !(video.embedUrl || video.contentUrl)) {
652
+ return undefined;
653
+ }
654
+ return {
655
+ '@type': 'VideoObject',
656
+ name: name.slice(0, 200),
657
+ description: video.description?.trim() || name,
658
+ thumbnailUrl: [video.thumbnailUrl],
659
+ uploadDate: video.uploadDate,
660
+ ...(video.embedUrl ? { embedUrl: video.embedUrl } : {}),
661
+ ...(video.contentUrl ? { contentUrl: video.contentUrl } : {}),
662
+ };
663
+ }
664
+
614
665
  /**
615
666
  * schema.org BlogPosting of a journal article (Google "Article" structured
616
- * data): headline, cover, dates, and the store as author and publisher.
667
+ * data): headline, cover, dates, and the store as author and publisher. The
668
+ * videos of the text (YouTube players and uploaded files) go in as
669
+ * VideoObject, so search engines know what the article shows.
617
670
  */
618
671
  export function storefrontArticleData(input: {
619
672
  canonical: string;
@@ -625,6 +678,7 @@ export function storefrontArticleData(input: {
625
678
  modified?: string;
626
679
  locale: string;
627
680
  storeName?: string;
681
+ videos?: IStorefrontVideo[];
628
682
  }): Record<string, unknown> {
629
683
  const store = {
630
684
  '@type': 'Organization',
@@ -632,6 +686,9 @@ export function storefrontArticleData(input: {
632
686
  url: `${input.origin}/`,
633
687
  };
634
688
  const modified = input.modified || input.published;
689
+ const videos = (input.videos ?? [])
690
+ .map((video) => storefrontVideoObject(video))
691
+ .filter((video): video is Record<string, unknown> => Boolean(video));
635
692
  return {
636
693
  '@context': 'https://schema.org',
637
694
  '@type': 'BlogPosting',
@@ -646,6 +703,7 @@ export function storefrontArticleData(input: {
646
703
  inLanguage: input.locale,
647
704
  author: store,
648
705
  publisher: store,
706
+ ...(videos.length ? { video: videos } : {}),
649
707
  };
650
708
  }
651
709
 
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Back from a payment gateway. The gateway's Success URL and Fail URL (set in
3
+ * its merchant cabinet) are the same plain addresses on every Basklee
4
+ * storefront, with no query: …/accounts/orders/latest/success and
5
+ * …/accounts/orders/latest/failed (…/latest alone works too). The gateway may
6
+ * have run inside the payment frame: the return page then takes the whole
7
+ * window out of the frame, back to the page the payment was made for, which
8
+ * shows the result once.
9
+ */
10
+
11
+ export const PAYMENT_RETURN_PATH = '/accounts/orders/latest';
12
+
13
+ export type TPaymentReturnResult = 'success' | 'failed';
14
+
15
+ type TStore = Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
16
+
17
+ type TFrameWindow = Pick<Window, 'self' | 'top' | 'location'>;
18
+
19
+ // The page a payment was opened for waits in localStorage: a gateway that
20
+ // opens in a new tab comes back in that tab, which has its own session.
21
+ const PLACE_KEY = 'basklee:payment-place';
22
+ const PLACE_MAX_AGE = 24 * 60 * 60 * 1000;
23
+ // The result waits for that page in this browser tab (a same-site payment
24
+ // frame shares it with the window around it).
25
+ const RESULT_KEY = 'basklee:payment-return';
26
+ const RESULT_MAX_AGE = 10 * 60 * 1000;
27
+
28
+ /** The page every payment can be followed on when no other one is known. */
29
+ export const PAYMENT_RETURN_FALLBACK = '/wallet';
30
+
31
+ /** `success` or `failed` from the last part of the address; `undefined` for anything else. */
32
+ export function parsePaymentReturnResult(
33
+ value: unknown,
34
+ ): TPaymentReturnResult | undefined {
35
+ const item = Array.isArray(value) ? value[0] : value;
36
+
37
+ if (item === 'success') {
38
+ return 'success';
39
+ }
40
+
41
+ return item === 'failed' || item === 'fail' ? 'failed' : undefined;
42
+ }
43
+
44
+ /** True for …/accounts/orders/latest and every address under it. */
45
+ export function isPaymentReturnPath(path: string): boolean {
46
+ const clean = path.replace(/\/+$/, '');
47
+
48
+ return (
49
+ clean === PAYMENT_RETURN_PATH ||
50
+ clean.startsWith(`${PAYMENT_RETURN_PATH}/`)
51
+ );
52
+ }
53
+
54
+ /** A page of this storefront: one leading slash, not the return page itself. */
55
+ function storefrontPath(value: unknown): string | undefined {
56
+ if (
57
+ typeof value !== 'string' ||
58
+ !value.startsWith('/') ||
59
+ value.startsWith('//') ||
60
+ value.includes('\\')
61
+ ) {
62
+ return undefined;
63
+ }
64
+
65
+ return isPaymentReturnPath(value.split(/[?#]/)[0] ?? '') ? undefined : value;
66
+ }
67
+
68
+ /** The address of an order's own page in the given language. */
69
+ export function orderPaymentPlace(orderId: number, locale: string): string {
70
+ const query = new URLSearchParams({ order: String(orderId) });
71
+
72
+ if (locale) {
73
+ query.set('locale', locale);
74
+ }
75
+
76
+ return `/orders?${query}`;
77
+ }
78
+
79
+ /** The wallet page in the given language. */
80
+ export function walletPaymentPlace(locale: string): string {
81
+ return locale
82
+ ? `${PAYMENT_RETURN_FALLBACK}?${new URLSearchParams({ locale })}`
83
+ : PAYMENT_RETURN_FALLBACK;
84
+ }
85
+
86
+ function browserStorage(kind: 'localStorage' | 'sessionStorage'): TStore | undefined {
87
+ try {
88
+ return typeof window === 'undefined' ? undefined : window[kind];
89
+ } catch {
90
+ return undefined;
91
+ }
92
+ }
93
+
94
+ /** Remembers the page a payment was opened for, the way back from the gateway. */
95
+ export function rememberPaymentPlace(
96
+ path: string,
97
+ store: TStore | undefined = browserStorage('localStorage'),
98
+ now = Date.now(),
99
+ ): void {
100
+ const place = storefrontPath(path);
101
+
102
+ try {
103
+ if (place) {
104
+ store?.setItem(PLACE_KEY, JSON.stringify({ path: place, at: now }));
105
+ }
106
+ } catch {
107
+ // Storage off: the gateway comes back to the wallet.
108
+ }
109
+ }
110
+
111
+ /** The remembered page of the last day, or the wallet page. */
112
+ export function paymentReturnTarget(
113
+ store: TStore | undefined = browserStorage('localStorage'),
114
+ now = Date.now(),
115
+ ): string {
116
+ try {
117
+ const saved = store?.getItem(PLACE_KEY);
118
+
119
+ if (saved) {
120
+ const { path, at } = JSON.parse(saved) as { path?: unknown; at?: unknown };
121
+ const place = storefrontPath(path);
122
+
123
+ if (
124
+ place &&
125
+ typeof at === 'number' &&
126
+ now - at >= 0 &&
127
+ now - at <= PLACE_MAX_AGE
128
+ ) {
129
+ return place;
130
+ }
131
+ }
132
+ } catch {
133
+ // A damaged entry: the wallet lists every payment.
134
+ }
135
+
136
+ return PAYMENT_RETURN_FALLBACK;
137
+ }
138
+
139
+ export function rememberPaymentResult(
140
+ result: TPaymentReturnResult | undefined,
141
+ store: TStore | undefined = browserStorage('sessionStorage'),
142
+ now = Date.now(),
143
+ ): void {
144
+ try {
145
+ if (result) {
146
+ store?.setItem(RESULT_KEY, JSON.stringify({ result, at: now }));
147
+ } else {
148
+ store?.removeItem(RESULT_KEY);
149
+ }
150
+ } catch {
151
+ // Storage off: the page opens without the result window.
152
+ }
153
+ }
154
+
155
+ /** The result left by the return page in the last 10 minutes, once: it is removed as it is read. */
156
+ export function takePaymentResult(
157
+ store: TStore | undefined = browserStorage('sessionStorage'),
158
+ now = Date.now(),
159
+ ): TPaymentReturnResult | undefined {
160
+ try {
161
+ const saved = store?.getItem(RESULT_KEY);
162
+
163
+ if (!saved) {
164
+ return undefined;
165
+ }
166
+ store?.removeItem(RESULT_KEY);
167
+ const { result, at } = JSON.parse(saved) as { result?: unknown; at?: unknown };
168
+
169
+ return typeof at === 'number' && now - at >= 0 && now - at <= RESULT_MAX_AGE
170
+ ? parsePaymentReturnResult(result)
171
+ : undefined;
172
+ } catch {
173
+ return undefined;
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Opens `target` in the whole browser window. In the payment frame the top
179
+ * window goes there (one history entry, so Back returns to the page with the
180
+ * frame); on its own the page replaces itself, so Back does not land on this
181
+ * page again. A top window of another site refuses: the frame itself goes
182
+ * there then.
183
+ */
184
+ export function leavePaymentFrame(
185
+ target: string,
186
+ view: TFrameWindow,
187
+ ): 'top' | 'self' {
188
+ try {
189
+ if (view.top && view.top !== view.self) {
190
+ view.top.location.href = target;
191
+ return 'top';
192
+ }
193
+ } catch {
194
+ // Another site's window, or the browser refused to move it.
195
+ }
196
+ view.location.replace(target);
197
+
198
+ return 'self';
199
+ }
@@ -0,0 +1,50 @@
1
+ const en = {
2
+ title: 'Back from payment',
3
+ wait: 'Please wait. Returning to the shop…',
4
+ open: 'Open the shop',
5
+ continue: 'Continue',
6
+ success: {
7
+ title: 'Payment received',
8
+ text: 'Thank you! The payment counts as soon as the payment system confirms it. Its status is shown on this page.',
9
+ },
10
+ failed: {
11
+ title: 'Payment not completed',
12
+ text: 'The payment was cancelled or declined. Try again or choose another payment method.',
13
+ },
14
+ };
15
+
16
+ const ru: typeof en = {
17
+ title: 'Возврат после оплаты',
18
+ wait: 'Подождите. Возвращаемся в магазин…',
19
+ open: 'Открыть магазин',
20
+ continue: 'Продолжить',
21
+ success: {
22
+ title: 'Оплата получена',
23
+ text: 'Спасибо! Оплата засчитается, как только платёжная система её подтвердит. Её статус — на этой странице.',
24
+ },
25
+ failed: {
26
+ title: 'Оплата не прошла',
27
+ text: 'Оплата отменена или отклонена. Попробуйте ещё раз или выберите другой способ оплаты.',
28
+ },
29
+ };
30
+
31
+ const es: typeof en = {
32
+ title: 'Vuelta del pago',
33
+ wait: 'Espera. Volviendo a la tienda…',
34
+ open: 'Abrir la tienda',
35
+ continue: 'Continuar',
36
+ success: {
37
+ title: 'Pago recibido',
38
+ text: '¡Gracias! El pago cuenta en cuanto el sistema de pago lo confirma. Su estado está en esta página.',
39
+ },
40
+ failed: {
41
+ title: 'Pago no completado',
42
+ text: 'El pago se canceló o fue rechazado. Inténtalo de nuevo o elige otro método de pago.',
43
+ },
44
+ };
45
+
46
+ export function paymentReturnLabels(locale: string) {
47
+ const code = locale.toLowerCase();
48
+
49
+ return code.startsWith('ru') ? ru : code.startsWith('es') ? es : en;
50
+ }
@@ -35,6 +35,9 @@ export interface StorefrontStructuredProduct {
35
35
  c_feedbacks?: number | null;
36
36
  avg_raiting?: number | string | null;
37
37
  } | null;
38
+ /** The product's videos (Video tab of the panel) and its last change. */
39
+ videos?: { product_video?: string | null; preview?: string | null }[] | null;
40
+ date_updated?: string | null;
38
41
  }
39
42
 
40
43
  export interface StorefrontProductDataOptions {
@@ -130,6 +133,52 @@ function priceValue(
130
133
  return prices?.[currencyId] && Number.isFinite(value) ? value : undefined;
131
134
  }
132
135
 
136
+ // A backend date (`d.m.Y`, or ISO 8601 with a time) as an ISO 8601 date.
137
+ function structuredDate(value: string | null | undefined): string | undefined {
138
+ const text = (value ?? '').trim();
139
+ const dmy = /^(\d{2})\.(\d{2})\.(\d{4})/.exec(text);
140
+ if (dmy) {
141
+ return `${dmy[3]}-${dmy[2]}-${dmy[1]}`;
142
+ }
143
+ return /^\d{4}-\d{2}-\d{2}/.exec(text)?.[0];
144
+ }
145
+
146
+ /**
147
+ * The product's videos as schema.org VideoObject (Google "Video" structured
148
+ * data): the file, its preview (or the first photo) as the thumbnail, the
149
+ * product's name and description. Google needs a name, a thumbnail and an
150
+ * upload date: the product's last change stands for the upload date, and a
151
+ * video without a thumbnail or a date is left out.
152
+ */
153
+ export function storefrontProductVideoObjects(
154
+ product: StorefrontStructuredProduct | undefined,
155
+ options: Pick<StorefrontProductDataOptions, 'absoluteUrl' | 'description'> & {
156
+ name: string;
157
+ fallbackImage?: string;
158
+ },
159
+ ): Record<string, unknown>[] {
160
+ const uploadDate = structuredDate(product?.date_updated);
161
+ if (!product || !uploadDate) {
162
+ return [];
163
+ }
164
+ return (product.videos ?? []).flatMap((video, index, list) => {
165
+ const contentUrl = options.absoluteUrl(video.product_video ?? undefined);
166
+ const thumbnailUrl = options.absoluteUrl(video.preview ?? undefined) || options.fallbackImage;
167
+ if (!contentUrl || !thumbnailUrl) {
168
+ return [];
169
+ }
170
+ const name = list.length > 1 ? `${options.name} (${index + 1})` : options.name;
171
+ return [{
172
+ '@type': 'VideoObject',
173
+ name,
174
+ 'description': options.description?.trim() || name,
175
+ 'thumbnailUrl': [thumbnailUrl],
176
+ uploadDate,
177
+ contentUrl,
178
+ }];
179
+ });
180
+ }
181
+
133
182
  /** The schema.org Product of the page, or undefined when it cannot be built. */
134
183
  export function storefrontProductStructuredData(
135
184
  product: StorefrontStructuredProduct | undefined,
@@ -160,6 +209,12 @@ export function storefrontProductStructuredData(
160
209
  Boolean(image) && list.indexOf(image) === index,
161
210
  )
162
211
  .slice(0, MAX_IMAGES);
212
+ const videos = storefrontProductVideoObjects(product, {
213
+ name,
214
+ description: options.description,
215
+ absoluteUrl: options.absoluteUrl,
216
+ fallbackImage: images[0],
217
+ });
163
218
  const inStock =
164
219
  ON_SALE_STATUSES.includes(product.status?.status) &&
165
220
  product.c_real_left > 0;
@@ -213,6 +268,8 @@ export function storefrontProductStructuredData(
213
268
  ? { description: options.description.trim() }
214
269
  : {}),
215
270
  ...(images.length ? { image: images } : {}),
271
+ // The product's videos: the page plays them in its gallery.
272
+ ...(videos.length ? { subjectOf: videos } : {}),
216
273
  ...(brand ? { brand: { '@type': 'Brand', 'name': brand } } : {}),
217
274
  ...(offer ? { offers: offer } : {}),
218
275
  ...(reviews > 0 && Number.isFinite(rating) && rating > 0