forked from apollohg/react-native-prose-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNativeRichTextEditor.tsx
More file actions
3803 lines (3569 loc) · 153 KB
/
Copy pathNativeRichTextEditor.tsx
File metadata and controls
3803 lines (3569 loc) · 153 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, {
forwardRef,
useEffect,
useCallback,
useImperativeHandle,
useMemo,
useRef,
useState,
} from 'react';
import {
PixelRatio,
Platform,
Pressable,
ScrollView,
StyleSheet,
Text,
View,
type NativeSyntheticEvent,
type StyleProp,
type ViewStyle,
} from 'react-native';
import { requireNativeViewManager } from 'expo-modules-core';
import {
NativeEditorBridge,
type ActiveState,
type CommandBlockedInfo,
type DocumentJSON,
type EditorUpdate,
type HistoryState,
type RenderElement,
type Selection,
} from './NativeEditorBridge';
import {
DEFAULT_EDITOR_TOOLBAR_ITEMS,
EditorToolbar,
setActiveEditorToolbarFrameOwnerForEditor,
setEditorToolbarMentionState,
useEditorToolbarFrames,
type EditorToolbarCommand,
type EditorToolbarFrame,
type EditorToolbarGroupChildItem,
type EditorToolbarHeadingLevel,
type EditorToolbarIcon,
type EditorToolbarItem,
type EditorToolbarListType,
} from './EditorToolbar';
import { serializeEditorTheme, type EditorMentionTheme, type EditorTheme } from './EditorTheme';
import {
buildMentionFragmentJson,
serializeEditorAddons,
type EditorAddonEvent,
type EditorAddons,
type MentionQueryChangeEvent,
type MentionSelectionAttrsEvent,
type MentionSuggestion,
withMentionsSchema,
} from './addons';
import {
IMAGE_NODE_NAME,
buildImageFragmentJson,
normalizeDocumentJson,
tiptapSchema,
type ImageNodeAttributes,
type SchemaDefinition,
} from './schemas';
interface NativeEditorViewHandle {
focus?: () => void;
blur?: () => void;
getCaretRect?: () => Promise<string | null> | string | null;
applyEditorUpdate: (updateJson: string) => boolean | void | Promise<boolean | void>;
applyEditorResetUpdate?: (updateJson: string) => boolean | void | Promise<boolean | void>;
}
interface NativeEditorViewProps {
style?: StyleProp<ViewStyle>;
editorId: number;
placeholder?: string;
editable: boolean;
autoFocus: boolean;
autoCapitalize?: NativeRichTextEditorAutoCapitalize;
autoCorrect?: boolean;
keyboardType?: NativeRichTextEditorKeyboardType;
keyboardAppearance?: NativeRichTextEditorKeyboardAppearance;
showToolbar: boolean;
toolbarPlacement: NativeRichTextEditorToolbarPlacement;
heightBehavior: NativeRichTextEditorHeightBehavior;
allowImageResizing: boolean;
themeJson?: string;
addonsJson?: string;
toolbarItemsJson?: string;
toolbarFrameJson?: string;
remoteSelectionsJson?: string;
editorUpdateJson?: string;
editorUpdateEditorId?: number;
editorUpdateRevision?: number;
editorResetUpdateJson?: string;
editorResetUpdateEditorId?: number;
editorResetUpdateRevision?: number;
onEditorUpdate: (event: NativeSyntheticEvent<NativeUpdateEvent>) => void;
onSelectionChange: (event: NativeSyntheticEvent<NativeSelectionEvent>) => void;
onFocusChange: (event: NativeSyntheticEvent<NativeFocusEvent>) => void;
onContentHeightChange: (event: NativeSyntheticEvent<NativeContentHeightEvent>) => void;
onEditorReady?: (event: NativeSyntheticEvent<NativeEditorReadyEvent>) => void;
onToolbarAction: (event: NativeSyntheticEvent<NativeToolbarActionEvent>) => void;
onAddonEvent: (event: NativeSyntheticEvent<NativeAddonEvent>) => void;
}
const NativeEditorView = requireNativeViewManager('NativeEditor') as React.ComponentType<
NativeEditorViewProps & React.RefAttributes<NativeEditorViewHandle>
>;
const DEV_NATIVE_VIEW_KEY = __DEV__
? `native-editor-dev:${Math.random().toString(36).slice(2)}`
: 'native-editor';
const LINK_TOOLBAR_ACTION_KEY = '__native-editor-link__';
const IMAGE_TOOLBAR_ACTION_KEY = '__native-editor-image__';
const DEFAULT_MENTION_TRIGGER = '@';
const MAX_INLINE_MENTION_SUGGESTIONS = 8;
const INLINE_TOOLBAR_BORDER_COLOR = '#E5E5EA';
function mapToolbarChildForNative(
item: EditorToolbarGroupChildItem,
activeState: ActiveState,
editable: boolean,
onRequestLink?: NativeRichTextEditorProps['onRequestLink'],
onRequestImage?: NativeRichTextEditorProps['onRequestImage']
): EditorToolbarGroupChildItem {
if (item.type === 'link') {
return {
type: 'action',
key: LINK_TOOLBAR_ACTION_KEY,
label: item.label,
icon: item.icon as EditorToolbarIcon,
placement: item.placement,
isActive: activeState.marks.link === true,
isDisabled: !editable || !onRequestLink || !activeState.allowedMarks.includes('link'),
};
}
if (item.type === 'image') {
return {
type: 'action',
key: IMAGE_TOOLBAR_ACTION_KEY,
label: item.label,
icon: item.icon as EditorToolbarIcon,
placement: item.placement,
isActive: false,
isDisabled:
!editable ||
!onRequestImage ||
!activeState.insertableNodes.includes(IMAGE_NODE_NAME),
};
}
return item;
}
function mapToolbarItemsForNative(
items: readonly EditorToolbarItem[],
activeState: ActiveState,
editable: boolean,
onRequestLink?: NativeRichTextEditorProps['onRequestLink'],
onRequestImage?: NativeRichTextEditorProps['onRequestImage']
): EditorToolbarItem[] {
return items.map((item) => {
if (item.type === 'group') {
return {
...item,
items: item.items.map((child) =>
mapToolbarChildForNative(
child,
activeState,
editable,
onRequestLink,
onRequestImage
)
),
};
}
if (item.type === 'separator') {
return item;
}
return mapToolbarChildForNative(item, activeState, editable, onRequestLink, onRequestImage);
});
}
function isImageDataUrl(value: string): boolean {
return /^data:image\//i.test(value.trim());
}
function isRetryableNativeCommandBlock(reason: CommandBlockedInfo['reason']): boolean {
return reason === 'composition' || (Platform.OS === 'android' && reason === 'pendingUpdate');
}
function restoreSelectionInBridge(bridge: NativeEditorBridge, selection: Selection): boolean {
if (selection.type === 'text') {
const { anchor, head } = selection;
if (anchor == null || head == null) {
return false;
}
bridge.setSelection(anchor, head);
return true;
}
if (selection.type === 'node') {
const { pos } = selection;
if (pos == null) {
return false;
}
bridge.setSelection(pos, pos);
return true;
}
return false;
}
function isPromiseLike(value: unknown): value is Promise<unknown> {
return (
value != null &&
typeof value === 'object' &&
'then' in value &&
typeof (value as Promise<unknown>).then === 'function'
);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return value != null && typeof value === 'object' && !Array.isArray(value);
}
function resolveMentionTrigger(addons?: EditorAddons): string {
return addons?.mentions?.trigger?.trim() || DEFAULT_MENTION_TRIGGER;
}
function resolveMentionSuggestionLabel(suggestion: MentionSuggestion, trigger: string): string {
return suggestion.label?.trim() || `${trigger}${suggestion.title}`;
}
function filterMentionSuggestions(
suggestions: readonly MentionSuggestion[],
query: string,
trigger: string
): MentionSuggestion[] {
const normalizedQuery = query.trim().toLowerCase();
const filtered =
normalizedQuery.length === 0
? suggestions
: suggestions.filter((suggestion) => {
const label = resolveMentionSuggestionLabel(suggestion, trigger);
return (
suggestion.title.toLowerCase().includes(normalizedQuery) ||
label.toLowerCase().includes(normalizedQuery) ||
suggestion.subtitle?.toLowerCase().includes(normalizedQuery) === true
);
});
return filtered.slice(0, MAX_INLINE_MENTION_SUGGESTIONS);
}
function resolveMentionSuggestionAttrs(
suggestion: MentionSuggestion,
trigger: string
): Record<string, unknown> {
const attrs = { ...(suggestion.attrs ?? {}) };
if (!('label' in attrs)) {
attrs.label = resolveMentionSuggestionLabel(suggestion, trigger);
}
if (!('mentionSuggestionChar' in attrs)) {
attrs.mentionSuggestionChar = trigger;
}
return attrs;
}
function mergeMentionSuggestionTheme(
baseTheme: EditorMentionTheme | undefined,
resolvedTheme: EditorMentionTheme | undefined
): EditorMentionTheme | undefined {
if (baseTheme == null && resolvedTheme == null) {
return undefined;
}
const merged: EditorMentionTheme = {
...(baseTheme ?? {}),
...(resolvedTheme ?? {}),
};
if (resolvedTheme?.textColor != null && resolvedTheme.optionTextColor == null) {
merged.optionTextColor = resolvedTheme.textColor;
}
return merged;
}
interface AutoLinkCandidate {
docFrom: number;
docTo: number;
href: string;
}
interface AutoLinkInlineBlock {
chars: string[];
docPositions: number[];
linked: boolean[];
contentStart: number;
contentEnd: number;
nextPos: number;
}
const AUTO_LINK_URL_REGEX = /(?:https?:\/\/|www\.)\S+/giu;
const AUTO_LINK_INLINE_PLACEHOLDER = '\uFFFC';
const AUTO_LINK_LEADING_BOUNDARY_CHARS = new Set(['(', '[', '{', '<', '"', "'"]);
const AUTO_LINK_TRAILING_DELIMITER_CHARS = new Set([
'.',
',',
'!',
'?',
';',
':',
')',
']',
'}',
'>',
'"',
"'",
]);
const AUTO_LINK_ALWAYS_TRIM_CHARS = new Set(['.', ',', '!', '?', ';', ':']);
const AUTO_LINK_MATCHED_CLOSERS: Record<string, string> = {
')': '(',
']': '[',
'}': '{',
};
function unicodeScalars(text: string): string[] {
return Array.from(text);
}
function unicodeScalarCount(text: string): number {
return unicodeScalars(text).length;
}
function hasDocumentLinkMark(marks: unknown): boolean {
if (!Array.isArray(marks)) {
return false;
}
return marks.some(
(mark) => isRecord(mark) && typeof mark.type === 'string' && mark.type === 'link'
);
}
function isInlineDocumentNode(node: unknown): boolean {
if (!isRecord(node)) {
return false;
}
if (node.type === 'text') {
return true;
}
return !Array.isArray(node.content);
}
function isInlineTextBlockNode(node: Record<string, unknown>): boolean {
const content = Array.isArray(node.content) ? node.content : [];
return content.length > 0 && content.every((child) => isInlineDocumentNode(child));
}
function countOccurrences(text: string, target: string): number {
let count = 0;
for (const char of text) {
if (char === target) {
count += 1;
}
}
return count;
}
function trimAutoLinkTrailingPunctuation(value: string): string {
let result = value;
while (result.length > 0) {
const chars = unicodeScalars(result);
const lastChar = chars[chars.length - 1];
if (!lastChar) {
break;
}
if (AUTO_LINK_ALWAYS_TRIM_CHARS.has(lastChar)) {
chars.pop();
result = chars.join('');
continue;
}
const matchingOpener = AUTO_LINK_MATCHED_CLOSERS[lastChar];
if (
matchingOpener &&
countOccurrences(result, lastChar) > countOccurrences(result, matchingOpener)
) {
chars.pop();
result = chars.join('');
continue;
}
if (
(lastChar === '"' || lastChar === "'") &&
countOccurrences(result, lastChar) % 2 !== 0
) {
chars.pop();
result = chars.join('');
continue;
}
break;
}
return result;
}
function normalizeAutoDetectedHref(value: string): string | null {
const trimmed = trimAutoLinkTrailingPunctuation(value);
if (!trimmed) {
return null;
}
const normalized = /^www\./iu.test(trimmed) ? `https://${trimmed}` : trimmed;
try {
new URL(normalized);
return normalized;
} catch {
return null;
}
}
function isAutoLinkBoundaryChar(char: string | undefined): boolean {
if (!char) {
return true;
}
return (
/\s/u.test(char) ||
char === AUTO_LINK_INLINE_PLACEHOLDER ||
AUTO_LINK_LEADING_BOUNDARY_CHARS.has(char)
);
}
function isAutoLinkTrailingDelimiterChar(char: string | undefined): boolean {
if (!char) {
return true;
}
return (
/\s/u.test(char) ||
char === AUTO_LINK_INLINE_PLACEHOLDER ||
AUTO_LINK_TRAILING_DELIMITER_CHARS.has(char)
);
}
function codeUnitBoundariesForScalars(chars: readonly string[]): number[] {
const boundaries = [0];
let offset = 0;
for (const char of chars) {
offset += char.length;
boundaries.push(offset);
}
return boundaries;
}
function codeUnitOffsetToScalarIndex(boundaries: readonly number[], offset: number): number {
let scalarIndex = 0;
while (scalarIndex + 1 < boundaries.length && boundaries[scalarIndex + 1] <= offset) {
scalarIndex += 1;
}
return scalarIndex;
}
function buildAutoLinkInlineBlock(node: Record<string, unknown>, pos: number): AutoLinkInlineBlock {
const chars: string[] = [];
const docPositions: number[] = [];
const linked: boolean[] = [];
const content = Array.isArray(node.content) ? node.content : [];
let nextPos = pos + 1;
for (const child of content) {
if (!isRecord(child)) {
continue;
}
if (child.type === 'text') {
const childText = typeof child.text === 'string' ? child.text : '';
const childChars = unicodeScalars(childText);
const hasLink = hasDocumentLinkMark(child.marks);
for (const char of childChars) {
chars.push(char);
docPositions.push(nextPos);
linked.push(hasLink);
nextPos += 1;
}
continue;
}
chars.push(child.type === 'hardBreak' ? '\n' : AUTO_LINK_INLINE_PLACEHOLDER);
docPositions.push(nextPos);
linked.push(false);
nextPos += 1;
}
return {
chars,
docPositions,
linked,
contentStart: pos + 1,
contentEnd: nextPos,
nextPos: nextPos + 1,
};
}
function findAutoLinkCandidateInInlineBlock(
block: AutoLinkInlineBlock,
cursorDocPos: number
): AutoLinkCandidate | null {
if (cursorDocPos < block.contentStart || cursorDocPos > block.contentEnd) {
return null;
}
let localIndex = 0;
while (
localIndex < block.docPositions.length &&
block.docPositions[localIndex] < cursorDocPos
) {
localIndex += 1;
}
if (localIndex === 0) {
return null;
}
if (
cursorDocPos < block.contentEnd &&
!isAutoLinkTrailingDelimiterChar(block.chars[localIndex - 1])
) {
return null;
}
const prefixChars = block.chars.slice(0, localIndex);
const prefixText = prefixChars.join('');
if (!prefixText) {
return null;
}
const boundaries = codeUnitBoundariesForScalars(prefixChars);
AUTO_LINK_URL_REGEX.lastIndex = 0;
let lastMatch: RegExpExecArray | null = null;
for (const match of prefixText.matchAll(AUTO_LINK_URL_REGEX)) {
lastMatch = match;
}
if (!lastMatch || typeof lastMatch.index !== 'number') {
return null;
}
const rawStartScalar = codeUnitOffsetToScalarIndex(boundaries, lastMatch.index);
const normalizedHref = normalizeAutoDetectedHref(lastMatch[0]);
const trimmedText = trimAutoLinkTrailingPunctuation(lastMatch[0]);
if (!normalizedHref || !trimmedText) {
return null;
}
const candidateEndScalar = rawStartScalar + unicodeScalarCount(trimmedText);
if (candidateEndScalar > prefixChars.length) {
return null;
}
if (!isAutoLinkBoundaryChar(prefixChars[rawStartScalar - 1])) {
return null;
}
for (let index = candidateEndScalar; index < localIndex; index += 1) {
if (!isAutoLinkTrailingDelimiterChar(prefixChars[index])) {
return null;
}
}
for (let index = rawStartScalar; index < candidateEndScalar; index += 1) {
if (block.linked[index]) {
return null;
}
}
const docFrom = block.docPositions[rawStartScalar];
const docTo =
candidateEndScalar < block.docPositions.length
? block.docPositions[candidateEndScalar]
: block.contentEnd;
if (!(docTo > docFrom)) {
return null;
}
return {
docFrom,
docTo,
href: normalizedHref,
};
}
function findAutoLinkCandidateInDocument(
document: DocumentJSON,
cursorDocPos: number
): AutoLinkCandidate | null {
const visit = (
node: unknown,
pos: number,
isRoot = false
): { candidate: AutoLinkCandidate | null; nextPos: number } => {
if (!isRecord(node)) {
return { candidate: null, nextPos: pos };
}
const nodeType = typeof node.type === 'string' ? node.type : '';
const content = Array.isArray(node.content) ? node.content : [];
if (nodeType === 'text') {
const text = typeof node.text === 'string' ? node.text : '';
return { candidate: null, nextPos: pos + unicodeScalarCount(text) };
}
if (isRoot && nodeType === 'doc') {
let nextPos = pos;
for (const child of content) {
const result = visit(child, nextPos);
if (result.candidate) {
return result;
}
nextPos = result.nextPos;
}
return { candidate: null, nextPos };
}
if (isInlineTextBlockNode(node)) {
const block = buildAutoLinkInlineBlock(node, pos);
return {
candidate: findAutoLinkCandidateInInlineBlock(block, cursorDocPos),
nextPos: block.nextPos,
};
}
if (content.length === 0) {
return { candidate: null, nextPos: pos + 1 };
}
let nextPos = pos + 1;
for (const child of content) {
const result = visit(child, nextPos);
if (result.candidate) {
return result;
}
nextPos = result.nextPos;
}
return { candidate: null, nextPos: nextPos + 1 };
};
return visit(document, 0, true).candidate;
}
function didContentChange(
previousDocumentVersion: number | null,
update: EditorUpdate | null
): boolean {
if (!update) {
return false;
}
return (
previousDocumentVersion == null ||
typeof update.documentVersion !== 'number' ||
update.documentVersion !== previousDocumentVersion
);
}
function documentVersionFromUpdateJson(json: string): number | null {
try {
const parsed = JSON.parse(json) as { documentVersion?: unknown };
return typeof parsed.documentVersion === 'number' ? parsed.documentVersion : null;
} catch {
return null;
}
}
interface NativeUpdateEvent {
updateJson: string;
editorId?: number;
}
interface NativeSelectionEvent {
anchor: number;
head: number;
stateJson?: string;
editorId?: number;
documentVersion?: number;
}
interface NativeFocusEvent {
isFocused: boolean;
editorId?: number;
}
interface NativeContentHeightEvent {
contentHeight: number;
editorId?: number;
}
interface NativeEditorReadyEvent {
editorId?: number;
editorUpdateRevision?: number;
}
interface NativeToolbarActionEvent {
key: string;
editorId?: number;
updateJson?: string;
stateJson?: string;
documentVersion?: number;
}
interface NativeAddonEvent {
eventJson: string;
editorId?: number;
}
function isCurrentNativeEditorEvent(
event: { editorId?: number },
bridge: NativeEditorBridge | null
): boolean {
if (Platform.OS === 'android') {
return typeof event.editorId === 'number' && bridge?.editorId === event.editorId;
}
if (typeof event.editorId !== 'number') return true;
return event.editorId === 0 || bridge?.editorId === event.editorId;
}
function computeRenderedTextLength(elements: RenderElement[]): number {
let len = 0;
let blockCount = 0;
for (const el of elements) {
if (el.type === 'blockStart' && el.listContext) {
len += el.listContext.kind === 'task'
? unicodeScalarCount(el.listContext.checked ? '☑ ' : '☐ ')
: el.listContext.ordered
? unicodeScalarCount(`${el.listContext.index}. `)
: unicodeScalarCount('• ');
} else if (el.type === 'textRun' && el.text) {
len += unicodeScalarCount(el.text);
} else if (
el.type === 'voidInline' ||
el.type === 'voidBlock' ||
el.type === 'opaqueInlineAtom' ||
el.type === 'opaqueBlockAtom'
) {
if (el.type === 'opaqueInlineAtom' || el.type === 'opaqueBlockAtom') {
const visibleText =
el.nodeType === 'mention' ? (el.label ?? '?') : `[${el.label ?? '?'}]`;
len += unicodeScalarCount(visibleText);
} else {
// U+FFFC placeholder / hard break
len += 1;
}
} else if (el.type === 'blockEnd') {
blockCount++;
}
}
// Block breaks add 1 scalar each, except the last block
if (blockCount > 1) len += blockCount - 1;
return len;
}
function serializeRemoteSelections(
remoteSelections?: readonly RemoteSelectionDecoration[]
): string | undefined {
if (!remoteSelections || remoteSelections.length === 0) {
return undefined;
}
return stringifyCachedJson(remoteSelections);
}
function areToolbarFramesEqual(
left: EditorToolbarFrame | null | undefined,
right: EditorToolbarFrame | null | undefined
): boolean {
return (
left?.x === right?.x &&
left?.y === right?.y &&
left?.width === right?.width &&
left?.height === right?.height
);
}
function serializeToolbarFrames(
frames: readonly EditorToolbarFrame[] | null | undefined
): string | undefined {
if (!frames || frames.length === 0) {
return undefined;
}
return JSON.stringify(frames.length === 1 ? frames[0] : { frames });
}
function parseCaretRectJson(raw: string | null | undefined): NativeRichTextEditorCaretRect | null {
if (!raw) {
return null;
}
try {
const parsed = JSON.parse(raw) as Record<string, unknown>;
const x = typeof parsed.x === 'number' ? parsed.x : null;
const y = typeof parsed.y === 'number' ? parsed.y : null;
const width = typeof parsed.width === 'number' ? parsed.width : null;
const height = typeof parsed.height === 'number' ? parsed.height : null;
const editorWidth = typeof parsed.editorWidth === 'number' ? parsed.editorWidth : null;
const editorHeight = typeof parsed.editorHeight === 'number' ? parsed.editorHeight : null;
if (
x == null ||
y == null ||
width == null ||
height == null ||
editorWidth == null ||
editorHeight == null
) {
return null;
}
return { x, y, width, height, editorWidth, editorHeight };
} catch {
return null;
}
}
const serializedJsonCache = new WeakMap<object, string>();
function stringifyCachedJson(value: unknown): string {
if (value != null && typeof value === 'object') {
const cached = serializedJsonCache.get(value);
if (cached != null) {
return cached;
}
const serialized = JSON.stringify(value);
serializedJsonCache.set(value, serialized);
return serialized;
}
return JSON.stringify(value);
}
function useSerializedValue<T>(
value: T | null | undefined,
serialize: (value: T) => string | undefined,
revision?: unknown
): string | undefined {
const cacheRef = useRef<{
value: T | null | undefined;
revision: unknown;
hasRevision: boolean;
serialized: string | undefined;
} | null>(null);
const hasRevision = revision !== undefined;
const cached = cacheRef.current;
if (cached) {
if (hasRevision && cached.hasRevision && Object.is(cached.revision, revision)) {
return cached.serialized;
}
if (Object.is(cached.value, value) && cached.hasRevision === hasRevision) {
return cached.serialized;
}
}
const serialized = value == null ? undefined : serialize(value);
cacheRef.current = {
value,
revision,
hasRevision,
serialized,
};
return serialized;
}
export type NativeRichTextEditorHeightBehavior = 'fixed' | 'autoGrow';
export type NativeRichTextEditorToolbarPlacement = 'keyboard' | 'inline';
export type NativeRichTextEditorValueJSONUpdateMode = 'replace' | 'reset';
export type NativeRichTextEditorAutoCapitalize = 'none' | 'sentences' | 'words' | 'characters';
export type NativeRichTextEditorKeyboardType =
| 'default'
| 'email-address'
| 'numeric'
| 'phone-pad'
| 'ascii-capable'
| 'numbers-and-punctuation'
| 'url'
| 'number-pad'
| 'name-phone-pad'
| 'decimal-pad'
| 'twitter'
| 'web-search'
| 'visible-password'
| 'ascii-capable-number-pad';
export type NativeRichTextEditorKeyboardAppearance = 'default' | 'light' | 'dark';
export interface RemoteSelectionDecoration {
clientId: number;
anchor: number;
head: number;
color: string;
name?: string;
avatarUrl?: string;
isFocused?: boolean;
}
export interface LinkRequestContext {
href?: string;
isActive: boolean;
selection: Selection;
setLink: (href: string) => void;
unsetLink: () => void;
}
export interface ImageRequestContext {
selection: Selection;
allowBase64: boolean;
insertImage: (src: string, attrs?: Omit<ImageNodeAttributes, 'src'>) => void;
}
export interface NativeRichTextEditorProps {
/** Initial content as HTML (uncontrolled mode). */
initialContent?: string;
/** Initial content as ProseMirror JSON (uncontrolled mode). */
initialJSON?: DocumentJSON;
/** Controlled HTML content. External changes are diffed and applied. */
value?: string;
/** Controlled ProseMirror JSON content. Ignored if value is set. */
valueJSON?: DocumentJSON;
/** Optional stable revision hint for `valueJSON` to avoid reserializing equal docs on rerender. */
valueJSONRevision?: string | number;
/** Controls how external `valueJSON` changes are applied. Defaults to preserving undo history. */
valueJSONUpdateMode?: NativeRichTextEditorValueJSONUpdateMode;
/** When using reset-mode `valueJSON`, preserve the current local text selection after applying the reset. */
preserveSelectionOnValueJSONReset?: boolean;
/** Preferred selection to restore when applying reset-mode `valueJSON`; falls back to the live selection. */
selectionOnValueJSONReset?: Selection;
/** Schema definition. Defaults to tiptapSchema if not provided. */
schema?: SchemaDefinition;
/** Placeholder text shown when editor is empty. */
placeholder?: string;
/** Whether the editor is editable. */
editable?: boolean;
/** Maximum character length. */
maxLength?: number;
/** Whether to auto-focus on mount. */
autoFocus?: boolean;
/** Controls native keyboard auto-capitalization. Defaults to sentences. */
autoCapitalize?: NativeRichTextEditorAutoCapitalize;
/** Controls native keyboard autocorrection. Defaults to the platform-specific editor default. */
autoCorrect?: boolean;
/** Controls the native keyboard layout. Defaults to the platform default keyboard. */
keyboardType?: NativeRichTextEditorKeyboardType;
/** Controls the native keyboard appearance. */
keyboardAppearance?: NativeRichTextEditorKeyboardAppearance;
/** Controls whether the editor scrolls internally or grows with content. */
heightBehavior?: NativeRichTextEditorHeightBehavior;
/** Whether to show the formatting toolbar. Defaults to true. */
showToolbar?: boolean;
/** Whether the toolbar is attached to the keyboard natively or rendered inline in React. */
toolbarPlacement?: NativeRichTextEditorToolbarPlacement;
/** Displayed toolbar buttons, in order. Supports custom marks/nodes. */
toolbarItems?: readonly EditorToolbarItem[];
/** Called when a custom `action` toolbar item is pressed. */
onToolbarAction?: (key: string) => void;
/** Called when a toolbar link item is pressed so the host can collect/edit a URL. */
onRequestLink?: (context: LinkRequestContext) => void;
/** Called when a toolbar image item is pressed so the host can choose an image source. */
onRequestImage?: (context: ImageRequestContext) => void;
/** Whether plain URLs typed or pasted into the editor should be converted into link marks automatically. */
autoDetectLinks?: boolean;
/** Whether `data:image/...` sources are accepted for image insertion and HTML parsing. */
allowBase64Images?: boolean;
/** Whether selected images show native resize handles. */
allowImageResizing?: boolean;
/** Called when content changes with the current HTML. */
onContentChange?: (html: string) => void;
/** Called when content changes with the current ProseMirror JSON. */
onContentChangeJSON?: (json: DocumentJSON) => void;
/** Called when selection changes. */
onSelectionChange?: (selection: Selection) => void;
/** Called when active formatting state changes. */
onActiveStateChange?: (state: ActiveState) => void;
/** Called when undo/redo availability changes. */
onHistoryStateChange?: (state: HistoryState) => void;
/** Called when the editor gains focus. */
onFocus?: () => void;
/** Called when the editor loses focus. */
onBlur?: () => void;
/** Style applied to the native editor view. */
style?: StyleProp<ViewStyle>;
/** Style applied to the outer React container wrapping the editor and inline toolbar. */
containerStyle?: StyleProp<ViewStyle>;
/** Optional native content theme applied to rendered blocks and typing attrs. */
theme?: EditorTheme;
/** Optional addon configuration. */
addons?: EditorAddons;
/** Remote awareness selections rendered as native overlays. */
remoteSelections?: readonly RemoteSelectionDecoration[];
}