basklee-svelte 0.9.3 → 0.9.4

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.3",
3
+ "version": "0.9.4",
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.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -6,7 +6,7 @@ The article page shows one journal article: its cover, its text, the products at
6
6
 
7
7
  Article videos may come as the backend's own paths (`/ps3/...`). In an Android app build those paths (cover, videos, images and videos inside the text) load from the storefront address.
8
8
 
9
- The text is sanitized with DOMPurify in `src/lib/utils/basklee/blogArticleHtml.ts`. A YouTube player the editor inserts (an `<iframe>` with a `youtube.com` or `youtube-nocookie.com` `/embed/<id>` address) is kept and played from `youtube-nocookie.com` at the article's width in 16:9, with fixed `allow`, `loading="lazy"` and referrer attributes and an optional start second. Other frames, scripts, forms and event attributes are removed.
9
+ The server render shows the text as plain blocks (`blogArticleBlocks` in `src/lib/utils/basklee/blogArticleHtml.ts`): headings, paragraphs with their checked links, lists, quotes and pictures with captions, so search engines read the structure without scripts; in the browser the text is then sanitized with DOMPurify. A YouTube player the editor inserts (an `<iframe>` with a `youtube.com` or `youtube-nocookie.com` `/embed/<id>` address) is kept and played from `youtube-nocookie.com` at the article's width in 16:9, with fixed `allow`, `loading="lazy"` and referrer attributes and an optional start second. Other frames, scripts, forms and event attributes are removed.
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
 
@@ -23,10 +23,12 @@
23
23
  safePublicUrl,
24
24
  } from '@/lib/utils/basklee/presentation';
25
25
  import {
26
+ blogArticleBlocks,
26
27
  removeLeadingDuplicateBlogHeading,
27
28
  safeBlogArticleHtml,
29
+ type IBlogArticleInline,
30
+ type TBlogArticleBlock,
28
31
  } from '@/lib/utils/basklee/blogArticleHtml';
29
- import { htmlTextParagraphs } from '@/lib/utils/basklee/htmlText';
30
32
  import { APP_ORIGIN, appMediaUrl } from '@/lib/utils/basklee/nativeApp';
31
33
  import { requestBlogPost } from '@/lib/utils/basklee/blogLayout';
32
34
  import {
@@ -213,10 +215,12 @@
213
215
  removeLeadingDuplicateBlogHeading(source.value, title.value),
214
216
  );
215
217
  const html = computed(() => safeBlogArticleHtml(articleSource.value));
216
- // The server render and hydration show the text as plain paragraphs;
217
- // the sanitized HTML replaces them once the component is mounted.
218
+ // The server render and hydration show the text as plain blocks (headings,
219
+ // paragraphs with links, lists, quotes, pictures: blogArticleBlocks), so
220
+ // search engines read its structure; the sanitized HTML replaces them once
221
+ // the component is mounted.
218
222
  const mounted = ref(false);
