basklee-react 0.9.4 → 0.9.6

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.
Files changed (30) hide show
  1. package/README.md +4 -0
  2. package/package.json +2 -2
  3. package/templates/app/_storefront/SearchPage.tsx +2 -2
  4. package/templates/components/basklee/account/StorefrontLogout.README.md +4 -0
  5. package/templates/components/basklee/blog/BlogArticle.README.md +18 -0
  6. package/templates/components/basklee/blog/BlogArticle.tsx +12 -0
  7. package/templates/components/basklee/orders/OrderDetails.README.md +4 -0
  8. package/templates/components/basklee/orders/OrderDetails.tsx +5 -0
  9. package/templates/components/basklee/storefront/StorefrontFooter.README.md +6 -0
  10. package/templates/components/basklee/storefront/StorefrontFooter.module.css +27 -2
  11. package/templates/components/basklee/storefront/StorefrontFooter.tsx +14 -3
  12. package/templates/components/basklee/stores/StorefrontStores.README.md +4 -0
  13. package/templates/components/basklee/stores/StorefrontStores.tsx +2 -1
  14. package/templates/lib/basklee/blogMediaFallback.ts +322 -0
  15. package/templates/lib/basklee/browseLabels.ts +12 -0
  16. package/templates/lib/basklee/cartLabels.ts +4 -1
  17. package/templates/lib/basklee/contactLabels.ts +13 -1
  18. package/templates/lib/basklee/directoryLabels.ts +3 -0
  19. package/templates/lib/basklee/featureLabels.ts +12 -0
  20. package/templates/lib/basklee/footerLabels.ts +3 -0
  21. package/templates/lib/basklee/headerLabels.ts +1 -1
  22. package/templates/lib/basklee/profile.ts +52 -0
  23. package/templates/lib/basklee/profileLabels.ts +18 -3
  24. package/templates/lib/basklee/reviewLabels.ts +6 -0
  25. package/templates/lib/basklee/sellerDirectory.ts +93 -0
  26. package/templates/lib/basklee/sessionLabels.ts +6 -6
  27. package/templates/lib/basklee/storeDirectory.ts +26 -0
  28. package/templates/lib/basklee/subscriptionLabels.ts +3 -0
  29. package/templates/lib/basklee/tabLocation.ts +37 -0
  30. package/templates/lib/basklee/ticketDraft.ts +56 -0
package/README.md CHANGED
@@ -618,3 +618,7 @@ npm pack --dry-run
618
618
 
619
619
  The published tarball includes only the CLI, runtime source, README, license,
620
620
  starter templates, and package metadata.
