@cntrl-site/sdk-nextjs 1.9.4 → 1.9.6

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 (126) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +4 -4
  3. package/TODO.md +1 -1
  4. package/eslint.config.mjs +35 -35
  5. package/jest.config.js +6 -6
  6. package/lib/common/useItemFXData.js +7 -7
  7. package/lib/components/Article.js +5 -5
  8. package/lib/components/LayoutStyle.js +4 -4
  9. package/lib/components/Section/Section.js +27 -27
  10. package/lib/components/items/CodeEmbedItem/CodeEmbedItem.js +36 -36
  11. package/lib/components/items/ComponentItem/ComponentItem.js +13 -13
  12. package/lib/components/items/CompoundItem/CompoundChild.js +20 -20
  13. package/lib/components/items/CompoundItem/CompoundItem.js +14 -14
  14. package/lib/components/items/CustomItem/CustomItem.js +9 -9
  15. package/lib/components/items/EmbedVideoItem/VimeoEmbed.js +24 -24
  16. package/lib/components/items/EmbedVideoItem/YoutubeEmbed.js +27 -27
  17. package/lib/components/items/FileItem/ImageItem.js +52 -52
  18. package/lib/components/items/FileItem/VideoItem.js +76 -76
  19. package/lib/components/items/GroupItem/GroupItem.js +14 -14
  20. package/lib/components/items/Item.js +30 -30
  21. package/lib/components/items/RectangleItem/RectangleItem.js +40 -40
  22. package/lib/components/items/RichTextItem/RichTextItem.js +22 -22
  23. package/lib/utils/RichTextConverter/RichTextConverter.js +21 -21
  24. package/package.json +59 -59
  25. package/src/common/useCurrentLayout.ts +52 -52
  26. package/src/common/useExemplary.ts +9 -9
  27. package/src/common/useItemFXData.ts +47 -47
  28. package/src/common/useKeyframeValue.ts +85 -85
  29. package/src/common/useRegisterResize.ts +16 -16
  30. package/src/components/Article.tsx +73 -73
  31. package/src/components/ArticleWrapper.tsx +21 -21
  32. package/src/components/Head.tsx +56 -56
  33. package/src/components/LayoutStyle.tsx +21 -21
  34. package/src/components/Page.tsx +33 -33
  35. package/src/components/ScrollPlaybackVideo.tsx +56 -56
  36. package/src/components/Section/Section.tsx +127 -127
  37. package/src/components/Section/SectionImage.tsx +48 -48
  38. package/src/components/Section/SectionVideo.tsx +144 -144
  39. package/src/components/Section/useSectionColor.ts +19 -19
  40. package/src/components/Section/useSectionHeightMap.ts +19 -19
  41. package/src/components/items/CodeEmbedItem/CodeEmbedItem.tsx +145 -145
  42. package/src/components/items/CodeEmbedItem/useCodeEmbedItem.ts +36 -36
  43. package/src/components/items/ComponentItem/ComponentItem.tsx +67 -67
  44. package/src/components/items/ComponentItem/useComponentItem.ts +35 -35
  45. package/src/components/items/CompoundItem/CompoundChild.tsx +150 -150
  46. package/src/components/items/CompoundItem/CompoundItem.tsx +70 -70
  47. package/src/components/items/CompoundItem/useCompoundItem.ts +21 -21
  48. package/src/components/items/CustomItem/CustomItem.tsx +48 -48
  49. package/src/components/items/EmbedVideoItem/VimeoEmbed.tsx +206 -206
  50. package/src/components/items/EmbedVideoItem/YoutubeEmbed.tsx +193 -193
  51. package/src/components/items/EmbedVideoItem/useEmbedVideoItem.ts +46 -46
  52. package/src/components/items/FileItem/ImageItem.tsx +210 -211
  53. package/src/components/items/FileItem/VideoItem.tsx +327 -328
  54. package/src/components/items/FileItem/useFileItem.ts +81 -81
  55. package/src/components/items/GroupItem/GroupItem.tsx +81 -81
  56. package/src/components/items/GroupItem/useGroupItem.ts +34 -34
  57. package/src/components/items/Item.tsx +251 -251
  58. package/src/components/items/LinkWrapper.tsx +39 -39
  59. package/src/components/items/RectangleItem/RectangleItem.tsx +199 -199
  60. package/src/components/items/RectangleItem/useRectangleItem.ts +89 -89
  61. package/src/components/items/RichTextItem/RichTextItem.tsx +107 -107
  62. package/src/components/items/RichTextItem/useRichTextItem.ts +12 -12
  63. package/src/components/items/RichTextWrapper.tsx +15 -15
  64. package/src/components/items/itemsMap.ts +28 -28
  65. package/src/components/items/useDraggable.ts +252 -252
  66. package/src/components/items/useItemAngle.ts +13 -13
  67. package/src/components/items/useItemArea.ts +35 -35
  68. package/src/components/items/useItemPointerEvents.ts +23 -23
  69. package/src/components/items/useItemScale.ts +17 -17
  70. package/src/components/items/useItemTriggers.ts +15 -15
  71. package/src/components/items/useRichTextItemValues.ts +65 -65
  72. package/src/components/items/useSizing.ts +25 -25
  73. package/src/components/items/useStickyItemTop.ts +21 -21
  74. package/src/components/useLayoutContext.ts +7 -7
  75. package/src/index.ts +24 -24
  76. package/src/interactions/CSSPropertyNameMap.ts +37 -37
  77. package/src/interactions/InteractionsRegistry.ts +380 -380
  78. package/src/interactions/ItemInteractionCtrl.ts +78 -78
  79. package/src/interactions/getTransition.ts +27 -27
  80. package/src/interactions/types.ts +36 -36
  81. package/src/interactions/useItemInteractionCtrl.ts +18 -18
  82. package/src/provider/ArticleRectContext.ts +4 -4
  83. package/src/provider/CntrlContext.ts +5 -5
  84. package/src/provider/CntrlProvider.tsx +11 -11
  85. package/src/provider/CntrlSdkContext.ts +83 -83
  86. package/src/provider/CustomItemRegistry.ts +14 -14
  87. package/src/provider/CustomItemTypes.ts +3 -3
  88. package/src/provider/CustomSectionRegistry.ts +25 -25
  89. package/src/provider/InteractionsContext.tsx +59 -59
  90. package/src/provider/Keyframes.ts +11 -11
  91. package/src/provider/KeyframesContext.ts +5 -5
  92. package/src/provider/LayoutContext.ts +3 -3
  93. package/src/provider/WebGLContextManagerContext.tsx +4 -4
  94. package/src/provider/defaultContext.ts +8 -8
  95. package/src/provider/useCntrlContext.ts +8 -8
  96. package/src/styled-jsx.d.ts +1 -1
  97. package/src/utils/Animator/Animator.ts +570 -571
  98. package/src/utils/ArticleRectManager/ArticleRectObserver.ts +93 -93
  99. package/src/utils/ArticleRectManager/useArticleRectObserver.ts +17 -17
  100. package/src/utils/ArticleRectManager/useSectionRegistry.ts +11 -11
  101. package/src/utils/EventEmitter.ts +41 -41
  102. package/src/utils/RichTextConverter/RichTextConverter.tsx +326 -326
  103. package/src/utils/ScaleAnchorMap.ts +13 -13
  104. package/src/utils/StickyManager/StickyManager.ts +23 -23
  105. package/src/utils/Youtube/YouTubeIframeApiLoader.ts +58 -58
  106. package/src/utils/Youtube/YoutubeIframeApi.ts +101 -101
  107. package/src/utils/Youtube/useYouTubeIframeApi.ts +12 -12
  108. package/src/utils/areFillsVisible/areFillsVisible.test.ts +63 -63
  109. package/src/utils/areFillsVisible/areFillsVisible.ts +37 -37
  110. package/src/utils/binSearchInsertAt.ts +33 -33
  111. package/src/utils/castObject.ts +10 -10
  112. package/src/utils/checkOverflowClipSupport.ts +13 -13
  113. package/src/utils/effects/useImageFx.ts +156 -156
  114. package/src/utils/effects/useVideoFx.ts +158 -158
  115. package/src/utils/getAnchoredItemTop.ts +12 -12
  116. package/src/utils/getCompoundBoundaryStyles.ts +60 -60
  117. package/src/utils/getFill.ts +46 -46
  118. package/src/utils/getFontFamilyValue.ts +3 -3
  119. package/src/utils/getInvertedRanges.ts +43 -43
  120. package/src/utils/getItemTopStyle.ts +14 -14
  121. package/src/utils/getStyleFromItemStateAndParams.ts +8 -8
  122. package/src/utils/getValidYoutubeUrl.ts +29 -29
  123. package/src/utils/isItemType.ts +5 -5
  124. package/src/utils/rangeMap.ts +13 -13
  125. package/src/utils/useElementRect.ts +23 -23
  126. package/cntrl-site-sdk-nextjs-1.8.40.tgz +0 -0
