basklee-react 0.9.2 → 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.2",
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,13 +29,22 @@ 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
- tables, images and galleries, audio and video controls, collapsible sections,
38
+ tables, images and galleries, audio and video controls, YouTube players,
39
+ collapsible sections,
36
40
  alignment and supported text styles. External links open in a new tab with
37
- `noopener noreferrer`; editor article links use `/journal/<id>`. Scripts,
38
- frames, forms, event attributes, unsafe URLs and unsupported styles are removed.
41
+ `noopener noreferrer`; editor article links use `/journal/<id>`. A YouTube
42
+ player from the editor (an `<iframe>` with a `youtube.com` or
43
+ `youtube-nocookie.com` `/embed/<id>` address) is kept and played from
44
+ `youtube-nocookie.com` at the article's width in 16:9, with fixed `allow`,
45
+ `loading="lazy"` and referrer attributes and an optional start second.
46
+ Scripts, other frames, forms, event attributes, unsafe URLs and unsupported
47
+ styles are removed.
39
48
  A leading heading that repeats the page title is removed.
40
49
 
41
50
  For an authenticated, accessible non-public article with a positive reading
@@ -182,6 +182,17 @@
182
182
  }
183
183
 
184
184
  .prose :where(img, video, audio):where(:not([data-product-id] *, [data-product-ids] *)) { max-width: 100%; }
185
+ /* A YouTube player from the editor: the article's width, 16:9 (an attribute selector: CSS modules rename classes). */
186
+ .prose iframe[class~='blog-post-editor-youtube']:where(:not([data-product-id] *, [data-product-ids] *)) {
187
+ display: block;
188
+ width: 100%;
189
+ height: auto;
190
+ margin: 1.5rem 0;
191
+ clear: both;
192
+ aspect-ratio: 16 / 9;
193
+ border: 0;
194
+ background: #000;
195
+ }
185
196
  .prose img:where(:not([data-product-id] *, [data-product-ids] *)) { height: auto; }
186
197
  .prose figure:where(:not([data-product-id] *, [data-product-ids] *)) { max-width: 100%; }
187
198
  .prose figure > img:where(:not([data-product-id] *, [data-product-ids] *)) { display: block; margin-inline: auto; }
@@ -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,11 +4,17 @@ 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>;
11
11
 
12
+ /*
13
+ * Article HTML comes from the marketplace blog editor and is stored as-is by
14
+ * the backend, so the storefront sanitizes it before display. A frame is kept
15
+ * only when its address is a YouTube embed (see blogYoutubeEmbedSource);
16
+ * every other frame is removed.
17
+ */
12
18
  export const blogArticleTags = [
13
19
  'h1',
14
20
  'h2',
@@ -69,6 +75,7 @@ export const blogArticleTags = [
69
75
  'track',
70
76
  'details',
71
77
  'summary',
78
+ 'iframe',
72
79
  ];
73
80
 
74
81
  const attributes = [
@@ -126,6 +133,9 @@ const attributes = [
126
133
  'data-product-id',
127
134
  'data-product-ids',
128
135
  'data-product-hidden-badges',
136
+ 'allow',
137
+ 'allowfullscreen',
138
+ 'referrerpolicy',
129
139
  ];
130
140
 
131
141
  const marginLength = '(-?\\d+(\\.\\d+)?(px|em|rem|%)?|auto)';
@@ -135,6 +145,7 @@ const editorClasses = new Set([
135
145
  'blog-code-block',
136
146
  'blog-post-editor-image',
137
147
  'blog-post-editor-video',
148
+ 'blog-post-editor-youtube',
138
149
  ]);
139
150
 
140
151
  export const blogArticleColorTokens = new Set([
@@ -174,6 +185,53 @@ const editorArticlePath =
174
185
  /^\/(?:[a-z]{2}(?:-[a-z]{2})?\/)?blog\/[^/?#]+\/([1-9]\d*)\/?$/i;
175
186
  const authorRelTokens = new Set(['nofollow', 'sponsored', 'ugc']);
176
187
 
188
+ // A YouTube player the editor inserts: youtube.com or youtube-nocookie.com,
189
+ // /embed/ and an 11-character video ID, optionally a start second.
190
+ const youtubeEmbed =
191
+ /^https:\/\/(?:www\.)?youtube(?:-nocookie)?\.com\/embed\/([\w-]{11})(?:\?([^#]*))?$/i;
192
+
193
+ export const blogYoutubeAllow =
194
+ 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
195
+
196
+ /**
197
+ * The privacy-enhanced player address for a YouTube embed address, or an
198
+ * empty string for anything else (other sites, other YouTube pages).
199
+ */
200
+ export function blogYoutubeEmbedSource(value: string) {
201
+ const match = youtubeEmbed.exec(value.trim());
202
+
203
+ if (!match) {
204
+ return '';
205
+ }
206
+
207
+ const start = /(?:^|&)start=(\d{1,6})(?:&|$)/.exec(match[2] ?? '')?.[1];
208
+
209
+ return `https://www.youtube-nocookie.com/embed/${match[1]}${start && Number(start) > 0 ? `?start=${Number(start)}` : ''}`;
210
+ }
211
+
212
+ function prepareYoutubeFrame(node: Element) {
213
+ const source = blogYoutubeEmbedSource(node.getAttribute('src') ?? '');
214
+
215
+ if (!source) {
216
+ node.remove();
217
+ return;
218
+ }
219
+
220
+ const title = node.getAttribute('title')?.trim() || 'YouTube video';
221
+
222
+ for (const attribute of [...node.getAttributeNames()]) {
223
+ node.removeAttribute(attribute);
224
+ }
225
+
226
+ node.setAttribute('class', 'blog-post-editor-youtube');
227
+ node.setAttribute('src', source);
228
+ node.setAttribute('title', title);
229
+ node.setAttribute('allow', blogYoutubeAllow);
230
+ node.setAttribute('allowfullscreen', '');
231
+ node.setAttribute('loading', 'lazy');
232
+ node.setAttribute('referrerpolicy', 'strict-origin-when-cross-origin');
233
+ }
234
+
177
235
  function normalizedHeadingText(value: string) {
178
236
  return htmlTextParagraphs(value)
179
237
  .join(' ')
@@ -292,6 +350,11 @@ function prepareLink(link: Element) {
292
350
  function prepareElement(node: Element) {
293
351
  const name = node.nodeName;
294
352
 
353
+ if (name === 'IFRAME') {
354
+ prepareYoutubeFrame(node);
355
+ return;
356
+ }
357
+
295
358
  if (name === 'A') {
296
359
  prepareLink(node);
297
360
  }
@@ -369,3 +432,268 @@ export function safeBlogArticleHtml(
369
432
  purifier.removeHook('afterSanitizeAttributes', prepareElementHook);
370
433
  }
371
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) => {