@cntrl-site/sdk-nextjs 1.11.2 → 1.11.4-alpha.0

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.
Files changed (44) hide show
  1. package/lib/components/Article.js +4 -1
  2. package/lib/components/Section/Section.js +5 -3
  3. package/lib/components/StructuredBlockItem/BlockCaption/BlockCaption.js +19 -8
  4. package/lib/components/StructuredBlockItem/StructuredRichText/StructuredRichText.js +11 -18
  5. package/lib/components/StructuredBlockItem/StructuredTable/StructuredTable.js +10 -8
  6. package/lib/components/StructuredBlockItem/textStylesRule.js +24 -6
  7. package/lib/components/StructuredBlockItem/vw.js +8 -0
  8. package/lib/components/items/CodeEmbedItem/CodeEmbedItem.js +2 -2
  9. package/lib/components/items/ComponentItem/ComponentItem.js +3 -3
  10. package/lib/components/items/CompoundItem/CompoundItem.js +2 -2
  11. package/lib/components/items/EmbedVideoItem/VimeoEmbed.js +4 -4
  12. package/lib/components/items/EmbedVideoItem/YoutubeEmbed.js +5 -5
  13. package/lib/components/items/FileItem/ImageItem.js +2 -2
  14. package/lib/components/items/FileItem/VideoItem.js +3 -3
  15. package/lib/components/items/GroupItem/GroupItem.js +2 -2
  16. package/lib/components/items/LinkWrapper.js +33 -1
  17. package/lib/components/items/RectangleItem/RectangleItem.js +3 -3
  18. package/lib/utils/RichTextConverter/RichTextConverter.js +19 -9
  19. package/package.json +3 -3
  20. package/src/components/Article.test.tsx +52 -0
  21. package/src/components/Article.tsx +3 -0
  22. package/src/components/Section/Section.tsx +8 -4
  23. package/src/components/StructuredBlockItem/BlockCaption/BlockCaption.tsx +18 -8
  24. package/src/components/StructuredBlockItem/StructuredRichText/StructuredRichText.tsx +11 -14
  25. package/src/components/StructuredBlockItem/StructuredTable/StructuredTable.tsx +18 -14
  26. package/src/components/StructuredBlockItem/textStylesRule.ts +24 -6
  27. package/src/components/StructuredBlockItem/vw.ts +4 -0
  28. package/src/components/StructuredContent/StructuredContent.test.tsx +30 -3
  29. package/src/components/items/CodeEmbedItem/CodeEmbedItem.tsx +1 -1
  30. package/src/components/items/ComponentItem/ComponentItem.tsx +1 -0
  31. package/src/components/items/CompoundItem/CompoundItem.tsx +1 -1
  32. package/src/components/items/EmbedVideoItem/VimeoEmbed.tsx +1 -1
  33. package/src/components/items/EmbedVideoItem/YoutubeEmbed.tsx +1 -1
  34. package/src/components/items/FileItem/ImageItem.tsx +1 -1
  35. package/src/components/items/FileItem/VideoItem.tsx +1 -1
  36. package/src/components/items/GroupItem/GroupItem.tsx +1 -1
  37. package/src/components/items/LinkWrapper.tsx +43 -2
  38. package/src/components/items/RectangleItem/RectangleItem.tsx +1 -1
  39. package/src/utils/RichTextConverter/RichTextConverter.test.tsx +17 -0
  40. package/src/utils/RichTextConverter/RichTextConverter.tsx +23 -8
  41. package/.idea/codeStyles/codeStyleConfig.xml +0 -5
  42. package/.idea/modules.xml +0 -8
  43. package/.idea/sdk-nextjs.iml +0 -12
  44. package/.idea/vcs.xml +0 -6
@@ -48,11 +48,13 @@ const LIST_STYLES = `
48
48
  `;
