basklee-svelte 0.9.5 → 0.9.7

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "basklee-svelte",
3
- "version": "0.9.5",
3
+ "version": "0.9.7",
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",
@@ -10,6 +10,8 @@ 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`.
14
+
13
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`.
14
16
 
15
17
  Source: `src/lib/components/basklee/blog/BlogArticle.svelte`.
@@ -3,6 +3,7 @@
3
3
  import {
4
4
  computed,
5
5
  nextTick,
6
+ onBeforeUnmount,
6
7
  onMounted,
7
8
  ref,
8
9
  shallowRef,
@@ -31,6 +32,10 @@
31
32
  } from '@/lib/utils/basklee/blogArticleHtml';
32
33
  import { APP_ORIGIN, appMediaUrl } from '@/lib/utils/basklee/nativeApp';
33
34
  import { requestBlogPost } from '@/lib/utils/basklee/blogLayout';
35
+ import {
36
+ blogMediaFallbackLabels,
37
+ guardBlogMedia,
38
+ } from '@/lib/utils/basklee/blogMediaFallback';
34
39
  import {
35
40
  blogPlacementProductIds,
36
41
  blogPlacementRequests,
@@ -386,6 +391,27 @@
386
391
  { immediate: true },
387
392
  );
388
393
 
394
+ // Pictures, videos and YouTube players of the text that do not load get a placeholder.
395
+ let stopMediaGuard = () => {};
396
+ watch(
397
+ [
398
+ () => html.value,
399
+ () => mounted.value,
400
+ () => article.value,
401
+ () => selectionStore.localeCode,
402
+ ],
403
+ () => {
404
+ void nextTick(() => {
405
+ stopMediaGuard();
406
+ stopMediaGuard = mounted.value
407
+ ? guardBlogMedia(article.value, blogMediaFallbackLabels(selectionStore.localeCode))
408
+ : () => {};
409
+ });
410
+ },
411
+ { immediate: true },
412
+ );
413
+ onBeforeUnmount(() => stopMediaGuard());
414
+
389
415
  function openViewer(event: Event) {
390
416
  const images = openableImages();
391
417
  const index = blogViewerIndex(event.target, images);
@@ -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
+ }
@@ -368,7 +368,7 @@ const es: typeof en = {
368
368
  optionFileTooLarge: 'El archivo supera los {size} MB.',
369
369
  clearOption: 'Borrar',
370
370
  clearOptionHint: 'Borrar el texto y el archivo guardados',
371
- placeOrder: 'Pedido',
371
+ placeOrder: 'Realizar pedido',
372
372
  created: 'Pedido creado',
373
373
  viewOrder: 'Ver el pedido',
374
374
  paymentLinkFailed:
@@ -139,7 +139,7 @@ const es: typeof en = {
139
139
  another: 'Otro',
140
140
  anotherHint: 'Escribir otro mensaje',
141
141
  unsubscribe: 'Preferencias de correo',
142
- unsubscribeAction: 'Cancelar aviso',
142
+ unsubscribeAction: 'Darse de baja',
143
143
  newsletter: 'Dejar de recibir boletines',
144
144
  products: 'Dejar de recibir correos de disponibilidad',
145
145
  unsubscribeDone: 'Te has dado de baja de estos correos.',
@@ -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',
@@ -53,8 +53,12 @@ type SellerQueryValue = string | null | undefined | readonly (string | null)[];
53
53
 
54
54
  const sellerLocationKeys = ['name', 'rating', 'cats', 'sort', 'page'];
55
55
 
56
- function firstSellerQueryValue(value: SellerQueryValue) {
57
- return Array.isArray(value) ? value[0] : (value as string | null | undefined);
56
+ function firstSellerQueryValue(
57
+ value: SellerQueryValue,
58
+ ): string | null | undefined {
59
+ return typeof value === 'string' || value === null || value === undefined
60
+ ? value
61
+ : value[0];
58
62
  }
59
63
 
60
64
  function positiveSellerQueryNumber(value: string | null | undefined) {