-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRichTextEditor.tsx
More file actions
1846 lines (1699 loc) · 56.3 KB
/
RichTextEditor.tsx
File metadata and controls
1846 lines (1699 loc) · 56.3 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,
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState,
} from 'react';
import { LexicalComposer } from '@lexical/react/LexicalComposer';
import { RichTextPlugin } from '@lexical/react/LexicalRichTextPlugin';
import { ContentEditable } from '@lexical/react/LexicalContentEditable';
import { HistoryPlugin } from '@lexical/react/LexicalHistoryPlugin';
import { OnChangePlugin } from '@lexical/react/LexicalOnChangePlugin';
import { AutoFocusPlugin } from '@lexical/react/LexicalAutoFocusPlugin';
import { ListPlugin } from '@lexical/react/LexicalListPlugin';
import { LinkPlugin } from '@lexical/react/LexicalLinkPlugin';
import { TablePlugin } from '@lexical/react/LexicalTablePlugin';
import LexicalErrorBoundary from '@lexical/react/LexicalErrorBoundary';
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext';
import { $generateHtmlFromNodes, $generateNodesFromDOM } from '@lexical/html';
import {
$createHeadingNode,
$createQuoteNode,
$isHeadingNode,
HeadingNode,
QuoteNode,
type HeadingTagType,
} from '@lexical/rich-text';
import {
INSERT_ORDERED_LIST_COMMAND,
INSERT_UNORDERED_LIST_COMMAND,
REMOVE_LIST_COMMAND,
ListItemNode,
ListNode,
$isListNode,
type ListType,
} from '@lexical/list';
import { $isLinkNode, LinkNode, TOGGLE_LINK_COMMAND } from '@lexical/link';
import { mergeRegister } from '@lexical/utils';
import { $setBlocksType } from '@lexical/selection';
import {
$createParagraphNode,
$getRoot,
$getSelection,
$isRangeSelection,
$isNodeSelection,
CAN_REDO_COMMAND,
CAN_UNDO_COMMAND,
COMMAND_PRIORITY_CRITICAL,
COMMAND_PRIORITY_EDITOR,
FORMAT_ELEMENT_COMMAND,
FORMAT_TEXT_COMMAND,
PASTE_COMMAND,
REDO_COMMAND,
SELECTION_CHANGE_COMMAND,
UNDO_COMMAND,
type EditorState,
type LexicalEditor,
type NodeSelection,
type RangeSelection,
$createNodeSelection,
$createRangeSelection,
$createTextNode,
$getNodeByKey,
$setSelection,
} from 'lexical';
import {
$createTableSelection,
$deleteTableColumn__EXPERIMENTAL,
$deleteTableRow__EXPERIMENTAL,
$getTableCellNodeFromLexicalNode,
$getTableNodeFromLexicalNodeOrThrow,
$insertTableColumn__EXPERIMENTAL,
$insertTableRow__EXPERIMENTAL,
$isTableCellNode,
$isTableRowNode,
$isTableSelection,
INSERT_TABLE_COMMAND,
TableCellNode,
TableCellHeaderStates,
TableNode,
TableRowNode,
type TableSelection,
} from '@lexical/table';
import IconButton from './IconButton';
import Button from './Button';
import ContextMenuComponent, { type MenuItem as ContextMenuItem } from './ContextMenu';
import { RedoIcon, UndoIcon } from './Icons';
import {
AlignCenterIcon,
AlignJustifyIcon,
AlignLeftIcon,
AlignRightIcon,
BoldIcon,
BulletListIcon,
ClearFormattingIcon,
CodeInlineIcon,
HeadingOneIcon,
HeadingThreeIcon,
HeadingTwoIcon,
ImageIcon as ToolbarImageIcon,
ItalicIcon,
LinkIcon as ToolbarLinkIcon,
NumberListIcon,
ParagraphIcon,
QuoteIcon,
StrikethroughIcon,
TableIcon,
UnderlineIcon,
} from './rich-text/RichTextToolbarIcons';
import { $createImageNode, ImageNode, INSERT_IMAGE_COMMAND, type ImagePayload } from './rich-text/ImageNode';
import Modal from './Modal';
export interface RichTextEditorHandle {
focus: () => void;
format: () => void;
setScrollTop: (scrollTop: number) => void;
getScrollInfo: () => Promise<{ scrollTop: number; scrollHeight: number; clientHeight: number }>;
}
interface RichTextEditorProps {
html: string;
onChange: (html: string) => void;
readOnly?: boolean;
onScroll?: (scrollInfo: { scrollTop: number; scrollHeight: number; clientHeight: number }) => void;
onFocusChange?: (hasFocus: boolean) => void;
}
interface ToolbarButtonConfig {
id: string;
label: string;
icon: React.FC<{ className?: string }>;
group: 'history' | 'inline-format' | 'structure' | 'insert' | 'alignment' | 'utility';
isActive?: boolean;
disabled?: boolean;
onClick: () => void;
}
type BlockType = 'paragraph' | HeadingTagType | ListType | 'quote';
interface ContextMenuState {
x: number;
y: number;
visible: boolean;
}
type SelectionSnapshot =
| {
type: 'range';
anchorKey: string;
anchorOffset: number;
anchorType: 'text' | 'element';
focusKey: string;
focusOffset: number;
focusType: 'text' | 'element';
}
| { type: 'node'; keys: string[] }
| {
type: 'table';
tableKey: string;
anchorCellKey: string;
focusCellKey: string;
}
| null;
const RICH_TEXT_THEME = {
paragraph: 'mb-3 text-base leading-7 text-text-main',
heading: {
h1: 'text-3xl font-bold text-text-main mb-4 mt-6',
h2: 'text-2xl font-semibold text-text-main mb-3 mt-5',
h3: 'text-xl font-medium text-text-main mb-2 mt-4',
},
quote: 'border-l-4 border-primary/50 pl-4 py-1 my-4 text-text-secondary italic bg-primary/5 rounded-r',
list: {
nested: {
listitem: 'ml-4',
},
ol: 'list-decimal ml-8 mb-4 text-base leading-7 text-text-main',
ul: 'list-disc ml-8 mb-4 text-base leading-7 text-text-main',
listitem: 'mb-1 pl-1',
},
text: {
bold: 'font-bold text-text-main',
italic: 'italic',
underline: 'underline decoration-primary/50 underline-offset-4',
strikethrough: 'line-through opacity-70',
code: 'font-mono bg-secondary-hover rounded px-1.5 py-0.5 text-sm text-primary border border-border-color',
},
link: 'text-primary underline decoration-primary/30 hover:decoration-primary transition-colors cursor-pointer',
image: 'my-6 flex justify-center',
table: 'my-6 w-full border-collapse border border-border-color text-sm',
tableCell: 'border border-border-color px-3 py-2 align-top bg-secondary/40',
tableCellHeader: 'bg-secondary text-text-main font-semibold',
tableRow: 'even:bg-secondary/60',
tableSelection: 'outline outline-2 outline-primary',
};
const Placeholder: React.FC = () => null;
const normalizeUrl = (url: string): string => {
const trimmed = url.trim();
if (!trimmed) {
return '';
}
if (/^[a-zA-Z][\w+.-]*:/.test(trimmed)) {
return trimmed;
}
return `https://${trimmed}`;
};
const LinkModal: React.FC<{
isOpen: boolean;
initialUrl: string;
onSubmit: (url: string) => void;
onRemove: () => void;
onClose: () => void;
}> = ({ isOpen, initialUrl, onSubmit, onRemove, onClose }) => {
const inputRef = useRef<HTMLInputElement>(null);
const [url, setUrl] = useState(initialUrl);
useEffect(() => {
setUrl(initialUrl);
}, [initialUrl]);
const handleSubmit = (event: React.FormEvent) => {
event.preventDefault();
onSubmit(url);
};
if (!isOpen) {
return null;
}
return (
<Modal onClose={onClose} title="Insert link" initialFocusRef={inputRef}>
<form onSubmit={handleSubmit}>
<div className="p-6 space-y-3">
<label className="block text-sm font-semibold text-text-main" htmlFor="link-url-input">
Link URL
</label>
<input
id="link-url-input"
ref={inputRef}
type="text"
inputMode="url"
autoComplete="url"
required
value={url}
onChange={event => setUrl(event.target.value)}
className="w-full rounded-md border border-border-color bg-background px-3 py-2 text-sm text-text-main focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/30"
placeholder="https://example.com"
/>
<p className="text-xs text-text-secondary">
Enter a valid URL. If you omit the protocol, https:// will be added automatically.
</p>
</div>
<div className="flex justify-end gap-3 px-6 py-4 bg-background/50 border-t border-border-color rounded-b-lg">
<Button type="button" variant="secondary" onClick={onClose}>
Cancel
</Button>
<Button type="button" variant="secondary" onClick={onRemove}>
Remove link
</Button>
<Button type="submit">Save link</Button>
</div>
</form>
</Modal>
);
};
const TableModal: React.FC<{
isOpen: boolean;
onClose: () => void;
onInsertTable: (rows: number, columns: number, includeHeaderRow: boolean) => void;
onInsertRowAbove: () => void;
onInsertRowBelow: () => void;
onInsertColumnLeft: () => void;
onInsertColumnRight: () => void;
onDeleteRow: () => void;
onDeleteColumn: () => void;
onDeleteTable: () => void;
onToggleHeaderRow: () => void;
isInTable: boolean;
hasHeaderRow: boolean;
}> = ({
isOpen,
onClose,
onInsertTable,
onInsertRowAbove,
onInsertRowBelow,
onInsertColumnLeft,
onInsertColumnRight,
onDeleteRow,
onDeleteColumn,
onDeleteTable,
onToggleHeaderRow,
isInTable,
hasHeaderRow,
}) => {
const [rows, setRows] = useState(3);
const [columns, setColumns] = useState(3);
const [includeHeaderRow, setIncludeHeaderRow] = useState(true);
const [hoveredGrid, setHoveredGrid] = useState<{ rows: number; columns: number } | null>(null);
const inputRef = useRef<HTMLInputElement>(null);
const displayRows = hoveredGrid?.rows ?? rows;
const displayColumns = hoveredGrid?.columns ?? columns;
useEffect(() => {
if (!isOpen) {
return;
}
setRows(3);
setColumns(3);
setIncludeHeaderRow(true);
setHoveredGrid(null);
}, [isOpen]);
const handleSubmit = (event: React.FormEvent) => {
event.preventDefault();
onInsertTable(displayRows, displayColumns, includeHeaderRow);
};
const handleGridClick = (row: number, column: number) => {
setRows(row);
setColumns(column);
setHoveredGrid(null);
onInsertTable(row, column, includeHeaderRow);
};
if (!isOpen) {
return null;
}
return (
<Modal title="Table options" onClose={onClose} initialFocusRef={inputRef}>
<form onSubmit={handleSubmit} className="px-4 py-3 space-y-4">
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
<div className="space-y-3">
<div className="flex items-center justify-between text-sm text-text-secondary">
<span>Select size</span>
<span>
{displayRows} × {displayColumns} cells
</span>
</div>
<div className="grid grid-cols-6 gap-1 rounded-md border border-border-color bg-secondary/70 p-3">
{Array.from({ length: 6 }).map((_, rowIndex) => (
<React.Fragment key={`row-${rowIndex}`}>
{Array.from({ length: 6 }).map((_, columnIndex) => {
const rowNumber = rowIndex + 1;
const columnNumber = columnIndex + 1;
const isActive =
(hoveredGrid?.rows ?? rows) >= rowNumber && (hoveredGrid?.columns ?? columns) >= columnNumber;
return (
<button
type="button"
key={`cell-${rowNumber}-${columnNumber}`}
onMouseEnter={() => setHoveredGrid({ rows: rowNumber, columns: columnNumber })}
onMouseLeave={() => setHoveredGrid(null)}
onFocus={() => setHoveredGrid({ rows: rowNumber, columns: columnNumber })}
onBlur={() => setHoveredGrid(null)}
onClick={() => handleGridClick(rowNumber, columnNumber)}
className={`h-8 w-8 rounded border ${
isActive ? 'border-primary bg-primary/10' : 'border-border-color bg-secondary-hover'
} focus:outline-none focus:ring-1 focus:ring-primary/60`}
aria-label={`Insert ${rowNumber} by ${columnNumber} table`}
/>
);
})}
</React.Fragment>
))}
</div>
</div>
<div className="space-y-3">
<label className="block text-sm font-medium text-text-main" htmlFor="table-rows">
Custom size
</label>
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1">
<span className="text-xs text-text-secondary">Rows</span>
<input
id="table-rows"
ref={inputRef}
type="number"
min={1}
max={20}
value={rows}
onChange={event => setRows(Math.max(1, Math.min(20, Number(event.target.value) || 1)))}
className="w-full rounded-md border border-border-color bg-primary-text/5 px-3 py-2 text-sm text-text-main focus:border-primary focus:ring-1 focus:ring-primary"
/>
</div>
<div className="space-y-1">
<span className="text-xs text-text-secondary">Columns</span>
<input
type="number"
min={1}
max={20}
value={columns}
onChange={event => setColumns(Math.max(1, Math.min(20, Number(event.target.value) || 1)))}
className="w-full rounded-md border border-border-color bg-primary-text/5 px-3 py-2 text-sm text-text-main focus:border-primary focus:ring-1 focus:ring-primary"
/>
</div>
</div>
<label className="flex items-center gap-2 text-sm text-text-main">
<input
type="checkbox"
checked={includeHeaderRow}
onChange={event => setIncludeHeaderRow(event.target.checked)}
className="h-4 w-4 rounded border-border-color text-primary focus:ring-primary"
/>
<span>Use first row as a header</span>
</label>
<div className="flex justify-end">
<Button type="submit" size="sm" className="px-3">
Insert table
</Button>
</div>
</div>
</div>
<div className="space-y-2 border-t border-border-color pt-3">
<div className="flex items-center justify-between text-sm text-text-secondary">
<span>Current table tools</span>
<span>{isInTable ? 'Actions apply to the selected cell' : 'Place the caret inside a table to enable tools'}</span>
</div>
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
<Button type="button" size="sm" variant="secondary" onClick={onInsertRowAbove} disabled={!isInTable}>
Insert row above
</Button>
<Button type="button" size="sm" variant="secondary" onClick={onInsertRowBelow} disabled={!isInTable}>
Insert row below
</Button>
<Button type="button" size="sm" variant="secondary" onClick={onInsertColumnLeft} disabled={!isInTable}>
Insert column left
</Button>
<Button type="button" size="sm" variant="secondary" onClick={onInsertColumnRight} disabled={!isInTable}>
Insert column right
</Button>
<Button type="button" size="sm" variant="secondary" onClick={onToggleHeaderRow} disabled={!isInTable}>
{hasHeaderRow ? 'Remove header row' : 'Add header row'}
</Button>
<Button type="button" size="sm" variant="secondary" onClick={onDeleteRow} disabled={!isInTable}>
Delete row
</Button>
<Button type="button" size="sm" variant="secondary" onClick={onDeleteColumn} disabled={!isInTable}>
Delete column
</Button>
<Button
type="button"
size="sm"
variant="ghost"
className="text-danger hover:bg-danger/10"
onClick={onDeleteTable}
disabled={!isInTable}
>
Delete table
</Button>
</div>
</div>
</form>
</Modal>
);
};
const ToolbarButton: React.FC<ToolbarButtonConfig> = ({ label, icon: Icon, isActive = false, disabled = false, onClick }) => (
<IconButton
type="button"
tooltip={label}
size="xs"
variant="ghost"
onMouseDown={event => {
// Prevent the toolbar button from stealing focus, which would clear the
// user's selection in the editor before the command executes.
event.preventDefault();
}}
onClick={onClick}
disabled={disabled}
aria-pressed={isActive}
aria-label={label}
className={`transition-all duration-200 ${isActive
? 'bg-primary/10 text-primary hover:bg-primary/20 hover:text-primary shadow-sm'
: 'text-text-secondary hover:text-text-main hover:bg-secondary-hover'
} disabled:opacity-30 disabled:pointer-events-none`}
>
<Icon className="h-4 w-4" />
</IconButton>
);
const ToolbarPlugin: React.FC<{
readOnly: boolean;
onActionsChange: (actions: ToolbarButtonConfig[]) => void;
}> = ({ readOnly, onActionsChange }) => {
const [editor] = useLexicalComposerContext();
const fileInputRef = useRef<HTMLInputElement>(null);
const [isBold, setIsBold] = useState(false);
const [isItalic, setIsItalic] = useState(false);
const [isUnderline, setIsUnderline] = useState(false);
const [isStrikethrough, setIsStrikethrough] = useState(false);
const [isCode, setIsCode] = useState(false);
const [isLink, setIsLink] = useState(false);
const [blockType, setBlockType] = useState<BlockType>('paragraph');
const [alignment, setAlignment] = useState<'left' | 'center' | 'right' | 'justify'>('left');
const [canUndo, setCanUndo] = useState(false);
const [canRedo, setCanRedo] = useState(false);
const [isLinkModalOpen, setIsLinkModalOpen] = useState(false);
const [linkDraftUrl, setLinkDraftUrl] = useState('');
const [isTableModalOpen, setIsTableModalOpen] = useState(false);
const [isInTable, setIsInTable] = useState(false);
const [hasHeaderRow, setHasHeaderRow] = useState(false);
const pendingLinkSelectionRef = useRef<SelectionSnapshot>(null);
const pendingTableSelectionRef = useRef<SelectionSnapshot>(null);
const closeLinkModal = useCallback(() => {
setIsLinkModalOpen(false);
}, []);
const dismissLinkModal = useCallback(() => {
pendingLinkSelectionRef.current = null;
closeLinkModal();
}, [closeLinkModal]);
const restoreSelectionFromSnapshot = useCallback(
(snapshot: SelectionSnapshot | null | undefined = pendingLinkSelectionRef.current) => {
const snapshotToUse = snapshot ?? pendingLinkSelectionRef.current;
if (!snapshotToUse) {
return null;
}
if (snapshotToUse.type === 'table') {
const selection = $createTableSelection();
const tableNode = $getNodeByKey(snapshotToUse.tableKey);
const anchorCell = $getNodeByKey(snapshotToUse.anchorCellKey);
const focusCell = $getNodeByKey(snapshotToUse.focusCellKey);
if (!tableNode || !anchorCell || !focusCell) {
return null;
}
selection.set(snapshotToUse.tableKey, snapshotToUse.anchorCellKey, snapshotToUse.focusCellKey);
return selection;
}
if (snapshotToUse.type === 'range') {
const selection = $createRangeSelection();
const anchorNode = $getNodeByKey(snapshotToUse.anchorKey);
const focusNode = $getNodeByKey(snapshotToUse.focusKey);
if (!anchorNode || !focusNode) {
return null;
}
selection.anchor.set(snapshotToUse.anchorKey, snapshotToUse.anchorOffset, snapshotToUse.anchorType);
selection.focus.set(snapshotToUse.focusKey, snapshotToUse.focusOffset, snapshotToUse.focusType);
return selection;
}
const selection = $createNodeSelection();
snapshotToUse.keys.forEach(key => {
const node = $getNodeByKey(key);
if (node) {
selection.add(node.getKey());
}
});
return selection.getNodes().length > 0 ? selection : null;
}, []);
const updateToolbar = useCallback(() => {
const selection = $getSelection();
const hasValidSelection = $isRangeSelection(selection) || $isTableSelection(selection);
if (!hasValidSelection) {
setIsBold(false);
setIsItalic(false);
setIsUnderline(false);
setIsStrikethrough(false);
setIsCode(false);
setIsLink(false);
setBlockType('paragraph');
setAlignment('left');
setIsInTable(false);
setHasHeaderRow(false);
return;
}
const anchorNode = selection.anchor.getNode();
const tableCellNode = $getTableCellNodeFromLexicalNode(anchorNode);
if (tableCellNode) {
const tableNode = $getTableNodeFromLexicalNodeOrThrow(tableCellNode);
setIsInTable(true);
const firstRow = tableNode.getFirstChild();
let hasHeader = false;
if (firstRow && $isTableRowNode(firstRow)) {
hasHeader = firstRow.getChildren().some(child => $isTableCellNode(child) && child.hasHeaderState(TableCellHeaderStates.ROW));
}
setHasHeaderRow(hasHeader);
} else {
setIsInTable(false);
setHasHeaderRow(false);
}
if (!$isRangeSelection(selection)) {
setIsBold(false);
setIsItalic(false);
setIsUnderline(false);
setIsStrikethrough(false);
setIsCode(false);
setIsLink(false);
setBlockType('paragraph');
setAlignment('left');
return;
}
setIsBold(selection.hasFormat('bold'));
setIsItalic(selection.hasFormat('italic'));
setIsUnderline(selection.hasFormat('underline'));
setIsStrikethrough(selection.hasFormat('strikethrough'));
setIsCode(selection.hasFormat('code'));
const element = anchorNode.getTopLevelElementOrThrow();
if ($isHeadingNode(element)) {
setBlockType(element.getTag());
} else if ($isListNode(element)) {
setBlockType(element.getListType());
} else if (element.getType() === 'quote') {
setBlockType('quote');
} else {
setBlockType('paragraph');
}
const elementAlignment = element.getFormatType();
setAlignment((elementAlignment || 'left') as 'left' | 'center' | 'right' | 'justify');
const nodes = selection.getNodes();
setIsLink(nodes.some(node => $isLinkNode(node) || $isLinkNode(node.getParent())));
}, []);
useEffect(() => {
return mergeRegister(
editor.registerCommand(
SELECTION_CHANGE_COMMAND,
() => {
updateToolbar();
return false;
},
COMMAND_PRIORITY_CRITICAL,
),
editor.registerUpdateListener(({ editorState }) => {
editorState.read(() => {
updateToolbar();
});
}),
editor.registerCommand(
CAN_UNDO_COMMAND,
payload => {
setCanUndo(payload);
return false;
},
COMMAND_PRIORITY_CRITICAL,
),
editor.registerCommand(
CAN_REDO_COMMAND,
payload => {
setCanRedo(payload);
return false;
},
COMMAND_PRIORITY_CRITICAL,
),
);
}, [editor, updateToolbar]);
const formatHeading = useCallback(
(heading: HeadingTagType) => {
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
$setBlocksType(selection, () => $createHeadingNode(heading));
}
});
},
[editor],
);
const formatParagraph = useCallback(() => {
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
$setBlocksType(selection, () => $createParagraphNode());
}
});
}, [editor]);
const formatQuote = useCallback(() => {
editor.update(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
$setBlocksType(selection, () => $createQuoteNode());
}
});
}, [editor]);
const captureLinkState = useCallback(() => {
let detectedUrl = '';
editor.getEditorState().read(() => {
const selection = $getSelection();
if ($isRangeSelection(selection)) {
pendingLinkSelectionRef.current = {
type: 'range',
anchorKey: selection.anchor.key,
anchorOffset: selection.anchor.offset,
anchorType: selection.anchor.type,
focusKey: selection.focus.key,
focusOffset: selection.focus.offset,
focusType: selection.focus.type,
};
const selectionNodes = selection.getNodes();
if (selectionNodes.length === 0) {
return;
}
const firstNode = selectionNodes[0];
const linkNode = $isLinkNode(firstNode)
? firstNode
: $isLinkNode(firstNode.getParent())
? firstNode.getParent()
: null;
if ($isLinkNode(linkNode)) {
detectedUrl = linkNode.getURL();
}
return;
}
if ($isNodeSelection(selection)) {
const nodes = selection.getNodes();
pendingLinkSelectionRef.current = { type: 'node', keys: nodes.map(node => node.getKey()) };
} else {
pendingLinkSelectionRef.current = null;
}
});
if (!pendingLinkSelectionRef.current) {
return false;
}
setLinkDraftUrl(detectedUrl);
setIsLinkModalOpen(true);
return true;
}, [editor]);
const captureTableSelection = useCallback(() => {
let snapshot: SelectionSnapshot = null;
editor.getEditorState().read(() => {
const selection = $getSelection();
if ($isTableSelection(selection)) {
const anchorCell = $getTableCellNodeFromLexicalNode(selection.anchor.getNode());
const focusCell = $getTableCellNodeFromLexicalNode(selection.focus.getNode());
if (!anchorCell || !focusCell) {
return;
}
const tableNode = $getTableNodeFromLexicalNodeOrThrow(anchorCell);
snapshot = {
type: 'table',
tableKey: tableNode.getKey(),
anchorCellKey: anchorCell.getKey(),
focusCellKey: focusCell.getKey(),
};
return;
}
if ($isRangeSelection(selection)) {
const anchorCell = $getTableCellNodeFromLexicalNode(selection.anchor.getNode());
const focusCell = $getTableCellNodeFromLexicalNode(selection.focus.getNode());
if (!anchorCell || !focusCell) {
return;
}
snapshot = {
type: 'range',
anchorKey: selection.anchor.key,
anchorOffset: selection.anchor.offset,
anchorType: selection.anchor.type,
focusKey: selection.focus.key,
focusOffset: selection.focus.offset,
focusType: selection.focus.type,
};
}
});
pendingTableSelectionRef.current = snapshot;
return snapshot !== null;
}, [editor]);
const applyLink = useCallback(
(url: string) => {
closeLinkModal();
const selectionSnapshot = pendingLinkSelectionRef.current;
pendingLinkSelectionRef.current = null;
const normalizedUrl = normalizeUrl(url);
if (!normalizedUrl) {
editor.focus();
return;
}
editor.update(() => {
const selectionFromSnapshot = restoreSelectionFromSnapshot(selectionSnapshot);
const selectionToUse = selectionFromSnapshot ?? (() => {
const activeSelection = $getSelection();
if ($isRangeSelection(activeSelection) || $isNodeSelection(activeSelection)) {
return activeSelection;
}
const root = $getRoot();
return root.selectEnd();
})();
if (!selectionToUse) {
return;
}
$setSelection(selectionToUse);
editor.dispatchCommand(TOGGLE_LINK_COMMAND, normalizedUrl);
});
editor.focus();
},
[closeLinkModal, editor, restoreSelectionFromSnapshot],
);
const removeLink = useCallback(() => {
closeLinkModal();
const selectionSnapshot = pendingLinkSelectionRef.current;
pendingLinkSelectionRef.current = null;
editor.update(() => {
const selectionFromSnapshot = restoreSelectionFromSnapshot(selectionSnapshot);
const selectionToUse = selectionFromSnapshot ?? (() => {
const activeSelection = $getSelection();
if ($isRangeSelection(activeSelection) || $isNodeSelection(activeSelection)) {
return activeSelection;
}
const root = $getRoot();
return root.selectEnd();
})();
if (!selectionToUse) {
return;
}
$setSelection(selectionToUse);
editor.dispatchCommand(TOGGLE_LINK_COMMAND, null);
});
editor.focus();
}, [closeLinkModal, editor, restoreSelectionFromSnapshot]);
const toggleLink = useCallback(() => {
if (readOnly) {
return;
}
const hasSelection = captureLinkState();
if (!hasSelection) {
editor.focus();
}
}, [captureLinkState, editor, readOnly]);
const insertImage = useCallback(
(payload: ImagePayload) => {
if (!payload.src) {
return;
}
editor.dispatchCommand(INSERT_IMAGE_COMMAND, payload);
},
[editor],
);
const closeTableModal = useCallback(() => {
pendingTableSelectionRef.current = null;
setIsTableModalOpen(false);
}, []);
const openTableModal = useCallback(() => {
if (readOnly) {
return;
}
captureTableSelection();
setIsTableModalOpen(true);
}, [captureTableSelection, readOnly]);
const runWithActiveTable = useCallback(
(action: (selection: RangeSelection | NodeSelection | TableSelection) => void) => {
editor.update(() => {
let selection = $getSelection();
if (!selection || (!$isRangeSelection(selection) && !$isTableSelection(selection))) {
const restoredSelection = restoreSelectionFromSnapshot(pendingTableSelectionRef.current);
if (restoredSelection) {
$setSelection(restoredSelection);
selection = restoredSelection;
}
}
if (!selection || (!$isRangeSelection(selection) && !$isTableSelection(selection))) {
return;
}
const anchorNode = selection.anchor.getNode();
if (!$getTableCellNodeFromLexicalNode(anchorNode)) {
return;
}
action(selection);
});
},
[editor, restoreSelectionFromSnapshot],
);
const insertTable = useCallback(
(rows: number, columns: number, includeHeaderRow: boolean) => {
if (readOnly) {
return;
}
const normalizedRows = Math.max(1, Math.min(20, rows));
const normalizedColumns = Math.max(1, Math.min(20, columns));
editor.dispatchCommand(INSERT_TABLE_COMMAND, {
columns: String(normalizedColumns),
rows: String(normalizedRows),
includeHeaders: includeHeaderRow ? { rows: true, columns: false } : false,
});
setIsTableModalOpen(false);
editor.focus();
},
[editor, readOnly],
);
const insertTableRow = useCallback(
(insertAfter: boolean) =>
runWithActiveTable(() => {
$insertTableRow__EXPERIMENTAL(insertAfter);
}),
[runWithActiveTable],
);
const insertTableColumn = useCallback(
(insertAfter: boolean) =>
runWithActiveTable(() => {
$insertTableColumn__EXPERIMENTAL(insertAfter);
}),
[runWithActiveTable],
);
const deleteTableRow = useCallback(
() =>
runWithActiveTable(() => {
$deleteTableRow__EXPERIMENTAL();
}),
[runWithActiveTable],
);
const deleteTableColumn = useCallback(
() =>
runWithActiveTable(() => {
$deleteTableColumn__EXPERIMENTAL();
}),
[runWithActiveTable],
);
const deleteTable = useCallback(() => {
runWithActiveTable(selection => {
const tableCell = $getTableCellNodeFromLexicalNode(selection.anchor.getNode());
if (!tableCell) {
return;
}
const tableNode = $getTableNodeFromLexicalNodeOrThrow(tableCell);
tableNode.remove();
});
setIsTableModalOpen(false);
}, [runWithActiveTable]);
const toggleHeaderRow = useCallback(
() =>
runWithActiveTable(selection => {
const tableCell = $getTableCellNodeFromLexicalNode(selection.anchor.getNode());
if (!tableCell) {
return;
}
const tableNode = $getTableNodeFromLexicalNodeOrThrow(tableCell);
const firstRow = tableNode.getFirstChild();
if (!firstRow || !$isTableRowNode(firstRow)) {
return;
}