219
- const paragraphs = computed(() => htmlTextParagraphs(articleSource.value));
223
+ const blocks = computed(() => blogArticleBlocks(articleSource.value));
220
224
  const cover = computed(() => {
221
225
  const images = [...(post.value?.preview_images ?? [])].sort(
222
226
  (left, right) => left.display_order - right.display_order,
@@ -415,6 +419,52 @@
415
419
  });
416
420
  </script>
417
421
 
422
+ {#snippet articleInline(parts: IBlogArticleInline[])}
423
+ {#each parts as part, index (index)}
424
+ {#if part.href}
425
+ <a
426
+ href={part.href}
427
+ target={part.external ? '_blank' : undefined}
428
+ rel={part.external ? 'noopener noreferrer' : undefined}
429
+ >{part.text}</a>
430
+ {:else}{part.text}{/if}
431
+ {/each}
432
+ {/snippet}
433
+
434
+ {#snippet articleBlocks(items: TBlogArticleBlock[])}
435
+ {#each items as block, index (index)}
436
+ {#if block.kind === 'heading'}
437
+ <svelte:element this={`h${block.level}`}>{@render articleInline(block.inline)}</svelte:element>
438
+ {:else if block.kind === 'paragraph'}
439
+ <p>{@render articleInline(block.inline)}</p>
440
+ {:else if block.kind === 'list'}
441
+ <svelte:element this={block.ordered ? 'ol' : 'ul'}>
442
+ {#each block.items as item, itemIndex (itemIndex)}
443
+ <li>{@render articleInline(item)}</li>
444
+ {/each}
445
+ </svelte:element>
446
+ {:else if block.kind === 'quote'}
447
+ <blockquote>{@render articleBlocks(block.blocks)}</blockquote>
448
+ {:else if block.kind === 'image'}
449
+ <figure>
450
+ <!-- Without the editor's size the box stays 3:2 until the formatted text replaces it. -->
451
+ <img
452
+ src={block.src}
453
+ alt={block.alt}
454
+ width={block.width}
455
+ height={block.height}
456
+ loading="lazy"
457
+ decoding="async"
458
+ style={block.width && block.height ? undefined : 'aspect-ratio: 3 / 2; object-fit: contain'}
459
+ />
460
+ {#if block.caption}
461
+ <figcaption>{block.caption}</figcaption>
462
+ {/if}
463
+ </figure>
464
+ {/if}
465
+ {/each}
466
+ {/snippet}
467
+
418
468
  <section
419
469
  {...attributes}
420
470
  data-feature-part="BlogArticle"
@@ -528,11 +578,7 @@
528
578
  bind:this={article.value}
529
579
  class={['op-feature-prose']}
530
580
  >
531
- {#each paragraphs.value as paragraph, index (index)}
532
- <p>
533
- {paragraph}
534
- </p>
535
- {/each}
581
+ {@render articleBlocks(blocks.value)}
536
582
  </div>
537
583
  {/if}
538
584
  {#each placements.value as placement, index (index)}
@@ -4,7 +4,7 @@ import type {
4
4
  DOMPurify as TPurifier,
5
5
  UponSanitizeAttributeHookEvent,
6
6
  } from 'dompurify';
7
- import { htmlTextParagraphs } from '@/lib/utils/basklee/htmlText';
7
+ import { decodeEntities, htmlTextParagraphs } from '@/lib/utils/basklee/htmlText';
8
8
  import { APP_ORIGIN, appMediaUrl } from '@/lib/utils/basklee/nativeApp';
9
9
 
10
10
  type TStylePatterns = Record<string, RegExp>;
@@ -205,7 +205,7 @@ const youtubeEmbed =
205
205
  /^https:\/\/(?:www\.)?youtube(?:-nocookie)?\.com\/embed\/([\w-]{11})(?:\?([^#]*))?$/i;
206
206
 
207
207
  export const blogYoutubeAllow =
208
- 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share';
208
+ 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
209
209
 
210
210
  /**
211
211
  * The privacy-enhanced player address for a YouTube embed address, or an
@@ -455,3 +455,268 @@ export function safeBlogArticleHtml(
455
455
  purifier.removeHook('afterSanitizeAttributes', prepareElementHook);
456
456
  }
457
457
  }
458
+
459
+ const BLOCK_MEDIA_ORIGIN = APP_ORIGIN;
460
+
461
+ /*
462
+ * The server render (and the hydration that must match it) cannot run
463
+ * DOMPurify, so it shows the article as plain blocks built from the editor
464
+ * HTML: headings, paragraphs with their links, lists, quotes and pictures
465
+ * with captions. Nothing of the source markup is passed on: each block holds
466
+ * only text and checked addresses, and the component renders them with its
467
+ * own escaping. Search engines read the structure without scripts; the
468
+ * sanitized HTML replaces the blocks once the component is mounted.
469
+ */
470
+
471
+ export interface IBlogArticleInline {
472
+ text: string;
473
+ href?: string;
474
+ external?: boolean;
475
+ }
476
+
477
+ export type TBlogArticleBlock =
478
+ | { kind: 'heading'; level: 2 | 3 | 4; inline: IBlogArticleInline[] }
479
+ | { kind: 'paragraph'; inline: IBlogArticleInline[] }
480
+ | { kind: 'list'; ordered: boolean; items: IBlogArticleInline[][] }
481
+ | { kind: 'quote'; blocks: TBlogArticleBlock[] }
482
+ | { kind: 'image'; src: string; alt: string; caption: string; width?: number; height?: number };
483
+
484
+ const MAX_ARTICLE_BLOCKS = 600;
485
+
486
+ const skippedElements =
487
+ /<(script|style|template|iframe|noscript|svg|math|object|textarea|select|button|video|audio)\b[\s\S]*?<\/\1\s*>/gi;
488
+
489
+ function tagAttribute(attributes: string, name: string) {
490
+ const match = new RegExp(
491
+ `(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`,
492
+ 'i',
493
+ ).exec(attributes);
494
+
495
+ return decodeEntities(match?.[1] ?? match?.[2] ?? match?.[3] ?? '').trim();
496
+ }
497
+
498
+ // The scheme is checked without the characters a browser drops from an
499
+ // address (`java\tscript:` would run as javascript:).
500
+ function addressScheme(value: string) {
501
+ return /^([a-z][a-z\d+.-]*):/i
502
+ .exec(value.replace(/[\u0000- \u007f-\u009f]/g, ''))?.[1]
503
+ ?.toLowerCase();
504
+ }
505
+
506
+ function blockLink(value: string): Omit<IBlogArticleInline, 'text'> | undefined {
507
+ const scheme = addressScheme(value);
508
+
509
+ if (!value || value.startsWith('//') || (scheme && !['http', 'https', 'mailto', 'tel'].includes(scheme))) {
510
+ return undefined;
511
+ }
512
+
513
+ const article = editorArticlePath.exec(value);
514
+
515
+ if (article) {
516
+ return { href: `/journal/${article[1]}` };
517
+ }
518
+
519
+ return scheme === 'http' || scheme === 'https'
520
+ ? { href: value, external: true }
521
+ : { href: value };
522
+ }
523
+
524
+ // The editor's own picture size, when it wrote one: the server render reserves
525
+ // that box; without it the component keeps a 3:2 box (the guide's screenshots).
526
+ function blockImageSize(attributes: string) {
527
+ const width = Number(tagAttribute(attributes, 'width'));
528
+ const height = Number(tagAttribute(attributes, 'height'));
529
+
530
+ return Number.isInteger(width) && Number.isInteger(height) &&
531
+ width > 0 && height > 0 && width <= 10000 && height <= 10000
532
+ ? { width, height }
533
+ : {};
534
+ }
535
+
536
+ function blockImage(value: string, appOrigin: string) {
537
+ const scheme = addressScheme(value);
538
+
539
+ if (scheme === 'http' || scheme === 'https') {
540
+ return value;
541
+ }
542
+
543
+ return !scheme && value.startsWith('/') && !value.startsWith('//')
544
+ ? appMediaUrl(value, appOrigin)
545
+ : '';
546
+ }
547
+
548
+ function blockImageSizeOf(figure: { width?: number; height?: number }) {
549
+ return figure.width && figure.height ? { width: figure.width, height: figure.height } : {};
550
+ }
551
+
552
+ /** The article as plain blocks for the server render and the hydration. */
553
+ export function blogArticleBlocks(
554
+ value: string | undefined,
555
+ appOrigin = BLOCK_MEDIA_ORIGIN,
556
+ ): TBlogArticleBlock[] {
557
+ const html = (value ?? '')
558
+ .replace(/<!--[\s\S]*?-->/g, ' ')
559
+ .replace(skippedElements, ' ');
560
+ const blocks: TBlogArticleBlock[] = [];
561
+ const quotes: TBlogArticleBlock[][] = [];
562
+ let inline: IBlogArticleInline[] = [];
563
+ let mode: 'heading' | 'paragraph' | 'item' | 'caption' = 'paragraph';
564
+ let level: 2 | 3 | 4 = 2;
565
+ let list: { ordered: boolean; items: IBlogArticleInline[][] } | undefined;
566
+ let link: Omit<IBlogArticleInline, 'text'> | undefined;
567
+ let figure: { src: string; alt: string; caption: string; width?: number; height?: number } | undefined;
568
+ let count = 0;
569
+
570
+ const target = () => quotes[quotes.length - 1] ?? blocks;
571
+ const push = (block: TBlogArticleBlock) => {
572
+ if (count < MAX_ARTICLE_BLOCKS) {
573
+ count += 1;
574
+ target().push(block);
575
+ }
576
+ };
577
+ const flush = () => {
578
+ const parts = inline
579
+ .map((part) => ({ ...part, text: part.text.replace(/\s+/g, ' ') }))
580
+ .filter((part) => part.text);
581
+
582
+ inline = [];
583
+ if (parts.length) {
584
+ parts[0]!.text = parts[0]!.text.trimStart();
585
+ parts[parts.length - 1]!.text = parts[parts.length - 1]!.text.trimEnd();
586
+ }
587
+ const kept = parts.filter((part) => part.text);
588
+
589
+ if (!kept.length) {
590
+ return;
591
+ }
592
+ if (mode === 'caption' && figure) {
593
+ figure.caption = `${figure.caption} ${kept.map((part) => part.text).join('')}`.trim();
594
+ } else if (list && mode === 'item') {
595
+ list.items.push(kept);
596
+ } else if (mode === 'heading') {
597
+ push({ kind: 'heading', level, inline: kept });
598
+ } else {
599
+ push({ kind: 'paragraph', inline: kept });
600
+ }
601
+ };
602
+ const closeList = () => {
603
+ if (list?.items.length) {
604
+ push({ kind: 'list', ordered: list.ordered, items: list.items });
605
+ }
606
+ list = undefined;
607
+ };
608
+ const closeFigure = () => {
609
+ if (figure?.src) {
610
+ push({ kind: 'image', src: figure.src, alt: figure.alt, caption: figure.caption, ...blockImageSizeOf(figure) });
611
+ }
612
+ figure = undefined;
613
+ };
614
+
615
+ for (const token of html.matchAll(/<(\/?)([a-z][a-z\d]*)\b([^>]*)>|([^<]+)/gi)) {
616
+ const [, closing, rawName, attributes = '', text] = token;
617
+
618
+ if (text !== undefined) {
619
+ const decoded = decodeEntities(text);
620
+ const last = inline[inline.length - 1];
621
+
622
+ if (last && last.href === link?.href) {
623
+ last.text += decoded;
624
+ } else {
625
+ inline.push({ text: decoded, ...(link ?? {}) });
626
+ }
627
+ continue;
628
+ }
629
+
630
+ const name = rawName!.toLowerCase();
631
+
632
+ if (closing) {
633
+ if (/^(?:h[1-6]|p|div|pre|tr|summary|li|figcaption|dt|dd)$/.test(name)) {
634
+ flush();
635
+ mode = list ? 'item' : 'paragraph';
636
+ } else if (name === 'ul' || name === 'ol') {
637
+ flush();
638
+ closeList();
639
+ mode = 'paragraph';
640
+ } else if (name === 'blockquote') {
641
+ flush();
642
+ closeList();
643
+ const quoted = quotes.pop();
644
+
645
+ if (quoted?.length) {
646
+ push({ kind: 'quote', blocks: quoted });
647
+ }
648
+ } else if (name === 'figure') {
649
+ flush();
650
+ closeFigure();
651
+ mode = 'paragraph';
652
+ } else if (name === 'a') {
653
+ link = undefined;
654
+ }
655
+ continue;
656
+ }
657
+
658
+ if (/^h[1-6]$/.test(name)) {
659
+ flush();
660
+ mode = 'heading';
661
+ level = Math.min(4, Math.max(2, Number(name[1]))) as 2 | 3 | 4;
662
+ } else if (/^(?:p|div|pre|tr|summary|section|article|details|dt|dd)$/.test(name)) {
663
+ flush();
664
+ mode = list ? 'item' : 'paragraph';
665
+ } else if (name === 'ul' || name === 'ol') {
666
+ flush();
667
+ if (!list) {
668
+ list = { ordered: name === 'ol', items: [] };
669
+ }
670
+ mode = 'item';
671
+ } else if (name === 'li') {
672
+ flush();
673
+ mode = 'item';
674
+ } else if (name === 'blockquote') {
675
+ flush();
676
+ closeList();
677
+ if (quotes.length < 3) {
678
+ quotes.push([]);
679
+ }
680
+ mode = 'paragraph';
681
+ } else if (name === 'figure') {
682
+ flush();
683
+ closeFigure();
684
+ figure = { src: '', alt: '', caption: '' };
685
+ } else if (name === 'figcaption') {
686
+ flush();
687
+ mode = 'caption';
688
+ } else if (name === 'img') {
689
+ const src = blockImage(tagAttribute(attributes, 'src'), appOrigin);
690
+ const alt = tagAttribute(attributes, 'alt');
691
+
692
+ if (!src) {
693
+ continue;
694
+ }
695
+ if (figure && !figure.src) {
696
+ Object.assign(figure, { src, alt, ...blockImageSize(attributes) });
697
+ } else {
698
+ flush();
699
+ push({ kind: 'image', src, alt, caption: '', ...blockImageSize(attributes) });
700
+ }
701
+ } else if (name === 'a') {
702
+ link = blockLink(tagAttribute(attributes, 'href'));
703
+ } else if (name === 'br' || name === 'td' || name === 'th') {
704
+ inline.push({ text: ' ', ...(link ?? {}) });
705
+ } else if (name === 'hr') {
706
+ flush();
707
+ }
708
+ }
709
+
710
+ flush();
711
+ closeList();
712
+ closeFigure();
713
+ while (quotes.length) {
714
+ const quoted = quotes.pop();
715
+
716
+ if (quoted?.length) {
717
+ push({ kind: 'quote', blocks: quoted });
718
+ }
719
+ }
720
+
721
+ return blocks;
722
+ }
@@ -20,7 +20,7 @@ const namedEntities: Record<string, string> = {
20
20
  hellip: '…',
21
21
  };
22
22
 
23
- function decodeEntities(value: string) {
23
+ export function decodeEntities(value: string) {
24
24
  return value.replace(
25
25
  /&(#x[0-9a-f]+|#\d+|[a-z]+);/gi,
26
26
  (entity, name: string) => {