49
49
  class RichTextConverter {
50
50
  /** The text as elements, the styles of its ranges, and, where it has a list, the list styles every text shares, for the caller to render once. */
51
- toHtml(richText, layouts, { isScaledToViewport = true } = {}) {
51
+ toHtml(richText, layouts, { isScaledToViewport = true, paragraphTag: Paragraph = 'div' } = {}) {
52
52
  var _a, _b, _c, _d;
53
53
  const { text, blocks = [] } = richText.commonParams;
54
54
  const hasLists = blocks.some(block => block.type in LIST_ITEM_CLASSES);
55
55
  const root = [];
56
+ // what a div is of itself, a paragraph drawn in another element is told: a block, without margins
57
+ const paragraphRules = [];
56
58
  const styleRules = layouts.reduce((rec, layout) => {
57
59
  rec[layout.id] = [];
58
60
  return rec;
@@ -71,7 +73,9 @@ class RichTextConverter {
71
73
  // an empty line keeps its height, as in the editor; a text never typed into comes without even its line break
72
74
  if (content === '' || content === '\n') {
73
75
  const id = `rt_${richText.id}_br_${blockIndex}`;
74
- root.push((0, jsx_runtime_1.jsx)("div", { className: `${id}${typeClass}`, children: (0, jsx_runtime_1.jsx)("br", {}) }, id));
76
+ root.push((0, jsx_runtime_1.jsx)(Paragraph, { className: `${id}${typeClass}`, children: (0, jsx_runtime_1.jsx)("br", {}) }, id));
77
+ if (Paragraph !== 'div')
78
+ paragraphRules.push(`.${id} { display: block; margin: 0; }`);
75
79
  layouts.forEach(l => {
76
80
  const lhForLayout = currentLineHeight[l.id];
77
81
  if (lhForLayout === undefined)
@@ -132,7 +136,7 @@ class RichTextConverter {
132
136
  offset = entity.end;
133
137
  }
134
138
  if (entity.link) {
135
- kids.push((0, jsx_runtime_1.jsx)(LinkWrapper_1.LinkWrapper, { url: entity.link, target: entity.target, children: entityKids }, entity.start));
139
+ kids.push((0, jsx_runtime_1.jsx)(LinkWrapper_1.LinkWrapper, { url: entity.link, target: entity.target, download: entity.download, children: entityKids }, entity.start));
136
140
  continue;
137
141
  }
138
142
  kids.push(...entityKids);
@@ -179,14 +183,20 @@ class RichTextConverter {
179
183
  }
180
184
  }
181
185
  }
182
- root.push((0, jsx_runtime_1.jsx)("div", { className: `${blockClass}${typeClass}`, children: kids }, blockClass));
186
+ root.push((0, jsx_runtime_1.jsx)(Paragraph, { className: `${blockClass}${typeClass}`, children: kids }, blockClass));
187
+ // each layout shows or hides the paragraph itself
188
+ if (Paragraph !== 'div')
189
+ paragraphRules.push(`.${blockClass} { margin: 0; }`);
183
190
  }
184
191
  }
185
- const styles = layouts.map(l => `
192
+ const styles = [
193
+ ...paragraphRules,
194
+ ...layouts.map(l => `
186
195
  ${(0, sdk_1.getLayoutMediaQuery)(l.id, layouts)} {
187
196
  ${styleRules[l.id].join('\n')}
188
197
  }
189
- `).join('\n');
198
+ `)
199
+ ].join('\n');
190
200
  return [
191
201
  root,
192
202
  styles,
@@ -221,7 +231,7 @@ class RichTextConverter {
221
231
  return styleGroups;
222
232
  }
223
233
  groupEntities(entities, styleGroups) {
224
- var _a, _b, _c, _d, _e, _f, _g, _h;
234
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
225
235
  const entitiesGroups = [];
226
236
  if (!entities.length && !styleGroups)
227
237
  return;
@@ -241,7 +251,7 @@ class RichTextConverter {
241
251
  const end = dividers[i + 1];
242
252
  const entity = entities.find(e => e.start === start);
243
253
  entitiesGroups.push(Object.assign({ stylesGroup: [], start,
244
- end }, (entity && { link: (_b = (_a = entity.data) === null || _a === void 0 ? void 0 : _a.url) !== null && _b !== void 0 ? _b : '', target: (_d = (_c = entity.data) === null || _c === void 0 ? void 0 : _c.target) !== null && _d !== void 0 ? _d : '_self' })));
254
+ end }, (entity && { link: (_b = (_a = entity.data) === null || _a === void 0 ? void 0 : _a.url) !== null && _b !== void 0 ? _b : '', target: (_d = (_c = entity.data) === null || _c === void 0 ? void 0 : _c.target) !== null && _d !== void 0 ? _d : '_self', download: (_e = entity.data) === null || _e === void 0 ? void 0 : _e.download })));
245
255
  }
246
256
  return entitiesGroups;
247
257
  }
@@ -268,7 +278,7 @@ class RichTextConverter {
268
278
  const end = entityDividers[i + 1];
269
279
  const entity = entities.find(e => e.start === start);
270
280
  entitiesGroups.push(Object.assign({ stylesGroup: styleGroups.filter(s => s.start >= start && s.end <= end), start,
271
- end }, (entity && { link: (_f = (_e = entity.data) === null || _e === void 0 ? void 0 : _e.url) !== null && _f !== void 0 ? _f : '', target: (_h = (_g = entity.data) === null || _g === void 0 ? void 0 : _g.target) !== null && _h !== void 0 ? _h : '_self' })));
281
+ end }, (entity && { link: (_g = (_f = entity.data) === null || _f === void 0 ? void 0 : _f.url) !== null && _g !== void 0 ? _g : '', target: (_j = (_h = entity.data) === null || _h === void 0 ? void 0 : _h.target) !== null && _j !== void 0 ? _j : '_self', download: (_k = entity.data) === null || _k === void 0 ? void 0 : _k.download })));
272
282
  }
273
283
  return entitiesGroups;
274
284
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cntrl-site/sdk-nextjs",
3
- "version": "1.11.2",
3
+ "version": "1.11.4-alpha.0",
4
4
  "description": "SDK for Next.js",
5
5
  "author": "arsen@momdesign.nyc",
6
6
  "license": "MIT",
@@ -30,9 +30,9 @@
30
30
  },
