basklee-react 0.9.11 → 0.9.13

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
@@ -522,7 +522,7 @@ maintained API client. Page metadata uses those returned records and follows
522
522
  client navigation and language selection. Home-page event clicks open enrollment
523
523
  for the returned event, preserving its return path through sign-in.
524
524
  A product page takes the product's SEO tab: its heading is the page title (the product name without one), its meta description and keywords fill their tags, and its own Open Graph and Twitter Cards tags are added in the page's language only, replacing a default tag of the same name.
525
- Pages with a canonical address also link the same page in the other storefront languages (`hreflang`) and set `og:type` and `og:locale`; a journal article adds its publication date (`article:published_time`) and schema.org `BlogPosting` data. The store icon (`logos.ico`) is the page's `<link rel="icon">`. An unknown `?locale` opens the default language.
525
+ 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
526
 
527
527
  List pages (journal, categories, stores) link their previous and next pages as real links (`?page=2`). Each later page has its own canonical address and a title with its page number; a journal page past the last one answers 404.
528
528
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "basklee-react",
3
- "version": "0.9.11",
3
+ "version": "0.9.13",
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",
@@ -89,9 +89,10 @@ function ShellContent({ children }: { children: ReactNode }) {
89
89
  // The Android app falls back to the language picked on the device.
90
90
  const requested =
91
91
  searchParams.get('locale') || (APP_ORIGIN ? savedAppLocale() : '');
92
- // Only a new language resets the currency and units to its own.
92
+ // Only a new language resets the currency and units to its own. A
93
+ // language from the address is shown, not kept as the customer's pick.
93
94
  if (requested && !localesMatch(requested, selections.getState().localeCode)) {
94
- selections.getState().setLocale(requested);
95
+ selections.getState().setLocale(requested, false);
95
96
  }
96
97
  }, [pathname, searchParams, selections]);
97
98
 
