@cntrl-site/sdk-nextjs 1.9.78 → 1.9.79

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 (145) 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 +5 -5
  11. package/lib/components/Article.js +5 -5
  12. package/lib/components/LayoutStyle.js +4 -4
  13. package/lib/components/Section/Section.js +27 -27
  14. package/lib/components/StructuredBlockItem/StructuredBlockItem.js +13 -13
  15. package/lib/components/StructuredBlockItem/StructuredComponent/StructuredComponent.js +12 -12
  16. package/lib/components/StructuredContent/StructuredContent.js +11 -11
  17. package/lib/components/items/CodeEmbedItem/CodeEmbedItem.js +36 -36
  18. package/lib/components/items/ComponentItem/ComponentItem.js +13 -13
  19. package/lib/components/items/CompoundItem/CompoundChild.js +20 -20
  20. package/lib/components/items/CompoundItem/CompoundItem.js +14 -14
  21. package/lib/components/items/CustomItem/CustomItem.js +9 -9
  22. package/lib/components/items/EmbedVideoItem/VimeoEmbed.js +24 -24
  23. package/lib/components/items/EmbedVideoItem/YoutubeEmbed.js +27 -27
  24. package/lib/components/items/FileItem/ImageItem.js +40 -40
  25. package/lib/components/items/FileItem/VideoItem.js +64 -64
  26. package/lib/components/items/GroupItem/GroupItem.js +14 -14
  27. package/lib/components/items/Item.js +30 -30
  28. package/lib/components/items/RectangleItem/RectangleItem.js +27 -27
  29. package/lib/components/items/RichTextItem/RichTextItem.js +22 -22
  30. package/lib/utils/RichTextConverter/RichTextConverter.js +21 -21
  31. package/package.json +62 -62
  32. package/src/ItemGeometry/CSSPropertyNameMap.ts +37 -37
  33. package/src/ItemGeometry/GenericGeometryController.ts +59 -59
  34. package/src/ItemGeometry/ItemGeometryContext.ts +4 -4
  35. package/src/ItemGeometry/ItemGeometryController.ts +22 -22
  36. package/src/ItemGeometry/ItemGeometryService.ts +34 -34
  37. package/src/ItemGeometry/RichTextGeometryController.ts +166 -166
  38. package/src/ItemGeometry/useItemGeometry.ts +25 -25
  39. package/src/common/useCurrentLayout.ts +52 -52
  40. package/src/common/useExemplary.ts +9 -9
  41. package/src/common/useItemFXData.ts +63 -63
  42. package/src/common/useKeyframeValue.ts +85 -85
  43. package/src/common/useRegisterResize.ts +16 -16
  44. package/src/components/Article.tsx +69 -69
  45. package/src/components/ArticleWrapper.tsx +21 -21
  46. package/src/components/Head.tsx +95 -95
  47. package/src/components/LayoutStyle.tsx +21 -21
  48. package/src/components/Page.tsx +47 -47
  49. package/src/components/ScrollPlaybackVideo.tsx +75 -75
  50. package/src/components/Section/Section.tsx +162 -162
  51. package/src/components/Section/SectionImage.tsx +48 -48
  52. package/src/components/Section/SectionVideo.tsx +144 -144
  53. package/src/components/Section/useSectionColor.ts +19 -19
  54. package/src/components/Section/useSectionHeightMap.ts +19 -19
  55. package/src/components/StructuredBlockItem/StructuredBlockItem.tsx +69 -69
  56. package/src/components/StructuredBlockItem/StructuredComponent/StructuredComponent.tsx +66 -66
  57. package/src/components/StructuredContent/StructuredContent.tsx +42 -42
  58. package/src/components/items/CodeEmbedItem/CodeEmbedItem.tsx +148 -148
  59. package/src/components/items/CodeEmbedItem/useCodeEmbedItem.ts +36 -36
  60. package/src/components/items/ComponentItem/ComponentItem.tsx +85 -85
  61. package/src/components/items/ComponentItem/useComponentItem.ts +35 -35
  62. package/src/components/items/CompoundItem/CompoundChild.tsx +151 -151
  63. package/src/components/items/CompoundItem/CompoundItem.tsx +88 -88
  64. package/src/components/items/CompoundItem/useCompoundItem.ts +21 -21
  65. package/src/components/items/CustomItem/CustomItem.tsx +50 -50
  66. package/src/components/items/EmbedVideoItem/VimeoEmbed.tsx +217 -217
  67. package/src/components/items/EmbedVideoItem/YoutubeEmbed.tsx +201 -201
  68. package/src/components/items/EmbedVideoItem/useEmbedVideoItem.ts +46 -46
  69. package/src/components/items/FileItem/ImageItem.tsx +166 -166
  70. package/src/components/items/FileItem/VideoItem.tsx +287 -287
  71. package/src/components/items/FileItem/useFileItem.ts +81 -81
  72. package/src/components/items/GroupItem/GroupItem.tsx +99 -99
  73. package/src/components/items/GroupItem/useGroupItem.ts +34 -34
  74. package/src/components/items/Item.tsx +268 -268
  75. package/src/components/items/LinkWrapper.tsx +39 -39
  76. package/src/components/items/RectangleItem/RectangleItem.tsx +177 -177
  77. package/src/components/items/RectangleItem/useRectangleItem.ts +89 -89
  78. package/src/components/items/RichTextItem/RichTextItem.tsx +113 -113
  79. package/src/components/items/RichTextItem/useRichTextItem.ts +12 -12
  80. package/src/components/items/RichTextWrapper.tsx +15 -15
  81. package/src/components/items/itemsMap.ts +28 -28
  82. package/src/components/items/useDraggable.ts +252 -252
  83. package/src/components/items/useItemAngle.ts +13 -13
  84. package/src/components/items/useItemArea.ts +35 -35
  85. package/src/components/items/useItemPointerEvents.ts +23 -23
  86. package/src/components/items/useItemScale.ts +17 -17
  87. package/src/components/items/useItemTriggers.ts +15 -15
  88. package/src/components/items/useRichTextItemValues.ts +66 -66
  89. package/src/components/items/useSizing.ts +25 -25
  90. package/src/components/items/useStickyItemTop.ts +21 -21
  91. package/src/components/useLayoutContext.ts +7 -7
  92. package/src/index.ts +25 -25
  93. package/src/interactions/InteractionsRegistry.ts +513 -513
  94. package/src/interactions/ItemInteractionCtrl.ts +78 -78
  95. package/src/interactions/getTransition.ts +27 -27
  96. package/src/interactions/types.ts +36 -36
  97. package/src/interactions/useItemInteractionCtrl.ts +18 -18
  98. package/src/provider/ArticleRectContext.ts +4 -4
  99. package/src/provider/CntrlContext.ts +5 -5
  100. package/src/provider/CntrlProvider.tsx +11 -11
  101. package/src/provider/CntrlSdkContext.ts +113 -113
  102. package/src/provider/CustomItemRegistry.ts +14 -14
  103. package/src/provider/CustomItemTypes.ts +3 -3
  104. package/src/provider/CustomSectionRegistry.ts +25 -25
  105. package/src/provider/InteractionsContext.tsx +73 -73
  106. package/src/provider/Keyframes.ts +11 -11
  107. package/src/provider/KeyframesContext.ts +5 -5
  108. package/src/provider/LayoutContext.ts +3 -3
  109. package/src/provider/WebGLContextManagerContext.tsx +4 -4
  110. package/src/provider/defaultContext.ts +8 -8
  111. package/src/provider/useCntrlContext.ts +8 -8
  112. package/src/styled-jsx.d.ts +1 -1
  113. package/src/types/components-utils.d.ts +7 -7
  114. package/src/utils/Animator/Animator.ts +570 -570
  115. package/src/utils/ArticleRectManager/ArticleRectObserver.ts +93 -93
  116. package/src/utils/ArticleRectManager/useArticleRectObserver.ts +17 -17
  117. package/src/utils/ArticleRectManager/useSectionRegistry.ts +11 -11
  118. package/src/utils/CSSNumeric.ts +19 -19
  119. package/src/utils/EventEmitter.ts +41 -41
  120. package/src/utils/RichTextConverter/RichTextConverter.tsx +342 -342
  121. package/src/utils/ScaleAnchorMap.ts +13 -13
  122. package/src/utils/StickyManager/StickyManager.ts +23 -23
  123. package/src/utils/Youtube/YouTubeIframeApiLoader.ts +58 -58
  124. package/src/utils/Youtube/YoutubeIframeApi.ts +101 -101
  125. package/src/utils/Youtube/useYouTubeIframeApi.ts +12 -12
  126. package/src/utils/areFillsVisible/areFillsVisible.test.ts +63 -63
  127. package/src/utils/areFillsVisible/areFillsVisible.ts +37 -37
  128. package/src/utils/binSearchInsertAt.ts +33 -33
  129. package/src/utils/castObject.ts +10 -10
  130. package/src/utils/checkOverflowClipSupport.ts +13 -13
  131. package/src/utils/domDfs.ts +11 -11
  132. package/src/utils/effects/useImageFx.ts +154 -154
  133. package/src/utils/effects/useVideoFx.ts +156 -156
  134. package/src/utils/evaluateComponentBundle.ts +83 -83
  135. package/src/utils/getAnchoredItemTop.ts +12 -12
  136. package/src/utils/getCompoundBoundaryStyles.ts +60 -60
  137. package/src/utils/getFill.ts +46 -46
  138. package/src/utils/getFontFamilyValue.ts +3 -3
  139. package/src/utils/getInvertedRanges.ts +43 -43
  140. package/src/utils/getItemTopStyle.ts +39 -39
  141. package/src/utils/getStyleFromItemStateAndParams.ts +8 -8
  142. package/src/utils/getValidYoutubeUrl.ts +29 -29
  143. package/src/utils/isItemType.ts +5 -5
  144. package/src/utils/rangeMap.ts +13 -13
  145. package/src/utils/useElementRect.ts +23 -23
@@ -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
+ }