basklee-svelte 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 +1 -1
- package/package.json +1 -1
- package/templates/src/lib/basklee/appRoutes.ts +8 -1
- package/templates/src/lib/basklee/pageLoad.ts +1 -1
- package/templates/src/lib/components/basklee/blog/BlogArticle.README.md +1 -1
- package/templates/src/lib/layouts/StorefrontLayout.svelte +2 -1
- package/templates/src/lib/stores/baskleeSelections.svelte.ts +53 -4
- package/templates/src/lib/utils/basklee/blogArticleHtml.ts +13 -2
- package/templates/src/lib/utils/basklee/blogMediaFallback.ts +18 -1
- package/templates/src/lib/utils/basklee/blogYoutubeCover.ts +285 -0
- package/templates/src/lib/utils/basklee/presentation.ts +105 -0
- package/templates/src/lib/utils/basklee/privacyLabels.ts +8 -7
- package/templates/src/routes/+layout.server.ts +29 -2
- package/templates/src/routes/+layout.svelte +3 -1
package/README.md
CHANGED
|
@@ -528,7 +528,7 @@ Page titles, descriptions and link-preview metadata follow the current page
|
|
|
528
528
|
and selected language, including client navigation. Public events and banner
|
|
529
529
|
images come from Application Load.
|
|
530
530
|
A product page takes the product's SEO tab: its heading is the page title (the product name without one), its meta description and keywords fill their tags, and its own Open Graph and Twitter Cards tags are added in the page's language only, replacing a default tag of the same name.
|
|
531
|
-
Pages with a canonical address also link the same page in the other storefront languages (`hreflang`) and set `og:type` and `og:locale`; a journal article adds its publication date (`article:published_time`) and schema.org `BlogPosting` data. The store icon (`logos.ico`) is the page's `<link rel="icon">`. An unknown `?locale` opens the
|
|
531
|
+
Pages with a canonical address also link the same page in the other storefront languages (`hreflang`) and set `og:type` and `og:locale`; a journal article adds its publication date (`article:published_time`) and schema.org `BlogPosting` data. The store icon (`logos.ico`) is the page's `<link rel="icon">`. An unknown `?locale` opens the 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.
|
|
532
532
|
|
|
533
533
|
List pages (journal, categories, stores) link their previous and next pages as real links (`?page=2`). Each later page has its own canonical address and a title with its page number; a journal page past the last one answers 404.
|
|
534
534
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "basklee-svelte",
|
|
3
|
-
"version": "0.9.
|
|
3
|
+
"version": "0.9.13",
|
|
4
4
|
"description": "SvelteKit 2 storefront for your Basklee marketplace: setup CLI, server API gateway, typed store and ready-made catalog, cart, checkout and account components in English, Russian and Spanish, plus an Android app build. Powered by Basklee: https://basklee.com",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -7,6 +7,7 @@ import { browserTransport } from '@/lib/composables/useBaskleeApi.svelte';
|
|
|
7
7
|
import { BaskleeApi } from '@/lib/utils/basklee/api';
|
|
8
8
|
import { nativeAppCookies, savedAppLocale } from '@/lib/utils/basklee/nativeApp';
|
|
9
9
|
import { storefrontErrorLocale } from '@/lib/utils/basklee/errorPageLabels';
|
|
10
|
+
import { savedChoices } from '@/lib/utils/basklee/presentation';
|
|
10
11
|
import type { BaskleeSnapshot } from '@/lib/basklee/appLoadData';
|
|
11
12
|
import type { StorefrontPageEvent } from '@/lib/basklee/pageLoad';
|
|
12
13
|
|
|
@@ -49,7 +50,12 @@ export async function loadAppLayout({ url, untrack }: AppLayoutEvent) {
|
|
|
49
50
|
}
|
|
50
51
|
const store = new BaskleeStore(snapshot);
|
|
51
52
|
if (locale) {
|
|
52
|
-
store.setLocale(locale);
|
|
53
|
+
store.setLocale(locale, false);
|
|
54
|
+
}
|
|
55
|
+
// The app keeps a currency the customer picked like the website does.
|
|
56
|
+
const { currency } = savedChoices(document.cookie);
|
|
57
|
+
if (currency) {
|
|
58
|
+
store.setCurrency(currency, false);
|
|
53
59
|
}
|
|
54
60
|
if (!store.isReady) {
|
|
55
61
|
store.localeCode = storefrontErrorLocale(locale, store.localeCode);
|
|
@@ -57,6 +63,7 @@ export async function loadAppLayout({ url, untrack }: AppLayoutEvent) {
|
|
|
57
63
|
return {
|
|
58
64
|
basklee: snapshot,
|
|
59
65
|
baskleeLocale: store.localeCode,
|
|
66
|
+
baskleeCurrency: store.currencyId,
|
|
60
67
|
};
|
|
61
68
|
}
|
|
62
69
|
|
|
@@ -48,7 +48,7 @@ export async function loadStorefrontPageData(
|
|
|
48
48
|
const query = event.url.searchParams;
|
|
49
49
|
const locale = query.get('locale');
|
|
50
50
|
if (locale) {
|
|
51
|
-
store.setLocale(locale);
|
|
51
|
+
store.setLocale(locale, false);
|
|
52
52
|
}
|
|
53
53
|
if (accountRoutes.has(path) && store.isReady && !store.isAuthenticated) {
|
|
54
54
|
const target = new URLSearchParams({
|
|
@@ -10,7 +10,7 @@ The server render shows the text as plain blocks (`blogArticleBlocks` in `src/li
|
|
|
10
10
|
|
|
11
11
|
The cover and the images of the text open larger: a click, Enter or Space on one opens `ProductReviewImageViewer` at that image, with the article's other images a step away and each image's caption (its `figcaption`, else its `title`, else its `alt`) under it. The images get `role="button"`, a keyboard stop and an «Open image» name; a zoom-in cursor marks them. Images inside a link, a button or a product placement keep their own action. The helper is `src/lib/utils/basklee/blogImageViewer.ts`.
|
|
12
12
|
|
|
13
|
-
A picture, video or YouTube player of the text that does not load is replaced by a placeholder in the text's own colours: «The image could not be loaded» with the picture's `alt`, or «The video could not be loaded» with a link to the video file or to the video on YouTube. A blocked YouTube gives no error, so the article checks once per page whether YouTube's image server answers within 8 seconds; the players stay when it does. Pictures of product cards keep the card's own placeholder. The helper is `src/lib/utils/basklee/blogMediaFallback.ts`.
|
|
13
|
+
A picture, video or YouTube player of the text that does not load is replaced by a placeholder in the text's own colours: «The image could not be loaded» with the picture's `alt`, or «The video could not be loaded» with a link to the video file or to the video on YouTube. A blocked YouTube gives no error, so the article checks once per page whether YouTube's image server answers within 8 seconds; the players stay when it does. A player that plays gets a cover over YouTube's suggestions of other videos: while it is paused («Continue watching») or has ended («Watch again»), the page lays its own layer over the frame, because YouTube has no setting that turns the suggestions off. Player addresses carry `rel=0` (suggestions from the video's own channel only) and `enablejsapi=1`, so the page hears the player through postMessage; no YouTube script is loaded into the page. In full screen the cover cannot reach the player. The helper is `src/lib/utils/basklee/blogYoutubeCover.ts`, called by `guardBlogMedia`. Pictures of product cards keep the card's own placeholder. The helper is `src/lib/utils/basklee/blogMediaFallback.ts`.
|
|
14
14
|
|
|
15
15
|
Products the author places in the text appear at those positions: an empty block with `data-product-id="12"` shows one product card, `data-product-ids="12,15,9"` a row of up to 24 cards. The block keeps the editor's float or centred style, and `data-product-hidden-badges` (`new`, `popular`, `good-deal`) turns card badges off. Products missing from `related_products` are loaded with `products_search` and `filters.id_in`, up to 35 IDs per request, and stored with `store.setProduct()`; a block whose products are not found stays hidden. Article text styles do not reach the cards, and in a narrow article a floated card stands alone in the middle. The helper is `src/lib/utils/basklee/blogProductPlacements.ts`.
|
|
16
16
|
|
|
@@ -78,8 +78,9 @@
|
|
|
78
78
|
const available = Object.entries(store.locales).some(([code, item]) =>
|
|
79
79
|
localesMatch(item.code || code, locale),
|
|
80
80
|
);
|
|
81
|
+
// A language from the address is shown, not kept as the customer's pick.
|
|
81
82
|
if (available && !localesMatch(store.localeCode, locale)) {
|
|
82
|
-
store.setLocale(locale);
|
|
83
|
+
store.setLocale(locale, false);
|
|
83
84
|
}
|
|
84
85
|
},
|
|
85
86
|
{ immediate: true },
|
|
@@ -3,6 +3,13 @@ import type { ComputedRef } from '@/lib/basklee/reactivity.svelte';
|
|
|
3
3
|
import { defineStore } from '@/lib/basklee/scope.svelte';
|
|
4
4
|
import type { StoreScope } from '@/lib/basklee/scope.svelte';
|
|
5
5
|
import { resolveBaskleeDomain } from '@/lib/stores/baskleeDomainAccess.svelte';
|
|
6
|
+
import {
|
|
7
|
+
closestLocale,
|
|
8
|
+
rememberChoice,
|
|
9
|
+
SAVED_CURRENCY_COOKIE,
|
|
10
|
+
SAVED_LOCALE_COOKIE,
|
|
11
|
+
savedChoices,
|
|
12
|
+
} from '@/lib/utils/basklee/presentation';
|
|
6
13
|
import '@/lib/stores/basklee.svelte';
|
|
7
14
|
import type { IAppLoadCommon } from '@/lib/interfaces/basklee/appBase/IAppLoadCommon';
|
|
8
15
|
|
|
@@ -52,7 +59,10 @@ export function useBaskleeSelections(
|
|
|
52
59
|
);
|
|
53
60
|
}
|
|
54
61
|
|
|
55
|
-
|
|
62
|
+
// The customer's pick (remember = true, the language and currency
|
|
63
|
+
// switchers) is kept for later visits; a language that comes from the
|
|
64
|
+
// address or the server render is shown without being kept.
|
|
65
|
+
function setLocale(code: string, remember = true) {
|
|
56
66
|
const entry = findLocale(code);
|
|
57
67
|
if (!entry) {
|
|
58
68
|
return;
|
|
@@ -61,11 +71,18 @@ export function useBaskleeSelections(
|
|
|
61
71
|
currencyId.value = availableCurrency(entry[1].currency);
|
|
62
72
|
weightId.value = unitId(weights.value, entry[1].weight);
|
|
63
73
|
lengthId.value = unitId(lengths.value, entry[1].length);
|
|
74
|
+
if (remember) {
|
|
75
|
+
rememberChoice(SAVED_LOCALE_COOKIE, localeCode.value);
|
|
76
|
+
rememberChoice(SAVED_CURRENCY_COOKIE, currencyId.value);
|
|
77
|
+
}
|
|
64
78
|
}
|
|
65
79
|
|
|
66
|
-
function setCurrency(id: string) {
|
|
80
|
+
function setCurrency(id: string, remember = true) {
|
|
67
81
|
if (currencies.value[id]?.allowed_select) {
|
|
68
82
|
currencyId.value = id;
|
|
83
|
+
if (remember) {
|
|
84
|
+
rememberChoice(SAVED_CURRENCY_COOKIE, id);
|
|
85
|
+
}
|
|
69
86
|
}
|
|
70
87
|
}
|
|
71
88
|
|
|
@@ -81,14 +98,46 @@ export function useBaskleeSelections(
|
|
|
81
98
|
}
|
|
82
99
|
}
|
|
83
100
|
|
|
101
|
+
// What the customer picked on an earlier visit; read in the browser
|
|
102
|
+
// only (the server render reads the request's cookies itself).
|
|
103
|
+
function savedInBrowser() {
|
|
104
|
+
return typeof document === 'undefined'
|
|
105
|
+
? { locale: '', currency: '' }
|
|
106
|
+
: savedChoices(document.cookie);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// A language still offered stays; in the browser (the app build loads
|
|
110
|
+
// there) the one picked on an earlier visit, then the one closest to
|
|
111
|
+
// navigator.languages; else the first one.
|
|
112
|
+
function browserLocale() {
|
|
113
|
+
if (typeof window === 'undefined') {
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
const code = closestLocale(
|
|
117
|
+
Object.entries(locales.value).map(
|
|
118
|
+
([key, value]) => value.code?.trim() || key,
|
|
119
|
+
),
|
|
120
|
+
[savedInBrowser().locale, ...(window.navigator.languages ?? [])]
|
|
121
|
+
.filter(Boolean),
|
|
122
|
+
);
|
|
123
|
+
return code ? findLocale(code) : undefined;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// The currency likewise: the one still offered, the one picked on an
|
|
127
|
+
// earlier visit, the language's own.
|
|
84
128
|
function reconcile() {
|
|
85
129
|
const selected =
|
|
86
|
-
findLocale(localeCode.value) ??
|
|
130
|
+
findLocale(localeCode.value) ??
|
|
131
|
+
browserLocale() ??
|
|
132
|
+
Object.entries(locales.value)[0];
|
|
133
|
+
const saved = savedInBrowser().currency;
|
|
87
134
|
localeCode.value = selected?.[1].code?.trim() || selected?.[0] || '';
|
|
88
135
|
currencyId.value = availableCurrency(
|
|
89
136
|
currencies.value[currencyId.value]?.allowed_select
|
|
90
137
|
? currencyId.value
|
|
91
|
-
:
|
|
138
|
+
: currencies.value[saved]?.allowed_select
|
|
139
|
+
? saved
|
|
140
|
+
: selected?.[1].currency,
|
|
92
141
|
);
|
|
93
142
|
weightId.value = unitId(
|
|
94
143
|
weights.value,
|
|
@@ -204,12 +204,18 @@ const authorRelTokens = new Set(['nofollow', 'sponsored', 'ugc']);
|
|
|
204
204
|
const youtubeEmbed =
|
|
205
205
|
/^https:\/\/(?:www\.)?youtube(?:-nocookie)?\.com\/embed\/([\w-]{11})(?:\?([^#]*))?$/i;
|
|
206
206
|
|
|
207
|
+
// Options of every player address: suggestions from the same channel only, events for the page.
|
|
208
|
+
const youtubeEmbedOptions = ['rel=0', 'enablejsapi=1'];
|
|
209
|
+
|
|
207
210
|
export const blogYoutubeAllow =
|
|
208
211
|
'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
|
|
209
212
|
|
|
210
213
|
/**
|
|
211
214
|
* The privacy-enhanced player address for a YouTube embed address, or an
|
|
212
|
-
* empty string for anything else (other sites, other YouTube pages).
|
|
215
|
+
* empty string for anything else (other sites, other YouTube pages). The
|
|
216
|
+
* address keeps YouTube's suggestions to the video's own channel (`rel=0`)
|
|
217
|
+
* and lets the page hear the player (`enablejsapi=1`), so blogYoutubeCover.ts
|
|
218
|
+
* can cover the suggestions while the player is paused or ended.
|
|
213
219
|
*/
|
|
214
220
|
export function blogYoutubeEmbedSource(value: string) {
|
|
215
221
|
const match = youtubeEmbed.exec(value.trim());
|
|
@@ -220,7 +226,12 @@ export function blogYoutubeEmbedSource(value: string) {
|
|
|
220
226
|
|
|
221
227
|
const start = /(?:^|&)start=(\d{1,6})(?:&|$)/.exec(match[2] ?? '')?.[1];
|
|
222
228
|
|
|
223
|
-
|
|
229
|
+
const query = [
|
|
230
|
+
...(start && Number(start) > 0 ? [`start=${Number(start)}`] : []),
|
|
231
|
+
...youtubeEmbedOptions,
|
|
232
|
+
].join('&');
|
|
233
|
+
|
|
234
|
+
return `https://www.youtube-nocookie.com/embed/${match[1]}?${query}`;
|
|
224
235
|
}
|
|
225
236
|
|
|
226
237
|
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
|
|
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
|
+
}
|
|
@@ -70,3 +70,108 @@ export function localesMatch(left: string, right: string) {
|
|
|
70
70
|
value.trim().toLowerCase().replaceAll('_', '-');
|
|
71
71
|
return normalize(left) === normalize(right);
|
|
72
72
|
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The languages a customer's browser asks for, most wanted first: an
|
|
76
|
+
* Accept-Language header («ru-RU,ru;q=0.9,en;q=0.8») or navigator.languages.
|
|
77
|
+
*/
|
|
78
|
+
export function wantedLanguages(
|
|
79
|
+
source: string | readonly string[] | null | undefined,
|
|
80
|
+
): string[] {
|
|
81
|
+
if (!source) {
|
|
82
|
+
return [];
|
|
83
|
+
}
|
|
84
|
+
if (typeof source !== 'string') {
|
|
85
|
+
return source.map((tag) => tag.trim()).filter(Boolean);
|
|
86
|
+
}
|
|
87
|
+
return source
|
|
88
|
+
.split(',')
|
|
89
|
+
.map((part, index) => {
|
|
90
|
+
const [tag = '', ...parameters] = part.split(';');
|
|
91
|
+
const weight = parameters
|
|
92
|
+
.map((parameter) => /^q=([0-9.]+)$/i.exec(parameter.trim()))
|
|
93
|
+
.find(Boolean);
|
|
94
|
+
return { tag: tag.trim(), weight: weight ? Number(weight[1]) : 1, index };
|
|
95
|
+
})
|
|
96
|
+
.filter((item) => item.tag && item.tag !== '*' && item.weight > 0)
|
|
97
|
+
.sort((left, right) => right.weight - left.weight || left.index - right.index)
|
|
98
|
+
.map((item) => item.tag);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The shop's language closest to what the customer wants, in the customer's
|
|
103
|
+
* order: the same tag first (pt_BR = pt-BR), then the same language (ru-RU
|
|
104
|
+
* finds ru, en finds en-GB). Nothing when no wanted language is offered.
|
|
105
|
+
*/
|
|
106
|
+
export function closestLocale(
|
|
107
|
+
available: readonly string[],
|
|
108
|
+
wanted: readonly string[],
|
|
109
|
+
): string | undefined {
|
|
110
|
+
const language = (tag: string) =>
|
|
111
|
+
tag.trim().toLowerCase().split(/[-_]/)[0] ?? '';
|
|
112
|
+
for (const tag of wanted) {
|
|
113
|
+
const same = available.find((code) => localesMatch(code, tag));
|
|
114
|
+
if (same) {
|
|
115
|
+
return same;
|
|
116
|
+
}
|
|
117
|
+
const kin = language(tag)
|
|
118
|
+
? available.find((code) => language(code) === language(tag))
|
|
119
|
+
: undefined;
|
|
120
|
+
if (kin) {
|
|
121
|
+
return kin;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
return undefined;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Cookies that keep the language and currency the customer picked. */
|
|
128
|
+
export const SAVED_LOCALE_COOKIE = 'basklee_locale';
|
|
129
|
+
export const SAVED_CURRENCY_COOKIE = 'basklee_currency';
|
|
130
|
+
const SAVED_CHOICE_SECONDS = 60 * 60 * 24 * 365;
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* The language and currency the customer picked on an earlier visit, read
|
|
134
|
+
* from a `Cookie` header or document.cookie; empty when nothing was picked.
|
|
135
|
+
*/
|
|
136
|
+
export function savedChoices(cookies: string | null | undefined): {
|
|
137
|
+
locale: string;
|
|
138
|
+
currency: string;
|
|
139
|
+
} {
|
|
140
|
+
const values = new Map<string, string>();
|
|
141
|
+
for (const pair of (cookies ?? '').split(';')) {
|
|
142
|
+
const separator = pair.indexOf('=');
|
|
143
|
+
if (separator <= 0) {
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
try {
|
|
147
|
+
values.set(
|
|
148
|
+
pair.slice(0, separator).trim(),
|
|
149
|
+
decodeURIComponent(pair.slice(separator + 1).trim()),
|
|
150
|
+
);
|
|
151
|
+
} catch {
|
|
152
|
+
// A value that is not URI-encoded is not ours.
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
locale: values.get(SAVED_LOCALE_COOKIE) ?? '',
|
|
157
|
+
currency: values.get(SAVED_CURRENCY_COOKIE) ?? '',
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Keeps a pick of the customer for a year (in the browser only): the next
|
|
163
|
+
* visit without `?locale=` opens in it instead of the browser's language.
|
|
164
|
+
*/
|
|
165
|
+
export function rememberChoice(name: string, value: string) {
|
|
166
|
+
if (typeof document === 'undefined' || !value) {
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
const secure = globalThis.location?.protocol === 'https:' ? '; Secure' : '';
|
|
170
|
+
try {
|
|
171
|
+
document.cookie =
|
|
172
|
+
`${name}=${encodeURIComponent(value)}; Path=/; ` +
|
|
173
|
+
`Max-Age=${SAVED_CHOICE_SECONDS}; SameSite=Lax${secure}`;
|
|
174
|
+
} catch {
|
|
175
|
+
// Without cookies the pick lasts until the page is closed.
|
|
176
|
+
}
|
|
177
|
+
}
|
|
@@ -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
|
|
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
|
|
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
|
|
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
|
},
|
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
import { loadBaskleeAppLoad } from '@/lib/basklee/appLoadServer';
|
|
2
2
|
import { BaskleeStore } from '@/lib/basklee/store.svelte';
|
|
3
3
|
import { storefrontErrorLocale } from '@/lib/utils/basklee/errorPageLabels';
|
|
4
|
+
import {
|
|
5
|
+
closestLocale,
|
|
6
|
+
savedChoices,
|
|
7
|
+
wantedLanguages,
|
|
8
|
+
} from '@/lib/utils/basklee/presentation';
|
|
4
9
|
import type { LayoutServerLoad } from './$types';
|
|
5
10
|
|
|
6
11
|
// Initialization depends on the request domain and session, so pages are dynamic.
|
|
@@ -18,8 +23,29 @@ export const load: LayoutServerLoad = async (event) => {
|
|
|
18
23
|
const locale = event.untrack(() =>
|
|
19
24
|
event.url.searchParams.get('locale'),
|
|
20
25
|
);
|
|
21
|
-
|
|
22
|
-
|
|
26
|
+
// ?locale= first, then the language the customer picked on an earlier
|
|
27
|
+
// visit (the basklee_locale cookie), then the languages the browser asks
|
|
28
|
+
// for (Accept-Language); the storefront's first language when none is
|
|
29
|
+
// offered. A currency picked before (basklee_currency) replaces the
|
|
30
|
+
// language's own while the shop still offers it.
|
|
31
|
+
const saved = savedChoices(
|
|
32
|
+
event.request.headers.get('cookie'),
|
|
33
|
+
);
|
|
34
|
+
const wanted = closestLocale(
|
|
35
|
+
Object.entries(store.locales ?? {}).map(
|
|
36
|
+
([key, value]) => value.code?.trim() || key,
|
|
37
|
+
),
|
|
38
|
+
[
|
|
39
|
+
locale ?? '',
|
|
40
|
+
saved.locale,
|
|
41
|
+
...wantedLanguages(event.request.headers.get('accept-language')),
|
|
42
|
+
].filter(Boolean),
|
|
43
|
+
);
|
|
44
|
+
if (wanted) {
|
|
45
|
+
store.setLocale(wanted, false);
|
|
46
|
+
}
|
|
47
|
+
if (saved.currency) {
|
|
48
|
+
store.setCurrency(saved.currency, false);
|
|
23
49
|
}
|
|
24
50
|
if (!store.isReady) {
|
|
25
51
|
store.localeCode = storefrontErrorLocale(locale, store.localeCode);
|
|
@@ -33,5 +59,6 @@ export const load: LayoutServerLoad = async (event) => {
|
|
|
33
59
|
return {
|
|
34
60
|
basklee: { result, failure },
|
|
35
61
|
baskleeLocale: store.localeCode,
|
|
62
|
+
baskleeCurrency: store.currencyId,
|
|
36
63
|
};
|
|
37
64
|
};
|
|
@@ -35,7 +35,9 @@
|
|
|
35
35
|
marketplace.result ? { result: marketplace.result, failure: null } : null,
|
|
36
36
|
);
|
|
37
37
|
}
|
|
38
|
-
|
|
38
|
+
// The server's pick (see +layout.server.ts), not a new pick of the customer.
|
|
39
|
+
marketplace.setLocale(untrack(() => data.baskleeLocale), false);
|
|
40
|
+
marketplace.setCurrency(untrack(() => data.baskleeCurrency), false);
|
|
39
41
|
if (!marketplace.isReady) {
|
|
40
42
|
marketplace.localeCode = untrack(() => data.baskleeLocale);
|
|
41
43
|
}
|