@@ -3,7 +3,10 @@ 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 { getBaskleeServerLocale } from '@/lib/basklee/serverLocale';
6
+ import {
7
+ getBaskleeSavedChoices,
8
+ getBaskleeServerLocale,
9
+ } from '@/lib/basklee/serverLocale';
7
10
  import {
8
11
  getStorefrontMetadata,
9
12
  getStorefrontMetadataContext,
@@ -25,6 +28,7 @@ export default async function RootLayout({
25
28
  // Bootstrap precedes page rendering. Failures stay in the store for the interface to handle.
26
29
  const { result, failure } = await getBaskleeAppLoad();
27
30
  const language = await getBaskleeServerLocale();
31
+ const { currency } = await getBaskleeSavedChoices();
28
32
  const { tags, jsonLd } = await getStorefrontMetadataContext();
29
33
  return (
30
34
  <html lang={language}>
@@ -57,6 +61,7 @@ export default async function RootLayout({
57
61
  result={result}
58
62
  failure={failure}
59
63
  locale={language}
64
+ currency={currency}
60
65
  >
61
66
  <StorefrontShell>{children}</StorefrontShell>
62
67
  </BaskleeProvider>
@@ -38,6 +38,15 @@ within 8 seconds; the players stay when it does. Pictures of product cards
38
38
  keep the card's own placeholder. The helper is
39
39
  `lib/basklee/blogMediaFallback.ts`.
40
40
 
41
+ A player that plays gets a cover over YouTube's suggestions of other videos:
42
+ while it is paused («Continue watching») or has ended («Watch again»), the page
43
+ lays its own layer over the frame, because YouTube has no setting that turns
44
+ the suggestions off. Player addresses carry `rel=0` (suggestions from the
45
+ video's own channel only) and `enablejsapi=1`, so the page hears the player
46
+ through postMessage; no YouTube script is loaded into the page. In full screen
47
+ the cover cannot reach the player. The helper is
48
+ `lib/basklee/blogYoutubeCover.ts`, called by `guardBlogMedia`.
49
+
41
50
  During server rendering, editor HTML becomes plain blocks (`blogArticleBlocks`
42
51
  in `lib/basklee/blogArticleHtml.ts`): headings, paragraphs with their checked
43
52
  links, lists, quotes and pictures with captions, rendered with React's own
@@ -146,6 +155,15 @@ ID тарифов, ссылка также передаёт их в `ids`. Дл
146
155
  сохраняют собственную заглушку карточки. Вспомогательный модуль —
147
156
  `lib/basklee/blogMediaFallback.ts`.
148
157
 
158
+ Плеер, который воспроизводится, получает слой поверх предложений других видео
159
+ от YouTube: пока видео на паузе («Продолжить просмотр») или закончилось
160
+ («Смотреть снова»), страница кладёт поверх фрейма свой слой, потому что у
161
+ YouTube нет настройки, отключающей предложения. Адреса плееров содержат
162
+ `rel=0` (предложения только с канала этого видео) и `enablejsapi=1`, чтобы
163
+ страница слышала плеер через postMessage; скрипт YouTube в страницу не
164
+ загружается. В полноэкранном режиме слой до плеера не достаёт. Вспомогательный
165
+ модуль — `lib/basklee/blogYoutubeCover.ts`, его вызывает `guardBlogMedia`.
166
+
149
167
  При серверном рендеринге HTML редактора превращается в экранированные
150
168
  текстовые абзацы. После гидратации DOMPurify заменяет их очищенным
151
169
  форматированным HTML. Разрешены заголовки, оформление текста, ссылки, списки,
@@ -190,12 +190,18 @@ const authorRelTokens = new Set(['nofollow', 'sponsored', 'ugc']);
190
190
  const youtubeEmbed =
191
191
  /^https:\/\/(?:www\.)?youtube(?:-nocookie)?\.com\/embed\/([\w-]{11})(?:\?([^#]*))?$/i;
192
192
 
193
+ // Options of every player address: suggestions from the same channel only, events for the page.
194
+ const youtubeEmbedOptions = ['rel=0', 'enablejsapi=1'];
195
+
193
196
  export const blogYoutubeAllow =
194
197
  'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
195
198
 
196
199
  /**
197
200
  * The privacy-enhanced player address for a YouTube embed address, or an
198
- * empty string for anything else (other sites, other YouTube pages).
201
+ * empty string for anything else (other sites, other YouTube pages). The
202
+ * address keeps YouTube's suggestions to the video's own channel (`rel=0`)
203
+ * and lets the page hear the player (`enablejsapi=1`), so blogYoutubeCover.ts
204
+ * can cover the suggestions while the player is paused or ended.
199
205
  */
200
206
  export function blogYoutubeEmbedSource(value: string) {
201
207
  const match = youtubeEmbed.exec(value.trim());
@@ -206,7 +212,12 @@ export function blogYoutubeEmbedSource(value: string) {
206
212
 
207
213
  const start = /(?:^|&)start=(\d{1,6})(?:&|$)/.exec(match[2] ?? '')?.[1];
208
214
 
209
- return `https://www.youtube-nocookie.com/embed/${match[1]}${start && Number(start) > 0 ? `?start=${Number(start)}` : ''}`;
215
+ const query = [
216
+ ...(start && Number(start) > 0 ? [`start=${Number(start)}`] : []),
217
+ ...youtubeEmbedOptions,
218
+ ].join('&');
219
+
220
+ return `https://www.youtube-nocookie.com/embed/${match[1]}?${query}`;
210
221
  }
211
222
 
212
223
  function prepareYoutubeFrame(node: Element) {
@@ -5,16 +5,23 @@
5
5
  * takes its place: the reader sees what was meant to be there instead of a
6
6
  * broken-image icon or an empty frame; a video placeholder links to the video.
7
7
  *
8
+ * The YouTube players that do play get a cover over YouTube's suggestions of
9
+ * other videos while paused or ended (blogYoutubeCover.ts, next to this file).
10
+ *
8
11
  * Framework-free: call it on the element holding the article HTML after each
9
12
  * render and call the returned function when the element goes away. The same
10
13
  * file is used by every storefront (keep the copies identical).
11
14
  */
12
15
 
16
+ import { coverYoutubeSuggestions } from './blogYoutubeCover';
17
+
13
18
  export interface IBlogMediaFallbackLabels {
14
19
  image: string;
15
20
  video: string;
16
21
  openVideo: string;
17
22
  watchYoutube: string;
23
+ videoResume: string;
24
+ videoReplay: string;
18
25
  }
19
26
 
20
27
  const LABELS: Record<string, IBlogMediaFallbackLabels> = {
@@ -23,18 +30,24 @@ const LABELS: Record<string, IBlogMediaFallbackLabels> = {
23
30
  video: 'The video could not be loaded',
24
31
  openVideo: 'Open the video',
25
32
  watchYoutube: 'Watch on YouTube',
33
+ videoResume: 'Continue watching',
34
+ videoReplay: 'Watch again',
26
35
  },
27
36
  ru: {
28
37
  image: 'Не удалось загрузить изображение',
29
38
  video: 'Не удалось загрузить видео',
30
39
  openVideo: 'Открыть видео',
31
40
  watchYoutube: 'Смотреть на YouTube',
41
+ videoResume: 'Продолжить просмотр',
42
+ videoReplay: 'Смотреть снова',
32
43
  },
33
44
  es: {
34
45
  image: 'No se pudo cargar la imagen',
35
46
  video: 'No se pudo cargar el vídeo',
36
47
  openVideo: 'Abrir el vídeo',
37
48
  watchYoutube: 'Ver en YouTube',
49
+ videoResume: 'Seguir viendo',
50
+ videoReplay: 'Ver de nuevo',
38
51
  },
39
52
  };
40
53
 
@@ -247,7 +260,8 @@ function youtubeReachable(view: Window & typeof globalThis, videoId: string, lat
247
260
 
248
261
  /**
249
262
  * 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.
263
+ * ones that fail with a placeholder; the players get the suggestions cover.
264
+ * Returns the function that stops watching.
251
265
  */
252
266
  export function guardBlogMedia(
253
267
  root: HTMLElement | null | undefined,
@@ -315,8 +329,11 @@ export function guardBlogMedia(
315
329
  });
316
330
  }
317
331
 
332
+ const stopCovers = coverYoutubeSuggestions(root, { resume: labels.videoResume, replay: labels.videoReplay });
333
+
318
334
  return () => {
319
335
  active = false;
320
336
  root.removeEventListener('error', onError, true);
337
+ stopCovers();
321
338
  };
322
339
  }
@@ -0,0 +1,285 @@
1
+ /**
2
+ * Keeps YouTube's suggestions of other videos off a player of the page: the
3
+ * «More videos» shelf a paused player shows and the grid of videos at the end.
4
+ * YouTube has no setting that turns them off (`rel=0` only keeps them to the
5
+ * video's own channel), so the page listens to the player and lays its own
6
+ * cover over the frame while the player is paused («Continue watching») or has
7
+ * ended («Watch again»). The cover takes the whole frame: a paused player also
8
+ * shows a «More videos» button in its control bar.
9
+ *
10
+ * The player talks to the page with postMessage when its address has
11
+ * `enablejsapi=1`; no YouTube script is loaded into the page. A player that
12
+ * sends nothing (an address without `enablejsapi=1`, YouTube blocked) stays as
13
+ * it is. In full screen the cover cannot reach the player and is not shown.
14
+ *
15
+ * Framework-free and without imports: call it on the element holding the
16
+ * players after each render and call the returned function when the element
17
+ * goes away. The same file is used by every storefront (keep the copies
18
+ * identical).
19
+ */
20
+
21
+ export interface IYoutubeCoverLabels {
22
+ resume: string;
23
+ replay: string;
24
+ }
25
+
26
+ const LABELS: Record<string, IYoutubeCoverLabels> = {
27
+ en: { resume: 'Continue watching', replay: 'Watch again' },
28
+ ru: { resume: 'Продолжить просмотр', replay: 'Смотреть снова' },
29
+ es: { resume: 'Seguir viendo', replay: 'Ver de nuevo' },
30
+ };
31
+
32
+ /** The cover texts in the page language («ru», «en-US», …); English when the language is unknown. */
33
+ export function youtubeCoverLabels(locale?: string | null): IYoutubeCoverLabels {
34
+ const code = String(locale ?? '').toLowerCase().split(/[-_]/)[0] ?? '';
35
+
36
+ return LABELS[code] ?? LABELS.en!;
37
+ }
38
+
39
+ const COVER = 'data-youtube-cover';
40
+ const STYLE_ID = 'basklee-youtube-cover-style';
41
+ // A player that answers: youtube.com or youtube-nocookie.com, /embed/<id>, with enablejsapi=1.
42
+ const PLAYER = /^https:\/\/(?:www\.)?youtube(?:-nocookie)?\.com\/embed\/[\w-]{11}\?(?:[^#]*&)?enablejsapi=1(?:[&#]|$)/i;
43
+ const ORIGINS = new Set([
44
+ 'https://www.youtube-nocookie.com',
45
+ 'https://youtube-nocookie.com',
46
+ 'https://www.youtube.com',
47
+ 'https://youtube.com',
48
+ ]);
49
+ const ENDED = 0;
50
+ const PAUSED = 2;
51
+ const PING_MS = 250;
52
+ const PING_MAX = 40;
53
+
54
+ // The cover sits in <body>, so the page's own styles of the article do not reach it.
55
+ const STYLE = `
56
+ [${COVER}]{all:initial;position:absolute;z-index:2;box-sizing:border-box;display:flex;align-items:center;justify-content:center;padding:1rem;cursor:pointer;color:#fff;font:600 1rem/1.2 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;background:rgb(15 23 42 / 45%);-webkit-backdrop-filter:blur(16px);backdrop-filter:blur(16px)}
57
+ [${COVER}][hidden]{display:none!important}
58
+ [${COVER}="ended"]{background:rgb(15 23 42 / 92%)}
59
+ [${COVER}]>span{display:inline-flex;align-items:center;gap:.6rem;padding:.75rem 1.25rem;border-radius:999px;background:rgb(255 255 255 / 14%);box-shadow:inset 0 0 0 1px rgb(255 255 255 / 40%);transition:background .15s ease}
60
+ [${COVER}]:hover>span,[${COVER}]:focus-visible>span{background:rgb(255 255 255 / 26%)}
61
+ [${COVER}]:focus-visible{outline:3px solid #fff;outline-offset:-3px}
62
+ [${COVER}] svg{width:1.4em;height:1.4em;flex:none}
63
+ `;
64
+
65
+ const SVG_NS = 'http://www.w3.org/2000/svg';
66
+ const ICONS = {
67
+ resume: 'M8 5.5v13l10.5-6.5z',
68
+ replay: 'M4 12a8 8 0 1 0 2.35-5.65M4 4v4h4',
69
+ };
70
+
71
+ function ensureStyle(document: Document) {
72
+ if (document.getElementById(STYLE_ID)) {
73
+ return;
74
+ }
75
+ const style = document.createElement('style');
76
+ style.id = STYLE_ID;
77
+ style.textContent = STYLE;
78
+ document.head?.appendChild(style);
79
+ }
80
+
81
+ function icon(document: Document, kind: keyof typeof ICONS) {
82
+ const svg = document.createElementNS(SVG_NS, 'svg');
83
+ const path = document.createElementNS(SVG_NS, 'path');
84
+ svg.setAttribute('viewBox', '0 0 24 24');
85
+ svg.setAttribute('aria-hidden', 'true');
86
+ path.setAttribute('d', ICONS[kind]);
87
+ if (kind === 'resume') {
88
+ path.setAttribute('fill', 'currentColor');
89
+ } else {
90
+ path.setAttribute('fill', 'none');
91
+ path.setAttribute('stroke', 'currentColor');
92
+ path.setAttribute('stroke-width', '2');
93
+ path.setAttribute('stroke-linecap', 'round');
94
+ path.setAttribute('stroke-linejoin', 'round');
95
+ }
96
+ svg.appendChild(path);
97
+ return svg;
98
+ }
99
+
100
+ function playerState(data: unknown): number | undefined {
101
+ let message = data;
102
+ if (typeof message === 'string') {
103
+ try {
104
+ message = JSON.parse(message);
105
+ } catch {
106
+ return undefined;
107
+ }
108
+ }
109
+ if (!message || typeof message !== 'object') {
110
+ return undefined;
111
+ }
112
+ const { event, info } = message as { event?: unknown; info?: unknown };
113
+ if (event === 'onStateChange' && typeof info === 'number') {
114
+ return info;
115
+ }
116
+ if (event === 'infoDelivery' && info && typeof info === 'object') {
117
+ const state = (info as { playerState?: unknown }).playerState;
118
+ return typeof state === 'number' ? state : undefined;
119
+ }
120
+ return undefined;
121
+ }
122
+
123
+ function cover(frame: HTMLIFrameElement, labels: IYoutubeCoverLabels): () => void {
124
+ const document = frame.ownerDocument;
125
+ const view = document.defaultView!;
126
+ const target = new URL(frame.src).origin;
127
+ const element = document.createElement('button');
128
+ const face = document.createElement('span');
129
+ const caption = document.createElement('span');
130
+ let mode: 'paused' | 'ended' | '' = '';
131
+ let heard = false;
132
+ let pings = 0;
133
+ let pinger: ReturnType<typeof setInterval> | undefined;
134
+
135
+ element.type = 'button';
136
+ element.hidden = true;
137
+ element.setAttribute(COVER, '');
138
+ face.append(caption);
139
+ element.append(face);
140
+ document.body.appendChild(element);
141
+
142
+ const post = (message: Record<string, unknown>) => {
143
+ frame.contentWindow?.postMessage(JSON.stringify({ ...message, id: 1, channel: 'widget' }), target);
144
+ };
145
+
146
+ // Over the frame wherever the page puts it: the cover's own containing block is <body> or <html>.
147
+ const place = () => {
148
+ if (!mode) {
149
+ return;
150
+ }
151
+ const box = frame.getBoundingClientRect();
152
+ const host = element.offsetParent as HTMLElement | null;
153
+ let top = box.top + view.scrollY;
154
+ let left = box.left + view.scrollX;
155
+ if (host && view.getComputedStyle(host).position !== 'static') {
156
+ const hostBox = host.getBoundingClientRect();
157
+ top = box.top - hostBox.top - host.clientTop + host.scrollTop;
158
+ left = box.left - hostBox.left - host.clientLeft + host.scrollLeft;
159
+ }
160
+ element.style.top = `${top}px`;
161
+ element.style.left = `${left}px`;
162
+ element.style.width = `${box.width}px`;
163
+ element.style.height = `${box.height}px`;
164
+ };
165
+
166
+ const show = (next: typeof mode) => {
167
+ if (next && (document.fullscreenElement === frame || !frame.isConnected || frame.getClientRects().length === 0)) {
168
+ next = '';
169
+ }
170
+ mode = next;
171
+ if (!next) {
172
+ element.hidden = true;
173
+ element.removeAttribute('aria-label');
174
+ return;
175
+ }
176
+ const text = next === 'paused' ? labels.resume : labels.replay;
177
+ element.setAttribute(COVER, next);
178
+ element.setAttribute('aria-label', text);
179
+ caption.textContent = text;
180
+ face.querySelector('svg')?.remove();
181
+ face.prepend(icon(document, next === 'paused' ? 'resume' : 'replay'));
182
+ element.hidden = false;
183
+ place();
184
+ };
185
+
186
+ const onMessage = (event: MessageEvent) => {
187
+ if (event.source !== frame.contentWindow || !ORIGINS.has(event.origin)) {
188
+ return;
189
+ }
190
+ heard = true;
191
+ const state = playerState(event.data);
192
+ if (state === undefined) {
193
+ return;
194
+ }
195
+ show(state === PAUSED ? 'paused' : state === ENDED ? 'ended' : '');
196
+ };
197
+
198
+ const onClick = () => {
199
+ if (mode === 'ended') {
200
+ post({ event: 'command', func: 'seekTo', args: [0, true] });
201
+ }
202
+ post({ event: 'command', func: 'playVideo', args: [] });
203
+ show('');
204
+ };
205
+
206
+ // The player starts sending once the page says it listens; it may still be loading, so ask a few times.
207
+ const ping = () => {
208
+ if (heard || pings >= PING_MAX) {
209
+ clearInterval(pinger);
210
+ pinger = undefined;
211
+ return;
212
+ }
213
+ pings += 1;
214
+ post({ event: 'listening' });
215
+ };
216
+ const startPinging = () => {
217
+ pings = 0;
218
+ clearInterval(pinger);
219
+ ping();
220
+ pinger = setInterval(ping, PING_MS);
221
+ };
222
+
223
+ const onLayout = () => place();
224
+ const onFullscreen = () => {
225
+ if (document.fullscreenElement === frame) {
226
+ show('');
227
+ }
228
+ };
229
+
230
+ view.addEventListener('message', onMessage);
231
+ view.addEventListener('resize', onLayout);
232
+ document.addEventListener('scroll', onLayout, true);
233
+ document.addEventListener('fullscreenchange', onFullscreen);
234
+ frame.addEventListener('load', startPinging);
235
+ element.addEventListener('click', onClick);
236
+ startPinging();
237
+
238
+ return () => {
239
+ clearInterval(pinger);
240
+ view.removeEventListener('message', onMessage);
241
+ view.removeEventListener('resize', onLayout);
242
+ document.removeEventListener('scroll', onLayout, true);
243
+ document.removeEventListener('fullscreenchange', onFullscreen);
244
+ frame.removeEventListener('load', startPinging);
245
+ element.remove();
246
+ };
247
+ }
248
+
249
+ const covered = new WeakSet<HTMLIFrameElement>();
250
+
251
+ /**
252
+ * Covers YouTube's suggestions in every player under `root` (an iframe or an
253
+ * element holding them). Returns the function that removes the covers.
254
+ */
255
+ export function coverYoutubeSuggestions(
256
+ root: Element | null | undefined,
257
+ labels: IYoutubeCoverLabels = youtubeCoverLabels(),
258
+ ): () => void {
259
+ const document = root?.ownerDocument;
260
+ if (!root || !document?.defaultView || !document.body) {
261
+ return () => {};
262
+ }
263
+ const frames = [
264
+ ...(root.tagName === 'IFRAME' ? [root as HTMLIFrameElement] : []),
265
+ ...root.querySelectorAll('iframe'),
266
+ ].filter((frame) => PLAYER.test(frame.getAttribute('src') ?? '') && !covered.has(frame));
267
+ if (!frames.length) {
268
+ return () => {};
269
+ }
270
+ ensureStyle(document);
271
+ const stops = frames.map((frame) => {
272
+ covered.add(frame);
273
+ const stop = cover(frame, labels);
274
+ return () => {
275
+ covered.delete(frame);
276
+ stop();
277
+ };
278
+ });
279
+
280
+ return () => {
281
+ for (const stop of stops) {
282
+ stop();
283
+ }
284
+ };
285
+ }
@@ -40,6 +40,59 @@ export function localesMatch(left: string, right: string): boolean {
40
40
  return normalize(left) === normalize(right);
41
41
  }
42
42
 
43
+ /**
44
+ * The languages a customer's browser asks for, most wanted first: an
45
+ * Accept-Language header («ru-RU,ru;q=0.9,en;q=0.8») or navigator.languages.
46
+ */
47
+ export function wantedLanguages(
48
+ source: string | readonly string[] | null | undefined,
49
+ ): string[] {
50
+ if (!source) {
51
+ return [];
52
+ }
53
+ if (typeof source !== 'string') {
54
+ return source.map((tag) => tag.trim()).filter(Boolean);
55
+ }
56
+ return source
57
+ .split(',')
58
+ .map((part, index) => {
59
+ const [tag = '', ...parameters] = part.split(';');
60
+ const weight = parameters
61
+ .map((parameter) => /^q=([0-9.]+)$/i.exec(parameter.trim()))
62
+ .find(Boolean);
63
+ return { tag: tag.trim(), weight: weight ? Number(weight[1]) : 1, index };
64
+ })
65
+ .filter((item) => item.tag && item.tag !== '*' && item.weight > 0)
66
+ .sort((left, right) => right.weight - left.weight || left.index - right.index)
67
+ .map((item) => item.tag);
68
+ }
69
+
70
+ /**
71
+ * The shop's language closest to what the customer wants, in the customer's
72
+ * order: the same tag first (pt_BR = pt-BR), then the same language (ru-RU
73
+ * finds ru, en finds en-GB). Nothing when no wanted language is offered.
74
+ */
75
+ export function closestLocale(
76
+ available: readonly string[],
77
+ wanted: readonly string[],
78
+ ): string | undefined {
79
+ const language = (tag: string) =>
80
+ tag.trim().toLowerCase().split(/[-_]/)[0] ?? '';
81
+ for (const tag of wanted) {
82
+ const same = available.find((code) => localesMatch(code, tag));
83
+ if (same) {
84
+ return same;
85
+ }
86
+ const kin = language(tag)
87
+ ? available.find((code) => language(code) === language(tag))
88
+ : undefined;
89
+ if (kin) {
90
+ return kin;
91
+ }
92
+ }
93
+ return undefined;
94
+ }
95
+
43
96
  export function getAvailableValueFromObject<T>(
44
97
  values: Record<string, T> | null | undefined,
45
98
  locale: string,
@@ -82,3 +135,55 @@ export function getAvailableNestedValueFromObject<T, Key extends keyof T>(
82
135
  export function plainText(value: string | undefined): string {
83
136
  return (value ?? '').replace(/<[^>]*>/g, '').trim();
84
137
  }
138
+
139
+ /** Cookies that keep the language and currency the customer picked. */
140
+ export const SAVED_LOCALE_COOKIE = 'basklee_locale';
141
+ export const SAVED_CURRENCY_COOKIE = 'basklee_currency';
142
+ const SAVED_CHOICE_SECONDS = 60 * 60 * 24 * 365;
143
+
144
+ /**
145
+ * The language and currency the customer picked on an earlier visit, read
146
+ * from a `Cookie` header or document.cookie; empty when nothing was picked.
147
+ */
148
+ export function savedChoices(cookies: string | null | undefined): {
149
+ locale: string;
150
+ currency: string;
151
+ } {
152
+ const values = new Map<string, string>();
153
+ for (const pair of (cookies ?? '').split(';')) {
154
+ const separator = pair.indexOf('=');
155
+ if (separator <= 0) {
156
+ continue;
157
+ }
158
+ try {
159
+ values.set(
160
+ pair.slice(0, separator).trim(),
161
+ decodeURIComponent(pair.slice(separator + 1).trim()),
162
+ );
163
+ } catch {
164
+ // A value that is not URI-encoded is not ours.
165
+ }
166
+ }
167
+ return {
168
+ locale: values.get(SAVED_LOCALE_COOKIE) ?? '',
169
+ currency: values.get(SAVED_CURRENCY_COOKIE) ?? '',
170
+ };
171
+ }
172
+
173
+ /**
174
+ * Keeps a pick of the customer for a year (in the browser only): the next
175
+ * visit without `?locale=` opens in it instead of the browser's language.
176
+ */
177
+ export function rememberChoice(name: string, value: string) {
178
+ if (typeof document === 'undefined' || !value) {
179
+ return;
180
+ }
181
+ const secure = globalThis.location?.protocol === 'https:' ? '; Secure' : '';
182
+ try {
183
+ document.cookie =
184
+ `${name}=${encodeURIComponent(value)}; Path=/; ` +
185
+ `Max-Age=${SAVED_CHOICE_SECONDS}; SameSite=Lax${secure}`;
186
+ } catch {
187
+ // Without cookies the pick lasts until the page is closed.
188
+ }
189
+ }
@@ -2,7 +2,8 @@
2
2
  * Texts of the privacy page (/privacy) and the cookie notice.
3
3
  *
4
4
  * The page describes what the storefront itself does: the account, orders,
5
- * the two platform cookies and the notice's own storage mark. A store that
5
+ * the platform cookies (the session, the CSRF token, the language and
6
+ * currency the customer picked) and the notice's own storage mark. A store that
6
7
  * adds analytics, chat widgets or other cookies lists them in the cookies
7
8
  * section here. The operator is the store's company from the platform's
8
9
  * contact details; `{company}` in a text is replaced with its name.
@@ -89,7 +90,7 @@ const ru: PrivacyLabels = {
89
90
  id: 'cookies',
90
91
  title: '7. Cookie и локальное хранилище',
91
92
  text: [
92
- 'Сайт использует только необходимые для работы cookie: sessionid сохраняет вход в аккаунт, csrftoken защищает формы от подделки запросов.',
93
+ 'Сайт использует только необходимые для работы cookie: sessionid сохраняет вход в аккаунт, csrftoken защищает формы от подделки запросов. Если вы сами выберете язык или валюту, cookie basklee_locale и basklee_currency запомнят выбор на год, чтобы сайт открывался с ним.',
93
94
  'В локальном хранилище браузера сохраняется отметка о том, что вы видели уведомление о cookie. Рекламных и аналитических cookie нет. Если запретить cookie, вход и оформление заказа не будут работать.',
94
95
  ],
95
96
  },
@@ -103,7 +104,7 @@ const ru: PrivacyLabels = {
103
104
  ],
104
105
  cookie: {
105
106
  label: 'Уведомление о cookie',
106
- text: 'Сайт использует только необходимые cookie: для входа в аккаунт и защиты форм.',
107
+ text: 'Сайт использует только необходимые cookie: для входа в аккаунт, защиты форм и чтобы запомнить выбранные вами язык и валюту.',
107
108
  link: 'Подробнее',
108
109
  ok: 'Понятно',
109
110
  },
@@ -166,7 +167,7 @@ const es: PrivacyLabels = {
166
167
  id: 'cookies',
167
168
  title: '7. Cookies y almacenamiento local',
168
169
  text: [
169
- 'El sitio solo usa las cookies que necesita para funcionar: sessionid mantiene tu sesión iniciada y csrftoken protege los formularios contra la falsificación de solicitudes.',
170
+ 'El sitio solo usa las cookies que necesita para funcionar: sessionid mantiene tu sesión iniciada y csrftoken protege los formularios contra la falsificación de solicitudes. Si eliges tú el idioma o la moneda, las cookies basklee_locale y basklee_currency guardan tu elección durante un año para que el sitio se abra con ella.',
170
171
  'El almacenamiento local del navegador guarda el hecho de que ya has visto el aviso de cookies. No hay cookies publicitarias ni de analítica. Si bloqueas las cookies, no funcionan el inicio de sesión ni la compra.',
171
172
  ],
172
173
  },
@@ -178,7 +179,7 @@ const es: PrivacyLabels = {
178
179
  ],
179
180
  cookie: {
180
181
  label: 'Aviso de cookies',
181
- text: 'El sitio solo usa las cookies que necesita: para iniciar tu sesión y proteger los formularios.',
182
+ text: 'El sitio solo usa las cookies que necesita: para iniciar tu sesión, proteger los formularios y recordar el idioma y la moneda que elijas.',
182
183
  link: 'Más información',
183
184
  ok: 'Aceptar',
184
185
  },
@@ -241,7 +242,7 @@ const en: PrivacyLabels = {
241
242
  id: 'cookies',
242
243
  title: '7. Cookies and local storage',
243
244
  text: [
244
- 'The site uses only the cookies it needs to work: sessionid keeps you signed in, csrftoken protects forms from request forgery.',
245
+ 'The site uses only the cookies it needs to work: sessionid keeps you signed in, csrftoken protects forms from request forgery. When you pick a language or currency yourself, basklee_locale and basklee_currency keep the choice for a year, so the site opens with it.',
245
246
  'The browser’s local storage keeps the fact that you have seen the cookie notice. There are no advertising or analytics cookies. If you block cookies, signing in and checking out do not work.',
246
247
  ],
247
248
  },
@@ -253,7 +254,7 @@ const en: PrivacyLabels = {
253
254
  ],
254
255
  cookie: {
255
256
  label: 'Cookie notice',
256
- text: 'The site uses only the cookies it needs: to sign you in and to protect forms.',
257
+ text: 'The site uses only the cookies it needs: to sign you in, to protect forms and to remember the language and currency you pick.',
257
258
  link: 'Learn more',
258
259
  ok: 'OK',
259
260
  },
@@ -3,6 +3,11 @@ import { headers } from 'next/headers';
3
3
  import { getBaskleeAppLoad } from '@/lib/basklee/appLoadServer';
4
4
  import { createBaskleeSelectionsStore } from '@/stores/baskleeSelections';
5
5
  import { storefrontErrorLocale } from '@/lib/basklee/errorPageLabels';
6
+ import {
7
+ closestLocale,
8
+ savedChoices,
9
+ wantedLanguages,
10
+ } from '@/lib/basklee/presentation';
6
11
 
7
12
  export const getStorefrontRequestUrl = cache(async () => {
8
13
  const incoming = await headers();
@@ -12,6 +17,11 @@ export const getStorefrontRequestUrl = cache(async () => {
12
17
  );
13
18
  });
14
19
 
20
+ /** The language and currency the customer picked on an earlier visit. */
21
+ export const getBaskleeSavedChoices = cache(async () =>
22
+ savedChoices((await headers()).get('cookie')),
23
+ );
24
+
15
25
  export const getBaskleeServerLocale = cache(async () => {
16
26
  const { result } = await getBaskleeAppLoad();
17
27
  const url = await getStorefrontRequestUrl();
@@ -19,11 +29,24 @@ export const getBaskleeServerLocale = cache(async () => {
19
29
  if (!result) {
20
30
  return storefrontErrorLocale(requested, undefined);
21
31
  }
22
- const selections = createBaskleeSelectionsStore(
23
- result?.response.page_data.init ?? null,
32
+ const init = result.response.page_data.init;
33
+ const selections = createBaskleeSelectionsStore(init ?? null);
34
+ // ?locale= first, then the language the customer picked on an earlier
35
+ // visit (the basklee_locale cookie), then the languages the browser asks
36
+ // for (Accept-Language); the storefront's first language when none is
37
+ // offered.
38
+ const wanted = closestLocale(
39
+ Object.entries(init?.locale ?? {}).map(
40
+ ([key, value]) => value.code?.trim() || key,
41
+ ),
42
+ [
43
+ requested ?? '',
44
+ (await getBaskleeSavedChoices()).locale,
45
+ ...wantedLanguages((await headers()).get('accept-language')),
46
+ ].filter(Boolean),
24
47
  );
25
- if (requested) {
26
- selections.getState().setLocale(requested);
48
+ if (wanted) {
49
+ selections.getState().setLocale(wanted, false);
27
50
  }
28
51
  return selections.getState().localeCode || 'en';
29
52
  });
@@ -48,6 +48,8 @@ export interface BaskleeProviderProps {
48
48
  result?: AppLoadResult | null;
49
49
  failure?: AppLoadFailure | null;
50
50
  locale?: string;
51
+ /** The currency the customer picked on an earlier visit (a cookie). */
52
+ currency?: string;
51
53
  children: ReactNode;
52
54
  }
53
55
 
@@ -56,11 +58,12 @@ export function BaskleeProvider({
56
58
  result = null,
57
59
  failure = null,
58
60
  locale,
61
+ currency,
59
62
  children,
60
63
  }: BaskleeProviderProps) {
61
64
  const stores = useRef<BaskleeStores>(null);
62
65
  if (!stores.current) {
63
- stores.current = createBaskleeStores(result, failure, locale);
66
+ stores.current = createBaskleeStores(result, failure, locale, currency);
64
67
  }
65
68
 
66
69
  const current = stores.current;
@@ -66,11 +66,12 @@ export function createBaskleeStores(
66
66
  result: AppLoadResult | null = null,
67
67
  failure: AppLoadFailure | null = null,
68
68
  locale = '',
69
+ currency = '',
69
70
  ): BaskleeStores {
70
71
  const init = failure ? null : (result?.response.page_data.init ?? null);
71
72
  const store = createBaskleeStore(initialSnapshot(result, failure));
72
73
  const domains = {
73
- selections: createBaskleeSelectionsStore(init, locale),
74
+ selections: createBaskleeSelectionsStore(init, locale, currency),
74
75
  products: createBaskleeProductsStore(init),
75
76
  catalog: createBaskleeCatalogStore(init),
76
77
  browse: createBaskleeBrowseStore(init),
@@ -1,5 +1,12 @@
1
1
  import { createStore } from 'zustand/vanilla';
2
2
  import type { IAppLoadCommon } from '@/interfaces/basklee';
3
+ import {
4
+ closestLocale,
5
+ rememberChoice,
6
+ SAVED_CURRENCY_COOKIE,
7
+ SAVED_LOCALE_COOKIE,
8
+ savedChoices,
9
+ } from '@/lib/basklee/presentation';
3
10
 
4
11
  export interface BaskleeSelectionsState {
5
12
  localeCode: string;
@@ -7,8 +14,9 @@ export interface BaskleeSelectionsState {
7
14
  weightId: string;
8
15
  lengthId: string;
9
16
  init: IAppLoadCommon | null;
10
- setLocale: (code: string) => void;
11
- setCurrency: (id: string) => void;
17
+ /** remember (default): the customer's pick, kept for later visits. */
18
+ setLocale: (code: string, remember?: boolean) => void;
19
+ setCurrency: (id: string, remember?: boolean) => void;
12
20
  setUnit: (kind: 'weights' | 'lengths', id: string) => void;
13
21
  reconcile: (init: IAppLoadCommon | null) => void;
14
22
  reset: () => void;
@@ -40,13 +48,25 @@ function availableCurrency(init: IAppLoadCommon, preferred?: number | string) {
40
48
  ) ?? '';
41
49
  }
42
50
 
43
- export function initialSelections(init: IAppLoadCommon | null, locale = '') {
51
+ /** currency: the one picked on an earlier visit, when it is still offered. */
52
+ export function initialSelections(
53
+ init: IAppLoadCommon | null,
54
+ locale = '',
55
+ currency = '',
56
+ ) {
44
57
  const selected = init
45
58
  ? findLocale(init, locale) ?? Object.entries(init.locale)[0]
46
59
  : undefined;
47
60
  return {
48
61
  localeCode: selected?.[1].code?.trim() || selected?.[0] || '',
49
- currencyId: init ? availableCurrency(init, selected?.[1].currency) : '',
62
+ currencyId: init
63
+ ? availableCurrency(
64
+ init,
65
+ init.currencies[currency]?.allowed_select
66
+ ? currency
67
+ : selected?.[1].currency,
68
+ )
69
+ : '',
50
70
  weightId: init ? unitId(init.weights ?? {}, selected?.[1].weight) : '',
51
71
  lengthId: init ? unitId(init.lengths ?? {}, selected?.[1].length) : '',
52
72
  };
@@ -56,28 +76,40 @@ export function initialSelections(init: IAppLoadCommon | null, locale = '') {
56
76
  export function createBaskleeSelectionsStore(
57
77
  init: IAppLoadCommon | null = null,
58
78
  locale = '',
79
+ currency = '',
59
80
  ) {
60
81
  return createStore<BaskleeSelectionsState>()((set, get) => ({
61
- ...initialSelections(init, locale),
82
+ ...initialSelections(init, locale, currency),
62
83
  init,
63
84
 
64
- setLocale(code) {
85
+ // The customer's pick (the language and currency switchers) is kept for
86
+ // later visits; a language that comes from the address is shown with
87
+ // remember = false and is not kept.
88
+ setLocale(code, remember = true) {
65
89
  const current = get().init;
66
90
  const entry = current && findLocale(current, code);
67
91
  if (!current || !entry) {
68
92
  return;
69
93
  }
70
- set({
94
+ const picked = {
71
95
  localeCode: entry[1].code?.trim() || entry[0],
72
96
  currencyId: availableCurrency(current, entry[1].currency),
73
97
  weightId: unitId(current.weights ?? {}, entry[1].weight),
74
98
  lengthId: unitId(current.lengths ?? {}, entry[1].length),
75
- });
99
+ };
100
+ set(picked);
101
+ if (remember) {
102
+ rememberChoice(SAVED_LOCALE_COOKIE, picked.localeCode);
103
+ rememberChoice(SAVED_CURRENCY_COOKIE, picked.currencyId);
104
+ }
76
105
  },
77
106
 
78
- setCurrency(id) {
107
+ setCurrency(id, remember = true) {
79
108
  if (get().init?.currencies[id]?.allowed_select) {
80
109
  set({ currencyId: id });
110
+ if (remember) {
111
+ rememberChoice(SAVED_CURRENCY_COOKIE, id);
112
+ }
81
113
  }
82
114
  },
83
115
 
@@ -96,13 +128,31 @@ export function createBaskleeSelectionsStore(
96
128
  }
97
129
 
98
130
  const previous = get();
131
+ // A language still offered stays; in the browser (the app build loads
132
+ // there) the one picked on an earlier visit, then the one closest to
133
+ // navigator.languages; else the first one. The currency likewise: the
134
+ // one still offered, the one picked before, the language's own.
135
+ const saved = typeof document === 'undefined'
136
+ ? { locale: '', currency: '' }
137
+ : savedChoices(document.cookie);
138
+ const browser = typeof window === 'undefined'
139
+ ? undefined
140
+ : closestLocale(
141
+ Object.entries(next.locale).map(
142
+ ([key, value]) => value.code?.trim() || key,
143
+ ),
144
+ [saved.locale, ...(window.navigator.languages ?? [])].filter(Boolean),
145
+ );
99
146
  const selected = findLocale(next, previous.localeCode) ??
147
+ (browser ? findLocale(next, browser) : undefined) ??
100
148
  Object.entries(next.locale)[0];
101
149
  const localeCode = selected?.[1].code?.trim() || selected?.[0] || '';
102
150
  const preferredCurrency = next.currencies[previous.currencyId]
103
151
  ?.allowed_select
104
152
  ? previous.currencyId
105
- : selected?.[1].currency;
153
+ : next.currencies[saved.currency]?.allowed_select
154
+ ? saved.currency
155
+ : selected?.[1].currency;
106
156
 
107
157
  set({
108
158
  init: next,