@@ -1,326 +1,326 @@
1
- import { ReactElement, ReactNode } from 'react';
2
- import { CntrlColor } from '@cntrl-site/color';
3
- import {
4
- getLayoutMediaQuery,
5
- TextTransform,
6
- Layout,
7
- RichTextItem,
8
- VerticalAlign,
9
- RichTextStyle,
10
- RichTextEntity
11
- } from '@cntrl-site/sdk';
12
- import { LinkWrapper } from '../../components/items/LinkWrapper';
13
- import { getFontFamilyValue } from '../getFontFamilyValue';
14
-
15
- interface StyleGroup {
16
- start: number;
17
- end: number;
18
- styles: Style[];
19
- }
20
-
21
- interface EntitiesGroup {
22
- link?: string;
23
- target?: string;
24
- stylesGroup: StyleGroup[];
25
- start: number;
26
- end: number;
27
- }
28
-
29
- interface Style {
30
- name: string;
31
- value?: string;
32
- }
33
-
34
- export const FontStyles: Record<string, Record<string, string>> = {
35
- normal: { 'font-style': 'normal' },
36
- bold: { 'font-weight': 'bold' },
37
- italic: { 'font-style': 'italic' }
38
- };
39
-
40
- export class RichTextConverter {
41
- toHtml(
42
- richText: RichTextItem,
43
- layouts: Layout[]
44
- ): [ReactNode[], string] {
45
- const { text, blocks = [] } = richText.commonParams;
46
- const root: ReactElement[] = [];
47
- const styleRules = layouts.reduce<Record<string, string[]>>((rec, layout) => {
48
- rec[layout.id] = [];
49
- return rec;
50
- }, {});
51
- const currentLineHeight = layouts.reduce<Record<string, string | undefined>>((rec, layout) => {
52
- const styles = richText.layoutParams[layout.id].rangeStyles;
53
- rec[layout.id] = styles?.find(s => s.style === 'LINEHEIGHT')?.value;
54
- return rec;
55
- }, {});
56
-
57
- for (let blockIndex = 0; blockIndex < blocks.length; blockIndex++) {
58
- const block = blocks[blockIndex];
59
- const content = text.slice(block.start, block.end + 1);
60
- const entities = block.entities!.sort((a, b) => a.start - b.start) ?? [];
61
- if (content.length === 1) {
62
- const id = `rt_${richText.id}_br_${blockIndex}`;
63
- root.push(<div key={id} className={id}><br /></div>);
64
- layouts.forEach(l => {
65
- const lhForLayout = currentLineHeight[l.id];
66
- if (lhForLayout === undefined) return;
67
- const lh = RichTextConverter.fromRangeStylesToInline({
68
- name: 'LINEHEIGHT',
69
- value: lhForLayout
70
- }, l.exemplary);
71
- styleRules[l.id].push(`.rt_${richText.id}_br_${blockIndex} {${lh}}`);
72
- });
73
- continue;
74
- }
75
- const newStylesGroup = layouts.map(({ id: layoutId }) => {
76
- const params = richText.layoutParams[layoutId];
77
- const styles = params.rangeStyles!
78
- .filter(s => s.start >= block.start && s.end <= block.end)
79
- .map(s => ({ ...s, start: s.start - block.start, end: s.end - block.start }));
80
- return ({
81
- layout: layoutId,
82
- styles: this.normalizeStyles(styles, entities)
83
- });
84
- });
85
- const sameLayouts = groupBy(newStylesGroup, (item) => this.serializeRanges(item.styles ?? []));
86
- for (const group of Object.values(sameLayouts)) {
87
- const blockClass = `rt_${richText.id}-b${blockIndex}_${layouts.map(l => group.some(g => g.layout === l.id) ? '1' : '0').join('')}`;
88
- const kids: ReactNode[] = [];
89
- layouts.forEach(l => {
90
- const ta = richText.layoutParams[l.id].textAlign;
91
- styleRules[l.id].push(`
92
- .${blockClass} {
93
- display: ${group.some(g => g.layout === l.id) ? 'block' : 'none'};
94
- text-align: ${ta};
95
- white-space: pre-wrap;
96
- overflow-wrap: break-word;
97
- }
98
- `);
99
- });
100
- const item = group[0];
101
- const entitiesGroups = this.groupEntities(entities, item.styles) ?? [];
102
- let offset = 0;
103
- for (const entity of entitiesGroups) {
104
- const entityKids: ReactNode[] = [];
105
- if (offset < entity.start) {
106
- kids.push(sliceSymbols(content, offset, entity.start));
107
- offset = entity.start;
108
- }
109
- for (const style of entity.stylesGroup) {
110
- if (offset < style.start) {
111
- entityKids.push(sliceSymbols(content, offset, style.start));
112
- }
113
- entityKids.push(
114
- <span key={style.start} className={`s-${style.start}-${style.end}`}>
115
- {sliceSymbols(content, style.start, style.end)}
116
- </span>
117
- );
118
- offset = style.end;
119
- }
120
- if (offset < entity.end) {
121
- entityKids.push(sliceSymbols(content, offset, entity.end));
122
- offset = entity.end;
123
- }
124
- if (entity.link) {
125
- kids.push(<LinkWrapper key={entity.start} url={entity.link} target={entity.target}>{entityKids}</LinkWrapper>);
126
- continue;
127
- }
128
- kids.push(...entityKids);
129
- }
130
- if (offset < getSymbolsCount(content)) {
131
- kids.push(sliceSymbols(content, offset));
132
- }
133
- for (const item of group) {
134
- const { exemplary } = layouts.find(l => l.id === item.layout)!;
135
- const entitiesGroups = this.groupEntities(entities, item.styles) ?? [];
136
- for (const entitiesGroup of entitiesGroups) {
137
- if (!entitiesGroup.stylesGroup) continue;
138
- for (const styleGroup of entitiesGroup.stylesGroup) {
139
- const lineHeight = styleGroup.styles.find(s => s.name === 'LINEHEIGHT');
140
- const color = styleGroup.styles.find(s => s.name === 'COLOR');
141
- if (lineHeight?.value) {
142
- currentLineHeight[item.layout] = lineHeight.value;
143
- }
144
- styleRules[item.layout].push(`
145
- .${blockClass} .s-${styleGroup.start}-${styleGroup.end} {
146
- ${styleGroup.styles.map(s => RichTextConverter.fromRangeStylesToInline(s, exemplary)).join('\n')}
147
- }
148
- `);
149
- if (color) {
150
- styleRules[item.layout].push(`
151
- @supports not (color: oklch(42% 0.3 90 / 1)) {
152
- .${blockClass} .s-${styleGroup.start}-${styleGroup.end} {
153
- color: ${CntrlColor.parse(getResolvedValue(color.value, 'COLOR')!).fmt('rgba')};
154
- }
155
- }
156
- `);
157
- }
158
- }
159
- }
160
- }
161
- root.push(<div key={blockClass} className={blockClass}>{kids}</div>);
162
- }
163
- }
164
- const styles = layouts.map(l => `
165
- ${getLayoutMediaQuery(l.id, layouts)} {
166
- ${styleRules[l.id].join('\n')}
167
- }
168
- `).join('\n');
169
- return [
170
- root,
171
- styles
172
- ];
173
- }
174
-
175
- private serializeRanges(ranges: { start: number; end: number; }[]): string {
176
- return ranges.map(r => `${r.start},${r.end}`).join(' ');
177
- }
178
-
179
- private normalizeStyles(styles: RichTextStyle[], entities: RichTextEntity[]): StyleGroup[] | undefined {
180
- const styleGroups: StyleGroup[] = [];
181
- const dividers = [...styles, ...entities].reduce((ds, s) => {
182
- ds.add(s.start);
183
- ds.add(s.end);
184
- return ds;
185
- }, new Set<number>());
186
- if (dividers.size === 0) return;
187
- const edges = Array.from(dividers).sort((a, b) => a - b);
188
- for (let i = 0; i < edges.length - 1; i += 1) {
189
- const start = edges[i];
190
- const end = edges[i + 1];
191
- const applied = styles.filter(s => Math.max(s.start, start) < Math.min(s.end, end));
192
- if (applied.length === 0) continue;
193
- styleGroups.push({
194
- start,
195
- end,
196
- styles: applied.map(s => ({ name: s.style, value: s.value }))
197
- });
198
- }
199
-
200
- return styleGroups;
201
- }
202
-
203
- private groupEntities(entities: RichTextEntity[], styleGroups?: StyleGroup[]): EntitiesGroup[] | undefined {
204
- const entitiesGroups: EntitiesGroup[] = [];
205
- if (!entities.length && !styleGroups) return;
206
- if (!styleGroups || styleGroups.length === 0) {
207
- const dividersSet = entities.reduce((ds, e) => {
208
- // some entities may have no data, need to filter them out
209
- // (case with deleting a section/page that was linked to)
210
- if (!e.hasOwnProperty('data')) return ds;
211
- ds.add(e.start);
212
- ds.add(e.end);
213
- return ds;
214
- }, new Set<number>([entities[0].start, entities[entities.length - 1].end]));
215
- const dividers = Array.from(dividersSet).sort((a, b) => a - b);
216
- for (let i = 0; i < dividers.length - 1; i += 1) {
217
- const start = dividers[i];
218
- const end = dividers[i + 1];
219
- const entity = entities.find(e => e.start === start);
220
- entitiesGroups.push({
221
- stylesGroup: [],
222
- start,
223
- end,
224
- ...(entity && { link: entity.data?.url ?? '', target: entity.data?.target ?? '_self' })
225
- });
226
- }
227
- return entitiesGroups;
228
- }
229
- if (entities.length === 0) {
230
- entitiesGroups.push({
231
- stylesGroup: styleGroups,
232
- start: styleGroups[0].start,
233
- end: styleGroups[styleGroups.length - 1].end
234
- });
235
- return entitiesGroups;
236
- }
237
- const start = entities[0].start < styleGroups[0].start ? entities[0].start : styleGroups[0].start;
238
- const end = entities[entities.length - 1].end > styleGroups[styleGroups.length - 1].end ? entities[entities.length - 1].end : styleGroups[styleGroups.length - 1].end;
239
- const entitiesDividers = entities.reduce((ds, e) => {
240
- if (!e.hasOwnProperty('data')) return ds;
241
- ds.add(e.start);
242
- ds.add(e.end);
243
- return ds;
244
- }, new Set<number>([start, end]));
245
- const entityDividers = Array.from(entitiesDividers).sort((a, b) => a - b);
246
-
247
- for (let i = 0; i < entityDividers.length - 1; i += 1) {
248
- const start = entityDividers[i];
249
- const end = entityDividers[i + 1];
250
- const entity = entities.find(e => e.start === start);
251
- entitiesGroups.push({
252
- stylesGroup: styleGroups.filter(s => s.start >= start && s.end <= end),
253
- start,
254
- end,
255
- ...(entity && { link: entity.data?.url ?? '', target: entity.data?.target ?? '_self' })
256
- });
257
- }
258
-
259
- return entitiesGroups;
260
- }
261
-
262
- private static fromRangeStylesToInline(draftStyle: Style, exemplary: number): string {
263
- const { value, name } = draftStyle;
264
- const map: Record<string, Record<string, string | undefined>> = {
265
- COLOR: { color: getResolvedValue(value, name) },
266
- TYPEFACE: { 'font-family': `${getFontFamilyValue(value!)}` },
267
- FONTSTYLE: value ? { ...FontStyles[value] } : {},
268
- FONTWEIGHT: { 'font-weight': value },
269
- FONTSIZE: { 'font-size': `${Number.parseFloat(value!) * exemplary}px` },
270
- LINEHEIGHT: { 'line-height': `${Number.parseFloat(value!) * exemplary}px` },
271
- LETTERSPACING: { 'letter-spacing': `${Number.parseFloat(value!) * exemplary}px` },
272
- WORDSPACING: { 'word-spacing': `${Number.parseFloat(value!) * exemplary}px` },
273
- TEXTTRANSFORM: value ? { 'text-transform': value as TextTransform } : { 'text-transform': TextTransform.None },
274
- VERTICALALIGN: value ? { 'vertical-align': value as VerticalAlign } : { 'vertical-align': VerticalAlign.Unset },
275
- TEXTDECORATION: { 'text-decoration': value },
276
- FONTVARIANT: { 'font-variant': value }
277
- };
278
- const css = map[name];
279
- if (!css) {
280
- return '';
281
- }
282
- return Object.entries(css).filter(([, value]) => !!value).map(([prop, value]) => `${prop}: ${value};`).join('\n');
283
- }
284
- }
285
-
286
- function groupBy<I>(items: I[], getKey: (item: I) => PropertyKey): Record<PropertyKey, I[]> {
287
- const groups: Record<PropertyKey, I[]> = {};
288
- for (const item of items) {
289
- const key = getKey(item);
290
- if (!groups[key]) {
291
- groups[key] = [];
292
- }
293
- groups[key]!.push(item);
294
- }
295
- return groups;
296
- }
297
-
298
- function getResolvedValue(value: string | undefined, name: string) {
299
- if (name !== 'COLOR') return value;
300
- return value ? CntrlColor.parse(value).toCss() : value;
301
- }
302
-
303
- function sliceSymbols(text: string, start: number, end: number = Number.NaN): string {
304
- let startOffset = Number.NaN;
305
- let endOffset = 0;
306
- let count = -1;
307
- for (const ch of text) {
308
- count += 1;
309
- if (count === start) {
310
- startOffset = endOffset;
311
- }
312
- if (count === end) break;
313
- endOffset += ch.length;
314
- }
315
- if (isNaN(startOffset)) return '';
316
- return text.slice(startOffset, endOffset);
317
- }
318
-
319
- function getSymbolsCount(input: string): number {
320
- let count = 0;
321
- let ch: string;
322
- for (ch of input) {
323
- count += 1;
324
- }
325
- return count;
326
- }
1
+ import { ReactElement, ReactNode } from 'react';
2
+ import { CntrlColor } from '@cntrl-site/color';
3
+ import {
4
+ getLayoutMediaQuery,
5
+ TextTransform,
6
+ Layout,
7
+ RichTextItem,
8
+ VerticalAlign,
9
+ RichTextStyle,
10
+ RichTextEntity
11
+ } from '@cntrl-site/sdk';
12
+ import { LinkWrapper } from '../../components/items/LinkWrapper';
13
+ import { getFontFamilyValue } from '../getFontFamilyValue';
14
+
15
+ interface StyleGroup {
16
+ start: number;
17
+ end: number;
18
+ styles: Style[];
19
+ }
20
+
21
+ interface EntitiesGroup {
22
+ link?: string;
23
+ target?: string;
24
+ stylesGroup: StyleGroup[];
25
+ start: number;
26
+ end: number;
27
+ }
28
+
29
+ interface Style {
30
+ name: string;
31
+ value?: string;
32
+ }
33
+
34
+ export const FontStyles: Record<string, Record<string, string>> = {
35
+ normal: { 'font-style': 'normal' },
36
+ bold: { 'font-weight': 'bold' },
37
+ italic: { 'font-style': 'italic' }
38
+ };
39
+
40
+ export class RichTextConverter {
41
+ toHtml(
42
+ richText: RichTextItem,
43
+ layouts: Layout[]
44
+ ): [ReactNode[], string] {
45
+ const { text, blocks = [] } = richText.commonParams;
46
+ const root: ReactElement[] = [];
47
+ const styleRules = layouts.reduce<Record<string, string[]>>((rec, layout) => {
48
+ rec[layout.id] = [];
49
+ return rec;
50
+ }, {});
51
+ const currentLineHeight = layouts.reduce<Record<string, string | undefined>>((rec, layout) => {
52
+ const styles = richText.layoutParams[layout.id].rangeStyles;
53
+ rec[layout.id] = styles?.find(s => s.style === 'LINEHEIGHT')?.value;
54
+ return rec;
55
+ }, {});
56
+
57
+ for (let blockIndex = 0; blockIndex < blocks.length; blockIndex++) {
58
+ const block = blocks[blockIndex];
59
+ const content = text.slice(block.start, block.end + 1);
60
+ const entities = block.entities!.sort((a, b) => a.start - b.start) ?? [];
61
+ if (content.length === 1) {
62
+ const id = `rt_${richText.id}_br_${blockIndex}`;
63
+ root.push(<div key={id} className={id}><br /></div>);
64
+ layouts.forEach(l => {
65
+ const lhForLayout = currentLineHeight[l.id];
66
+ if (lhForLayout === undefined) return;
67
+ const lh = RichTextConverter.fromRangeStylesToInline({
68
+ name: 'LINEHEIGHT',
69
+ value: lhForLayout
70
+ }, l.exemplary);
71
+ styleRules[l.id].push(`.rt_${richText.id}_br_${blockIndex} {${lh}}`);
72
+ });
73
+ continue;
74
+ }
75
+ const newStylesGroup = layouts.map(({ id: layoutId }) => {
76
+ const params = richText.layoutParams[layoutId];
77
+ const styles = params.rangeStyles!
78
+ .filter(s => s.start >= block.start && s.end <= block.end)
79
+ .map(s => ({ ...s, start: s.start - block.start, end: s.end - block.start }));
80
+ return ({
81
+ layout: layoutId,
82
+ styles: this.normalizeStyles(styles, entities)
83
+ });
84
+ });
85
+ const sameLayouts = groupBy(newStylesGroup, (item) => this.serializeRanges(item.styles ?? []));
86
+ for (const group of Object.values(sameLayouts)) {
87
+ const blockClass = `rt_${richText.id}-b${blockIndex}_${layouts.map(l => group.some(g => g.layout === l.id) ? '1' : '0').join('')}`;
88
+ const kids: ReactNode[] = [];
89
+ layouts.forEach(l => {
90
+ const ta = richText.layoutParams[l.id].textAlign;
91
+ styleRules[l.id].push(`
92
+ .${blockClass} {
93
+ display: ${group.some(g => g.layout === l.id) ? 'block' : 'none'};
94
+ text-align: ${ta};
95
+ white-space: pre-wrap;
96
+ overflow-wrap: break-word;
97
+ }
98
+ `);
99
+ });
100
+ const item = group[0];
101
+ const entitiesGroups = this.groupEntities(entities, item.styles) ?? [];
102
+ let offset = 0;
103
+ for (const entity of entitiesGroups) {
104
+ const entityKids: ReactNode[] = [];
105
+ if (offset < entity.start) {
106
+ kids.push(sliceSymbols(content, offset, entity.start));
107
+ offset = entity.start;
108
+ }
109
+ for (const style of entity.stylesGroup) {
110
+ if (offset < style.start) {
111
+ entityKids.push(sliceSymbols(content, offset, style.start));
112
+ }
113
+ entityKids.push(
114
+ <span key={style.start} className={`s-${style.start}-${style.end}`}>
115
+ {sliceSymbols(content, style.start, style.end)}
116
+ </span>
117
+ );
118
+ offset = style.end;
119
+ }
120
+ if (offset < entity.end) {
121
+ entityKids.push(sliceSymbols(content, offset, entity.end));
122
+ offset = entity.end;
123
+ }
124
+ if (entity.link) {
125
+ kids.push(<LinkWrapper key={entity.start} url={entity.link} target={entity.target}>{entityKids}</LinkWrapper>);
126
+ continue;
127
+ }
128
+ kids.push(...entityKids);
129
+ }
130
+ if (offset < getSymbolsCount(content)) {
131
+ kids.push(sliceSymbols(content, offset));
132
+ }
133
+ for (const item of group) {
134
+ const { exemplary } = layouts.find(l => l.id === item.layout)!;
135
+ const entitiesGroups = this.groupEntities(entities, item.styles) ?? [];
136
+ for (const entitiesGroup of entitiesGroups) {
137
+ if (!entitiesGroup.stylesGroup) continue;
138
+ for (const styleGroup of entitiesGroup.stylesGroup) {
139
+ const lineHeight = styleGroup.styles.find(s => s.name === 'LINEHEIGHT');
140
+ const color = styleGroup.styles.find(s => s.name === 'COLOR');
141
+ if (lineHeight?.value) {
142
+ currentLineHeight[item.layout] = lineHeight.value;
143
+ }
144
+ styleRules[item.layout].push(`
145
+ .${blockClass} .s-${styleGroup.start}-${styleGroup.end} {
146
+ ${styleGroup.styles.map(s => RichTextConverter.fromRangeStylesToInline(s, exemplary)).join('\n')}
147
+ }
148
+ `);
149
+ if (color) {
150
+ styleRules[item.layout].push(`
151
+ @supports not (color: oklch(42% 0.3 90 / 1)) {
152
+ .${blockClass} .s-${styleGroup.start}-${styleGroup.end} {
153
+ color: ${CntrlColor.parse(getResolvedValue(color.value, 'COLOR')!).fmt('rgba')};
154
+ }
155
+ }
156
+ `);
157
+ }
158
+ }
159
+ }
160
+ }
161
+ root.push(<div key={blockClass} className={blockClass}>{kids}</div>);
162
+ }
163
+ }
164
+ const styles = layouts.map(l => `
165
+ ${getLayoutMediaQuery(l.id, layouts)} {
166
+ ${styleRules[l.id].join('\n')}
167
+ }
168
+ `).join('\n');
169
+ return [
170
+ root,
171
+ styles
172
+ ];
173
+ }
174
+
175
+ private serializeRanges(ranges: { start: number; end: number; }[]): string {
176
+ return ranges.map(r => `${r.start},${r.end}`).join(' ');
177
+ }
178
+
179
+ private normalizeStyles(styles: RichTextStyle[], entities: RichTextEntity[]): StyleGroup[] | undefined {
180
+ const styleGroups: StyleGroup[] = [];
181
+ const dividers = [...styles, ...entities].reduce((ds, s) => {
182
+ ds.add(s.start);
183
+ ds.add(s.end);
184
+ return ds;
185
+ }, new Set<number>());
186
+ if (dividers.size === 0) return;
187
+ const edges = Array.from(dividers).sort((a, b) => a - b);
188
+ for (let i = 0; i < edges.length - 1; i += 1) {
189
+ const start = edges[i];
190
+ const end = edges[i + 1];
191
+ const applied = styles.filter(s => Math.max(s.start, start) < Math.min(s.end, end));
192
+ if (applied.length === 0) continue;
193
+ styleGroups.push({
194
+ start,
195
+ end,
196
+ styles: applied.map(s => ({ name: s.style, value: s.value }))
197
+ });
198
+ }
199
+
200
+ return styleGroups;
201
+ }
202
+
203
+ private groupEntities(entities: RichTextEntity[], styleGroups?: StyleGroup[]): EntitiesGroup[] | undefined {
204
+ const entitiesGroups: EntitiesGroup[] = [];
205
+ if (!entities.length && !styleGroups) return;
206
+ if (!styleGroups || styleGroups.length === 0) {
207
+ const dividersSet = entities.reduce((ds, e) => {
208
+ // some entities may have no data, need to filter them out
209
+ // (case with deleting a section/page that was linked to)
210
+ if (!e.hasOwnProperty('data')) return ds;
211
+ ds.add(e.start);
212
+ ds.add(e.end);
213
+ return ds;
214
+ }, new Set<number>([entities[0].start, entities[entities.length - 1].end]));
215
+ const dividers = Array.from(dividersSet).sort((a, b) => a - b);
216
+ for (let i = 0; i < dividers.length - 1; i += 1) {
217
+ const start = dividers[i];
218
+ const end = dividers[i + 1];
219
+ const entity = entities.find(e => e.start === start);
220
+ entitiesGroups.push({
221
+ stylesGroup: [],
222
+ start,
223
+ end,
224
+ ...(entity && { link: entity.data?.url ?? '', target: entity.data?.target ?? '_self' })
225
+ });
226
+ }
227
+ return entitiesGroups;
228
+ }
229
+ if (entities.length === 0) {
230
+ entitiesGroups.push({
231
+ stylesGroup: styleGroups,
232
+ start: styleGroups[0].start,
233
+ end: styleGroups[styleGroups.length - 1].end
234
+ });
235
+ return entitiesGroups;
236
+ }
237
+ const start = entities[0].start < styleGroups[0].start ? entities[0].start : styleGroups[0].start;
238
+ const end = entities[entities.length - 1].end > styleGroups[styleGroups.length - 1].end ? entities[entities.length - 1].end : styleGroups[styleGroups.length - 1].end;
239
+ const entitiesDividers = entities.reduce((ds, e) => {
240
+ if (!e.hasOwnProperty('data')) return ds;
241
+ ds.add(e.start);
242
+ ds.add(e.end);
243
+ return ds;
244
+ }, new Set<number>([start, end]));
245
+ const entityDividers = Array.from(entitiesDividers).sort((a, b) => a - b);
246
+
247
+ for (let i = 0; i < entityDividers.length - 1; i += 1) {
248
+ const start = entityDividers[i];
249
+ const end = entityDividers[i + 1];
250
+ const entity = entities.find(e => e.start === start);
251
+ entitiesGroups.push({
252
+ stylesGroup: styleGroups.filter(s => s.start >= start && s.end <= end),
253
+ start,
254
+ end,
255
+ ...(entity && { link: entity.data?.url ?? '', target: entity.data?.target ?? '_self' })
256
+ });
257
+ }
258
+
259
+ return entitiesGroups;
260
+ }
261
+
262
+ private static fromRangeStylesToInline(draftStyle: Style, exemplary: number): string {
263
+ const { value, name } = draftStyle;
264
+ const map: Record<string, Record<string, string | undefined>> = {
265
+ COLOR: { color: getResolvedValue(value, name) },
266
+ TYPEFACE: { 'font-family': `${getFontFamilyValue(value!)}` },
267
+ FONTSTYLE: value ? { ...FontStyles[value] } : {},
268
+ FONTWEIGHT: { 'font-weight': value },
269
+ FONTSIZE: { 'font-size': `${Number.parseFloat(value!) * exemplary}px` },
270
+ LINEHEIGHT: { 'line-height': `${Number.parseFloat(value!) * exemplary}px` },
271
+ LETTERSPACING: { 'letter-spacing': `${Number.parseFloat(value!) * exemplary}px` },
272
+ WORDSPACING: { 'word-spacing': `${Number.parseFloat(value!) * exemplary}px` },
273
+ TEXTTRANSFORM: value ? { 'text-transform': value as TextTransform } : { 'text-transform': TextTransform.None },
274
+ VERTICALALIGN: value ? { 'vertical-align': value as VerticalAlign } : { 'vertical-align': VerticalAlign.Unset },
275
+ TEXTDECORATION: { 'text-decoration': value },
276
+ FONTVARIANT: { 'font-variant': value }
277
+ };
278
+ const css = map[name];
279
+ if (!css) {
280
+ return '';
281
+ }
282
+ return Object.entries(css).filter(([, value]) => !!value).map(([prop, value]) => `${prop}: ${value};`).join('\n');
283
+ }
284
+ }
285
+
286
+ function groupBy<I>(items: I[], getKey: (item: I) => PropertyKey): Record<PropertyKey, I[]> {
287
+ const groups: Record<PropertyKey, I[]> = {};
288
+ for (const item of items) {
289
+ const key = getKey(item);
290
+ if (!groups[key]) {
291
+ groups[key] = [];
292
+ }
293
+ groups[key]!.push(item);
294
+ }
295
+ return groups;
296
+ }
297
+
298
+ function getResolvedValue(value: string | undefined, name: string) {
299
+ if (name !== 'COLOR') return value;
300
+ return value ? CntrlColor.parse(value).toCss() : value;
301
+ }
302
+
303
+ function sliceSymbols(text: string, start: number, end: number = Number.NaN): string {
304
+ let startOffset = Number.NaN;
305
+ let endOffset = 0;
306
+ let count = -1;
307
+ for (const ch of text) {
308
+ count += 1;
309
+ if (count === start) {
310
+ startOffset = endOffset;
311
+ }
312
+ if (count === end) break;
313
+ endOffset += ch.length;
314
+ }
315
+ if (isNaN(startOffset)) return '';
316
+ return text.slice(startOffset, endOffset);
317
+ }
318
+
319
+ function getSymbolsCount(input: string): number {
320
+ let count = 0;
321
+ let ch: string;
322
+ for (ch of input) {
323
+ count += 1;
324
+ }
325
+ return count;
326
+ }