@cntrl-site/sdk-nextjs 1.11.0-2 → 1.11.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 (51) hide show
  1. package/jest.config.js +4 -1
  2. package/lib/common/useComponentElement.js +40 -0
  3. package/lib/common/useLazyVideo.js +102 -0
  4. package/lib/components/Head.js +3 -3
  5. package/lib/components/Navigation/NavigationComponent.js +5 -4
  6. package/lib/components/Section/SectionVideo.js +4 -2
  7. package/lib/components/StructuredBlockItem/StructuredBlockItem.js +4 -4
  8. package/lib/components/StructuredBlockItem/StructuredCode/StructuredCode.js +5 -1
  9. package/lib/components/StructuredBlockItem/StructuredComponent/StructuredComponent.js +6 -5
  10. package/lib/components/StructuredBlockItem/StructuredEmbed/StructuredYoutubeEmbed.js +13 -1
  11. package/lib/components/StructuredBlockItem/StructuredImage/StructuredImage.js +3 -1
  12. package/lib/components/StructuredBlockItem/StructuredRichText/StructuredRichText.js +5 -5
  13. package/lib/components/StructuredBlockItem/StructuredTable/StructuredTable.js +102 -0
  14. package/lib/components/StructuredBlockItem/StructuredVideo/StructuredVideo.js +6 -7
  15. package/lib/components/StructuredBlockItem/blocksMap.js +7 -5
  16. package/lib/components/StructuredBlockItem/textStylesRule.js +7 -9
  17. package/lib/components/StructuredContent/StructuredContent.js +3 -2
  18. package/lib/components/StructuredContent/StructuredHeader.js +71 -23
  19. package/lib/components/items/ComponentItem/ComponentItem.js +7 -6
  20. package/lib/components/items/FileItem/VideoItem.js +3 -1
  21. package/lib/components/items/RichTextItem/useRichTextItem.js +3 -4
  22. package/lib/provider/CntrlSdkContext.js +0 -7
  23. package/lib/utils/RichTextConverter/RichTextConverter.js +8 -4
  24. package/package.json +3 -3
  25. package/src/common/useComponentElement.test.ts +71 -0
  26. package/src/common/useComponentElement.ts +48 -0
  27. package/src/common/useLazyVideo.test.tsx +215 -0
  28. package/src/common/useLazyVideo.ts +100 -0
  29. package/src/components/Head.tsx +2 -2
  30. package/src/components/Navigation/NavigationComponent.tsx +7 -4
  31. package/src/components/Section/SectionVideo.tsx +3 -2
  32. package/src/components/StructuredBlockItem/StructuredBlockItem.tsx +6 -4
  33. package/src/components/StructuredBlockItem/StructuredCode/StructuredCode.tsx +5 -1
  34. package/src/components/StructuredBlockItem/StructuredComponent/StructuredComponent.tsx +7 -4
  35. package/src/components/StructuredBlockItem/StructuredEmbed/StructuredYoutubeEmbed.tsx +12 -1
  36. package/src/components/StructuredBlockItem/StructuredImage/StructuredImage.tsx +3 -1
  37. package/src/components/StructuredBlockItem/StructuredRichText/StructuredRichText.tsx +4 -3
  38. package/src/components/StructuredBlockItem/StructuredTable/StructuredTable.tsx +118 -0
  39. package/src/components/StructuredBlockItem/StructuredVideo/StructuredVideo.tsx +7 -10
  40. package/src/components/StructuredBlockItem/blocksMap.ts +7 -6
  41. package/src/components/StructuredBlockItem/textStylesRule.ts +7 -9
  42. package/src/components/StructuredContent/StructuredContent.test.tsx +141 -14
  43. package/src/components/StructuredContent/StructuredContent.tsx +3 -2
  44. package/src/components/StructuredContent/StructuredHeader.tsx +78 -24
  45. package/src/components/items/ComponentItem/ComponentItem.tsx +8 -5
  46. package/src/components/items/FileItem/VideoItem.tsx +3 -2
  47. package/src/components/items/RichTextItem/RichTextItem.tsx +1 -0
  48. package/src/components/items/RichTextItem/useRichTextItem.ts +3 -4
  49. package/src/provider/CntrlSdkContext.ts +1 -8
  50. package/src/utils/RichTextConverter/RichTextConverter.test.tsx +6 -4
  51. package/src/utils/RichTextConverter/RichTextConverter.tsx +9 -4
@@ -14,7 +14,8 @@ const StructuredHeader_1 = require("./StructuredHeader");
14
14
  /**
15
15
  * A section's blocks, one under another across the section's whole width: a block drawn from a
16
16
  * preset is placed on the content grid by its own area. A content-based section's header comes
17
- * first, drawing the blocks it points at, which the stack leaves out.
17
+ * first, drawing the blocks it points at, which the stack leaves out; only the header keeps a gap
18
+ * above it there, where a default section's blocks keep theirs.
18
19
  */
