@cntrl-site/sdk-nextjs 1.9.40 → 1.9.41

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