@folijs/react 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,756 @@
1
+ import {
2
+ type Alignment,
3
+ AllSelection,
4
+ alignAt,
5
+ type Command,
6
+ colorAt,
7
+ type Editor,
8
+ type EditorState,
9
+ insertHorizontalRule,
10
+ insertPageBreak,
11
+ isSafeHref,
12
+ liftListItem,
13
+ linkAt,
14
+ listTypeAt,
15
+ NodeSelection,
16
+ normalizeHref,
17
+ openLinkEditor,
18
+ redo,
19
+ redoDepth,
20
+ removeLink,
21
+ requestsLinkEditor,
22
+ setAlign,
23
+ setBlockType,
24
+ setHighlight,
25
+ setLink,
26
+ setTextColor,
27
+ sinkListItem,
28
+ toggleList,
29
+ toggleMark,
30
+ undo,
31
+ undoDepth,
32
+ wrapInList,
33
+ } from "@folijs/core";
34
+ import {
35
+ type FormEvent,
36
+ Fragment,
37
+ type KeyboardEvent,
38
+ type MouseEvent,
39
+ type ReactNode,
40
+ useEffect,
41
+ useId,
42
+ useRef,
43
+ useState,
44
+ } from "react";
45
+ import { useEditorOrContext, useEditorState } from "./editor.js";
46
+
47
+ export interface FoliToolbarProps {
48
+ /** Default: the editor of the nearest `FoliEditorProvider`. */
49
+ editor?: Editor | undefined;
50
+ /**
51
+ * Every button is disabled. Pass it whenever the canvas is `readOnly`: commands run through
52
+ * the editor, which code may always change (`FoliEditor` does this for you).
53
+ */
54
+ disabled?: boolean | undefined;
55
+ /**
56
+ * Called after a click ran a command, to show its result in the document (`FoliEditor`
57
+ * focuses its canvas). Keyboard activation keeps the focus in the toolbar.
58
+ */
59
+ onClickCommand?: (() => void) | undefined;
60
+ /** Accessible name of the toolbar (default "Formatting"). */
61
+ label?: string | undefined;
62
+ className?: string | undefined;
63
+ }
64
+
65
+ interface Item {
66
+ key: string;
67
+ /** Tooltip: what the button does. */
68
+ label: string;
69
+ /** Visible text: the accessible name, unless it is a symbol (then the label is). */
70
+ text: string;
71
+ symbol?: boolean;
72
+ /** Shown instead of `text` (a symbol: the label is the name). */
73
+ icon?: ReactNode;
74
+ /** Whether the button shows as pressed (toggle buttons only). */
75
+ pressed?: (state: EditorState, editor: Editor) => boolean;
76
+ /**
77
+ * Whether the command can run now (default: always; in schema v1 every selection is in
78
+ * textblocks, which take every mark, block type and page break). A cheap check, not a dry
79
+ * run: it runs after every transaction, and a dry run builds the whole transaction (for a
80
+ * block type over a large selection, quadratic in the number of blocks).
81
+ */
82
+ enabled?: (state: EditorState) => boolean;
83
+ /** The command a press runs (not for a menu button). */
84
+ command?: (state: EditorState) => Command;
85
+ /** A menu button: its options, the current value, and what picking one runs. */
86
+ menu?: {
87
+ options: readonly ColorOption[];
88
+ value: (state: EditorState) => string | null;
89
+ pick: (color: string | null) => Command;
90
+ };
91
+ }
92
+
93
+ interface ColorOption {
94
+ name: string;
95
+ /** Lowercase `#rrggbb`; null removes the color. */
96
+ color: string | null;
97
+ }
98
+
99
+ /**
100
+ * The palettes (fixed: a document should not need a color picker). Text colors keep at least
101
+ * 4.5:1 contrast on white; highlights keep dark text readable.
102
+ */
103
+ const TEXT_COLORS: readonly ColorOption[] = [
104
+ { name: "Automatic", color: null },
105
+ { name: "Gray", color: "#5f6368" },
106
+ { name: "Red", color: "#c00000" },
107
+ { name: "Orange", color: "#b45309" },
108
+ { name: "Green", color: "#2e7d32" },
109
+ { name: "Blue", color: "#1f5fbf" },
110
+ { name: "Purple", color: "#7030a0" },
111
+ ];
112
+ const HIGHLIGHTS: readonly ColorOption[] = [
113
+ { name: "None", color: null },
114
+ { name: "Yellow", color: "#fff59d" },
115
+ { name: "Green", color: "#c8e6c9" },
116
+ { name: "Blue", color: "#bbdefb" },
117
+ { name: "Pink", color: "#f8bbd0" },
118
+ { name: "Orange", color: "#ffe0b2" },
119
+ { name: "Gray", color: "#e0e0e0" },
120
+ ];
121
+
122
+ /** Whether the selection holds a textblock (a caret's own block first; else it walks the range). */
123
+ function hasTextblock(state: EditorState): boolean {
124
+ if (state.selection.$from.parent.isTextblock) return true;
125
+ let found = false;
126
+ state.doc.nodesBetween(state.selection.from, state.selection.to, (node) => {
127
+ if (node.isTextblock) found = true;
128
+ return !found;
129
+ });
130
+ return found;
131
+ }
132
+
133
+ /** Four bars, like the alignment they stand for (x and width per bar). */
134
+ const alignIcon = (bars: readonly [number, number][]) => (
135
+ <svg viewBox="0 0 16 16" width="16" height="16" aria-hidden="true" focusable="false">
136
+ {bars.map(([x, width], i) => (
137
+ // biome-ignore lint/suspicious/noArrayIndexKey: a fixed drawing.
138
+ <rect key={i} x={x} y={2.5 + i * 3.5} width={width} height="1.5" fill="currentColor" />
139
+ ))}
140
+ </svg>
141
+ );
142
+
143
+ const align = (value: Alignment, label: string, bars: readonly [number, number][]): Item => ({
144
+ key: `align-${value}`,
145
+ label,
146
+ text: label,
147
+ symbol: true,
148
+ icon: alignIcon(bars),
149
+ pressed: (state) => alignAt(state) === value,
150
+ enabled: hasTextblock,
151
+ command: () => setAlign(value),
152
+ });
153
+
154
+ /** Whether the selection holds textblocks and all of them are `type` with `level` (if given). */
155
+ function blockIs(state: EditorState, type: string, level?: number): boolean {
156
+ const { from, to } = state.selection;
157
+ let all = true;
158
+ let any = false;
159
+ state.doc.nodesBetween(from, to, (node) => {
160
+ if (!all) return false;
161
+ if (node.isTextblock) {
162
+ any = true;
163
+ if (node.type.name !== type || (level && node.attrs.level !== level)) all = false;
164
+ }
165
+ return !node.isTextblock;
166
+ });
167
+ return any && all;
168
+ }
169
+
170
+ const mark = (key: string, label: string, text: string): Item => ({
171
+ key,
172
+ label,
173
+ text,
174
+ symbol: true,
175
+ pressed: (_state, editor) => editor.isMarkActive(key),
176
+ command: () => toggleMark(key),
177
+ });
178
+
179
+ const heading = (level: number): Item => ({
180
+ key: `h${level}`,
181
+ label: `Heading ${level}`,
182
+ text: `H${level}`,
183
+ pressed: (state) => blockIs(state, "heading", level),
184
+ // Pressing an active heading turns it back into a paragraph.
185
+ command: (state) =>
186
+ blockIs(state, "heading", level)
187
+ ? setBlockType("paragraph")
188
+ : setBlockType("heading", { level }),
189
+ });
190
+
191
+ const GROUPS: Item[][] = [
192
+ [
193
+ mark("bold", "Bold", "B"),
194
+ mark("italic", "Italic", "I"),
195
+ mark("underline", "Underline", "U"),
196
+ mark("strike", "Strikethrough", "S"),
197
+ {
198
+ key: "link",
199
+ label: "Link",
200
+ text: "Link",
201
+ pressed: (state) => linkAt(state) !== null,
202
+ enabled: (state) => openLinkEditor(state),
203
+ // Asks for the link dialog, as Mod-K does: the toolbar listens for that request.
204
+ command: () => openLinkEditor,
205
+ },
206
+ {
207
+ key: "textColor",
208
+ label: "Text color",
209
+ text: "A",
210
+ symbol: true,
211
+ enabled: hasTextblock,
212
+ menu: {
213
+ options: TEXT_COLORS,
214
+ value: (state) => colorAt(state, "textColor"),
215
+ pick: setTextColor,
216
+ },
217
+ },
218
+ {
219
+ key: "highlight",
220
+ label: "Highlight",
221
+ text: "H",
222
+ symbol: true,
223
+ enabled: hasTextblock,
224
+ menu: {
225
+ options: HIGHLIGHTS,
226
+ value: (state) => colorAt(state, "highlight"),
227
+ pick: setHighlight,
228
+ },
229
+ },
230
+ ],
231
+ [
232
+ {
233
+ key: "paragraph",
234
+ label: "Paragraph",
235
+ text: "¶",
236
+ symbol: true,
237
+ pressed: (state) => blockIs(state, "paragraph"),
238
+ command: () => setBlockType("paragraph"),
239
+ },
240
+ heading(1),
241
+ heading(2),
242
+ heading(3),
243
+ ],
244
+ [
245
+ align("start", "Align left", [
246
+ [1, 14],
247
+ [1, 9],
248
+ [1, 14],
249
+ [1, 9],
250
+ ]),
251
+ align("center", "Center", [
252
+ [1, 14],
253
+ [3.5, 9],
254
+ [1, 14],
255
+ [3.5, 9],
256
+ ]),
257
+ align("end", "Align right", [
258
+ [1, 14],
259
+ [6, 9],
260
+ [1, 14],
261
+ [6, 9],
262
+ ]),
263
+ align("justify", "Justify", [
264
+ [1, 14],
265
+ [1, 14],
266
+ [1, 14],
267
+ [1, 14],
268
+ ]),
269
+ ],
270
+ [
271
+ {
272
+ key: "bulletList",
273
+ label: "Bulleted list",
274
+ text: "•",
275
+ symbol: true,
276
+ pressed: (state) => listTypeAt(state)?.name === "bulletList",
277
+ enabled: (state) => listTypeAt(state) !== null || wrapInList("bulletList")(state),
278
+ command: () => toggleList("bulletList"),
279
+ },
280
+ {
281
+ key: "orderedList",
282
+ label: "Numbered list",
283
+ // A symbol, not "1.": visible text that is not part of the name fails WCAG 2.5.3.
284
+ text: "№",
285
+ symbol: true,
286
+ pressed: (state) => listTypeAt(state)?.name === "orderedList",
287
+ enabled: (state) => listTypeAt(state) !== null || wrapInList("orderedList")(state),
288
+ command: () => toggleList("orderedList"),
289
+ },
290
+ {
291
+ key: "outdent",
292
+ label: "Decrease indent",
293
+ text: "⇤",
294
+ symbol: true,
295
+ enabled: (state) => listTypeAt(state) !== null,
296
+ command: () => liftListItem(),
297
+ },
298
+ {
299
+ key: "indent",
300
+ label: "Increase indent",
301
+ text: "⇥",
302
+ symbol: true,
303
+ enabled: (state) => canIndent(state),
304
+ command: () => sinkListItem(),
305
+ },
306
+ ],
307
+ [
308
+ {
309
+ key: "undo",
310
+ label: "Undo",
311
+ text: "Undo",
312
+ enabled: (state) => undoDepth(state) > 0,
313
+ command: () => undo,
314
+ },
315
+ {
316
+ key: "redo",
317
+ label: "Redo",
318
+ text: "Redo",
319
+ enabled: (state) => redoDepth(state) > 0,
320
+ command: () => redo,
321
+ },
322
+ ],
323
+ [
324
+ {
325
+ key: "horizontalRule",
326
+ label: "Horizontal rule",
327
+ text: "―",
328
+ symbol: true,
329
+ enabled: (state) =>
330
+ state.selection.$from.parent.isTextblock ||
331
+ state.selection instanceof AllSelection ||
332
+ (state.selection instanceof NodeSelection && state.selection.node.isBlock),
333
+ command: () => insertHorizontalRule,
334
+ },
335
+ { key: "pageBreak", label: "Page break", text: "Page break", command: () => insertPageBreak },
336
+ ],
337
+ ];
338
+ const ITEMS = GROUPS.flat();
339
+
340
+ /** Whether the selection starts in a list item that has an item before it (cheap: no dry run). */
341
+ function canIndent(state: EditorState): boolean {
342
+ const { $from } = state.selection;
343
+ for (let depth = $from.depth; depth > 0; depth--) {
344
+ if ($from.node(depth).type.name === "listItem") return $from.index(depth - 1) > 0;
345
+ }
346
+ return false;
347
+ }
348
+
349
+ interface LinkDialogState {
350
+ /** The link at the selection when the dialog opened ("" for none). */
351
+ href: string;
352
+ selection: EditorState["selection"];
353
+ /** Where the focus goes back to on close. */
354
+ restore: HTMLElement | null;
355
+ request: number;
356
+ }
357
+
358
+ interface ItemState {
359
+ pressed: boolean | undefined;
360
+ enabled: boolean;
361
+ /** A menu button's current value (a color, or null). */
362
+ value: string | null | undefined;
363
+ }
364
+
365
+ const sameStates = (a: ItemState[], b: ItemState[]) =>
366
+ a.length === b.length &&
367
+ a.every(
368
+ (item, i) =>
369
+ item.pressed === b[i]?.pressed &&
370
+ item.enabled === b[i]?.enabled &&
371
+ item.value === b[i]?.value,
372
+ );
373
+
374
+ /** Runs after every transaction: O(selection), no transactions built. */
375
+ const selectStates = (state: EditorState, editor: Editor): ItemState[] =>
376
+ ITEMS.map((item) => ({
377
+ pressed: item.pressed?.(state, editor),
378
+ enabled: item.enabled?.(state) ?? true,
379
+ value: item.menu?.value(state),
380
+ }));
381
+
382
+ /**
383
+ * Formatting buttons for an editor: marks, link (a dialog, also on Mod-K in the document), text
384
+ * color and highlight menus, paragraph and heading levels, alignment, lists (bulleted,
385
+ * numbered, decrease and increase indent), undo, redo, horizontal rule, page break. One tab stop (arrow keys,
386
+ * Home and End move between buttons); toggles carry
387
+ * `aria-pressed`; a button whose command cannot run now is `aria-disabled` (still focusable).
388
+ * Clicks leave the focus and selection in the document.
389
+ */
390
+ export function FoliToolbar({
391
+ editor: given,
392
+ disabled = false,
393
+ onClickCommand,
394
+ label = "Formatting",
395
+ className,
396
+ }: FoliToolbarProps) {
397
+ const editor = useEditorOrContext(given, "FoliToolbar");
398
+ const states = useEditorState(selectStates, { editor, isEqual: sameStates });
399
+ const [active, setActive] = useState(0);
400
+ const buttons = useRef<(HTMLButtonElement | null)[]>([]);
401
+ // The open menu (a menu button's key), if any.
402
+ const [menu, setMenu] = useState<string | null>(null);
403
+ useEffect(() => {
404
+ if (disabled) setMenu(null);
405
+ }, [disabled]);
406
+
407
+ const run = (index: number, event: MouseEvent) => {
408
+ const item = ITEMS[index];
409
+ if (!item || disabled || !states[index]?.enabled) return;
410
+ if (item.menu) {
411
+ if (menu !== item.key) {
412
+ setMenu(item.key);
413
+ return;
414
+ }
415
+ // Closing by its button: the focus was in the menu, which goes away.
416
+ setMenu(null);
417
+ if (event.detail > 0 && onClickCommand) onClickCommand();
418
+ else buttons.current[index]?.focus();
419
+ return;
420
+ }
421
+ if (!item.command) return;
422
+ editor.run(item.command(editor.state));
423
+ // `detail` counts pointer clicks; Enter and Space on a button give 0.
424
+ if (event.detail > 0) onClickCommand?.();
425
+ };
426
+
427
+ // The link dialog opens on a request from the link button or Mod-K in the document, and
428
+ // gives the focus back to where it was (the document, or the button) when it closes. It is
429
+ // for the selection it opened on: a change to the document or the selection (a click in the
430
+ // document) closes it. A second request while it is open focuses it again.
431
+ const [dialog, setDialog] = useState<LinkDialogState | null>(null);
432
+ useEffect(
433
+ () =>
434
+ editor.subscribe((state, transactions) => {
435
+ if (disabled) return;
436
+ if (!transactions.some(requestsLinkEditor)) {
437
+ setDialog((current) =>
438
+ current &&
439
+ (transactions.some((tr) => tr.docChanged) || !state.selection.eq(current.selection))
440
+ ? null
441
+ : current,
442
+ );
443
+ return;
444
+ }
445
+ const active = typeof document === "undefined" ? null : document.activeElement;
446
+ setDialog((current) =>
447
+ current
448
+ ? { ...current, request: current.request + 1 }
449
+ : {
450
+ href: linkAt(state) ?? "",
451
+ selection: state.selection,
452
+ restore: active instanceof HTMLElement ? active : null,
453
+ request: 0,
454
+ },
455
+ );
456
+ }),
457
+ [editor, disabled],
458
+ );
459
+ // A dialog never outlives a disabled toolbar (it would come back when enabled again).
460
+ useEffect(() => {
461
+ if (disabled) setDialog(null);
462
+ }, [disabled]);
463
+ const closeDialog = () => {
464
+ dialog?.restore?.focus();
465
+ setDialog(null);
466
+ };
467
+
468
+ const onKeyDown = (event: KeyboardEvent) => {
469
+ // Alt+Left (back) and other shortcuts are the browser's.
470
+ if (event.altKey || event.ctrlKey || event.metaKey) return;
471
+ const count = ITEMS.length;
472
+ const moves: Record<string, number> = {
473
+ ArrowRight: (active + 1) % count,
474
+ ArrowLeft: (active - 1 + count) % count,
475
+ Home: 0,
476
+ End: count - 1,
477
+ };
478
+ const next = moves[event.key];
479
+ if (next === undefined) return;
480
+ event.preventDefault();
481
+ setActive(next);
482
+ buttons.current[next]?.focus();
483
+ };
484
+
485
+ let index = 0;
486
+ return (
487
+ <>
488
+ <div
489
+ role="toolbar"
490
+ aria-label={label}
491
+ className={className ? `foli-toolbar ${className}` : "foli-toolbar"}
492
+ onKeyDown={onKeyDown}
493
+ >
494
+ {GROUPS.map((group, g) => (
495
+ <Fragment key={group[0]?.key}>
496
+ {g > 0 && <hr className="foli-toolbar-separator" aria-orientation="vertical" />}
497
+ {group.map((item) => {
498
+ const i = index++;
499
+ const state = states[i];
500
+ const off = disabled || !state?.enabled;
501
+ const button = (
502
+ <button
503
+ key={item.key}
504
+ ref={(element) => {
505
+ buttons.current[i] = element;
506
+ }}
507
+ type="button"
508
+ className={`foli-toolbar-button foli-toolbar-${item.key}`}
509
+ // Speech input users say what they see: "H1", "Undo"; symbols get a name.
510
+ aria-label={item.symbol ? item.label : undefined}
511
+ title={item.label}
512
+ aria-pressed={item.pressed ? Boolean(state?.pressed) : undefined}
513
+ aria-haspopup={item.menu ? "menu" : undefined}
514
+ aria-expanded={item.menu ? menu === item.key : undefined}
515
+ aria-disabled={off || undefined}
516
+ tabIndex={i === active ? 0 : -1}
517
+ // Keep the focus (and the selection) in the document on click.
518
+ onMouseDown={(event) => event.preventDefault()}
519
+ onFocus={() => setActive(i)}
520
+ onClick={(event) => run(i, event)}
521
+ onKeyDown={(event) => {
522
+ // ArrowDown opens a menu (the WAI-ARIA menu button pattern).
523
+ if (!item.menu || off || event.key !== "ArrowDown") return;
524
+ event.preventDefault();
525
+ setMenu(item.key);
526
+ }}
527
+ >
528
+ {item.icon ?? item.text}
529
+ {item.menu && (
530
+ <span
531
+ className="foli-toolbar-swatch"
532
+ aria-hidden="true"
533
+ style={{ background: state?.value ?? "transparent" }}
534
+ />
535
+ )}
536
+ </button>
537
+ );
538
+ const options = item.menu?.options;
539
+ if (!options || !item.menu) return button;
540
+ const { pick } = item.menu;
541
+ return (
542
+ <span key={item.key} className="foli-toolbar-menu">
543
+ {button}
544
+ {menu === item.key && !disabled && (
545
+ <ColorMenu
546
+ label={item.label}
547
+ options={options}
548
+ current={state?.value ?? null}
549
+ onPick={(color, pointer) => {
550
+ editor.run(pick(color));
551
+ setMenu(null);
552
+ if (pointer) onClickCommand?.();
553
+ else buttons.current[i]?.focus();
554
+ }}
555
+ onClose={(refocus) => {
556
+ setMenu(null);
557
+ if (refocus) buttons.current[i]?.focus();
558
+ }}
559
+ />
560
+ )}
561
+ </span>
562
+ );
563
+ })}
564
+ </Fragment>
565
+ ))}
566
+ </div>
567
+ {dialog && !disabled && (
568
+ <LinkDialog
569
+ editor={editor}
570
+ href={dialog.href}
571
+ request={dialog.request}
572
+ onClose={closeDialog}
573
+ />
574
+ )}
575
+ </>
576
+ );
577
+ }
578
+
579
+ /**
580
+ * A color menu (WAI-ARIA menu with radio items): the current color checked and focused on
581
+ * open; arrow keys, Home and End move; Enter or Space (or a click) picks; Escape closes it back
582
+ * to its button, Tab closes it and moves on; leaving it (a click elsewhere) closes it.
583
+ */
584
+ function ColorMenu({
585
+ label,
586
+ options,
587
+ current,
588
+ onPick,
589
+ onClose,
590
+ }: {
591
+ label: string;
592
+ options: readonly ColorOption[];
593
+ current: string | null;
594
+ onPick: (color: string | null, pointer: boolean) => void;
595
+ onClose: (refocus: boolean) => void;
596
+ }) {
597
+ const items = useRef<(HTMLButtonElement | null)[]>([]);
598
+ const checked = Math.max(
599
+ 0,
600
+ options.findIndex((option) => option.color === current),
601
+ );
602
+ // biome-ignore lint/correctness/useExhaustiveDependencies: focus once, on open.
603
+ useEffect(() => {
604
+ items.current[checked]?.focus();
605
+ }, []);
606
+
607
+ const onKeyDown = (event: KeyboardEvent) => {
608
+ const count = options.length;
609
+ const at = items.current.indexOf(event.target as HTMLButtonElement);
610
+ const moves: Record<string, number> = {
611
+ ArrowDown: (at + 1) % count,
612
+ ArrowUp: (at - 1 + count) % count,
613
+ Home: 0,
614
+ End: count - 1,
615
+ };
616
+ const next = moves[event.key];
617
+ // The toolbar's own arrow keys must not see these.
618
+ event.stopPropagation();
619
+ if (next !== undefined) {
620
+ event.preventDefault();
621
+ items.current[next]?.focus();
622
+ } else if (event.key === "Escape") {
623
+ event.preventDefault();
624
+ onClose(true);
625
+ } else if (event.key === "Tab") {
626
+ // Back to the button, then the browser's Tab moves on from it (out of the toolbar).
627
+ onClose(true);
628
+ }
629
+ };
630
+
631
+ return (
632
+ <div
633
+ role="menu"
634
+ aria-label={label}
635
+ className="foli-menu"
636
+ onKeyDown={onKeyDown}
637
+ onBlur={(event) => {
638
+ if (!event.currentTarget.contains(event.relatedTarget as Node | null)) onClose(false);
639
+ }}
640
+ >
641
+ {options.map((option, i) => (
642
+ <button
643
+ key={option.name}
644
+ ref={(element) => {
645
+ items.current[i] = element;
646
+ }}
647
+ type="button"
648
+ role="menuitemradio"
649
+ aria-checked={option.color === current}
650
+ tabIndex={-1}
651
+ className="foli-menu-item"
652
+ onMouseDown={(event) => event.preventDefault()}
653
+ onClick={(event) => onPick(option.color, event.detail > 0)}
654
+ >
655
+ <span
656
+ className="foli-menu-swatch"
657
+ aria-hidden="true"
658
+ style={{ background: option.color ?? "transparent" }}
659
+ />
660
+ {option.name}
661
+ </button>
662
+ ))}
663
+ </div>
664
+ );
665
+ }
666
+
667
+ /**
668
+ * The link dialog: a URL field (prefilled with the link at the selection), Apply, Remove link
669
+ * (for an existing link) and Cancel; Escape cancels. An unsafe or invalid URL is not applied:
670
+ * the field is marked invalid and the message is announced.
671
+ */
672
+ function LinkDialog({
673
+ editor,
674
+ href,
675
+ request,
676
+ onClose,
677
+ }: {
678
+ editor: Editor;
679
+ href: string;
680
+ /** Counts the open requests: each one focuses the field. */
681
+ request: number;
682
+ onClose: () => void;
683
+ }) {
684
+ const [value, setValue] = useState(href);
685
+ const [invalid, setInvalid] = useState(false);
686
+ const input = useRef<HTMLInputElement>(null);
687
+ const id = useId();
688
+
689
+ // biome-ignore lint/correctness/useExhaustiveDependencies: each request focuses the field again.
690
+ useEffect(() => {
691
+ input.current?.focus();
692
+ input.current?.select();
693
+ }, [request]);
694
+
695
+ const apply = (event: FormEvent) => {
696
+ event.preventDefault();
697
+ // The same link again changes nothing (the command does not apply): that is not an error.
698
+ const normalized = normalizeHref(value);
699
+ const unchanged = isSafeHref(normalized) && linkAt(editor.state) === normalized;
700
+ if (unchanged || editor.run(setLink(value))) onClose();
701
+ else {
702
+ setInvalid(true);
703
+ input.current?.focus();
704
+ }
705
+ };
706
+ const remove = () => {
707
+ editor.run(removeLink);
708
+ onClose();
709
+ };
710
+
711
+ return (
712
+ <div
713
+ role="dialog"
714
+ aria-label={href ? "Edit link" : "Add link"}
715
+ className="foli-link-dialog"
716
+ onKeyDown={(event) => {
717
+ if (event.key !== "Escape") return;
718
+ event.preventDefault();
719
+ onClose();
720
+ }}
721
+ >
722
+ <form onSubmit={apply} noValidate>
723
+ <label htmlFor={`${id}-url`}>URL</label>
724
+ <input
725
+ ref={input}
726
+ id={`${id}-url`}
727
+ type="text"
728
+ inputMode="url"
729
+ autoComplete="off"
730
+ spellCheck={false}
731
+ value={value}
732
+ aria-invalid={invalid || undefined}
733
+ aria-describedby={invalid ? `${id}-error` : undefined}
734
+ onChange={(event) => {
735
+ setValue(event.target.value);
736
+ setInvalid(false);
737
+ }}
738
+ />
739
+ <button type="submit">Apply</button>
740
+ {href && (
741
+ <button type="button" onClick={remove}>
742
+ Remove link
743
+ </button>
744
+ )}
745
+ <button type="button" onClick={onClose}>
746
+ Cancel
747
+ </button>
748
+ {invalid && (
749
+ <p id={`${id}-error`} className="foli-link-error" role="alert">
750
+ Enter a web or email address, or a link starting with http, https, mailto or tel.
751
+ </p>
752
+ )}
753
+ </form>
754
+ </div>
755
+ );
756
+ }