621
+
622
+ ---
623
+
624
+ Powered by [Basklee](https://basklee.com).
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "basklee-react",
3
- "version": "0.9.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.",
3
+ "version": "0.9.6",
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",
7
7
  "author": "Basklee",
@@ -3,7 +3,7 @@
3
3
  import { useEffect, useState } from 'react';
4
4
  import { useBaskleeApi } from '@/hooks/useBaskleeApi';
5
5
  import { directoryLabels } from '@/lib/basklee/directoryLabels';
6
- import { storeAddress, storePhoneLink } from '@/lib/basklee/storeDirectory';
6
+ import { storeAddress, storePhoneLink, storePhoneText } from '@/lib/basklee/storeDirectory';
7
7
  import type { IPhysicalStore, IStoreDirectoryResponse } from '@/interfaces/basklee/stores/IStoreDirectory';
8
8
  import { ProductSearchResults } from '@/components/basklee/search/ProductSearchResults';
9
9
  import {
@@ -158,7 +158,7 @@ export function SearchPage({
158
158
  <p>{storeAddress(physicalStore, locale)}</p>
159
159
  {physicalStore.phone_number ? (
160
160
  <a href={storePhoneLink(physicalStore.phone_number)}>
161
- {physicalStore.phone_number}
161
+ {storePhoneText(physicalStore.phone_number)}
162
162
  </a>
163
163
  ) : null}
164
164
  {physicalStore.working_hours ? (
@@ -13,6 +13,8 @@ Retry calls `onRetry`. The Home action calls `onSelectHome`. The component does
13
13
  not start either request or navigation on its own, which keeps its initial
14
14
  server render free of browser-only work.
15
15
 
16
+ The progress and success messages say that the session is ended on all devices: `profile_logout` signs the customer out everywhere, and the page says so.
17
+
16
18
  ### Props
17
19
 
18
20
  | Prop | Meaning |
@@ -37,6 +39,8 @@ server render free of browser-only work.
37
39
  Компонент сам не запускает запрос и навигацию, поэтому его начальный серверный
38
40
  рендер не зависит от браузерных API.
39
41
 
42
+ Сообщения о ходе и об успешном выходе говорят, что сеанс завершён на всех устройствах: `profile_logout` выводит покупателя из аккаунта везде, и страница так и пишет.
43
+
40
44
  ### Свойства
41
45
 
42
46
  | Свойство | Назначение |
@@ -29,6 +29,15 @@ stop and an «Open image» name; a zoom-in cursor marks them. Images inside a
29
29
  link, a button or a product placement keep their own action. The helper is
30
30
  `lib/basklee/blogImageViewer.ts`.
31
31
 
32
+ A picture, video or YouTube player of the text that does not load is replaced
33
+ by a placeholder in the text's own colours: «The image could not be loaded»
34
+ with the picture's `alt`, or «The video could not be loaded» with a link to
35
+ the video file or to the video on YouTube. A blocked YouTube gives no error,
36
+ so the article checks once per page whether YouTube's image server answers
37
+ within 8 seconds; the players stay when it does. Pictures of product cards
38
+ keep the card's own placeholder. The helper is
39
+ `lib/basklee/blogMediaFallback.ts`.
40
+
32
41
  During server rendering, editor HTML becomes plain blocks (`blogArticleBlocks`
33
42
  in `lib/basklee/blogArticleHtml.ts`): headings, paragraphs with their checked
34
43
  links, lists, quotes and pictures with captions, rendered with React's own
@@ -128,6 +137,15 @@ ID тарифов, ссылка также передаёт их в `ids`. Дл
128
137
  ссылки, кнопки или размещения товара сохраняют своё действие. Вспомогательный
129
138
  модуль — `lib/basklee/blogImageViewer.ts`.
130
139
 
140
+ Изображение, видео или плеер YouTube из текста, которые не загрузились,
141
+ заменяются заглушкой в цветах текста: «Не удалось загрузить изображение» с
142
+ `alt` картинки или «Не удалось загрузить видео» со ссылкой на файл видео или
143
+ на видео в YouTube. Заблокированный YouTube не сообщает об ошибке, поэтому
144
+ статья один раз на странице проверяет, отвечает ли сервер изображений YouTube
145
+ за 8 секунд; если отвечает, плееры остаются. Изображения карточек товаров
146
+ сохраняют собственную заглушку карточки. Вспомогательный модуль —
147
+ `lib/basklee/blogMediaFallback.ts`.
148
+
131
149
  При серверном рендеринге HTML редактора превращается в экранированные
132
150
  текстовые абзацы. После гидратации DOMPurify заменяет их очищенным
133
151
  форматированным HTML. Разрешены заголовки, оформление текста, ссылки, списки,
@@ -57,6 +57,10 @@ import {
57
57
  markBlogViewerImages,
58
58
  type IBlogViewerImage,
59
59
  } from '@/lib/basklee/blogImageViewer';
60
+ import {
61
+ blogMediaFallbackLabels,
62
+ guardBlogMedia,
63
+ } from '@/lib/basklee/blogMediaFallback';
60
64
  import { ProductReviewImageViewer } from '@/components/basklee/products/ProductReviewImageViewer';
61
65
  import { ProductCard } from '@/components/basklee/products/ProductCard';
62
66
  import {
@@ -225,6 +229,14 @@ export function BlogArticle({
225
229
  setCoverFailed(false);
226
230
  }, [cover]);
227
231
 
232
+ // Pictures, videos and YouTube players of the text that do not load get a placeholder.
233
+ useEffect(() => {
234
+ if (!mounted) {
235
+ return undefined;
236
+ }
237
+ return guardBlogMedia(articleRef.current, blogMediaFallbackLabels(locale));
238
+ }, [html, mounted, locale]);
239
+
228
240
  // The text is set as HTML: its images become buttons after each render.
229
241
  useEffect(() => {
230
242
  markBlogViewerImages(
@@ -47,6 +47,8 @@ Source is maintained in `components/basklee/orders/OrderDetails.tsx`; the
47
47
  physical order contract is in
48
48
  `interfaces/basklee/orders/IOrderHistory.ts`.
49
49
 
50
+ While nothing has left yet, the first step of the rail carries the order's own status word, Processing, in place of Placed: the status card and the rail name one stage, not two.
51
+
50
52
  ### Props
51
53
 
52
54
  | Prop | Meaning |
@@ -105,6 +107,8 @@ physical order contract is in
105
107
  Исходный файл: `components/basklee/orders/OrderDetails.tsx`; физический
106
108
  контракт заказа находится в `interfaces/basklee/orders/IOrderHistory.ts`.
107
109
 
110
+ Пока ничего не отправлено, первый шаг шкалы несёт слово собственного статуса заказа — «В обработке» — вместо «Оформлен»: карточка статуса и шкала называют один этап, а не два.
111
+
108
112
  ### Свойства
109
113
 
110
114
  | Свойство | Назначение |
@@ -175,6 +175,11 @@ export function OrderDetails({
175
175
  if (step.state === 'partial' && step.key === 'delivered') {
176
176
  return labels.statuses.partlyDelivered;
177
177
  }
178
+ // While nothing has left, the first step carries the order's own status
179
+ // word («Processing»): the card and the rail name one stage, not two.
180
+ if (step.key === 'placed' && step.current) {
181
+ return labels.statuses.processing;
182
+ }
178
183
  return labels.steps[step.key];
179
184
  }
180
185
 
@@ -53,3 +53,9 @@ When Application Load reports `init.visual_settings.single_seller_mode: true`, S
53
53
  Navigation omits categories with `exclude_from_tree: true` and all their descendants. The full published catalog remains available for product main-category names, links and breadcrumbs.
54
54
 
55
55
  В навигации скрываются категории с `exclude_from_tree: true` и все их подкатегории. Полный каталог опубликованных категорий сохраняется для названий, ссылок и цепочек основной категории товара.
56
+
57
+ ## Powered by Basklee
58
+
59
+ The bottom line of the footer ends with a small link, «Powered by Basklee»: an `<a href="https://basklee.com">` that opens in a new tab and is marked `data-footer-part="PoweredBy"`. Its text is the `powered` label of `footerLabels` (English, Russian, Spanish). The link is external, so the navigation callback is not called for it.
60
+
61
+ Нижняя строка футера заканчивается маленькой ссылкой «Работает на Basklee»: это `<a href="https://basklee.com">`, она открывается в новой вкладке и отмечена `data-footer-part="PoweredBy"`. Её текст — подпись `powered` из `footerLabels` (английский, русский, испанский). Ссылка внешняя, поэтому обработчик навигации для неё не вызывается.
@@ -79,8 +79,12 @@
79
79
  }
80
80
  }
81
81
 
82
- .copyright {
83
- margin: 0;
82
+ .bottom {
83
+ display: flex;
84
+ flex-wrap: wrap;
85
+ align-items: baseline;
86
+ justify-content: space-between;
87
+ gap: 0.25rem 1.5rem;
84
88
  padding-top: 1.5rem;
85
89
  border-top: 1px solid color-mix(
86
90
  in srgb,
@@ -94,6 +98,27 @@
94
98
  text-transform: uppercase;
95
99
  }
96
100
 
101
+ .copyright {
102
+ margin: 0;
103
+ }
104
+
105
+ .powered {
106
+ color: var(--basklee-inverse-muted);
107
+ text-decoration: none;
108
+ }
109
+
110
+ .powered:focus-visible {
111
+ color: var(--basklee-inverse-text);
112
+ outline: none;
113
+ }
114
+
115
+ @media (hover: hover) {
116
+ .powered:hover {
117
+ color: var(--basklee-inverse-text);
118
+ outline: none;
119
+ }
120
+ }
121
+
97
122
  /* The footer's own width (it spans the window: the former screen widths). */
98
123
  @container (min-width: 640px) {
99
124
  .content {
@@ -159,9 +159,20 @@ export function StorefrontFooter({
159
159
  </a>
160
160
  </nav>
161
161
  </div>
162
- <p className={styles.copyright}>
163
- © {year} {company} · {labels.rights}
164
- </p>
162
+ <div className={styles.bottom}>
163
+ <p className={styles.copyright}>
164
+ © {year} {company} · {labels.rights}
165
+ </p>
166
+ <a
167
+ href="https://basklee.com"
168
+ target="_blank"
169
+ rel="noopener"
170
+ className={styles.powered}
171
+ data-footer-part="PoweredBy"
172
+ >
173
+ {labels.powered}
174
+ </a>
175
+ </div>
165
176
  </div>
166
177
  </footer>
167
178
  );
@@ -27,6 +27,8 @@ list.
27
27
  maintained in `components/basklee/stores/StorefrontStores.tsx`; the primary
28
28
  contract is `interfaces/basklee/stores/IStoreDirectory.ts`.
29
29
 
30
+ A phone number is shown as people read it: a number typed with its own spaces, brackets or dashes stays as typed, and a bare run of digits is grouped from the end (`+78120000078` reads `+7 812 000 00 78`). The dial link keeps the digits only.
31
+
30
32
  ### Props
31
33
 
32
34
  | Prop | Meaning |
@@ -70,6 +72,8 @@ contract is `interfaces/basklee/stores/IStoreDirectory.ts`.
70
72
  `components/basklee/stores/StorefrontStores.tsx`; основной контракт:
71
73
  `interfaces/basklee/stores/IStoreDirectory.ts`.
72
74
 
75
+ Телефон показывается так, как его читают: номер, набранный с пробелами, скобками или дефисами, остаётся как набран, а сплошной ряд цифр разбивается на группы с конца (`+78120000078` читается `+7 812 000 00 78`). В ссылке для звонка остаются только цифры.
76
+
73
77
  ### Свойства
74
78
 
75
79
  | Свойство | Назначение |
@@ -24,6 +24,7 @@ import {
24
24
  storeMapMarkers,
25
25
  storeMarkerId,
26
26
  storePhoneLink,
27
+ storePhoneText,
27
28
  } from '@/lib/basklee/storeDirectory';
28
29
  import { DeliveryMap } from '@/components/basklee/cart/DeliveryMap';
29
30
  import { BaskleeEmptyState } from '@/components/basklee/shared/BaskleeEmptyState';
@@ -349,7 +350,7 @@ export function StorefrontStores({
349
350
  className={styles.phone}
350
351
  href={storePhoneLink(store.phone_number)}
351
352
  >
352
- {store.phone_number}
353
+ {storePhoneText(store.phone_number)}
353
354
  </a>
354
355
  ) : null}
355
356
  {store.working_hours ? (
@@ -0,0 +1,322 @@
1
+ /**
2
+ * Placeholders for the media of an article text that do not load: a picture
3
+ * whose file does not come, a video file that does not play, a YouTube player
4
+ * when YouTube does not answer. The failed element is hidden and a placeholder
5
+ * takes its place: the reader sees what was meant to be there instead of a
6
+ * broken-image icon or an empty frame; a video placeholder links to the video.
7
+ *
8
+ * Framework-free: call it on the element holding the article HTML after each
9
+ * render and call the returned function when the element goes away. The same
10
+ * file is used by every storefront (keep the copies identical).
11
+ */
12
+
13
+ export interface IBlogMediaFallbackLabels {
14
+ image: string;
15
+ video: string;
16
+ openVideo: string;
17
+ watchYoutube: string;
18
+ }
19
+
20
+ const LABELS: Record<string, IBlogMediaFallbackLabels> = {
21
+ en: {
22
+ image: 'The image could not be loaded',
23
+ video: 'The video could not be loaded',
24
+ openVideo: 'Open the video',
25
+ watchYoutube: 'Watch on YouTube',
26
+ },
27
+ ru: {
28
+ image: 'Не удалось загрузить изображение',
29
+ video: 'Не удалось загрузить видео',
30
+ openVideo: 'Открыть видео',
31
+ watchYoutube: 'Смотреть на YouTube',
32
+ },
33
+ es: {
34
+ image: 'No se pudo cargar la imagen',
35
+ video: 'No se pudo cargar el vídeo',
36
+ openVideo: 'Abrir el vídeo',
37
+ watchYoutube: 'Ver en YouTube',
38
+ },
39
+ };
40
+
41
+ /** The placeholder texts in the page language («ru», «en-US», …); English when the language is unknown. */
42
+ export function blogMediaFallbackLabels(locale?: string | null): IBlogMediaFallbackLabels {
43
+ const code = String(locale ?? '').toLowerCase().split(/[-_]/)[0] ?? '';
44
+
45
+ return LABELS[code] ?? LABELS.en!;
46
+ }
47
+
48
+ const FAILED = 'data-media-failed';
49
+ const FALLBACK = 'data-media-fallback';
50
+ const STYLE_ID = 'basklee-media-fallback-style';
51
+ // Product cards placed in the article draw their own picture placeholders.
52
+ const SKIPPED = '[data-product-id], [data-product-ids], [data-media-fallback-skip]';
53
+ const YOUTUBE_WAIT = 8000;
54
+ const youtubeEmbed = /^https:\/\/(?:www\.)?youtube(?:-nocookie)?\.com\/embed\/([\w-]{11})(?:[?#]|$)/i;
55
+
56
+ // Placeholders take the colours of the text around them, so they fit every storefront look.
57
+ const STYLE = `
58
+ [${FAILED}]{display:none!important}
59
+ [${FALLBACK}]{box-sizing:border-box;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:.5rem;width:100%;max-width:100%;min-height:9rem;margin:0;padding:1.25rem 1rem;border:1px dashed color-mix(in srgb,currentColor 28%,transparent);border-radius:.5rem;background:color-mix(in srgb,currentColor 5%,transparent);color:inherit;font-size:.875rem;line-height:1.4;text-align:center;white-space:normal}
60
+ [${FALLBACK}="video"]{aspect-ratio:16/9;min-height:0}
61
+ [${FALLBACK}] svg{width:2.25rem;height:2.25rem;flex:none;opacity:.55}
62
+ [${FALLBACK}] [data-media-fallback-text]{opacity:.8}
63
+ [${FALLBACK}] [data-media-fallback-alt]{max-width:36rem;opacity:.6;font-size:.8125rem;overflow-wrap:anywhere}
64
+ [${FALLBACK}] a{color:inherit;font-weight:600;text-decoration:underline;text-underline-offset:.2em}
65
+ `;
66
+
67
+ const SVG_NS = 'http://www.w3.org/2000/svg';
68
+ const ICONS = {
69
+ image: ['M5 5h14v14H5z', 'M9.5 9.5m-1.5 0a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0-3 0', 'm5 16 4-4 3 3 2-2 5 5', 'M3 3l18 18'],
70
+ video: ['M3 6h12v12H3z', 'm15 10 6-3v10l-6-3', 'M2 2l20 20'],
71
+ };
72
+
73
+ function ensureStyle(document: Document) {
74
+ if (document.getElementById(STYLE_ID)) {
75
+ return;
76
+ }
77
+ const style = document.createElement('style');
78
+ style.id = STYLE_ID;
79
+ style.textContent = STYLE;
80
+ document.head?.appendChild(style);
81
+ }
82
+
83
+ function icon(document: Document, kind: keyof typeof ICONS) {
84
+ const svg = document.createElementNS(SVG_NS, 'svg');
85
+ svg.setAttribute('viewBox', '0 0 24 24');
86
+ svg.setAttribute('fill', 'none');
87
+ svg.setAttribute('stroke', 'currentColor');
88
+ svg.setAttribute('stroke-width', '1.5');
89
+ svg.setAttribute('stroke-linecap', 'round');
90
+ svg.setAttribute('stroke-linejoin', 'round');
91
+ svg.setAttribute('aria-hidden', 'true');
92
+ for (const d of ICONS[kind]) {
93
+ const path = document.createElementNS(SVG_NS, 'path');
94
+ path.setAttribute('d', d);
95
+ svg.appendChild(path);
96
+ }
97
+ return svg;
98
+ }
99
+
100
+ function text(document: Document, tag: string, value: string, mark: string) {
101
+ const element = document.createElement(tag);
102
+ element.textContent = value;
103
+ element.setAttribute(mark, '');
104
+ return element;
105
+ }
106
+
107
+ function safeHttpUrl(value: string | null | undefined, base: string) {
108
+ if (!value) {
109
+ return '';
110
+ }
111
+ try {
112
+ const url = new URL(value, base);
113
+ return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : '';
114
+ } catch {
115
+ return '';
116
+ }
117
+ }
118
+
119
+ /** Hides `element` and puts a placeholder of the given kind before it (once). */
120
+ function replace(
121
+ element: HTMLElement,
122
+ kind: 'image' | 'video',
123
+ message: string,
124
+ extra: { alt?: string; href?: string; linkText?: string } = {},
125
+ ) {
126
+ if (element.hasAttribute(FAILED)) {
127
+ return;
128
+ }
129
+ const document = element.ownerDocument;
130
+ const placeholder = document.createElement('span');
131
+ placeholder.setAttribute(FALLBACK, kind);
132
+ placeholder.setAttribute('role', 'note');
133
+ placeholder.appendChild(icon(document, kind));
134
+ placeholder.appendChild(text(document, 'span', message, 'data-media-fallback-text'));
135
+ if (extra.alt) {
136
+ placeholder.appendChild(text(document, 'span', extra.alt, 'data-media-fallback-alt'));
137
+ }
138
+ if (extra.href && extra.linkText) {
139
+ const link = document.createElement('a');
140
+ link.href = extra.href;
141
+ link.target = '_blank';
142
+ link.rel = 'noopener noreferrer';
143
+ link.textContent = extra.linkText;
144
+ placeholder.appendChild(link);
145
+ }
146
+ // A picture of the article keeps the space it was given.
147
+ const width = Number(element.getAttribute('width'));
148
+ const height = Number(element.getAttribute('height'));
149
+ if (kind === 'image' && width > 1 && height > 1) {
150
+ placeholder.style.aspectRatio = `${width} / ${height}`;
151
+ placeholder.style.maxWidth = `${width}px`;
152
+ placeholder.style.minHeight = '0';
153
+ }
154
+ element.setAttribute(FAILED, '');
155
+ element.parentNode?.insertBefore(placeholder, element);
156
+ }
157
+
158
+ /** Shows `element` again and removes its placeholder (a YouTube check that answered late). */
159
+ function restore(element: HTMLElement) {
160
+ if (!element.hasAttribute(FAILED)) {
161
+ return;
162
+ }
163
+ const previous = element.previousElementSibling;
164
+ if (previous?.hasAttribute(FALLBACK)) {
165
+ previous.remove();
166
+ }
167
+ element.removeAttribute(FAILED);
168
+ }
169
+
170
+ function skipped(element: Element) {
171
+ return Boolean(element.closest(SKIPPED));
172
+ }
173
+
174
+ function failImage(image: HTMLImageElement, labels: IBlogMediaFallbackLabels) {
175
+ if (skipped(image)) {
176
+ return;
177
+ }
178
+ // A missing picture is not a button of the photo viewer any more.
179
+ image.setAttribute('data-blog-image-viewer-skip', '');
180
+ image.removeAttribute('role');
181
+ image.removeAttribute('tabindex');
182
+ image.removeAttribute('aria-label');
183
+ replace(image, 'image', labels.image, { alt: image.getAttribute('alt')?.trim() });
184
+ }
185
+
186
+ function videoSource(video: HTMLVideoElement) {
187
+ return safeHttpUrl(
188
+ video.getAttribute('src') || video.querySelector('source[src]')?.getAttribute('src'),
189
+ video.ownerDocument.baseURI,
190
+ );
191
+ }
192
+
193
+ function failVideo(video: HTMLVideoElement, labels: IBlogMediaFallbackLabels) {
194
+ if (skipped(video)) {
195
+ return;
196
+ }
197
+ replace(video, 'video', labels.video, { href: videoSource(video), linkText: labels.openVideo });
198
+ }
199
+
200
+ function imageFailed(image: HTMLImageElement) {
201
+ return Boolean(image.getAttribute('src')) && image.complete && image.naturalWidth === 0;
202
+ }
203
+
204
+ function videoFailed(video: HTMLVideoElement) {
205
+ const NO_SOURCE = 3; // HTMLMediaElement.NETWORK_NO_SOURCE
206
+ return Boolean(video.error) || (Boolean(videoSource(video)) && video.networkState === NO_SOURCE);
207
+ }
208
+
209
+ let youtubeCheck: Promise<boolean> | undefined;
210
+
211
+ /**
212
+ * Whether YouTube answers here: one picture of YouTube's image server per page,
213
+ * shared by every player. A player frame gives no error when YouTube is blocked.
214
+ */
215
+ function youtubeReachable(view: Window & typeof globalThis, videoId: string, late: () => void): Promise<boolean> {
216
+ youtubeCheck ??= new Promise<boolean>((resolve) => {
217
+ const probe = new view.Image();
218
+ let settled = false;
219
+ const timer = setTimeout(() => {
220
+ settled = true;
221
+ youtubeCheck = undefined;
222
+ resolve(false);
223
+ }, YOUTUBE_WAIT);
224
+ probe.onload = () => {
225
+ if (settled) {
226
+ late();
227
+ return;
228
+ }
229
+ settled = true;
230
+ clearTimeout(timer);
231
+ resolve(true);
232
+ };
233
+ probe.onerror = () => {
234
+ if (settled) {
235
+ return;
236
+ }
237
+ settled = true;
238
+ clearTimeout(timer);
239
+ youtubeCheck = undefined;
240
+ resolve(false);
241
+ };
242
+ probe.src = `https://i.ytimg.com/vi/${videoId}/default.jpg`;
243
+ });
244
+
245
+ return youtubeCheck;
246
+ }
247
+
248
+ /**
249
+ * Watches the images, videos and YouTube players under `root` and replaces the
250
+ * ones that fail with a placeholder. Returns the function that stops watching.
251
+ */
252
+ export function guardBlogMedia(
253
+ root: HTMLElement | null | undefined,
254
+ labels: IBlogMediaFallbackLabels = blogMediaFallbackLabels(),
255
+ ): () => void {
256
+ const view = root?.ownerDocument?.defaultView;
257
+ if (!root || !view || typeof root.querySelectorAll !== 'function') {
258
+ return () => {};
259
+ }
260
+ ensureStyle(root.ownerDocument);
261
+ let active = true;
262
+
263
+ // `error` does not bubble, but the capture phase still passes through the root.
264
+ const onError = (event: Event) => {
265
+ const target = event.target as Element | null;
266
+ const parent = target?.parentElement;
267
+ if (target?.tagName === 'IMG') {
268
+ failImage(target as HTMLImageElement, labels);
269
+ } else if (target?.tagName === 'VIDEO') {
270
+ failVideo(target as HTMLVideoElement, labels);
271
+ } else if (target?.tagName === 'SOURCE' && parent?.tagName === 'VIDEO') {
272
+ const video = parent as HTMLVideoElement;
273
+ // The video gives up only after its last source.
274
+ setTimeout(() => {
275
+ if (active && videoFailed(video)) {
276
+ failVideo(video, labels);
277
+ }
278
+ });
279
+ }
280
+ };
281
+ root.addEventListener('error', onError, true);
282
+
283
+ // Failures that came before this call (pictures from the page HTML, cached errors).
284
+ for (const image of root.querySelectorAll('img')) {
285
+ if (imageFailed(image)) {
286
+ failImage(image, labels);
287
+ }
288
+ }
289
+ for (const video of root.querySelectorAll('video')) {
290
+ if (videoFailed(video)) {
291
+ failVideo(video, labels);
292
+ }
293
+ }
294
+
295
+ const players = [...root.querySelectorAll('iframe')]
296
+ .map((frame) => ({ frame, id: youtubeEmbed.exec(frame.getAttribute('src') ?? '')?.[1] }))
297
+ .filter((player): player is { frame: HTMLIFrameElement; id: string } =>
298
+ Boolean(player.id) && !skipped(player.frame));
299
+ if (players.length) {
300
+ const showPlayers = () => {
301
+ for (const { frame } of players) {
302
+ restore(frame);
303
+ }
304
+ };
305
+ void youtubeReachable(view, players[0]!.id, showPlayers).then((reachable) => {
306
+ if (!active || reachable) {
307
+ return;
308
+ }
309
+ for (const { frame, id } of players) {
310
+ replace(frame, 'video', labels.video, {
311
+ href: `https://www.youtube.com/watch?v=${id}`,
312
+ linkText: labels.watchYoutube,
313
+ });
314
+ }
315
+ });
316
+ }
317
+
318
+ return () => {
319
+ active = false;
320
+ root.removeEventListener('error', onError, true);
321
+ };
322
+ }
@@ -19,6 +19,10 @@ export function browseLabels(locale: string) {
19
19
  clear: 'Сбросить',
20
20
  emptyTitle: 'Ничего не найдено',
21
21
  emptyHint: 'Попробуйте изменить запрос или сбросить фильтры.',
22
+ emptyHintPlain: 'Проверьте написание или попробуйте слово покороче.',
23
+ emptyCategoryPlain: 'В этой категории пока нет товаров. Загляните в другие разделы каталога.',
24
+ editSearch: 'Изменить запрос',
25
+ browseCatalog: 'Открыть каталог',
22
26
  emptyCategoryHint:
23
27
  'В этой категории пока нет подходящих товаров. Попробуйте убрать фильтры или выбрать другую категорию.',
24
28
  startTitle: 'Что вы ищете?',
@@ -67,6 +71,10 @@ export function browseLabels(locale: string) {
67
71
  clear: 'Borrar',
68
72
  emptyTitle: 'No se han encontrado productos',
69
73
  emptyHint: 'Prueba otra búsqueda o borra los filtros.',
74
+ emptyHintPlain: 'Revisa la ortografía o prueba con una palabra más corta.',
75
+ emptyCategoryPlain: 'Aún no hay productos en esta categoría. Mira las demás secciones del catálogo.',
76
+ editSearch: 'Cambiar la búsqueda',
77
+ browseCatalog: 'Ver el catálogo',
70
78
  emptyCategoryHint:
71
79
  'Todavía no hay productos que coincidan en esta categoría. Prueba a quitar filtros o elige otra categoría.',
72
80
  startTitle: '¿Qué estás buscando?',
@@ -115,6 +123,10 @@ export function browseLabels(locale: string) {
115
123
  clear: 'Clear',
116
124
  emptyTitle: 'No products found',
117
125
  emptyHint: 'Try another search or clear the filters.',
126
+ emptyHintPlain: 'Check the spelling or try a shorter word.',
127
+ emptyCategoryPlain: 'There are no products in this category yet. Look through the rest of the catalogue.',
128
+ editSearch: 'Change the search',
129
+ browseCatalog: 'Browse the catalogue',
118
130
  emptyCategoryHint:
119
131
  'No matching products in this category yet. Try removing filters or choosing another category.',
120
132
  startTitle: 'What are you looking for?',
@@ -66,6 +66,7 @@ const en = {
66
66
  deliveryDiscount: 'Delivery discount',
67
67
  total: 'Total',
68
68
  promo: 'Promo code',
69
+ promoOptional: 'optional',
69
70
  apply: 'Apply',
70
71
  removePromo: 'Remove',
71
72
  removePromoHint: 'Remove promo code',
@@ -193,6 +194,7 @@ const ru: typeof en = {
193
194
  deliveryDiscount: 'Скидка на доставку',
194
195
  total: 'Итого',
195
196
  promo: 'Промокод',
197
+ promoOptional: 'необязательно',
196
198
  apply: 'Применить',
197
199
  removePromo: 'Удалить',
198
200
  removePromoHint: 'Удалить промокод',
@@ -318,6 +320,7 @@ const es: typeof en = {
318
320
  deliveryDiscount: 'Descuento en el envío',
319
321
  total: 'Total',
320
322
  promo: 'Código promocional',
323
+ promoOptional: 'opcional',
321
324
  apply: 'Aplicar',
322
325
  removePromo: 'Quitar',
323
326
  removePromoHint: 'Quitar el código promocional',
@@ -365,7 +368,7 @@ const es: typeof en = {
365
368
  clearOption: 'Borrar',
366
369
  clearOptionHint: 'Borrar el texto y el archivo guardados',
367
370
  stockChanged: 'Han cambiado las cantidades o los precios de los artículos. Revisa tu carrito.',
368
- placeOrder: 'Pedido',
371
+ placeOrder: 'Realizar pedido',
369
372
  created: 'Pedido creado',
370
373
  viewOrder: 'Ver el pedido',
371
374
  paymentLinkFailed:
@@ -36,6 +36,10 @@ const en = {
36
36
  newsletter: 'Stop receiving newsletters',
37
37
  products: 'Stop product availability emails',
38
38
  unsubscribeDone: 'You have unsubscribed from these emails.',
39
+ invalidLinkHelp:
40
+ 'No longer have that email? You can switch these emails off in your profile, or write to the shop.',
41
+ emailSettings: 'Email settings',
42
+ writeToShop: 'Contact the shop',
39
43
  invalidLink:
40
44
  'This link is incomplete. Open the unsubscribe link from your email.',
41
45
  event: 'Take part in this offer',
@@ -86,6 +90,10 @@ const ru: typeof en = {
86
90
  newsletter: 'Отказаться от новостной рассылки',
87
91
  products: 'Отказаться от писем о наличии товаров',
88
92
  unsubscribeDone: 'Вы отписались от этих писем.',
93
+ invalidLinkHelp:
94
+ 'Письма уже нет? Отключить рассылку можно в профиле, или напишите в магазин.',
95
+ emailSettings: 'Настройки писем',
96
+ writeToShop: 'Написать в магазин',
89
97
  invalidLink: 'Ссылка неполная. Откройте ссылку отписки из письма.',
90
98
  event: 'Участвовать в акции',
91
99
  eventDescription: 'Подтвердите участие, чтобы получить предложение по почте.',
@@ -131,10 +139,14 @@ const es: typeof en = {
131
139
  another: 'Otro',
132
140
  anotherHint: 'Escribir otro mensaje',
133
141
  unsubscribe: 'Preferencias de correo',
134
- unsubscribeAction: 'Cancelar aviso',
142
+ unsubscribeAction: 'Darse de baja',
135
143
  newsletter: 'Dejar de recibir boletines',
136
144
  products: 'Dejar de recibir correos de disponibilidad',
137
145
  unsubscribeDone: 'Te has dado de baja de estos correos.',
146
+ invalidLinkHelp:
147
+ '¿Ya no tienes ese correo? Puedes desactivar estos correos en tu perfil o escribir a la tienda.',
148
+ emailSettings: 'Ajustes de correo',
149
+ writeToShop: 'Contactar con la tienda',
138
150
  invalidLink:
139
151
  'Este enlace está incompleto. Abre el enlace de baja desde tu correo.',
140
152
  event: 'Participa en esta oferta',
@@ -11,6 +11,7 @@ const en = {
11
11
  letter: 'Names starting with',
12
12
  rating: 'Seller rating',
13
13
  reviews: 'Reviews',
14
+ noRatings: 'No ratings yet',
14
15
  since: 'Selling since',
15
16
  hours: 'Opening hours',
16
17
  phone: 'Phone',
@@ -76,6 +77,7 @@ const ru: typeof en = {
76
77
  letter: 'Названия на букву',
77
78
  rating: 'Рейтинг продавца',
78
79
  reviews: 'Отзывы',
80
+ noRatings: 'Оценок пока нет',
79
81
  since: 'Продаёт с',
80
82
  hours: 'Часы работы',
81
83
  phone: 'Телефон',
@@ -141,6 +143,7 @@ const es: typeof en = {
141
143
  letter: 'Nombres que empiezan por',
142
144
  rating: 'Valoración del vendedor',
143
145
  reviews: 'Reseñas',
146
+ noRatings: 'Aún sin valoraciones',
144
147
  since: 'Vende desde',
145
148
  hours: 'Horario',
146
149
  phone: 'Teléfono',
@@ -36,6 +36,7 @@ const en = {
36
36
  activity: 'My activity',
37
37
  },
38
38
  logout: 'Logout',
39
+ logoutScope: 'on all devices',
39
40
  addresses: {
40
41
  title: 'My addresses',
41
42
  description: 'Saved addresses for delivery.',
@@ -97,6 +98,9 @@ const en = {
97
98
  paid_subs: 'Subscriptions',
98
99
  empty: 'No payments in this category yet.',
99
100
  unavailable: 'No payment methods are available.',
101
+ unavailableHint:
102
+ 'The wallet cannot be topped up from your account right now: the shop offers no payment method for it. Orders can still be paid at checkout. If you expected to see a method here, write to the shop.',
103
+ contactShop: 'Write to the shop',
100
104
  pay: 'Pay',
101
105
  cancelInvoice: 'Cancel',
102
106
  cancelQuestion: 'Cancel this unpaid invoice?',
@@ -171,6 +175,7 @@ const ru: typeof en = {
171
175
  activity: 'Моя активность',
172
176
  },
173
177
  logout: 'Выйти',
178
+ logoutScope: 'на всех устройствах',
174
179
  addresses: {
175
180
  title: 'Мои адреса',
176
181
  description: 'Сохранённые адреса для доставки.',
@@ -232,6 +237,9 @@ const ru: typeof en = {
232
237
  paid_subs: 'Подписки',
233
238
  empty: 'В этой категории пока нет платежей.',
234
239
  unavailable: 'Нет доступных способов оплаты.',
240
+ unavailableHint:
241
+ 'Сейчас пополнить кошелёк с вашего аккаунта нельзя: магазин не предлагает для этого способа оплаты. Заказы по-прежнему можно оплатить при оформлении. Если способ оплаты здесь должен быть, напишите магазину.',
242
+ contactShop: 'Написать магазину',
235
243
  pay: 'Оплатить',
236
244
  cancelInvoice: 'Отменить',
237
245
  cancelQuestion: 'Отменить этот неоплаченный счёт?',
@@ -304,6 +312,7 @@ const es: typeof en = {
304
312
  activity: 'Mi actividad',
305
313
  },
306
314
  logout: 'Cerrar sesión',
315
+ logoutScope: 'en todos los dispositivos',
307
316
  addresses: {
308
317
  title: 'Mis direcciones',
309
318
  description: 'Direcciones guardadas para la entrega.',
@@ -365,6 +374,9 @@ const es: typeof en = {
365
374
  paid_subs: 'Suscripciones',
366
375
  empty: 'Todavía no hay pagos en esta categoría.',
367
376
  unavailable: 'No hay métodos de pago disponibles.',
377
+ unavailableHint:
378
+ 'Ahora no se puede recargar el monedero desde su cuenta: la tienda no ofrece ningún método de pago para ello. Los pedidos se pueden pagar al finalizar la compra. Si esperaba ver un método aquí, escriba a la tienda.',
379
+ contactShop: 'Escribir a la tienda',
368
380
  pay: 'Pagar',
369
381
  cancelInvoice: 'Cancelar',
370
382
  cancelQuestion: '¿Cancelar esta factura sin pagar?',
@@ -12,6 +12,7 @@ export function footerLabels(locale: string) {
12
12
  profile: 'Личный кабинет',
13
13
  journal: 'Журнал',
14
14
  rights: 'Все права защищены.',
15
+ powered: 'Работает на Basklee',
15
16
  products: 'Товары',
16
17
  discounts: 'Скидки',
17
18
  new: 'Новинки',
@@ -29,6 +30,7 @@ export function footerLabels(locale: string) {
29
30
  profile: 'Mi cuenta',
30
31
  journal: 'Blog',
31
32
  rights: 'Todos los derechos reservados.',
33
+ powered: 'Funciona con Basklee',
32
34
  products: 'Productos',
33
35
  discounts: 'Descuentos',
34
36
  new: 'Novedades',
@@ -45,6 +47,7 @@ export function footerLabels(locale: string) {
45
47
  profile: 'My account',
46
48
  journal: 'Journal',
47
49
  rights: 'All rights reserved.',
50
+ powered: 'Powered by Basklee',
48
51
  products: 'Products',
49
52
  discounts: 'Discounts',
50
53
  new: 'New arrivals',
@@ -73,7 +73,7 @@ const labels = {
73
73
  close: 'Cerrar el catálogo',
74
74
  back: 'Atrás',
75
75
  viewCategory: 'Ver',
76
- highlights: 'Categorías destacadas',
76
+ highlights: 'Productos destacados',
77
77
  empty: 'No hay categorías disponibles',
78
78
  emptyProducts: 'No hay productos representativos',
79
79
  saved: 'Favoritos',
@@ -167,3 +167,55 @@ export function profileFailure(reason: unknown, failed: string) {
167
167
 
168
168
  return { errors: fields, error: text || failed };
169
169
  }
170
+
171
+ /**
172
+ * A language by its code, named in the language of the page («English»,
173
+ * «Español», «Русский»). The shop's own short names («Eng») do not tell a
174
+ * customer which language their order letters come in; `fallback` is used
175
+ * when the browser has no name for the code.
176
+ */
177
+ export function profileLanguageName(code: string, locale: string, fallback: string) {
178
+ try {
179
+ const name = new Intl.DisplayNames([locale], { type: 'language' }).of(code);
180
+
181
+ if (name && name.toLowerCase() !== code.toLowerCase()) {
182
+ return name.charAt(0).toLocaleUpperCase(locale) + name.slice(1);
183
+ }
184
+ } catch {
185
+ // An unknown code keeps the shop's own name.
186
+ }
187
+ return fallback;
188
+ }
189
+
190
+ // Personal details typed and not saved yet. They stay in the page's memory
191
+ // while the customer visits other pages, so coming back to the profile shows
192
+ // what was typed. Memory only: a reload starts from the saved profile, the
193
+ // server keeps nothing, and a draft belongs to one customer ID.
194
+ export interface ProfileDetailsDraft {
195
+ first_name: string;
196
+ last_name: string;
197
+ dob: string;
198
+ }
199
+
200
+ const profileDrafts = new Map<number, ProfileDetailsDraft>();
201
+
202
+ export function readProfileDraft(customerId: number | undefined) {
203
+ return typeof window !== 'undefined' && customerId
204
+ ? profileDrafts.get(customerId)
205
+ : undefined;
206
+ }
207
+
208
+ // `null` drops the draft: the details were saved or the customer discarded them.
209
+ export function keepProfileDraft(
210
+ customerId: number | undefined,
211
+ draft: ProfileDetailsDraft | null,
212
+ ) {
213
+ if (typeof window === 'undefined' || !customerId) {
214
+ return;
215
+ }
216
+ if (draft) {
217
+ profileDrafts.set(customerId, { ...draft });
218
+ } else {
219
+ profileDrafts.delete(customerId);
220
+ }
221
+ }
@@ -23,7 +23,12 @@ export function profileLabels(locale: string) {
23
23
  email: 'Электронная почта',
24
24
  emailHint:
25
25
  'Подтвердите адрес для получения уведомлений о заказах и рассылки.',
26
- sendCode: 'Отправить',
26
+ emailConfirmed: 'Подтверждён',
27
+ emailConfirmedHint:
28
+ 'На этот адрес приходят письма о заказах и уведомления. Чтобы сменить его, введите новый адрес и отправьте код.',
29
+ unsaved: 'Есть несохранённые изменения.',
30
+ discard: 'Отменить изменения',
31
+ sendCode: 'Отправить',
27
32
  sendCodeHint: 'Отправить код подтверждения',
28
33
  code: 'Код подтверждения',
29
34
  verify: 'Подтвердить',
@@ -98,7 +103,12 @@ export function profileLabels(locale: string) {
98
103
  email: 'Dirección de correo',
99
104
  emailHint:
100
105
  'Verifica tu dirección antes de recibir novedades de pedidos y notificaciones por correo.',
101
- sendCode: 'Enviar',
106
+ emailConfirmed: 'Confirmada',
107
+ emailConfirmedHint:
108
+ 'Los avisos de pedidos y las notificaciones llegan a esta dirección. Para cambiarla, escriba una nueva y envíe un código.',
109
+ unsaved: 'Hay cambios sin guardar.',
110
+ discard: 'Descartar',
111
+ sendCode: 'Enviar',
102
112
  sendCodeHint: 'Enviar código de verificación',
103
113
  code: 'Código de verificación',
104
114
  verify: 'Verificar',
@@ -172,7 +182,12 @@ export function profileLabels(locale: string) {
172
182
  email: 'Email address',
173
183
  emailHint:
174
184
  'Verify your address before receiving order updates and email notifications.',
175
- sendCode: 'Send',
185
+ emailConfirmed: 'Confirmed',
186
+ emailConfirmedHint:
187
+ 'Order updates and notifications are sent to this address. To change it, type a new address and send a code.',
188
+ unsaved: 'You have unsaved changes.',
189
+ discard: 'Discard',
190
+ sendCode: 'Send',
176
191
  sendCodeHint: 'Send verification code',
177
192
  code: 'Verification code',
178
193
  verify: 'Verify',
@@ -24,6 +24,8 @@ const en = {
24
24
  productPhotos: 'Product photos',
25
25
  openProductPhoto: 'Open the photo full screen',
26
26
  empty: 'No reviews yet.',
27
+ emptyFiltered: 'No reviews match these filters.',
28
+ showAll: 'Show all reviews',
27
29
  emptyImages: 'No customer photos yet.',
28
30
  send: 'Submit',
29
31
  save: 'Save',
@@ -103,6 +105,8 @@ const ru: typeof en = {
103
105
  productPhotos: 'Фотографии товара',
104
106
  openProductPhoto: 'Открыть фотографию на весь экран',
105
107
  empty: 'Отзывов пока нет.',
108
+ emptyFiltered: 'Под эти фильтры не подходит ни один отзыв.',
109
+ showAll: 'Показать все отзывы',
106
110
  emptyImages: 'Покупатели ещё не добавили фотографии.',
107
111
  send: 'Отправить',
108
112
  save: 'Сохранить',
@@ -183,6 +187,8 @@ const es: typeof en = {
183
187
  productPhotos: 'Fotos del producto',
184
188
  openProductPhoto: 'Abrir la foto a pantalla completa',
185
189
  empty: 'Aún no hay reseñas.',
190
+ emptyFiltered: 'Ninguna reseña coincide con estos filtros.',
191
+ showAll: 'Ver todas las reseñas',
186
192
  emptyImages: 'Aún no hay fotos de clientes.',
187
193
  send: 'Enviar',
188
194
  save: 'Guardar',
@@ -39,6 +39,99 @@ export function hasSellerFilters(filters: ISellerDirectoryFilters) {
39
39
  );
40
40
  }
41
41
 
42
+ // Where the seller directory is: its filters, order and page. The directory
43
+ // keeps it in the URL as `?name&rating&cats&sort&page`, so Back from a seller,
44
+ // a reload and a copied address return to the same list.
45
+ export interface SellerDirectoryLocation {
46
+ filters: ISellerDirectoryFilters;
47
+ page: number;
48
+ }
49
+
50
+ type SellerQueryValue = string | null | undefined | readonly (string | null)[];
51
+
52
+ const sellerLocationKeys = ['name', 'rating', 'cats', 'sort', 'page'];
53
+
54
+ function firstSellerQueryValue(value: SellerQueryValue) {
55
+ return Array.isArray(value) ? value[0] : (value as string | null | undefined);
56
+ }
57
+
58
+ function positiveSellerQueryNumber(value: string | null | undefined) {
59
+ const number = Number(value);
60
+
61
+ return Number.isSafeInteger(number) && number > 0 ? number : undefined;
62
+ }
63
+
64
+ // Unknown or damaged values fall back to the full list in the default order.
65
+ export function sellerLocationFromQuery(
66
+ query: Record<string, SellerQueryValue>,
67
+ ): SellerDirectoryLocation {
68
+ const filters = emptySellerFilters();
69
+ const rating = positiveSellerQueryNumber(firstSellerQueryValue(query.rating));
70
+ const cats = (firstSellerQueryValue(query.cats) ?? '')
71
+ .split(',')
72
+ .map((part) => positiveSellerQueryNumber(part))
73
+ .filter((id): id is number => id !== undefined);
74
+
75
+ filters.seller_name = (firstSellerQueryValue(query.name) ?? '').slice(0, 200);
76
+ if (rating !== undefined && rating <= SELLER_RATING_MAXIMUM) {
77
+ filters.seller_rating_from = rating;
78
+ }
79
+ filters.seller_categories = [...new Set(cats)];
80
+ if (firstSellerQueryValue(query.sort) === 'low') {
81
+ filters.ordering = 'seller_raiting';
82
+ }
83
+
84
+ return {
85
+ filters,
86
+ page: positiveSellerQueryNumber(firstSellerQueryValue(query.page)) ?? 1,
87
+ };
88
+ }
89
+
90
+ // The query of `next`: other parameters such as `locale` stay and defaults
91
+ // are left out, so the plain directory keeps its plain address.
92
+ export function sellerLocationQuery(
93
+ query: Record<string, SellerQueryValue>,
94
+ next: SellerDirectoryLocation,
95
+ ) {
96
+ const result: Record<string, string> = {};
97
+ const name = next.filters.seller_name.trim();
98
+
99
+ for (const [key, value] of Object.entries(query)) {
100
+ const text = firstSellerQueryValue(value);
101
+
102
+ if (typeof text === 'string' && !sellerLocationKeys.includes(key)) {
103
+ result[key] = text;
104
+ }
105
+ }
106
+ if (name) {
107
+ result.name = name;
108
+ }
109
+ if (next.filters.seller_rating_from !== null) {
110
+ result.rating = String(next.filters.seller_rating_from);
111
+ }
112
+ if (next.filters.seller_categories.length) {
113
+ result.cats = next.filters.seller_categories.join(',');
114
+ }
115
+ if (next.filters.ordering === 'seller_raiting') {
116
+ result.sort = 'low';
117
+ }
118
+ if (next.page > 1) {
119
+ result.page = String(next.page);
120
+ }
121
+
122
+ return result;
123
+ }
124
+
125
+ export function sameSellerLocation(
126
+ left: SellerDirectoryLocation,
127
+ right: SellerDirectoryLocation,
128
+ ) {
129
+ return (
130
+ left.page === right.page &&
131
+ JSON.stringify(left.filters) === JSON.stringify(right.filters)
132
+ );
133
+ }
134
+
42
135
  export function sellerDirectoryRequest(
43
136
  filters: ISellerDirectoryFilters,
44
137
  page: number,
@@ -2,37 +2,37 @@ export function sessionLabels(locale: string) {
2
2
  return locale.toLowerCase().startsWith('ru')
3
3
  ? {
4
4
  title: 'Выход из аккаунта',
5
- pending: 'Завершаем сеанс…',
5
+ pending: 'Завершаем сеансы на всех устройствах…',
6
6
  hint: 'После выхода вы вернётесь на главную страницу.',
7
7
  failed: 'Не удалось завершить выход',
8
8
  retryHint:
9
9
  'Повторите попытку. Выход подтверждается только ответом сервера.',
10
10
  refreshFailed: 'Сеанс завершён. Не удалось загрузить магазин.',
11
11
  retry: 'Повторить',
12
- done: 'Вы вышли из аккаунта',
12
+ done: 'Вы вышли из аккаунта на всех устройствах',
13
13
  home: 'Главная',
14
14
  }
15
15
  : locale.toLowerCase().startsWith('es') ? {
16
16
  title: 'Cerrando sesión',
17
- pending: 'Terminando tu sesión…',
17
+ pending: 'Cerrando tu sesión en todos los dispositivos…',
18
18
  hint: 'Volverás a la página de inicio de la tienda.',
19
19
  failed: 'No se ha podido cerrar la sesión',
20
20
  retryHint: 'Inténtalo de nuevo. El cierre de sesión lo confirma el servidor.',
21
21
  refreshFailed:
22
22
  'Tu sesión ha terminado. No se ha podido recargar la tienda.',
23
23
  retry: 'Reintentar',
24
- done: 'Has cerrado la sesión',
24
+ done: 'Has cerrado la sesión en todos los dispositivos',
25
25
  home: 'Inicio',
26
26
  } : {
27
27
  title: 'Signing out',
28
- pending: 'Ending your session…',
28
+ pending: 'Ending your sessions on all devices…',
29
29
  hint: 'You will return to the storefront home page.',
30
30
  failed: 'Could not finish signing out',
31
31
  retryHint: 'Please try again. Sign-out is confirmed by the server.',
32
32
  refreshFailed:
33
33
  'Your session has ended. The storefront could not be reloaded.',
34
34
  retry: 'Retry',
35
- done: 'You are signed out',
35
+ done: 'You are signed out on all devices',
36
36
  home: 'Home',
37
37
  };
38
38
  }
@@ -45,3 +45,29 @@ export function storeMapMarkers(
45
45
  export function storePhoneLink(value: string) {
46
46
  return `tel:${value.replace(/[^+0-9]/g, '')}`;
47
47
  }
48
+
49
+ /**
50
+ * A store's telephone as people read it. A number typed with its own spaces,
51
+ * brackets or dashes is shown as typed; a bare run of digits («+78120000078»)
52
+ * is grouped from the end («+7 812 000 00 78»), the way the shop's contact
53
+ * page writes its number. The dial link keeps using `storePhoneLink`.
54
+ */
55
+ export function storePhoneText(value: string) {
56
+ const text = value.trim();
57
+
58
+ if (!/^\+?\d{7,15}$/.test(text)) {
59
+ return text;
60
+ }
61
+ const digits = text.replace('+', '');
62
+ const groups = [digits.slice(-2), digits.slice(-4, -2)];
63
+ let rest = digits.slice(0, -4);
64
+
65
+ while (rest.length > 3) {
66
+ groups.push(rest.slice(-3));
67
+ rest = rest.slice(0, -3);
68
+ }
69
+ if (rest) {
70
+ groups.push(rest);
71
+ }
72
+ return `${text.startsWith('+') ? '+' : ''}${groups.reverse().join(' ')}`;
73
+ }
@@ -21,6 +21,7 @@ const en = {
21
21
  intro:
22
22
  'Choose a plan and a subscription period. Paid periods are charged to the account balance.',
23
23
  noOffers: 'No subscription plans are available yet.',
24
+ toCatalog: 'Browse the catalogue',
24
25
  reset: 'Reset',
25
26
  support: 'Subscription support',
26
27
  wallet: 'Top up balance',
@@ -53,6 +54,7 @@ const ru: typeof en = {
53
54
  intro:
54
55
  'Выберите тариф и период подписки. Платные периоды оплачиваются с баланса аккаунта.',
55
56
  noOffers: 'Тарифов подписок пока нет.',
57
+ toCatalog: 'Открыть каталог',
56
58
  reset: 'Сбросить',
57
59
  support: 'Поддержка по подписке',
58
60
  wallet: 'Пополнить баланс',
@@ -86,6 +88,7 @@ const es: typeof en = {
86
88
  intro:
87
89
  'Elige un plan y un periodo de suscripción. Los periodos de pago se cobran del saldo de la cuenta.',
88
90
  noOffers: 'Todavía no hay planes de suscripción disponibles.',
91
+ toCatalog: 'Ver el catálogo',
89
92
  reset: 'Restablecer',
90
93
  support: 'Soporte de suscripciones',
91
94
  wallet: 'Recargar saldo',
@@ -0,0 +1,37 @@
1
+ // The chosen tab of an account page lives in the address as `?tab=`, so a
2
+ // reload, the browser's Back and a copied link open the view the customer
3
+ // chose. The first tab is the default and leaves the address plain.
4
+ type TabQueryValue = string | null | undefined | readonly (string | null)[];
5
+
6
+ // `tab` from the address; an unknown or missing value is the first tab.
7
+ export function tabFromQuery<T extends string>(
8
+ query: Record<string, TabQueryValue>,
9
+ tabs: readonly T[],
10
+ ): T {
11
+ const raw = query.tab;
12
+ const value = Array.isArray(raw) ? raw[0] : raw;
13
+
14
+ return tabs.find((tab) => tab === value) ?? tabs[0]!;
15
+ }
16
+
17
+ // The query with `tab` chosen: other parameters such as `locale` stay.
18
+ export function tabQuery<T extends string>(
19
+ query: Record<string, TabQueryValue>,
20
+ tab: T,
21
+ tabs: readonly T[],
22
+ ) {
23
+ const result: Record<string, string> = {};
24
+
25
+ for (const [key, raw] of Object.entries(query)) {
26
+ const value = Array.isArray(raw) ? raw[0] : raw;
27
+
28
+ if (typeof value === 'string' && key !== 'tab' && key !== 'page') {
29
+ result[key] = value;
30
+ }
31
+ }
32
+ if (tab !== tabs[0]) {
33
+ result.tab = tab;
34
+ }
35
+
36
+ return result;
37
+ }
@@ -0,0 +1,56 @@
1
+ // An unsent support message: its text, the attached files and the defect
2
+ // mark. It is kept in the page's memory while the customer moves around the
3
+ // shop, so leaving Support for another page and coming back does not lose
4
+ // what was written (the message form reads it when it opens).
5
+ //
6
+ // Memory only, on purpose: nothing is written to browser storage, so a
7
+ // reload or a closed tab starts clean and a shared computer keeps no text.
8
+ // On the server the memory belongs to every visitor at once, so there the
9
+ // functions keep nothing. A draft is the customer's own: its key starts
10
+ // with their ID, and another customer signing in on the same tab never
11
+ // sees it.
12
+ export interface TicketDraft {
13
+ text: string;
14
+ files: File[];
15
+ isDefect: boolean;
16
+ }
17
+
18
+ const drafts = new Map<string, TicketDraft>();
19
+ const inBrowser = typeof window !== 'undefined';
20
+
21
+ // `place` names the form: `new` for a common question, `new:item:15` for a
22
+ // conversation about an order item, `ticket:8` for a reply.
23
+ export function ticketDraftKey(customerId: number | undefined, place: string) {
24
+ return customerId ? `${customerId}:${place}` : '';
25
+ }
26
+
27
+ export function emptyTicketDraft(): TicketDraft {
28
+ return { text: '', files: [], isDefect: false };
29
+ }
30
+
31
+ export function isEmptyTicketDraft(draft: TicketDraft) {
32
+ return !draft.text.trim() && !draft.files.length && !draft.isDefect;
33
+ }
34
+
35
+ export function readTicketDraft(key: string): TicketDraft {
36
+ const draft = inBrowser && key ? drafts.get(key) : undefined;
37
+
38
+ return draft ? { ...draft, files: [...draft.files] } : emptyTicketDraft();
39
+ }
40
+
41
+ // An emptied form leaves no draft behind.
42
+ export function keepTicketDraft(key: string, draft: TicketDraft) {
43
+ if (!inBrowser || !key) {
44
+ return;
45
+ }
46
+ if (isEmptyTicketDraft(draft)) {
47
+ drafts.delete(key);
48
+ } else {
49
+ drafts.set(key, { ...draft, files: [...draft.files] });
50
+ }
51
+ }
52
+
53
+ // The message was sent or the customer pressed Cancel.
54
+ export function dropTicketDraft(key: string) {
55
+ drafts.delete(key);
56
+ }