19
20
  const StructuredContent = ({ section }) => {
20
21
  const reactId = (0, react_1.useId)();
@@ -28,7 +29,7 @@ const StructuredContent = ({ section }) => {
28
29
  return null;
29
30
  return ((0, jsx_runtime_1.jsxs)("div", { className: `structured-content-${section.id}`, children: [header && (0, jsx_runtime_1.jsx)(StructuredHeader_1.StructuredHeader, { header: header, blocks: section.structuredContent, readingWidth: readingWidth }), section.structuredContent
30
31
  .filter(block => !headerElementIds.includes(block.id))
31
- .map(block => (0, jsx_runtime_1.jsx)(StructuredBlockItem_1.StructuredBlockItem, { block: block, readingWidth: readingWidth }, block.id)), (0, jsx_runtime_1.jsx)(style_1.default, { id: id, children: `
32
+ .map(block => (0, jsx_runtime_1.jsx)(StructuredBlockItem_1.StructuredBlockItem, { block: block, readingWidth: readingWidth, hasGap: section.type !== 'content-based' }, block.id)), (0, jsx_runtime_1.jsx)(style_1.default, { id: id, children: `
32
33
  .structured-content-${section.id} {
33
34
  display: flex;
34
35
  flex-direction: column;
@@ -12,18 +12,25 @@ const useCntrlContext_1 = require("../../provider/useCntrlContext");
12
12
  const blockPlacement_1 = require("../StructuredBlockItem/blockPlacement");
13
13
  const blocksMap_1 = require("../StructuredBlockItem/blocksMap");
14
14
  const TEXT_KINDS = ['title', 'subtitle', 'date'];
15
+ // an element a header stored before its kind was ordered goes last, not first
16
+ function orderOf(order, kind) {
17
+ const index = order.indexOf(kind);
18
+ return index === -1 ? order.length : index;
19
+ }
15
20
  /**
16
21
  * A content-based section's header, drawn first. Variant A draws the key image full width with the
17
- * other elements on its bottom edge, the image covering a share of the viewport's height if set to;
18
- * variant B flows the shown elements in order, each placed as in the stack. The variant, the order
19
- * and what is shown are a layout's, so every element is drawn once and arranged per layout.
22
+ * other elements on its bottom edge, the image covering a share of the viewport's height if set to,
23
+ * and staying put on the screen while the header scrolls over it if set to; variant B flows the
24
+ * shown elements in order, each placed as in the stack. The variant, the order and what is shown
25
+ * are a layout's, so every element is drawn once and arranged per layout.
20
26
  */
21
27
  const StructuredHeader = ({ header, blocks, readingWidth }) => {
22
28
  const reactId = (0, react_1.useId)();
23
29
  const { layouts } = (0, useCntrlContext_1.useCntrlContext)();
24
30
  const elementOf = (kind) => blocks.find(block => block.id === header.commonParams[kind]);
25
31
  const image = elementOf('image');
26
- const hasImage = (image === null || image === void 0 ? void 0 : image.type) === sdk_1.StructuredBlockType.HeaderImage && Boolean(image.commonParams.url);
32
+ const imageUrl = (image === null || image === void 0 ? void 0 : image.type) === sdk_1.StructuredBlockType.HeaderImage ? image.commonParams.url : '';
33
+ const hasImage = Boolean(imageUrl);
27
34
  const texts = TEXT_KINDS.flatMap((kind) => {
28
35
  const block = elementOf(kind);
29
36
  return block ? [{ kind, block }] : [];
@@ -31,44 +38,84 @@ const StructuredHeader = ({ header, blocks, readingWidth }) => {
31
38
  const headerClass = `structured-header-${header.id}`;
32
39
  const stackClass = `structured-header-stack-${header.id}`;
33
40
  const elementClass = (block) => `structured-header-element-${block.id}`;
34
- const renderElement = (block) => {
35
- const BlockComponent = blocksMap_1.blocksMap[block.type];
36
- return ((0, jsx_runtime_1.jsx)("div", { className: elementClass(block), children: (0, jsx_runtime_1.jsx)(BlockComponent, { block: block, readingWidth: readingWidth }) }, block.id));
41
+ const pinClass = (block, part = '') => `structured-header-pin${part}-${block.id}`;
42
+ const renderElement = (block, extra) => {
43
+ var _a;
44
+ const BlockComponent = (_a = blocksMap_1.blocksMap[block.type]) !== null && _a !== void 0 ? _a : blocksMap_1.UnknownBlock;
45
+ return ((0, jsx_runtime_1.jsxs)("div", { className: elementClass(block), children: [(0, jsx_runtime_1.jsx)(BlockComponent, { block: block, readingWidth: readingWidth }), extra] }, block.id));
37
46
  };
47
+ // a sticky backdrop, the way a section's fixed background is drawn: a screen-tall frame stuck
48
+ // inside a track a screen longer at each end, clipped to the header; the picture itself only
49
+ // sizes the header then
50
+ const renderPin = (block) => ((0, jsx_runtime_1.jsx)("div", { className: pinClass(block), children: (0, jsx_runtime_1.jsx)("div", { className: pinClass(block, '-track'), children: (0, jsx_runtime_1.jsx)("div", { className: pinClass(block, '-frame'), style: { backgroundImage: `url(${imageUrl})` } }) }) }));
51
+ const pinStyles = (block) => `
52
+ .${pinClass(block)} {
53
+ position: absolute;
54
+ inset: 0;
55
+ overflow: clip;
56
+ pointer-events: none;
57
+ }
58
+ .${pinClass(block, '-track')} {
59
+ position: relative;
60
+ width: 100%;
61
+ height: calc(100% + 200vh);
62
+ transform: translateY(-100vh);
63
+ }
64
+ .${pinClass(block, '-frame')} {
65
+ position: sticky;
66
+ top: 100vh;
67
+ width: 100%;
68
+ height: 100vh;
69
+ background-repeat: no-repeat;
70
+ }
71
+ `;
38
72
  const elementStyles = (kind, block) => (0, sdk_1.getLayoutStyles)(layouts, [header.layoutParams, block.area, block.layoutParams], ([layoutParams, area, blockLayoutParams]) => {
73
+ var _a;
39
74
  const isBackdrop = kind === 'image' && layoutParams.variant === 'A';
40
75
  const isHidden = !isBackdrop && layoutParams.hiddenElements.includes(kind);
41
76
  const isCover = isBackdrop && layoutParams.imageFit === 'cover';
77
+ const isSticky = isBackdrop && Boolean(layoutParams.stickyImage);
78
+ // every value is written on every layout: the media queries stack upward, so a layout's
79
+ // backdrop or cover would otherwise carry into the larger layouts drawn another way
42
80
  return (`
43
81
  .${elementClass(block)} {
44
82
  display: ${isHidden ? 'none' : 'block'};
45
83
  position: relative;
46
- order: ${layoutParams.order.indexOf(kind)};
84
+ order: ${orderOf(layoutParams.order, kind)};
47
85
  ${isBackdrop
48
86
  ? `width: 100%; left: 0; height: ${isCover ? '100%' : 'auto'}; padding: 0;`
49
87
  : (0, blockPlacement_1.blockPlacement)(area, blockLayoutParams)}
50
88
  }
51
- ${isBackdrop ? `
52
- .${elementClass(block)} .structured-caption-${block.id} {
53
- display: none;
54
- }
55
- ` : ''}
56
- ${isCover ? `
57
- .${elementClass(block)} .structured-header-image-${block.id},
58
- .${elementClass(block)} .structured-header-picture-${block.id} {
59
- height: 100%;
60
- }
61
- .${elementClass(block)} .structured-header-picture-${block.id} {
62
- object-fit: cover;
63
- }
64
- ` : ''}
89
+ .${elementClass(block)} .structured-caption-${block.id} {
90
+ display: ${isBackdrop ? 'none' : 'block'};
91
+ }
92
+ .${elementClass(block)} .structured-header-image-${block.id},
93
+ .${elementClass(block)} .structured-header-picture-${block.id} {
94
+ height: ${isCover ? '100%' : 'auto'};
95
+ }
96
+ .${elementClass(block)} .structured-header-picture-${block.id} {
97
+ object-fit: ${isCover ? 'cover' : 'fill'};
98
+ visibility: ${isSticky ? 'hidden' : 'visible'};
99
+ }
100
+ ${kind === 'image'
101
+ ? `
102
+ .${pinClass(block)} {
103
+ display: ${isSticky ? 'block' : 'none'};
104
+ }
105
+ .${pinClass(block, '-frame')} {
106
+ background-size: ${isCover ? 'cover' : '100% auto'};
107
+ background-position: ${isCover ? 'center' : 'top center'};
108
+ opacity: ${(_a = blockLayoutParams === null || blockLayoutParams === void 0 ? void 0 : blockLayoutParams.opacity) !== null && _a !== void 0 ? _a : 1};
109
+ }`
110
+ : ''}
65
111
  `);
66
112
  });
67
- return ((0, jsx_runtime_1.jsxs)("div", { className: headerClass, children: [image && renderElement(image), (0, jsx_runtime_1.jsx)("div", { className: stackClass, children: texts.map(({ block }) => renderElement(block)) }), (0, jsx_runtime_1.jsx)(style_1.default, { id: `${reactId}-header-${header.id}`, children: `
113
+ return ((0, jsx_runtime_1.jsxs)("div", { className: headerClass, children: [image && renderElement(image, hasImage && renderPin(image)), (0, jsx_runtime_1.jsx)("div", { className: stackClass, children: texts.map(({ block }) => renderElement(block)) }), (0, jsx_runtime_1.jsx)(style_1.default, { id: `${reactId}-header-${header.id}`, children: `
68
114
  .${headerClass} {
69
115
  position: relative;
70
116
  width: 100%;
71
117
  }
118
+ ${image && hasImage ? pinStyles(image) : ''}
72
119
  ${(0, sdk_1.getLayoutStyles)(layouts, [header.layoutParams, header.area], ([layoutParams, area]) => {
73
120
  var _a;
74
121
  const isA = layoutParams.variant === 'A';
@@ -78,6 +125,7 @@ const StructuredHeader = ({ header, blocks, readingWidth }) => {
78
125
  display: ${isA ? 'block' : 'flex'};
79
126
  flex-direction: column;
80
127
  z-index: ${(_a = area === null || area === void 0 ? void 0 : area.zIndex) !== null && _a !== void 0 ? _a : 0};
128
+ margin-top: ${(area === null || area === void 0 ? void 0 : area.paddingTop) ? `${area.paddingTop * 100}vw` : 0};
81
129
  height: ${isCover ? `${layoutParams.coverHeight * 100}vh` : 'auto'};
82
130
  height: ${isCover ? `${layoutParams.coverHeight * 100}svh` : 'auto'};
83
131
  }
@@ -17,6 +17,7 @@ const useLayoutContext_1 = require("../../useLayoutContext");
17
17
  const useItemGeometry_1 = require("../../../ItemGeometry/useItemGeometry");
18
18
  const LinkWrapper_1 = require("../LinkWrapper");
19
19
  const mergeComponentSettings_1 = require("../../../utils/mergeComponentSettings");
20
+ const useComponentElement_1 = require("../../../common/useComponentElement");
20
21
  const ComponentItem = ({ item, sectionId, onResize, interactionCtrl }) => {
21
22
  var _a, _b, _c, _d, _e, _f, _g, _h, _j;
22
23
  const sdk = (0, useCntrlContext_1.useCntrlContext)();
@@ -26,7 +27,8 @@ const ComponentItem = ({ item, sectionId, onResize, interactionCtrl }) => {
26
27
  const fallbackLayout = (_a = layouts[0]) === null || _a === void 0 ? void 0 : _a.id;
27
28
  const effectiveLayout = layout !== null && layout !== void 0 ? layout : fallbackLayout;
28
29
  const layoutValues = [item.area, item.layoutParams];
29
- const component = sdk.getComponent(item.commonParams.componentId);
30
+ const { Element, isPending, isFailed } = (0, useComponentElement_1.useComponentElement)(item.commonParams.componentId);
31
+ const keepsServerMarkup = isPending || isFailed;
30
32
  const [ref, setRef] = (0, react_1.useState)(null);
31
33
  const { opacity: itemOpacity, blur: itemBlur } = (0, useComponentItem_1.useComponentItem)(item, sectionId);
32
34
  (0, useRegisterResize_1.useRegisterResize)(ref, onResize);
@@ -35,7 +37,6 @@ const ComponentItem = ({ item, sectionId, onResize, interactionCtrl }) => {
35
37
  const angle = (0, getStyleFromItemStateAndParams_1.getStyleFromItemStateAndParams)((_b = stateParams === null || stateParams === void 0 ? void 0 : stateParams.styles) === null || _b === void 0 ? void 0 : _b.angle, itemAngle);
36
38
  const opacity = (0, getStyleFromItemStateAndParams_1.getStyleFromItemStateAndParams)((_c = stateParams === null || stateParams === void 0 ? void 0 : stateParams.styles) === null || _c === void 0 ? void 0 : _c.opacity, itemOpacity);
37
39
  const blur = (0, getStyleFromItemStateAndParams_1.getStyleFromItemStateAndParams)((_d = stateParams === null || stateParams === void 0 ? void 0 : stateParams.styles) === null || _d === void 0 ? void 0 : _d.blur, itemBlur);
38
- const Element = component ? component.element : undefined;
39
40
  const layoutParameters = effectiveLayout ? (_e = item.layoutParams[effectiveLayout]) === null || _e === void 0 ? void 0 : _e.parameters : undefined;
40
41
  const commonParameters = item.commonParams.parameters;
41
42
  const parameters = layoutParameters ? Object.assign(Object.assign({}, layoutParameters), { settings: (0, mergeComponentSettings_1.mergeComponentSettings)(layoutParameters.settings, commonParameters === null || commonParameters === void 0 ? void 0 : commonParameters.settings) }) : undefined;
@@ -43,12 +44,12 @@ const ComponentItem = ({ item, sectionId, onResize, interactionCtrl }) => {
43
44
  return ((0, jsx_runtime_1.jsx)(LinkWrapper_1.LinkWrapper, { url: (_g = item.link) === null || _g === void 0 ? void 0 : _g.url, target: (_h = item.link) === null || _h === void 0 ? void 0 : _h.target,
44
45
  // Let the component define its own hit area (e.g. rounded button),
45
46
  // so empty space around it does not activate the link.
46
- style: hasLink ? { pointerEvents: 'none' } : undefined, children: (0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("div", { className: `custom-component-${item.id}`, ref: setRef, style: Object.assign(Object.assign(Object.assign(Object.assign({}, (opacity !== undefined
47
- ? { opacity: layout == null ? 0 : opacity }
48
- : layout == null ? { opacity: 0 } : {})), (angle !== undefined ? { transform: `rotate(${angle}deg)` } : {})), (blur !== undefined && blur !== 0 ? { filter: `blur(${blur * 100}vw)` } : {})), { willChange: blur !== 0 && blur !== undefined ? 'transform' : 'unset', transition: (_j = stateParams === null || stateParams === void 0 ? void 0 : stateParams.transition) !== null && _j !== void 0 ? _j : 'none' }), children: parameters && Element && ((0, jsx_runtime_1.jsx)(Element, Object.assign({ metadata: {
47
+ style: hasLink ? { pointerEvents: 'none' } : undefined, children: (0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("div", Object.assign({ className: `custom-component-${item.id}`, ref: setRef, style: Object.assign(Object.assign(Object.assign(Object.assign({}, (opacity !== undefined
48
+ ? { opacity: layout == null || isPending ? 0 : opacity }
49
+ : layout == null || isPending ? { opacity: 0 } : {})), (angle !== undefined ? { transform: `rotate(${angle}deg)` } : {})), (blur !== undefined && blur !== 0 ? { filter: `blur(${blur * 100}vw)` } : {})), { willChange: blur !== 0 && blur !== undefined ? 'transform' : 'unset', transition: (_j = stateParams === null || stateParams === void 0 ? void 0 : stateParams.transition) !== null && _j !== void 0 ? _j : 'none' }) }, (keepsServerMarkup ? useComponentElement_1.pendingElementProps : {}), { children: keepsServerMarkup ? null : parameters && Element && ((0, jsx_runtime_1.jsx)(Element, Object.assign({ metadata: {
49
50
  itemId: item.id,
50
51
  submitUrl: sdk.getSubmitUrl(commonParameters === null || commonParameters === void 0 ? void 0 : commonParameters.pluginConfigId)
51
- }, portalId: "component-portal", content: item.commonParams.content }, parameters, { hasLink: hasLink }))) }), (0, jsx_runtime_1.jsx)(style_1.default, { id: item.id, children: `
52
+ }, portalId: "component-portal", content: item.commonParams.content }, parameters, { hasLink: hasLink }))) }), keepsServerMarkup ? 'pending' : 'ready'), (0, jsx_runtime_1.jsx)(style_1.default, { id: item.id, children: `
52
53
  .custom-component-${item.id} {
53
54
  width: 100%;
54
55
  height: 100%;
@@ -21,6 +21,7 @@ const useElementRect_1 = require("../../../utils/useElementRect");
21
21
  const useItemFXData_1 = require("../../../common/useItemFXData");
22
22
  const getFill_1 = require("../../../utils/getFill");
23
23
  const useItemGeometry_1 = require("../../../ItemGeometry/useItemGeometry");
24
+ const useLazyVideo_1 = require("../../../common/useLazyVideo");
24
25
  const VideoItem = ({ item, sectionId, onResize, interactionCtrl, onVisibilityChange }) => {
25
26
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v;
26
27
  const reactId = (0, react_1.useId)();
@@ -73,6 +74,7 @@ const VideoItem = ({ item, sectionId, onResize, interactionCtrl, onVisibilityCha
73
74
  }, width, height);
74
75
  (0, useRegisterResize_1.useRegisterResize)(ref, onResize);
75
76
  (0, useItemGeometry_1.useItemGeometry)(item.id, ref);
77
+ (0, useLazyVideo_1.useLazyVideo)(videoRef, (layoutParams === null || layoutParams === void 0 ? void 0 : layoutParams.play) === 'auto');
76
78
  const inlineStyles = Object.assign(Object.assign(Object.assign({}, (radius !== undefined ? { borderRadius: `${radius * 100}vw` } : {})), (strokeWidth !== undefined ? {
77
79
  borderWidth: `${strokeWidth * 100}vw`,
78
80
  borderColor: stroke,
@@ -101,7 +103,7 @@ const VideoItem = ({ item, sectionId, onResize, interactionCtrl, onVisibilityCha
101
103
  observer.observe(ref);
102
104
  return () => observer.disconnect();
103
105
  }, [layoutParams, videoRef, ref, userPaused, isVideoInteracted]);
104
- return ((0, jsx_runtime_1.jsxs)(LinkWrapper_1.LinkWrapper, { url: (_q = item.link) === null || _q === void 0 ? void 0 : _q.url, target: (_r = item.link) === null || _r === void 0 ? void 0 : _r.target, children: [(0, jsx_runtime_1.jsxs)("div", { className: `video-wrapper-${item.id}`, ref: setRef, style: Object.assign(Object.assign(Object.assign(Object.assign({}, (opacity !== undefined ? { opacity } : {})), (angle !== undefined ? { transform: `rotate(${angle}deg)` } : {})), (blur !== undefined ? { filter: `blur(${blur * 100}vw)` } : {})), { willChange: blur !== 0 && blur !== undefined ? 'transform' : 'unset', transition: (_s = wrapperStateParams === null || wrapperStateParams === void 0 ? void 0 : wrapperStateParams.transition) !== null && _s !== void 0 ? _s : 'none' }), children: [hasScrollPlayback && ((0, jsx_runtime_1.jsx)(ScrollPlaybackVideo_1.ScrollPlaybackVideo, { sectionId: sectionId, src: item.commonParams.url, playbackParams: scrollPlayback, style: inlineStyles, className: `video video-playback-wrapper video-${item.id}`, scrollPlaybackFrameData: item.commonParams.scrollPlaybackFrameData, frameBaseUrl: (_t = item.commonParams.scrollPlaybackFrameData) === null || _t === void 0 ? void 0 : _t.framesUrl })), hasGLEffect && isFXAllowed && ((0, jsx_runtime_1.jsx)("canvas", { style: inlineStyles, ref: fxCanvas, className: `video-canvas video-${item.id}`, width: rectWidth, height: rectHeight })), !hasScrollPlayback && !hasGLEffect && layoutParams && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("video", { poster: (_u = item.commonParams.coverUrl) !== null && _u !== void 0 ? _u : '', ref: setVideoRef, autoPlay: layoutParams.play === 'auto', preload: "auto", onClick: () => {
106
+ return ((0, jsx_runtime_1.jsxs)(LinkWrapper_1.LinkWrapper, { url: (_q = item.link) === null || _q === void 0 ? void 0 : _q.url, target: (_r = item.link) === null || _r === void 0 ? void 0 : _r.target, children: [(0, jsx_runtime_1.jsxs)("div", { className: `video-wrapper-${item.id}`, ref: setRef, style: Object.assign(Object.assign(Object.assign(Object.assign({}, (opacity !== undefined ? { opacity } : {})), (angle !== undefined ? { transform: `rotate(${angle}deg)` } : {})), (blur !== undefined ? { filter: `blur(${blur * 100}vw)` } : {})), { willChange: blur !== 0 && blur !== undefined ? 'transform' : 'unset', transition: (_s = wrapperStateParams === null || wrapperStateParams === void 0 ? void 0 : wrapperStateParams.transition) !== null && _s !== void 0 ? _s : 'none' }), children: [hasScrollPlayback && ((0, jsx_runtime_1.jsx)(ScrollPlaybackVideo_1.ScrollPlaybackVideo, { sectionId: sectionId, src: item.commonParams.url, playbackParams: scrollPlayback, style: inlineStyles, className: `video video-playback-wrapper video-${item.id}`, scrollPlaybackFrameData: item.commonParams.scrollPlaybackFrameData, frameBaseUrl: (_t = item.commonParams.scrollPlaybackFrameData) === null || _t === void 0 ? void 0 : _t.framesUrl })), hasGLEffect && isFXAllowed && ((0, jsx_runtime_1.jsx)("canvas", { style: inlineStyles, ref: fxCanvas, className: `video-canvas video-${item.id}`, width: rectWidth, height: rectHeight })), !hasScrollPlayback && !hasGLEffect && layoutParams && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)("video", { poster: (_u = item.commonParams.coverUrl) !== null && _u !== void 0 ? _u : '', ref: setVideoRef, preload: "none", onClick: () => {
105
107
  setIsVideoInteracted(true);
106
108
  }, muted: layoutParams.muted, onPlay: () => {
107
109
  setIsVideoPlaying(true);
@@ -4,9 +4,8 @@ exports.useRichTextItem = void 0;
4
4
  const RichTextConverter_1 = require("../../../utils/RichTextConverter/RichTextConverter");
5
5
  const useCntrlContext_1 = require("../../../provider/useCntrlContext");
6
6
  const richTextConverter = new RichTextConverter_1.RichTextConverter();
7
- const useRichTextItem = (item) => {
7
+ function useRichTextItem(item) {
8
8
  const { layouts } = (0, useCntrlContext_1.useCntrlContext)();
9
- const [content, styles] = richTextConverter.toHtml(item, layouts);
10
- return [content, styles];
11
- };
9
+ return richTextConverter.toHtml(item, layouts);
10
+ }
12
11
  exports.useRichTextItem = useRichTextItem;
@@ -10,7 +10,6 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.CntrlSdkContext = void 0;
13
- const components_1 = require("@cntrl-site/components");
14
13
  class CntrlSdkContext {
15
14
  constructor(customItems, customSections) {
16
15
  this.customItems = customItems;
@@ -42,7 +41,6 @@ class CntrlSdkContext {
42
41
  this._publicApiBase = publicApiBase;
43
42
  }
44
43
  this.setLayouts(project.layouts);
45
- this.setComponents(components_1.components);
46
44
  if (customComponents) {
47
45
  this.setCustomComponents(customComponents);
48
46
  }
@@ -63,11 +61,6 @@ class CntrlSdkContext {
63
61
  setLayouts(layouts) {
64
62
  this._layouts = layouts;
65
63
  }
66
- setComponents(components) {
67
- for (const component of components) {
68
- this.components.set(component.id, component);
69
- }
70
- }
71
64
  setCustomComponents(customComponents) {
72
65
  for (const [id, component] of customComponents) {
73
66
  this.components.set(id, component);
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RichTextConverter = exports.RICH_TEXT_LAYOUT_PENDING_CLASS = exports.FontStyles = void 0;
3
+ exports.RichTextConverter = exports.LIST_STYLES_ID = exports.RICH_TEXT_LAYOUT_PENDING_CLASS = exports.FontStyles = void 0;
4
4
  const jsx_runtime_1 = require("react/jsx-runtime");
5
5
  const color_1 = require("@cntrl-site/color");
6
6
  const sdk_1 = require("@cntrl-site/sdk");
@@ -17,6 +17,8 @@ const LIST_ITEM_CLASSES = {
17
17
  'unordered-list-item': 'rt-unordered-list-item',
18
18
  'ordered-list-item': 'rt-ordered-list-item'
19
19
  };
20
+ /** The id the list styles are rendered under: one copy a page, however many texts have lists. */
21
+ exports.LIST_STYLES_ID = 'cntrl-rich-text-lists';
20
22
  // a list item's marker hangs before its first line; a numbered run restarts after anything else
21
23
  const LIST_STYLES = `
22
24
  .rt-unordered-list-item,
@@ -45,6 +47,7 @@ const LIST_STYLES = `
45
47
  }
46
48
  `;
47
49
  class RichTextConverter {
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. */
48
51
  toHtml(richText, layouts, { isScaledToViewport = true } = {}) {
49
52
  var _a, _b, _c, _d;
50
53
  const { text, blocks = [] } = richText.commonParams;
@@ -63,7 +66,7 @@ class RichTextConverter {
63
66
  for (let blockIndex = 0; blockIndex < blocks.length; blockIndex++) {
64
67
  const block = blocks[blockIndex];
65
68
  const content = text.slice(block.start, block.end + 1);
66
- const entities = (_a = block.entities.sort((a, b) => a.start - b.start)) !== null && _a !== void 0 ? _a : [];
69
+ const entities = [...((_a = block.entities) !== null && _a !== void 0 ? _a : [])].sort((a, b) => a.start - b.start);
67
70
  const typeClass = hasLists ? ` ${(_b = LIST_ITEM_CLASSES[block.type]) !== null && _b !== void 0 ? _b : 'rt-paragraph'}` : '';
68
71
  if (content.length === 1) {
69
72
  const id = `rt_${richText.id}_br_${blockIndex}`;
@@ -182,10 +185,11 @@ class RichTextConverter {
182
185
  ${(0, sdk_1.getLayoutMediaQuery)(l.id, layouts)} {
183
186
  ${styleRules[l.id].join('\n')}
184
187
  }
185
- `).join('\n') + (hasLists ? LIST_STYLES : '');
188
+ `).join('\n');
186
189
  return [
187
190
  root,
188
- styles
191
+ styles,
192
+ hasLists ? LIST_STYLES : undefined
189
193
  ];
190
194
  }
191
195
  serializeRanges(ranges) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cntrl-site/sdk-nextjs",
3
- "version": "1.11.0-2",
3
+ "version": "1.11.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.97-8",
33
+ "@cntrl-site/components": "^1.0.106",
34
34
  "@cntrl-site/effects": "^1.4.2",
35
- "@cntrl-site/sdk": "^1.29.0-2",
35
+ "@cntrl-site/sdk": "^1.29.1",
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,71 @@
1
+ import { renderHook, waitFor } from '@testing-library/react';
2
+ import { components } from '@cntrl-site/components';
3
+ import * as elements from '@cntrl-site/components/elements';
4
+ import { useComponentElement } from './useComponentElement';
5
+
6
+ jest.mock('@cntrl-site/components/elements', () => {
7
+ const actual = jest.requireActual('@cntrl-site/components/elements');
8
+ return {
9
+ ...actual,
10
+ getComponentElement: jest.fn(actual.getComponentElement),
11
+ hasComponentElementFailed: jest.fn(actual.hasComponentElementFailed),
12
+ loadComponentElement: jest.fn(actual.loadComponentElement)
13
+ };
14
+ });
15
+
16
+ const mocked = jest.mocked(elements);
17
+ const actual = jest.requireActual<typeof elements>('@cntrl-site/components/elements');
18
+
19
+ describe('useComponentElement', () => {
20
+ afterEach(() => {
21
+ jest.restoreAllMocks();
22
+ mocked.getComponentElement.mockReset().mockImplementation(actual.getComponentElement);
23
+ mocked.hasComponentElementFailed.mockReset().mockImplementation(actual.hasComponentElementFailed);
24
+ mocked.loadComponentElement.mockReset().mockImplementation(actual.loadComponentElement);
25
+ });
26
+
27
+ it('gets built-in elements synchronously from elements.node under jest', () => {
28
+ const faq = components.find(component => component.id === 'faq');
29
+ const { result } = renderHook(() => useComponentElement('faq'));
30
+ expect(result.current).toEqual({ Element: faq?.element, isPending: false, isFailed: false });
31
+ expect(mocked.loadComponentElement).not.toHaveBeenCalled();
32
+ });
33
+
34
+ it('switches from pending to failed once the load rejects, without retrying on re-render', async () => {
35
+ let failed = false;
36
+ const error = new Error('ChunkLoadError');
37
+ const consoleError = jest.spyOn(console, 'error').mockImplementation(() => undefined);
38
+ mocked.getComponentElement.mockReturnValue(undefined);
39
+ mocked.hasComponentElementFailed.mockImplementation(() => failed);
40
+ mocked.loadComponentElement.mockImplementation(() => {
41
+ failed = true;
42
+ return Promise.reject(error);
43
+ });
44
+
45
+ const { result, rerender } = renderHook(() => useComponentElement('faq'));
46
+ expect(result.current).toEqual({ Element: undefined, isPending: true, isFailed: false });
47
+
48
+ await waitFor(() => expect(result.current.isFailed).toBe(true));
49
+ expect(result.current.isPending).toBe(false);
50
+ expect(consoleError).toHaveBeenCalledWith('Failed to load component "faq":', error);
51
+ const calls = mocked.loadComponentElement.mock.calls.length;
52
+
53
+ rerender();
54
+ rerender();
55
+ expect(mocked.loadComponentElement).toHaveBeenCalledTimes(calls);
56
+ });
57
+
58
+ it('shows the element once a pending load resolves', async () => {
59
+ const faq = components.find(component => component.id === 'faq');
60
+ let loaded = false;
61
+ mocked.getComponentElement.mockImplementation(() => (loaded ? faq?.element : undefined));
62
+ mocked.loadComponentElement.mockImplementation(() => {
63
+ loaded = true;
64
+ return Promise.resolve(faq?.element);
65
+ });
66
+
67
+ const { result } = renderHook(() => useComponentElement('faq'));
68
+ expect(result.current.isPending).toBe(true);
69
+ await waitFor(() => expect(result.current).toEqual({ Element: faq?.element, isPending: false, isFailed: false }));
70
+ });
71
+ });
@@ -0,0 +1,48 @@
1
+ import { ComponentType, useEffect, useReducer } from 'react';
2
+ import {
3
+ getComponentElement,
4
+ hasComponentElement,
5
+ hasComponentElementFailed,
6
+ loadComponentElement
7
+ } from '@cntrl-site/components/elements';
8
+ import { useCntrlContext } from '../provider/useCntrlContext';
9
+
10
+ type ComponentElement = {
11
+ Element: ComponentType<any> | undefined;
12
+ isPending: boolean;
13
+ isFailed: boolean;
14
+ };
15
+
16
+ export const pendingElementProps = {
17
+ dangerouslySetInnerHTML: { __html: '' },
18
+ suppressHydrationWarning: true
19
+ };
20
+
21
+ export function useComponentElement(componentId: string): ComponentElement {
22
+ const sdk = useCntrlContext();
23
+ const [, refresh] = useReducer((count: number) => count + 1, 0);
24
+ const Element = sdk.getComponent(componentId)?.element ?? getComponentElement(componentId);
25
+ const isLoading = !Element && hasComponentElement(componentId);
26
+ const isFailed = isLoading && hasComponentElementFailed(componentId);
27
+ const isPending = isLoading && !isFailed;
28
+ if (isPending) {
29
+ loadComponentElement(componentId).catch(() => undefined);
30
+ }
31
+
32
+ useEffect(() => {
33
+ if (!isLoading) return;
34
+ let cancelled = false;
35
+ loadComponentElement(componentId)
36
+ .catch((error) => {
37
+ console.error(`Failed to load component "${componentId}":`, error);
38
+ })
39
+ .then(() => {
40
+ if (!cancelled) refresh();
41
+ });
42
+ return () => {
43
+ cancelled = true;
44
+ };
45
+ }, [componentId, isLoading]);
46
+
47
+ return { Element, isPending, isFailed };
48
+ }