basklee-react 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-react",
3
- "version": "0.9.3",
3
+ "version": "0.9.4",
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.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -29,8 +29,11 @@ stop and an «Open image» name; a zoom-in cursor marks them. Images inside a
29
29
  link, a button or a product placement keep their own action. The helper is
30
30
  `lib/basklee/blogImageViewer.ts`.
31
31
 
32
- During server rendering, editor HTML is converted to escaped text paragraphs.
33
- After hydration, DOMPurify replaces those paragraphs with sanitized formatting.
32
+ During server rendering, editor HTML becomes plain blocks (`blogArticleBlocks`
33
+ in `lib/basklee/blogArticleHtml.ts`): headings, paragraphs with their checked
34
+ links, lists, quotes and pictures with captions, rendered with React's own
35
+ escaping, so search engines read the structure without scripts. After
36
+ hydration, DOMPurify replaces those blocks with sanitized formatting.
34
37
  The allowlist retains headings, text formatting, links, lists, quotes, code,
35
38
  tables, images and galleries, audio and video controls, YouTube players,
36
39
  collapsible sections,
@@ -1,6 +1,7 @@
1
1
  'use client';
2
2
 
3
3
  import {
4
+ Fragment,
4
5
  useCallback,
5
6
  useEffect,
6
7
  useMemo,
@@ -27,10 +28,12 @@ import {
27
28
  type BlogPlacementLoadAction,
28
29
  } from '@/lib/basklee/blogArticle';
29
30
  import {
31
+ blogArticleBlocks,
30
32
  removeLeadingDuplicateBlogHeading,
31
33
  safeBlogArticleHtml,
34
+ type IBlogArticleInline,
35
+ type TBlogArticleBlock,
32
36
  } from '@/lib/basklee/blogArticleHtml';
33
- import { htmlTextParagraphs } from '@/lib/basklee/htmlText';
34
37
  import { blogLabels } from '@/lib/basklee/blogLabels';
35
38
  import { featureLabels } from '@/lib/basklee/featureLabels';
36
39
  import { useBaskleeBlogReading } from '@/hooks/useBaskleeBlogReading';
@@ -141,8 +144,12 @@ export function BlogArticle({
141
144
  full ? 'post_view_text' : 'post_preview_text',
142
145
  );
143
146
  const articleSource = removeLeadingDuplicateBlogHeading(source, title);
144
- const paragraphs = useMemo(
145
- () => htmlTextParagraphs(articleSource),
147
+ // The server render and hydration show the text as plain blocks (headings,
148
+ // paragraphs with links, lists, quotes, pictures: blogArticleBlocks), so
149
+ // search engines read its structure; the sanitized HTML replaces them once
150
+ // the component is mounted.
151
+ const blocks = useMemo(
152
+ () => blogArticleBlocks(articleSource),
146
153
  [articleSource],
147
154
  );
148
155
  const html = useMemo(
@@ -385,9 +392,7 @@ export function BlogArticle({
385
392
  />
386
393
  ) : (
387
394
  <div ref={articleRef} className={styles.prose} data-blog-article-text>
388
- {paragraphs.map((paragraph, index) => (
389
- <p key={`${index}:${paragraph}`}>{paragraph}</p>
390
- ))}
395
+ <ArticleBlocks blocks={blocks} />
391
396
  </div>
392
397
  )}
393
398
 
@@ -522,6 +527,74 @@ export function BlogArticle({
522
527
  );
523
528
  }
524
529
 
530
+ function ArticleInline({ parts }: { parts: IBlogArticleInline[] }) {
531
+ return (
532
+ <>
533
+ {parts.map((part, index) =>
534
+ part.href ? (
535
+ <a
536
+ key={index}
537
+ href={part.href}
538
+ target={part.external ? '_blank' : undefined}
539
+ rel={part.external ? 'noopener noreferrer' : undefined}
540
+ >
541
+ {part.text}
542
+ </a>
543
+ ) : (
544
+ <Fragment key={index}>{part.text}</Fragment>
545
+ ),
546
+ )}
547
+ </>
548
+ );
549
+ }
550
+
551
+ function ArticleBlocks({ blocks }: { blocks: TBlogArticleBlock[] }) {
552
+ return (
553
+ <>
554
+ {blocks.map((block, index) => {
555
+ switch (block.kind) {
556
+ case 'heading': {
557
+ const Heading = `h${block.level}` as 'h2' | 'h3' | 'h4';
558
+
559
+ return <Heading key={index}><ArticleInline parts={block.inline} /></Heading>;
560
+ }
561
+ case 'list': {
562
+ const List = block.ordered ? 'ol' : 'ul';
563
+
564
+ return (
565
+ <List key={index}>
566
+ {block.items.map((item, itemIndex) => (
567
+ <li key={itemIndex}><ArticleInline parts={item} /></li>
568
+ ))}
569
+ </List>
570
+ );
571
+ }
572
+ case 'quote':
573
+ return <blockquote key={index}><ArticleBlocks blocks={block.blocks} /></blockquote>;
574
+ case 'image':
575
+ return (
576
+ <figure key={index}>
577
+ {/* Without the editor's size the box stays 3:2 until the formatted text replaces it. */}
578
+ <img
579
+ src={block.src}
580
+ alt={block.alt}
581
+ width={block.width}
582
+ height={block.height}
583
+ loading="lazy"
584
+ decoding="async"
585
+ style={block.width && block.height ? undefined : { aspectRatio: '3 / 2', objectFit: 'contain' }}
586
+ />
587
+ {block.caption ? <figcaption>{block.caption}</figcaption> : null}
588
+ </figure>
589
+ );
590
+ default:
591
+ return <p key={index}><ArticleInline parts={block.inline} /></p>;
592
+ }
593
+ })}
594
+ </>
595
+ );
596
+ }
597
+
525
598
  function ArticleSkeleton() {
526
599
  return (
527
600
  <div className={styles.skeleton} aria-hidden="true" data-blog-article-skeleton>
@@ -4,7 +4,7 @@ import type {
4
4
  DOMPurify as TPurifier,
5
5
  UponSanitizeAttributeHookEvent,
6
6
  } from 'dompurify';
7
- import { htmlTextParagraphs } from './htmlText';
7
+ import { decodeEntities, htmlTextParagraphs } from './htmlText';
8
8
  import { APP_ORIGIN, appMediaUrl } from './nativeApp';
9
9
 
10
10
  type StylePatterns = Record<string, RegExp>;
@@ -191,7 +191,7 @@ const youtubeEmbed =
191
191
  /^https:\/\/(?:www\.)?youtube(?:-nocookie)?\.com\/embed\/([\w-]{11})(?:\?([^#]*))?$/i;
192
192
 
193
193
  export const blogYoutubeAllow =
194
- 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share';
194
+ 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
195
195
 
196
196
  /**
197
197
  * The privacy-enhanced player address for a YouTube embed address, or an
@@ -432,3 +432,268 @@ export function safeBlogArticleHtml(
432
432
  purifier.removeHook('afterSanitizeAttributes', prepareElementHook);
433
433
  }
434
434
  }
435
+
436
+ const BLOCK_MEDIA_ORIGIN = APP_ORIGIN;
437
+
438
+ /*
439
+ * The server render (and the hydration that must match it) cannot run
440
+ * DOMPurify, so it shows the article as plain blocks built from the editor
441
+ * HTML: headings, paragraphs with their links, lists, quotes and pictures
442
+ * with captions. Nothing of the source markup is passed on: each block holds
443
+ * only text and checked addresses, and the component renders them with its
444
+ * own escaping. Search engines read the structure without scripts; the
445
+ * sanitized HTML replaces the blocks once the component is mounted.
446
+ */
447
+
448
+ export interface IBlogArticleInline {
449
+ text: string;
450
+ href?: string;
451
+ external?: boolean;
452
+ }
453
+
454
+ export type TBlogArticleBlock =
455
+ | { kind: 'heading'; level: 2 | 3 | 4; inline: IBlogArticleInline[] }
456
+ | { kind: 'paragraph'; inline: IBlogArticleInline[] }
457
+ | { kind: 'list'; ordered: boolean; items: IBlogArticleInline[][] }
458
+ | { kind: 'quote'; blocks: TBlogArticleBlock[] }
459
+ | { kind: 'image'; src: string; alt: string; caption: string; width?: number; height?: number };
460
+
461
+ const MAX_ARTICLE_BLOCKS = 600;
462
+
463
+ const skippedElements =
464
+ /<(script|style|template|iframe|noscript|svg|math|object|textarea|select|button|video|audio)\b[\s\S]*?<\/\1\s*>/gi;
465
+
466
+ function tagAttribute(attributes: string, name: string) {
467
+ const match = new RegExp(
468
+ `(?:^|\\s)${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+))`,
469
+ 'i',
470
+ ).exec(attributes);
471
+
472
+ return decodeEntities(match?.[1] ?? match?.[2] ?? match?.[3] ?? '').trim();
473
+ }
474
+
475
+ // The scheme is checked without the characters a browser drops from an
476
+ // address (`java\tscript:` would run as javascript:).
477
+ function addressScheme(value: string) {
478
+ return /^([a-z][a-z\d+.-]*):/i
479
+ .exec(value.replace(/[\u0000- \u007f-\u009f]/g, ''))?.[1]
480
+ ?.toLowerCase();
481
+ }
482
+
483
+ function blockLink(value: string): Omit<IBlogArticleInline, 'text'> | undefined {
484
+ const scheme = addressScheme(value);
485
+
486
+ if (!value || value.startsWith('//') || (scheme && !['http', 'https', 'mailto', 'tel'].includes(scheme))) {
487
+ return undefined;
488
+ }
489
+
490
+ const article = editorArticlePath.exec(value);
491
+
492
+ if (article) {
493
+ return { href: `/journal/${article[1]}` };
494
+ }
495
+
496
+ return scheme === 'http' || scheme === 'https'
497
+ ? { href: value, external: true }
498
+ : { href: value };
499
+ }
500
+
501
+ // The editor's own picture size, when it wrote one: the server render reserves
502
+ // that box; without it the component keeps a 3:2 box (the guide's screenshots).
503
+ function blockImageSize(attributes: string) {
504
+ const width = Number(tagAttribute(attributes, 'width'));
505
+ const height = Number(tagAttribute(attributes, 'height'));
506
+
507
+ return Number.isInteger(width) && Number.isInteger(height) &&
508
+ width > 0 && height > 0 && width <= 10000 && height <= 10000
509
+ ? { width, height }
510
+ : {};
511
+ }
512
+
513
+ function blockImage(value: string, appOrigin: string) {
514
+ const scheme = addressScheme(value);
515
+
516
+ if (scheme === 'http' || scheme === 'https') {
517
+ return value;
518
+ }
519
+
520
+ return !scheme && value.startsWith('/') && !value.startsWith('//')
521
+ ? appMediaUrl(value, appOrigin)
522
+ : '';
523
+ }
524
+
525
+ function blockImageSizeOf(figure: { width?: number; height?: number }) {
526
+ return figure.width && figure.height ? { width: figure.width, height: figure.height } : {};
527
+ }
528
+
529
+ /** The article as plain blocks for the server render and the hydration. */
530
+ export function blogArticleBlocks(
531
+ value: string | undefined,
532
+ appOrigin = BLOCK_MEDIA_ORIGIN,
533
+ ): TBlogArticleBlock[] {
534
+ const html = (value ?? '')
535
+ .replace(/<!--[\s\S]*?-->/g, ' ')
536
+ .replace(skippedElements, ' ');
537
+ const blocks: TBlogArticleBlock[] = [];
538
+ const quotes: TBlogArticleBlock[][] = [];
539
+ let inline: IBlogArticleInline[] = [];
540
+ let mode: 'heading' | 'paragraph' | 'item' | 'caption' = 'paragraph';
541
+ let level: 2 | 3 | 4 = 2;
542
+ let list: { ordered: boolean; items: IBlogArticleInline[][] } | undefined;
543
+ let link: Omit<IBlogArticleInline, 'text'> | undefined;
544
+ let figure: { src: string; alt: string; caption: string; width?: number; height?: number } | undefined;
545
+ let count = 0;
546
+
547
+ const target = () => quotes[quotes.length - 1] ?? blocks;
548
+ const push = (block: TBlogArticleBlock) => {
549
+ if (count < MAX_ARTICLE_BLOCKS) {
550
+ count += 1;
551
+ target().push(block);
552
+ }
553
+ };
554
+ const flush = () => {
555
+ const parts = inline
556
+ .map((part) => ({ ...part, text: part.text.replace(/\s+/g, ' ') }))
557
+ .filter((part) => part.text);
558
+
559
+ inline = [];
560
+ if (parts.length) {
561
+ parts[0]!.text = parts[0]!.text.trimStart();
562
+ parts[parts.length - 1]!.text = parts[parts.length - 1]!.text.trimEnd();
563
+ }
564
+ const kept = parts.filter((part) => part.text);
565
+
566
+ if (!kept.length) {
567
+ return;
568
+ }
569
+ if (mode === 'caption' && figure) {
570
+ figure.caption = `${figure.caption} ${kept.map((part) => part.text).join('')}`.trim();
571
+ } else if (list && mode === 'item') {
572
+ list.items.push(kept);
573
+ } else if (mode === 'heading') {
574
+ push({ kind: 'heading', level, inline: kept });
575
+ } else {
576
+ push({ kind: 'paragraph', inline: kept });
577
+ }
578
+ };
579
+ const closeList = () => {
580
+ if (list?.items.length) {
581
+ push({ kind: 'list', ordered: list.ordered, items: list.items });
582
+ }
583
+ list = undefined;
584
+ };
585
+ const closeFigure = () => {
586
+ if (figure?.src) {
587
+ push({ kind: 'image', src: figure.src, alt: figure.alt, caption: figure.caption, ...blockImageSizeOf(figure) });
588
+ }
589
+ figure = undefined;
590
+ };
591
+
592
+ for (const token of html.matchAll(/<(\/?)([a-z][a-z\d]*)\b([^>]*)>|([^<]+)/gi)) {
593
+ const [, closing, rawName, attributes = '', text] = token;
594
+
595
+ if (text !== undefined) {
596
+ const decoded = decodeEntities(text);
597
+ const last = inline[inline.length - 1];
598
+
599
+ if (last && last.href === link?.href) {
600
+ last.text += decoded;
601
+ } else {
602
+ inline.push({ text: decoded, ...(link ?? {}) });
603
+ }
604
+ continue;
605
+ }
606
+
607
+ const name = rawName!.toLowerCase();
608
+
609
+ if (closing) {
610
+ if (/^(?:h[1-6]|p|div|pre|tr|summary|li|figcaption|dt|dd)$/.test(name)) {
611
+ flush();
612
+ mode = list ? 'item' : 'paragraph';
613
+ } else if (name === 'ul' || name === 'ol') {
614
+ flush();
615
+ closeList();
616
+ mode = 'paragraph';
617
+ } else if (name === 'blockquote') {
618
+ flush();
619
+ closeList();
620
+ const quoted = quotes.pop();
621
+
622
+ if (quoted?.length) {
623
+ push({ kind: 'quote', blocks: quoted });
624
+ }
625
+ } else if (name === 'figure') {
626
+ flush();
627
+ closeFigure();
628
+ mode = 'paragraph';
629
+ } else if (name === 'a') {
630
+ link = undefined;
631
+ }
632
+ continue;
633
+ }
634
+
635
+ if (/^h[1-6]$/.test(name)) {
636
+ flush();
637
+ mode = 'heading';
638
+ level = Math.min(4, Math.max(2, Number(name[1]))) as 2 | 3 | 4;
639
+ } else if (/^(?:p|div|pre|tr|summary|section|article|details|dt|dd)$/.test(name)) {
640
+ flush();
641
+ mode = list ? 'item' : 'paragraph';
642
+ } else if (name === 'ul' || name === 'ol') {
643
+ flush();
644
+ if (!list) {
645
+ list = { ordered: name === 'ol', items: [] };
646
+ }
647
+ mode = 'item';
648
+ } else if (name === 'li') {
649
+ flush();
650
+ mode = 'item';
651
+ } else if (name === 'blockquote') {
652
+ flush();
653
+ closeList();
654
+ if (quotes.length < 3) {
655
+ quotes.push([]);
656
+ }
657
+ mode = 'paragraph';
658
+ } else if (name === 'figure') {
659
+ flush();
660
+ closeFigure();
661
+ figure = { src: '', alt: '', caption: '' };
662
+ } else if (name === 'figcaption') {
663
+ flush();
664
+ mode = 'caption';
665
+ } else if (name === 'img') {
666
+ const src = blockImage(tagAttribute(attributes, 'src'), appOrigin);
667
+ const alt = tagAttribute(attributes, 'alt');
668
+
669
+ if (!src) {
670
+ continue;
671
+ }
672
+ if (figure && !figure.src) {
673
+ Object.assign(figure, { src, alt, ...blockImageSize(attributes) });
674
+ } else {
675
+ flush();
676
+ push({ kind: 'image', src, alt, caption: '', ...blockImageSize(attributes) });
677
+ }
678
+ } else if (name === 'a') {
679
+ link = blockLink(tagAttribute(attributes, 'href'));
680
+ } else if (name === 'br' || name === 'td' || name === 'th') {
681
+ inline.push({ text: ' ', ...(link ?? {}) });
682
+ } else if (name === 'hr') {
683
+ flush();
684
+ }
685
+ }
686
+
687
+ flush();
688
+ closeList();
689
+ closeFigure();
690
+ while (quotes.length) {
691
+ const quoted = quotes.pop();
692
+
693
+ if (quoted?.length) {
694
+ push({ kind: 'quote', blocks: quoted });
695
+ }
696
+ }
697
+
698
+ return blocks;
699
+ }
@@ -12,7 +12,7 @@ const namedEntities: Record<string, string> = {
12
12
  hellip: '…',
13
13
  };
14
14
 
15
- function decodeEntities(value: string) {
15
+ export function decodeEntities(value: string) {
16
16
  return value.replace(
17
17
  /&(#x[0-9a-f]+|#\d+|[a-z]+);/gi,
18
18
  (entity, name: string) => {