31
31
  "dependencies": {
32
32
  "@cntrl-site/color": "^1.0.0",
33
- "@cntrl-site/components": "^1.0.106",
33
+ "@cntrl-site/components": "^1.0.107-alpha.0",
34
34
  "@cntrl-site/effects": "^1.4.2",
35
- "@cntrl-site/sdk": "^1.29.2",
35
+ "@cntrl-site/sdk": "^1.29.6-alpha.0",
36
36
  "@types/vimeo__player": "^2.18.0",
37
37
  "@vimeo/player": "^2.25.0",
38
38
  "franc-min": "^5.0.0",
@@ -0,0 +1,52 @@
1
+ import { render } from '@testing-library/react';
2
+ import { Article as TArticle, Layout, Section, SectionHeightMode } from '@cntrl-site/sdk';
3
+ import { CntrlContext } from '../provider/CntrlContext';
4
+ import { CntrlSdkContext } from '../provider/CntrlSdkContext';
5
+ import { CustomItemRegistry } from '../provider/CustomItemRegistry';
6
+ import { CustomSectionRegistry } from '../provider/CustomSectionRegistry';
7
+ import { Article } from './Article';
8
+
9
+ jest.mock('styled-jsx/style', () => ({ __esModule: true, default: () => null }));
10
+ // jsdom measures nothing, so a section's height is never observed
11
+ global.ResizeObserver = class { observe() {} unobserve() {} disconnect() {} } as unknown as typeof ResizeObserver;
12
+
13
+ const layouts: Layout[] = [
14
+ { id: 'desktop', title: 'Desktop', startsWith: 800, exemplary: 1440 },
15
+ { id: 'mobile', title: 'Mobile', startsWith: 0, exemplary: 375 }
16
+ ];
17
+
18
+ function section(id: string, type: Section['type']): Section {
19
+ return {
20
+ id,
21
+ type,
22
+ items: [],
23
+ minHeight: Object.fromEntries(layouts.map(layout => [layout.id, { mode: SectionHeightMode.ControlUnits, units: 0.5 }])),
24
+ color: {},
25
+ hidden: {},
26
+ structuredContent: [],
27
+ structuredContentSettings: { paddingBottom: {}, defaultWidth: {} }
28
+ } as unknown as Section;
29
+ }
30
+
31
+ function draw(sections: Section[]) {
32
+ const sdk = new CntrlSdkContext(new CustomItemRegistry(), new CustomSectionRegistry());
33
+ sdk.setLayouts(layouts);
34
+ const article: TArticle = { id: 'article', sections, interactions: {} };
35
+ return render(
36
+ <CntrlContext.Provider value={sdk}>
37
+ <Article article={article} sectionData={{}} />
38
+ </CntrlContext.Provider>
39
+ );
40
+ }
41
+
42
+ const tagOf = (container: HTMLElement, id: string) => container.querySelector(`.section-${id}`)?.tagName;
43
+
44
+ describe('Article', () => {
45
+ it('draws its first content-based section as the page\'s main content, any other as a section, the rest as they were', () => {
46
+ const { container } = draw([section('intro', 'default'), section('post', 'content-based'), section('more', 'content-based')]);
47
+ expect(tagOf(container, 'intro')).toBe('DIV');
48
+ expect(tagOf(container, 'post')).toBe('MAIN');
49
+ expect(tagOf(container, 'more')).toBe('SECTION');
50
+ expect(container.querySelectorAll('main')).toHaveLength(1);
51
+ });
52
+ });
@@ -32,6 +32,8 @@ export const Article: FC<Props> = ({ article, sectionData, navigation, pages = [
32
32
 
33
33
  const webglContextManager = useMemo(() => new WebGLContextManager(), []);
34
34
  const sectionsLength = article.sections.length;
35
+ // a page has one main content: its first content-based section
36
+ const mainSectionId = article.sections.find(section => section.type === 'content-based')?.id;
35
37
 
36
38
  return (
37
39
  <ArticleRectContext.Provider value={articleRectObserver}>
@@ -55,6 +57,7 @@ export const Article: FC<Props> = ({ article, sectionData, navigation, pages = [
55
57
  key={section.id}
56
58
  data={data}
57
59
  zIndex={sectionsLength - i}
60
+ isMain={section.id === mainSectionId}
58
61
  />
59
62
  );
60
63
  })}
@@ -24,9 +24,11 @@ interface Props {
24
24
  zIndex: number;
25
25
  data?: any;
26
26
  articleHeight: number;
27
+ /** Whether it holds the page's main content: the article's first content-based section drawn does. */
28
+ isMain?: boolean;
27
29
  }
28
30
 
29
- export const Section: FC<PropsWithChildren<Props>> = ({ section, data, zIndex, articleHeight }) => {
31
+ export const Section: FC<PropsWithChildren<Props>> = ({ section, data, zIndex, articleHeight, isMain = false }) => {
30
32
  const reactId = useId();
31
33
  const id = `${reactId}-section-${section.id}`;
32
34
  const sectionRef = useRef<HTMLDivElement | null>(null);
@@ -40,6 +42,8 @@ export const Section: FC<PropsWithChildren<Props>> = ({ section, data, zIndex, a
40
42
  ];
41
43
 
42
44
  const SectionComponent = section.name ? customSections.getComponent(section.name) : undefined;
45
+ // a content-based section holds a post's own content: the first is the page's main content, any other a section of it
46
+ const Tag = (section.type === 'content-based' ? (isMain ? 'main' : 'section') : 'div') as 'div';
43
47
  useSectionRegistry(section.id, sectionRef.current);
44
48
  const layoutMedia = layout && section.media && section.media[layout] ? section.media[layout] : undefined;
45
49
 
@@ -94,11 +98,11 @@ export const Section: FC<PropsWithChildren<Props>> = ({ section, data, zIndex, a
94
98
  </>
95
99
  );
96
100
 
97
- if (SectionComponent) return <div ref={sectionRef}><SectionComponent data={data}>{children}</SectionComponent></div>;
101
+ if (SectionComponent) return <Tag ref={sectionRef}><SectionComponent data={data}>{children}</SectionComponent></Tag>;
98
102
 
99
103
  return (
100
104
  <>
101
- <div
105
+ <Tag
102
106
  className={`section-${section.id}`}
103
107
  id={section.name}
104
108
  ref={sectionRef}
@@ -124,7 +128,7 @@ export const Section: FC<PropsWithChildren<Props>> = ({ section, data, zIndex, a
124
128
  </div>
125
129
  )}
126
130
  {children}
127
- </div>
131
+ </Tag>
128
132
  <JSXStyle id={id}>{`
129
133
  ${
130
134
  getLayoutStyles(layouts, layoutValues, ([height, color, media]) => (`
@@ -3,6 +3,7 @@ import { FC, useId } from 'react';
3
3
  import JSXStyle from 'styled-jsx/style';
4
4
  import { useCntrlContext } from '../../../provider/useCntrlContext';
5
5
  import { textStylesRule } from '../textStylesRule';
6
+ import { vw } from '../vw';
6
7
 
7
8
  interface Props {
8
9
  blockId: string;
@@ -13,7 +14,10 @@ interface Props {
13
14
 
14
15
  const CAPTION_GAP_PX = 5;
15
16
 
16
- /** The caption under an image: as wide as the reading column, or as the image where it is narrower, and centered under it. */
17
+ /**
18
+ * The caption under an image, centered under it: as wide as the caption preset says, else as the
19
+ * reading column, or as the image where that is narrower; with the preset's space above and below its text.
20
+ */
17
21
  export const BlockCaption: FC<Props> = ({ blockId, caption, layoutParams, readingWidth }) => {
18
22
  const reactId = useId();
19
23
  const { layouts } = useCntrlContext();
@@ -28,13 +32,19 @@ export const BlockCaption: FC<Props> = ({ blockId, caption, layoutParams, readin
28
32
  white-space: pre-wrap;
29
33
  overflow-wrap: break-word;
30
34
  }
31
- ${getLayoutStyles(layouts, layoutValues, ([params, width], exemplary) => (`
32
- .structured-caption-${blockId} {
33
- width: ${width !== undefined ? `min(${width * 100}vw, 100%)` : '100%'};
34
- margin-top: ${CAPTION_GAP_PX / exemplary * 100}vw;
35
- }
36
- ${params?.captionStyles ? textStylesRule(`.structured-caption-${blockId}`, params.captionStyles) : ''}
37
- `))}
35
+ ${getLayoutStyles(layouts, layoutValues, ([params, readingColumn], exemplary) => {
36
+ const captionStyles = params?.captionStyles;
37
+ const width = captionStyles?.maxWidth ?? readingColumn;
38
+ return `
39
+ .structured-caption-${blockId} {
40
+ width: ${width !== undefined ? `min(${vw(width)}, 100%)` : '100%'};
41
+ margin-top: ${CAPTION_GAP_PX / exemplary * 100}vw;
42
+ padding-top: ${vw(captionStyles?.innerPaddingTop)};
43
+ padding-bottom: ${vw(captionStyles?.innerPaddingBottom)};
44
+ }
45
+ ${captionStyles ? textStylesRule(`.structured-caption-${blockId}`, captionStyles) : ''}
46
+ `;
47
+ })}
38
48
  `}
39
49
  </JSXStyle>
40
50
  </>
@@ -7,7 +7,7 @@ import { LIST_STYLES_ID, RichTextConverter } from '../../../utils/RichTextConver
7
7
  import { detectLang } from '../../../utils/detectLang';
8
8
  import { getHeadingTag } from '../../../utils/getHeadingTag';
9
9
  import { StructuredBlockItemProps } from '../StructuredBlockItem';
10
- import { colorRule, textColumnsRule, textStylesRule } from '../textStylesRule';
10
+ import { boxRule, textColumnsRule, textStylesRule } from '../textStylesRule';
11
11
 
12
12
  type TextBlock = RichTextStructuredBlock | QuoteStructuredBlock | DateStructuredBlock;
13
13
 
@@ -15,7 +15,9 @@ const richTextConverter = new RichTextConverter();
15
15
 
16
16
  /**
17
17
  * A block of text: rich text, a quote, which is drawn in a box of its own, or a date, which comes as
18
- * the text it reads as. Its text is set in the styles it was drawn with, its ranges styled over them.
18
+ * the text it reads as. Its text is set in the styles it was drawn with, its ranges styled over them,
19
+ * and each paragraph is one of the page's; a quote is a quotation, and a heading, which takes no
20
+ * paragraphs, holds its lines in spans that look the same.
19
21
  */
20
22
  export const StructuredRichText: FC<StructuredBlockItemProps<TextBlock>> = ({ block }) => {
21
23
  const reactId = useId();
@@ -23,15 +25,17 @@ export const StructuredRichText: FC<StructuredBlockItemProps<TextBlock>> = ({ bl
23
25
  const { layouts } = useCntrlContext();
24
26
  const [ref, setRef] = useState<HTMLDivElement | null>(null);
25
27
  useItemGeometry(block.id, ref);
28
+ const headingTag = getHeadingTag(block);
29
+ const isQuote = block.type === StructuredBlockType.Quote;
30
+ const paragraphTag = headingTag ? 'span' : 'p';
26
31
  const [content, rangeStyles, listStyles] = useMemo(
27
- () => richTextConverter.toHtml(block, layouts, { isScaledToViewport: false }),
28
- [block, layouts]
32
+ () => richTextConverter.toHtml(block, layouts, { isScaledToViewport: false, paragraphTag }),
33
+ [block, layouts, paragraphTag]
29
34
  );
30
35
  const lang = useMemo(() => detectLang(block.commonParams.text), [block.commonParams.text]);
31
- const isQuote = block.type === StructuredBlockType.Quote;
32
36
  // only a text block of the stack flows in columns: a quote keeps to its box, a date to its line
33
37
  const isText = block.type === StructuredBlockType.RichText;
34
- const Wrapper = (getHeadingTag(block) ?? 'div') as 'div';
38
+ const Wrapper = (headingTag ?? (isQuote ? 'blockquote' : 'div')) as 'div';
35
39
  const layoutValues: Record<string, any>[] = [block.layoutParams];
36
40
  return (
37
41
  <>
@@ -49,14 +53,7 @@ export const StructuredRichText: FC<StructuredBlockItemProps<TextBlock>> = ({ bl
49
53
  {`${getLayoutStyles(layouts, layoutValues, ([layoutParams]) => (`
50
54
  ${textStylesRule(`.structured-text-${block.id}`, layoutParams)}
51
55
  ${isText ? textColumnsRule(`.structured-text-${block.id}`, layoutParams) : ''}
52
- ${isQuote ? `
53
- .structured-quote-box-${block.id} {
54
- padding: ${[layoutParams.boxPaddingTop, layoutParams.boxPaddingRight, layoutParams.boxPaddingBottom, layoutParams.boxPaddingLeft].map(side => `${(side ?? 0) * 100}vw`).join(' ')};
55
- border-radius: ${(layoutParams.boxRadius ?? 0) * 100}vw;
56
- background-color: transparent;
57
- }
58
- ${layoutParams.background ? colorRule(`.structured-quote-box-${block.id}`, 'background-color', layoutParams.background) : ''}
59
- ` : ''}
56
+ ${isQuote ? boxRule(`.structured-quote-box-${block.id}`, layoutParams) : ''}
60
57
  `))}`}
61
58
  </JSXStyle>
62
59
  </>
@@ -5,7 +5,8 @@ import { useCntrlContext } from '../../../provider/useCntrlContext';
5
5
  import { useItemGeometry } from '../../../ItemGeometry/useItemGeometry';
6
6
  import { LIST_STYLES_ID, RichTextConverter } from '../../../utils/RichTextConverter/RichTextConverter';
7
7
  import { StructuredBlockItemProps } from '../StructuredBlockItem';
8
- import { colorRule, textStylesRule } from '../textStylesRule';
8
+ import { boxRule, colorRule, textStylesRule } from '../textStylesRule';
9
+ import { vw } from '../vw';
9
10
 
10
11
  // the lines between the cells, in pixels of the layout, scaled with it like everything drawn in it
11
12
  const BORDER_PX = 1;
@@ -37,7 +38,7 @@ function convertCells(block: TableStructuredBlock, layouts: Layout[]): { cells:
37
38
  * lined in the styles it comes with, their ranges styled over them, each column its share of the
38
39
  * width and padded on either side as its own values say. Cells draw a heading row over a grid; rows
39
40
  * draw every row plain, the two fills alternating from the first; lines draw the heading and a line
40
- * between each pair of rows only.
41
+ * between each pair of rows only. The table is drawn in a box, which grows out past its columns.
41
42
  */
42
43
  export const StructuredTable: FC<StructuredBlockItemProps<TableStructuredBlock>> = ({ block }) => {
43
44
  const reactId = useId();
@@ -49,21 +50,24 @@ export const StructuredTable: FC<StructuredBlockItemProps<TableStructuredBlock>>
49
50
  const headingAsRow = kind === 'rows';
50
51
  const Heading = headingAsRow ? 'td' : 'th';
51
52
  const table = `.structured-table-${block.id}`;
53
+ const box = `.structured-table-box-${block.id}`;
52
54
  const cells = `${table} th, ${table} td`;
53
55
  const cellContent = (cell: StructuredBlockTableCell) => content.get(cell.id);
54
56
  return (
55
57
  <>
56
- <table ref={setRef} className={`structured-table-${block.id}`}>
57
- <colgroup>
58
- {header.map((_, col) => <col key={col} />)}
59
- </colgroup>
60
- <thead className={`structured-table-heading-${block.id}`}>
61
- <tr>{header.map(cell => <Heading key={cell.id}>{cellContent(cell)}</Heading>)}</tr>
62
- </thead>
63
- <tbody className={`structured-table-body-${block.id}`}>
64
- {rows.map((row, index) => <tr key={row[0]?.id ?? index}>{row.map(cell => <td key={cell.id}>{cellContent(cell)}</td>)}</tr>)}
65
- </tbody>
66
- </table>
58
+ <div className={`structured-table-box-${block.id}`}>
59
+ <table ref={setRef} className={`structured-table-${block.id}`}>
60
+ <colgroup>
61
+ {header.map((_, col) => <col key={col} />)}
62
+ </colgroup>
63
+ <thead className={`structured-table-heading-${block.id}`}>
64
+ <tr>{header.map(cell => <Heading key={cell.id}>{cellContent(cell)}</Heading>)}</tr>
65
+ </thead>
66
+ <tbody className={`structured-table-body-${block.id}`}>
67
+ {rows.map((row, index) => <tr key={row[0]?.id ?? index}>{row.map(cell => <td key={cell.id}>{cellContent(cell)}</td>)}</tr>)}
68
+ </tbody>
69
+ </table>
70
+ </div>
67
71
  {listStyles && <JSXStyle id={LIST_STYLES_ID}>{listStyles}</JSXStyle>}
68
72
  <JSXStyle id={`${reactId}-table-${block.id}`}>
69
73
  {rangeStyles}
@@ -83,10 +87,10 @@ export const StructuredTable: FC<StructuredBlockItemProps<TableStructuredBlock>>
83
87
  overflow-wrap: anywhere;
84
88
  }
85
89
  ${getLayoutStyles(layouts, [block.layoutParams], ([layoutParams], exemplary) => {
86
- const vw = (value: number) => `${value * 100}vw`;
87
90
  const border = vw(BORDER_PX / exemplary);
88
91
  const fill = (selector: string, color: string | undefined) => (color ? colorRule(selector, 'background-color', color) : '');
89
92
  return (`
93
+ ${boxRule(box, layoutParams)}
90
94
  ${textStylesRule(table, layoutParams)}
91
95
  ${cells} {
92
96
  padding-top: ${vw(layoutParams.cellPaddingTop)};
@@ -1,16 +1,17 @@
1
1
  import { CntrlColor } from '@cntrl-site/color';
2
- import { Hyphens, StructuredBlockRichTextLayoutParams, StructuredBlockTextStyles } from '@cntrl-site/sdk';
2
+ import { Hyphens, StructuredBlockBoxParams, StructuredBlockRichTextLayoutParams, StructuredBlockTextStyles } from '@cntrl-site/sdk';
3
3
  import { getFontFamilyValue } from '../../utils/getFontFamilyValue';
4
+ import { vw } from './vw';
4
5
 
5
6
  /** A block's text styles as a CSS rule for `selector`, its lengths in viewport units as the block's own. */
6
7
  export function textStylesRule(selector: string, styles: StructuredBlockTextStyles): string {
7
8
  return `
8
9
  ${selector} {
9
10
  font-family: ${getFontFamilyValue(styles.typeFace)};
10
- font-size: ${styles.fontSize * 100}vw;
11
- line-height: ${styles.lineHeight * 100}vw;
12
- letter-spacing: ${styles.letterSpacing * 100}vw;
13
- word-spacing: ${styles.wordSpacing * 100}vw;
11
+ font-size: ${vw(styles.fontSize)};
12
+ line-height: ${vw(styles.lineHeight)};
13
+ letter-spacing: ${vw(styles.letterSpacing)};
14
+ word-spacing: ${vw(styles.wordSpacing)};
14
15
  font-weight: ${styles.fontWeight};
15
16
  font-style: ${styles.fontStyle || 'normal'};
16
17
  font-variant: ${styles.fontVariant};
@@ -35,11 +36,28 @@ export function textColumnsRule(
35
36
  ${selector} {
36
37
  hyphens: ${hyphens};
37
38
  -webkit-hyphens: ${hyphens};
38
- ${columns > 1 ? `column-count: ${columns}; column-gap: ${columnGap * 100}vw; column-fill: balance;` : 'column-count: auto; column-gap: normal;'}
39
+ ${columns > 1 ? `column-count: ${columns}; column-gap: ${vw(columnGap)}; column-fill: balance;` : 'column-count: auto; column-gap: normal;'}
39
40
  }
40
41
  `;
41
42
  }
42
43
 
44
+ /**
45
+ * The box a quote's text or a table is drawn in, as a CSS rule for `selector`: padded inside, its
46
+ * sides grown out past the columns the block is placed on by as much as they pad it, so what it
47
+ * holds stays on them; rounded, and filled where it has a fill.
48
+ */
49
+ export function boxRule(selector: string, box: StructuredBlockBoxParams): string {
50
+ return `
51
+ ${selector} {
52
+ padding: ${[box.boxPaddingTop, box.boxPaddingRight, box.boxPaddingBottom, box.boxPaddingLeft].map(vw).join(' ')};
53
+ margin: 0 -${vw(box.boxPaddingRight)} 0 -${vw(box.boxPaddingLeft)};
54
+ border-radius: ${vw(box.boxRadius)};
55
+ background-color: transparent;
56
+ }
57
+ ${box.boxBackground ? colorRule(selector, 'background-color', box.boxBackground) : ''}
58
+ `;
59
+ }
60
+
43
61
  /** A colour of the palette as CSS for `property`, with a fallback where oklch is not supported. */
44
62
  export function colorRule(selector: string, property: string, value: string): string {
45
63
  const color = CntrlColor.parse(value);
@@ -0,0 +1,4 @@
1
+ /** A share of the layout width as CSS: the layout is the viewport's width, so a share is so many `vw`. */
2
+ export function vw(share: number | undefined): string {
3
+ return `${(share ?? 0) * 100}vw`;
4
+ }
@@ -59,7 +59,7 @@ const text = block(StructuredBlockType.RichText, 'text', paragraph('Read the pos
59
59
  const quote = block(StructuredBlockType.Quote, 'quote', { ...paragraph('A quote'), kind: 'boxed' }, {
60
60
  ...textStyles,
61
61
  rangeStyles: [],
62
- background: '#EEEEEE',
62
+ boxBackground: '#EEEEEE',
63
63
  boxPaddingTop: 0.02,
64
64
  boxPaddingRight: 0.03,
65
65
  boxPaddingBottom: 0.02,
@@ -74,7 +74,7 @@ const gallery = block(StructuredBlockType.Image, 'gallery', {
74
74
  urls: ['https://cdn.cntrl.site/a.jpg', 'https://cdn.cntrl.site/b.jpg'],
75
75
  altText: 'Two views',
76
76
  caption: 'Seen from the hill'
77
- }, { opacity: 0.8, captionStyles: { ...textStyles, fontSize: 0.01 } });
77
+ }, { opacity: 0.8, captionStyles: { ...textStyles, fontSize: 0.01, maxWidth: 0.45, innerPaddingTop: 0.02, innerPaddingBottom: 0.01 } });
78
78
  const video = block(StructuredBlockType.Video, 'video', { url: 'https://cdn.cntrl.site/clip.mp4', coverUrl: 'https://cdn.cntrl.site/cover.jpg' }, {
79
79
  play: 'on-click',
80
80
  muted: true,
@@ -182,6 +182,9 @@ describe('StructuredContent', () => {
182
182
  expect(container.querySelector('.structured-text-heading')!.tagName).toBe('H1');
183
183
  expect(container.querySelector('.structured-text-text')!.tagName).toBe('DIV');
184
184
  expect(css()).toMatch(/\.structured-text-heading \{\s*margin: 0;/);
185
+ // a heading takes no paragraphs: its lines are spans drawn as blocks; other text's are paragraphs
186
+ expect([...container.querySelector('.structured-text-heading')!.children].map(line => line.tagName)).toEqual(['SPAN']);
187
+ expect([...container.querySelector('.structured-text-text')!.children].map(line => line.tagName)).toEqual(['P']);
185
188
  });
186
189
 
187
190
  it('sets text in its styles, its ranges in viewport units', () => {
@@ -201,8 +204,15 @@ describe('StructuredContent', () => {
201
204
  it('draws a quote in its box and a date as the text it reads as', () => {
202
205
  const { container } = draw(section(false));
203
206
  expect(container.querySelector('.structured-quote-box-quote')!.textContent!.trim()).toBe('A quote');
204
- expect(css()).toMatch(/\.structured-quote-box-quote \{[^}]*padding: 2vw 3vw 2vw 1vw;[^}]*border-radius: 1vw;/);
207
+ // its sides grow out past the columns the text is placed on, which it stays on
208
+ expect(css()).toMatch(/\.structured-quote-box-quote \{[^}]*padding: 2vw 3vw 2vw 1vw;[^}]*margin: 0 -3vw 0 -1vw;[^}]*border-radius: 1vw;/);
209
+ expect(css()).toMatch(/\.structured-quote-box-quote \{\s*background-color: oklch/);
205
210
  expect(container.querySelector('.structured-text-date')!.textContent!.trim()).toBe('23 Sep 2026');
211
+ // a quote is a quotation of paragraphs, kept from the margins of both
212
+ expect(container.querySelector('.structured-text-quote')!.tagName).toBe('BLOCKQUOTE');
213
+ expect(container.querySelector('.structured-quote-box-quote > p')!.textContent!.trim()).toBe('A quote');
214
+ expect(css()).toMatch(/\.structured-text-quote \{\s*margin: 0;/);
215
+ expect(container.querySelector('.structured-text-date > p')!.textContent!.trim()).toBe('23 Sep 2026');
206
216
  });
207
217
 
208
218
  it('draws a gallery\'s images side by side, its caption under them', () => {
@@ -212,6 +222,7 @@ describe('StructuredContent', () => {
212
222
  // equally wide until their own proportions are known
213
223
  expect(images.map(image => image.style.flexGrow)).toEqual(['0.5', '0.5']);
214
224
  expect(container.querySelector('.structured-caption-gallery')!.textContent).toBe('Seen from the hill');
225
+ expect(css()).toMatch(/\.structured-caption-gallery \{[^}]*width: min\(45vw, 100%\);[^}]*padding-top: 2vw;[^}]*padding-bottom: 1vw;/);
215
226
  });
216
227
 
217
228
  it('draws no caption an image has switched off, nor one that says nothing', () => {
@@ -260,6 +271,22 @@ describe('StructuredContent', () => {
260
271
  expect(css()).toMatch(/\.structured-table-body-table \{\s*background-color: oklch/);
261
272
  });
262
273
 
274
+ it('draws a table in its box, its sides grown out past the columns the table stays on, filled and rounded', () => {
275
+ const boxed = block(StructuredBlockType.Table, 'boxed', { kind: 'rows', ...tableContent('boxed') }, {
276
+ ...tableCells,
277
+ boxBackground: '#FAFAFA',
278
+ boxPaddingTop: 0.01,
279
+ boxPaddingRight: 0.02,
280
+ boxPaddingBottom: 0.01,
281
+ boxPaddingLeft: 0.02,
282
+ boxRadius: 0.005
283
+ });
284
+ const { container } = draw({ ...section(false), structuredContent: [boxed] } as Section);
285
+ expect(container.querySelector('.structured-table-box-boxed > .structured-table-boxed')).not.toBeNull();
286
+ expect(css()).toMatch(/\.structured-table-box-boxed \{[^}]*padding: 1vw 2vw 1vw 2vw;[^}]*margin: 0 -2vw 0 -2vw;[^}]*border-radius: 0\.5vw;/);
287
+ expect(css()).toMatch(/\.structured-table-box-boxed \{\s*background-color: oklch/);
288
+ });
289
+
263
290
  it('sets a cell\'s ranges in their styles, as a text block\'s, and draws a list in a cell with the list styles once', () => {
264
291
  const listed = block(StructuredBlockType.Table, 'listed', {
265
292
  kind: 'cells',
@@ -81,7 +81,7 @@ export const CodeEmbedItem: FC<ItemProps<TCodeEmbedItem>> = ({ item, sectionId,
81
81
  }, [isInteractive, onVisibilityChange]);
82
82
 
83
83
  return (
84
- <LinkWrapper url={item.link?.url} target={item.link?.target}>
84
+ <LinkWrapper url={item.link?.url} target={item.link?.target} download={item.link?.download}>
85
85
  <div
86
86
  className={`embed-wrapper-${item.id}`}
87
87
  style={{
@@ -44,6 +44,7 @@ export const ComponentItem: FC<ItemProps<TComponentItem>> = ({ item, sectionId,
44
44
  <LinkWrapper
45
45
  url={item.link?.url}
46
46
  target={item.link?.target}
47
+ download={item.link?.download}
47
48
  // Let the component define its own hit area (e.g. rounded button),
48
49
  // so empty space around it does not activate the link.
49
50
  style={hasLink ? { pointerEvents: 'none' } : undefined}
@@ -45,7 +45,7 @@ export const CompoundItem: FC<ItemProps<TCompoundItem>> = ({ item, sectionId, on
45
45
  }, 0);
46
46
  }, [itemIds, item.id]);
47
47
  return (
48
- <LinkWrapper url={item.link?.url} target={item.link?.target}>
48
+ <LinkWrapper url={item.link?.url} target={item.link?.target} download={item.link?.download}>
49
49
  <>
50
50
  <div
51
51
  className={`compound-${item.id}`}
@@ -103,7 +103,7 @@ export const VimeoEmbedItem: FC<ItemProps<TVimeoEmbedItem>> = ({ item, sectionId
103
103
  }, [interactionCtrl, vimeoPlayer]);
104
104
 
105
105
  return (
106
- <LinkWrapper url={item.link?.url} target={item.link?.target}>
106
+ <LinkWrapper url={item.link?.url} target={item.link?.target} download={item.link?.download}>
107
107
  <div
108
108
  className={`embed-video-wrapper-${item.id}`}
109
109
  ref={setRef}
@@ -113,7 +113,7 @@ export const YoutubeEmbedItem: FC<ItemProps<TYoutubeEmbedItem>> = ({ item, secti
113
113
  }, [interactionCtrl, player]);
114
114
 
115
115
  return (
116
- <LinkWrapper url={item.link?.url} target={item.link?.target}>
116
+ <LinkWrapper url={item.link?.url} target={item.link?.target} download={item.link?.download}>
117
117
  <div
118
118
  className={`embed-youtube-video-wrapper-${item.id}`}
119
119
  onMouseEnter={() => {
@@ -85,7 +85,7 @@ export const ImageItem: FC<ItemProps<TImageItem>> = ({ item, sectionId, onResize
85
85
  onVisibilityChange?.(isInteractive);
86
86
  }, [isInteractive, onVisibilityChange]);
87
87
  return (
88
- <LinkWrapper url={item.link?.url} target={item.link?.target}>
88
+ <LinkWrapper url={item.link?.url} target={item.link?.target} download={item.link?.download}>
89
89
  <>
90
90
  <div
91
91
  className={`image-wrapper-${item.id}`}
@@ -115,7 +115,7 @@ export const VideoItem: FC<ItemProps<TVideoItem>> = ({ item, sectionId, onResize
115
115
  }, [layoutParams, videoRef, ref, userPaused, isVideoInteracted]);
116
116
 
117
117
  return (
118
- <LinkWrapper url={item.link?.url} target={item.link?.target}>
118
+ <LinkWrapper url={item.link?.url} target={item.link?.target} download={item.link?.download}>
119
119
  <div
120
120
  className={`video-wrapper-${item.id}`}
121
121
  ref={setRef}
@@ -46,7 +46,7 @@ export const GroupItem: FC<ItemProps<TGroupItem>> = ({ item, sectionId, onResize
46
46
  }, 0);
47
47
  }, [itemIds, item.id]);
48
48
  return (
49
- <LinkWrapper url={item.link?.url} target={item.link?.target}>
49
+ <LinkWrapper url={item.link?.url} target={item.link?.target} download={item.link?.download}>
50
50
  <>
51
51
  <div
52
52
  className={`group-${item.id}`}