@folijs/react 0.5.0 → 0.6.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,895 @@
1
+ import {
2
+ type BookmarkInfo,
3
+ deleteBookmark,
4
+ documentOutline,
5
+ type Editor,
6
+ type EditorState,
7
+ type FindMatch,
8
+ fieldCodesShown,
9
+ findAll,
10
+ goTo,
11
+ insertBookmark,
12
+ listBookmarks,
13
+ type NavigationRequest,
14
+ nextMatch,
15
+ type OutlineEntry,
16
+ type ReplaceRefusal,
17
+ type ReplaceReport,
18
+ renameBookmark,
19
+ replace,
20
+ replaceAll,
21
+ StoryStep,
22
+ type Transaction,
23
+ trackState,
24
+ wordContext,
25
+ } from "@folijs/core";
26
+ import { keyName } from "@folijs/view";
27
+ import {
28
+ type FormEvent,
29
+ type KeyboardEvent,
30
+ useCallback,
31
+ useEffect,
32
+ useId,
33
+ useMemo,
34
+ useRef,
35
+ useState,
36
+ } from "react";
37
+ import {
38
+ useActiveEditor,
39
+ useEditorOrContext,
40
+ useEditorState,
41
+ useIsomorphicLayoutEffect,
42
+ } from "./editor.js";
43
+
44
+ export interface FoliNavigationProps {
45
+ /** Default: the editor of the nearest `FoliEditorProvider`. */
46
+ editor?: Editor | undefined;
47
+ /** No replacing, and no changing bookmarks. */
48
+ readOnly?: boolean | undefined;
49
+ }
50
+
51
+ type PanelMode = "find" | "replace" | "goTo";
52
+
53
+ /** What each refusal is called in the panel's report. */
54
+ const REFUSALS: Record<ReplaceRefusal, string> = {
55
+ locked: "locked content",
56
+ control: "a content control",
57
+ field: "across a field's edge",
58
+ "field-code": "a field code",
59
+ deleted: "deleted text",
60
+ stale: "changed text",
61
+ refused: "could not be changed",
62
+ };
63
+
64
+ const WHERE: Record<string, string> = {
65
+ header: "header",
66
+ footer: "footer",
67
+ footnote: "footnote",
68
+ endnote: "endnote",
69
+ };
70
+
71
+ /** The text selected now, in the story open or the body. */
72
+ function activeState(body: Editor): { story: string | null; state: EditorState } {
73
+ const open = body.storyView?.open?.id ?? null;
74
+ const story = open ? body.story(open) : null;
75
+ return story ? { story: open, state: story.state } : { story: null, state: body.state };
76
+ }
77
+
78
+ function isSelected(body: Editor, match: FindMatch): boolean {
79
+ const { story, state } = activeState(body);
80
+ const { from, to } = state.selection;
81
+ return story === match.story && from === match.from && to === match.to;
82
+ }
83
+
84
+ /**
85
+ * `match` where `transactions` leave it, or null when they changed it or its story: until the next
86
+ * search the marks follow the text and Enter goes where they are.
87
+ */
88
+ function mapMatch(
89
+ match: FindMatch,
90
+ transactions: readonly Transaction[],
91
+ stories: ReadonlySet<string>,
92
+ ): FindMatch | null {
93
+ if (match.story !== null) return stories.has(match.story) ? null : match;
94
+ let { from, to } = match;
95
+ for (const tr of transactions)
96
+ for (const map of tr.mapping.maps) {
97
+ // Anything a step changes inside it (an edit of the same length too) ends it as a match.
98
+ let touched = false;
99
+ map.forEach((start, end) => {
100
+ if (start < to && end > from) touched = true;
101
+ });
102
+ if (touched) return null;
103
+ from = map.map(from, 1);
104
+ to = map.map(to, -1);
105
+ }
106
+ return from === match.from ? match : { ...match, from, to };
107
+ }
108
+
109
+ /** What the document shows has changed: another search is due. */
110
+ function searchKey(state: EditorState): readonly unknown[] {
111
+ return [
112
+ state.doc,
113
+ wordContext(state)?.envelope.stories,
114
+ wordContext(state)?.envelope.controls,
115
+ trackState(state)?.view,
116
+ fieldCodesShown(state),
117
+ ];
118
+ }
119
+
120
+ function reportText({ replaced, refused }: ReplaceReport): string {
121
+ const done = `Replaced ${replaced}.`;
122
+ if (!refused.length) return done;
123
+ const reasons = [...new Set(refused.map((r) => REFUSALS[r.reason]))].join(", ");
124
+ return `${done} ${refused.length} left as they are: ${reasons}.`;
125
+ }
126
+
127
+ /**
128
+ * Word's navigation for an editor: the find and replace panel (Ctrl+F, Ctrl+H, with Go to on
129
+ * Ctrl+G; F3 and Shift+F3 go to the next and previous match), the bookmarks dialog (Ctrl+Shift+F5)
130
+ * and the outline. The keys are taken only while the focus is in the document or in these panels:
131
+ * elsewhere on the page Ctrl+F stays the browser's. The toolbar's Navigate menu opens them too.
132
+ */
133
+ export function FoliNavigation({ editor: given, readOnly = false }: FoliNavigationProps) {
134
+ const body = useEditorOrContext(given, "FoliNavigation");
135
+ const active = useActiveEditor(body);
136
+ const [panel, setPanel] = useState<PanelMode | null>(null);
137
+ const [request, setRequest] = useState(0);
138
+ const [bookmarks, setBookmarks] = useState(false);
139
+ const [outline, setOutline] = useState(false);
140
+ const [query, setQuery] = useState("");
141
+ const [matchCase, setMatchCase] = useState(false);
142
+ const [wholeWord, setWholeWord] = useState(false);
143
+ /** Where the focus goes back to. */
144
+ const restore = useRef<HTMLElement | null>(null);
145
+ const live = useRef({ query, matchCase, wholeWord, panel });
146
+ live.current = { query, matchCase, wholeWord, panel };
147
+
148
+ const remember = useCallback(() => {
149
+ const element = typeof document === "undefined" ? null : document.activeElement;
150
+ // Inside the panels the focus already has a place to go back to.
151
+ if (
152
+ element instanceof HTMLElement &&
153
+ element !== document.body &&
154
+ !element.closest("[data-foli-navigation]")
155
+ )
156
+ restore.current = element;
157
+ }, []);
158
+ const giveBack = useCallback(() => {
159
+ const element = restore.current;
160
+ restore.current = null;
161
+ if (element?.isConnected && !element.closest("[aria-readonly=true]")) element.focus();
162
+ else body.storyView?.focus();
163
+ }, [body]);
164
+
165
+ useEffect(() => {
166
+ const step = (backward: boolean) => {
167
+ const current = live.current;
168
+ if (!current.query) return false;
169
+ const target = nextMatch(body, findAll(body, current.query, current), backward);
170
+ if (target) goTo(body, target, { focus: true });
171
+ return true;
172
+ };
173
+ const handler = (asked: NavigationRequest): boolean => {
174
+ if (asked === "next" || asked === "previous") {
175
+ // With the panel open its own buttons' logic runs through the keys it handles.
176
+ if (step(asked === "previous")) return true;
177
+ remember();
178
+ setPanel("find");
179
+ setRequest((n) => n + 1);
180
+ return true;
181
+ }
182
+ remember();
183
+ if (asked === "bookmarks") {
184
+ setBookmarks(true);
185
+ setRequest((n) => n + 1);
186
+ } else if (asked === "outline") setOutline((open) => !open);
187
+ else {
188
+ // What is selected is what to find, as in Word.
189
+ const { state } = activeState(body);
190
+ const { from, to, empty } = state.selection;
191
+ const text = empty ? "" : state.doc.textBetween(from, to, "\n");
192
+ if (text && text.length < 256 && !text.includes("\n")) setQuery(text);
193
+ setPanel(asked === "replace" && readOnly ? "find" : asked);
194
+ setRequest((n) => n + 1);
195
+ }
196
+ return true;
197
+ };
198
+ body.navigation = handler;
199
+ return () => {
200
+ if (body.navigation === handler) body.navigation = null;
201
+ };
202
+ }, [body, readOnly, remember]);
203
+
204
+ return (
205
+ <div className="foli-navigation" data-foli-navigation="">
206
+ {panel && (
207
+ <FindPanel
208
+ body={body}
209
+ mode={panel}
210
+ request={request}
211
+ readOnly={readOnly}
212
+ query={query}
213
+ matchCase={matchCase}
214
+ wholeWord={wholeWord}
215
+ onQuery={setQuery}
216
+ onMatchCase={setMatchCase}
217
+ onWholeWord={setWholeWord}
218
+ onMode={setPanel}
219
+ onBookmarks={() => {
220
+ setBookmarks(true);
221
+ setRequest((n) => n + 1);
222
+ }}
223
+ onClose={() => {
224
+ setPanel(null);
225
+ giveBack();
226
+ }}
227
+ />
228
+ )}
229
+ {bookmarks && (
230
+ <BookmarksDialog
231
+ body={body}
232
+ active={active}
233
+ readOnly={readOnly}
234
+ request={request}
235
+ onClose={(moved) => {
236
+ setBookmarks(false);
237
+ if (!moved) giveBack();
238
+ else restore.current = null;
239
+ }}
240
+ />
241
+ )}
242
+ {outline && (
243
+ <OutlinePanel
244
+ body={body}
245
+ onClose={() => {
246
+ setOutline(false);
247
+ giveBack();
248
+ }}
249
+ />
250
+ )}
251
+ </div>
252
+ );
253
+ }
254
+
255
+ interface FindPanelProps {
256
+ body: Editor;
257
+ mode: PanelMode;
258
+ request: number;
259
+ readOnly: boolean;
260
+ query: string;
261
+ matchCase: boolean;
262
+ wholeWord: boolean;
263
+ onQuery(query: string): void;
264
+ onMatchCase(on: boolean): void;
265
+ onWholeWord(on: boolean): void;
266
+ onMode(mode: PanelMode): void;
267
+ onBookmarks(): void;
268
+ onClose(): void;
269
+ }
270
+
271
+ interface Found {
272
+ matches: readonly FindMatch[];
273
+ current: FindMatch | null;
274
+ /** Whether the view goes to `current`: not when the document changed under the search. */
275
+ scroll: boolean;
276
+ /** The document changed since `matches` were found: only `current` is known to be right. */
277
+ stale?: boolean;
278
+ }
279
+
280
+ /** How long typing in the document pauses before the matches are looked for again, in ms. */
281
+ const RESEARCH_DELAY = 300;
282
+
283
+ /** The find, replace and go to panel: not modal, the document stays usable beside it. */
284
+ function FindPanel({
285
+ body,
286
+ mode,
287
+ request,
288
+ readOnly,
289
+ query,
290
+ matchCase,
291
+ wholeWord,
292
+ onQuery,
293
+ onMatchCase,
294
+ onWholeWord,
295
+ onMode,
296
+ onBookmarks,
297
+ onClose,
298
+ }: FindPanelProps) {
299
+ const id = useId();
300
+ const input = useRef<HTMLInputElement>(null);
301
+ const [replacement, setReplacement] = useState("");
302
+ const [found, setFound] = useState<Found>({ matches: [], current: null, scroll: false });
303
+ const [message, setMessage] = useState("");
304
+ const [version, setVersion] = useState(0);
305
+ const options = useMemo(() => ({ matchCase, wholeWord }), [matchCase, wholeWord]);
306
+
307
+ const [focusing, setFocusing] = useState(0);
308
+ // biome-ignore lint/correctness/useExhaustiveDependencies: each request focuses the panel again
309
+ useEffect(() => {
310
+ input.current?.focus();
311
+ input.current?.select();
312
+ }, [request, focusing]);
313
+
314
+ // Searched again when what the document shows changes, once typing there pauses.
315
+ useEffect(() => {
316
+ let key = searchKey(body.state);
317
+ let timer: ReturnType<typeof setTimeout> | undefined;
318
+ const unsubscribe = body.subscribe((state, transactions) => {
319
+ const next = searchKey(state);
320
+ if (transactions.some((tr) => tr.docChanged)) {
321
+ const stories = new Set<string>();
322
+ for (const tr of transactions)
323
+ for (const step of tr.steps) if (step instanceof StoryStep) stories.add(step.id);
324
+ // Only the current match follows the text at once: the rest waits for the search, and
325
+ // meanwhile is not marked where it no longer is.
326
+ setFound((found) => {
327
+ if (!found.matches.length) return found;
328
+ const current = found.current && mapMatch(found.current, transactions, stories);
329
+ if (found.stale && current === found.current) return found;
330
+ return { ...found, current, scroll: false, stale: true };
331
+ });
332
+ }
333
+ if (next.some((value, i) => value !== key[i])) {
334
+ clearTimeout(timer);
335
+ timer = setTimeout(() => setVersion((n) => n + 1), RESEARCH_DELAY);
336
+ }
337
+ key = next;
338
+ });
339
+ return () => {
340
+ clearTimeout(timer);
341
+ unsubscribe();
342
+ };
343
+ }, [body]);
344
+
345
+ // A new search goes to the match at or after the selection.
346
+ useEffect(() => {
347
+ const matches = findAll(body, query, options);
348
+ setFound({
349
+ matches,
350
+ current: matches.find((m) => isSelected(body, m)) ?? nextMatch(body, matches),
351
+ scroll: true,
352
+ });
353
+ }, [body, query, options]);
354
+ // The document changed: the same search again, the current match kept if it is still there,
355
+ // and the view left where the person typing has it.
356
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `version` stands for the document
357
+ useEffect(() => {
358
+ if (!version) return;
359
+ const matches = findAll(body, query, options);
360
+ setFound(({ current }) => ({
361
+ matches,
362
+ current:
363
+ (current &&
364
+ matches.find(
365
+ (m) => m.story === current.story && m.from === current.from && m.to === current.to,
366
+ )) ??
367
+ null,
368
+ scroll: false,
369
+ }));
370
+ }, [version]);
371
+ // biome-ignore lint/correctness/useExhaustiveDependencies: a new search says nothing of the last
372
+ useEffect(() => setMessage(""), [query, options]);
373
+
374
+ // With the count shown, in the same frame.
375
+ useIsomorphicLayoutEffect(() => {
376
+ const { stale, ...shown } = found;
377
+ const matches = stale ? (shown.current ? [shown.current] : []) : shown.matches;
378
+ body.storyView?.showMatches(query ? { query, ...options, ...shown, matches } : null);
379
+ }, [body, query, options, found]);
380
+ useEffect(() => () => body.storyView?.showMatches(null), [body]);
381
+
382
+ const show = (matches: readonly FindMatch[], current: FindMatch | null) => {
383
+ setFound({ matches, current, scroll: true });
384
+ if (current && !goTo(body, current))
385
+ setMessage(`This match is in a ${storyName(body, current)} no page shows.`);
386
+ else setMessage("");
387
+ };
388
+ /** The matches as the document is now, and the current one among them. */
389
+ const now = (): Found => {
390
+ if (!found.stale) return found;
391
+ const matches = findAll(body, query, options);
392
+ const was = found.current;
393
+ const current =
394
+ (was &&
395
+ matches.find((m) => m.story === was.story && m.from === was.from && m.to === was.to)) ??
396
+ null;
397
+ return { matches, current, scroll: false };
398
+ };
399
+ const step = (backward: boolean) => {
400
+ const { matches, current } = now();
401
+ const first = !backward && current && !isSelected(body, current);
402
+ show(matches, first ? current : nextMatch(body, matches, backward));
403
+ };
404
+ const replaceCurrent = () => {
405
+ const { matches, current } = now();
406
+ if (!current) return;
407
+ if (!isSelected(body, current)) {
408
+ show(matches, current);
409
+ return;
410
+ }
411
+ const report = replace(body, current, replacement, options);
412
+ const fresh = findAll(body, query, options);
413
+ show(fresh, nextMatch(body, fresh));
414
+ setMessage(reportText(report));
415
+ };
416
+ const all = () => {
417
+ const report = replaceAll(body, query, replacement, options);
418
+ // What is left at once, as after Replace: not the replaced text for a moment.
419
+ const fresh = findAll(body, query, options);
420
+ setFound({ matches: fresh, current: nextMatch(body, fresh), scroll: false });
421
+ setMessage(reportText(report));
422
+ };
423
+
424
+ const onKeyDown = (event: KeyboardEvent) => {
425
+ const name = keyName(event.nativeEvent);
426
+ const modes: Record<string, PanelMode> = { "Mod-f": "find", "Mod-g": "goTo" };
427
+ if (!readOnly) modes["Mod-h"] = "replace";
428
+ const next = Object.hasOwn(modes, name) ? modes[name] : undefined;
429
+ if (name === "Escape") onClose();
430
+ else if (next) {
431
+ onMode(next);
432
+ setFocusing((n) => n + 1);
433
+ } else if (name === "F3" || name === "Shift-F3") step(name !== "F3");
434
+ else if (name === "Shift-Enter" && (event.target as Element).tagName === "INPUT") step(true);
435
+ else if (name === "Mod-Shift-F5") onBookmarks();
436
+ else return;
437
+ event.preventDefault();
438
+ };
439
+
440
+ const onTabKey = (event: KeyboardEvent) => {
441
+ const step = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0;
442
+ if (!step) return;
443
+ event.preventDefault();
444
+ const at = tabs.findIndex(([value]) => value === mode);
445
+ const [next] = tabs[(at + step + tabs.length) % tabs.length] as [PanelMode, string];
446
+ onMode(next);
447
+ (event.currentTarget.querySelector(`[id$="-tab-${next}"]`) as HTMLElement | null)?.focus();
448
+ };
449
+
450
+ const position = found.current ? found.matches.indexOf(found.current) + 1 : 0;
451
+ const status =
452
+ message ||
453
+ (!query
454
+ ? ""
455
+ : found.matches.length && !position
456
+ ? `${found.matches.length} found`
457
+ : found.matches.length
458
+ ? `${position} of ${found.matches.length}${
459
+ found.current?.story ? `, in a ${storyName(body, found.current)}` : ""
460
+ }`
461
+ : "No results");
462
+ const tabs: [PanelMode, string][] = [
463
+ ["find", "Find"],
464
+ ...(readOnly ? [] : ([["replace", "Replace"]] as [PanelMode, string][])),
465
+ ["goTo", "Go to"],
466
+ ];
467
+
468
+ return (
469
+ // biome-ignore lint/a11y/noStaticElementInteractions: the dialog's own keys, as the toolbar's
470
+ <div
471
+ role="dialog"
472
+ aria-label="Find and replace"
473
+ className="foli-link-dialog foli-find-panel"
474
+ onKeyDown={onKeyDown}
475
+ >
476
+ <div className="foli-find-modes">
477
+ <div role="tablist" aria-label="What to do" onKeyDown={onTabKey}>
478
+ {tabs.map(([value, label]) => (
479
+ <button
480
+ key={value}
481
+ id={`${id}-tab-${value}`}
482
+ type="button"
483
+ role="tab"
484
+ aria-selected={mode === value}
485
+ aria-controls={`${id}-panel`}
486
+ tabIndex={mode === value ? 0 : -1}
487
+ onClick={() => onMode(value)}
488
+ >
489
+ {label}
490
+ </button>
491
+ ))}
492
+ </div>
493
+ <button type="button" onClick={onClose}>
494
+ Close
495
+ </button>
496
+ </div>
497
+ <div role="tabpanel" id={`${id}-panel`} aria-labelledby={`${id}-tab-${mode}`}>
498
+ {mode === "goTo" ? (
499
+ <GoToForm body={body} first={input} onDone={onClose} />
500
+ ) : (
501
+ <form
502
+ noValidate
503
+ onSubmit={(event: FormEvent) => {
504
+ event.preventDefault();
505
+ step(false);
506
+ }}
507
+ >
508
+ <label htmlFor={`${id}-find`}>Find what</label>
509
+ <input
510
+ ref={input}
511
+ id={`${id}-find`}
512
+ type="text"
513
+ value={query}
514
+ onChange={(event) => onQuery(event.target.value)}
515
+ />
516
+ {mode === "replace" && (
517
+ <>
518
+ <label htmlFor={`${id}-with`}>Replace with</label>
519
+ <input
520
+ id={`${id}-with`}
521
+ type="text"
522
+ value={replacement}
523
+ onChange={(event) => setReplacement(event.target.value)}
524
+ />
525
+ </>
526
+ )}
527
+ <label className="foli-find-option">
528
+ <input
529
+ type="checkbox"
530
+ checked={matchCase}
531
+ onChange={(event) => onMatchCase(event.target.checked)}
532
+ />
533
+ Match case
534
+ </label>
535
+ <label className="foli-find-option">
536
+ <input
537
+ type="checkbox"
538
+ checked={wholeWord}
539
+ onChange={(event) => onWholeWord(event.target.checked)}
540
+ />
541
+ Whole words
542
+ </label>
543
+ <button type="button" disabled={!found.matches.length} onClick={() => step(true)}>
544
+ Previous
545
+ </button>
546
+ <button type="submit" disabled={!found.matches.length}>
547
+ Next
548
+ </button>
549
+ {mode === "replace" && (
550
+ <>
551
+ <button type="button" disabled={!found.current} onClick={replaceCurrent}>
552
+ Replace
553
+ </button>
554
+ <button type="button" disabled={!found.matches.length} onClick={all}>
555
+ Replace all
556
+ </button>
557
+ </>
558
+ )}
559
+ <p role="status" className="foli-find-status">
560
+ {status}
561
+ </p>
562
+ </form>
563
+ )}
564
+ </div>
565
+ </div>
566
+ );
567
+ }
568
+
569
+ const storyName = (body: Editor, match: FindMatch) =>
570
+ WHERE[wordContext(body.state)?.stories.get(match.story ?? "")?.kind ?? ""] ?? "story";
571
+
572
+ /** Go to a page, a bookmark or a heading. */
573
+ function GoToForm({
574
+ body,
575
+ first,
576
+ onDone,
577
+ }: {
578
+ body: Editor;
579
+ first: React.RefObject<HTMLInputElement | null>;
580
+ onDone(): void;
581
+ }) {
582
+ const id = useId();
583
+ const [kind, setKind] = useState<"page" | "bookmark" | "heading">("page");
584
+ const [page, setPage] = useState("1");
585
+ const [failed, setFailed] = useState(false);
586
+ const [marks] = useState(() => listBookmarks(body));
587
+ const [headings] = useState(() => documentOutline(body.state));
588
+ const [picked, setPicked] = useState("0");
589
+ const go = (event: FormEvent) => {
590
+ event.preventDefault();
591
+ const view = body.storyView;
592
+ const at = Number(picked);
593
+ const mark = marks[at];
594
+ const heading = headings[at];
595
+ const done =
596
+ kind === "page"
597
+ ? !!view?.goToPage(Number(page), { focus: true })
598
+ : kind === "bookmark"
599
+ ? !!mark && goTo(body, mark, { focus: true })
600
+ : !!heading &&
601
+ goTo(
602
+ body,
603
+ { story: null, from: heading.pos + 1, to: heading.pos + 1 },
604
+ { focus: true },
605
+ );
606
+ if (done) onDone();
607
+ else setFailed(true);
608
+ };
609
+ const options =
610
+ kind === "bookmark" ? marks.map((m) => m.name) : headings.map((entry) => entry.text);
611
+ return (
612
+ <form noValidate onSubmit={go}>
613
+ <label htmlFor={`${id}-kind`}>Go to what</label>
614
+ <select
615
+ id={`${id}-kind`}
616
+ value={kind}
617
+ onChange={(event) => {
618
+ setKind(event.target.value as typeof kind);
619
+ setPicked("0");
620
+ setFailed(false);
621
+ }}
622
+ >
623
+ <option value="page">Page</option>
624
+ <option value="bookmark">Bookmark</option>
625
+ <option value="heading">Heading</option>
626
+ </select>
627
+ {kind === "page" ? (
628
+ <>
629
+ <label htmlFor={`${id}-page`}>Page number</label>
630
+ <input
631
+ ref={first}
632
+ id={`${id}-page`}
633
+ type="text"
634
+ inputMode="numeric"
635
+ value={page}
636
+ onChange={(event) => {
637
+ setPage(event.target.value);
638
+ setFailed(false);
639
+ }}
640
+ />
641
+ </>
642
+ ) : (
643
+ <>
644
+ <label htmlFor={`${id}-target`}>{kind === "bookmark" ? "Bookmark" : "Heading"}</label>
645
+ <select
646
+ id={`${id}-target`}
647
+ value={picked}
648
+ onChange={(event) => setPicked(event.target.value)}
649
+ >
650
+ {options.map((label, i) => (
651
+ // biome-ignore lint/suspicious/noArrayIndexKey: two headings can read the same
652
+ <option key={i} value={String(i)}>
653
+ {label}
654
+ </option>
655
+ ))}
656
+ </select>
657
+ </>
658
+ )}
659
+ <button type="submit">Go to</button>
660
+ {failed && (
661
+ <p className="foli-link-error" role="alert">
662
+ There is no such place.
663
+ </p>
664
+ )}
665
+ </form>
666
+ );
667
+ }
668
+
669
+ const BOOKMARK_ERRORS: Record<string, string> = {
670
+ "invalid-name":
671
+ "A bookmark's name starts with a letter and has only letters, digits and underscores (40 at most).",
672
+ "no-place": "A bookmark cannot go here.",
673
+ missing: "That bookmark is gone.",
674
+ exists: "Another bookmark has that name.",
675
+ refused: "The content here cannot change.",
676
+ };
677
+
678
+ /** The bookmarks: add (a name used moves it, as in Word), go to, rename, delete. */
679
+ function BookmarksDialog({
680
+ body,
681
+ active,
682
+ readOnly,
683
+ request,
684
+ onClose,
685
+ }: {
686
+ body: Editor;
687
+ active: Editor;
688
+ readOnly: boolean;
689
+ request: number;
690
+ onClose(moved: boolean): void;
691
+ }) {
692
+ const id = useId();
693
+ const input = useRef<HTMLInputElement>(null);
694
+ const [name, setName] = useState("");
695
+ const [hidden, setHidden] = useState(false);
696
+ const [error, setError] = useState("");
697
+ const [list, setList] = useState<BookmarkInfo[]>(() => listBookmarks(body));
698
+ const [picked, setPicked] = useState("");
699
+ // biome-ignore lint/correctness/useExhaustiveDependencies: each request focuses it again
700
+ useEffect(() => {
701
+ input.current?.focus();
702
+ }, [request]);
703
+ useEffect(() => setList(listBookmarks(body, { hidden })), [body, hidden]);
704
+ const refresh = () => setList(listBookmarks(body, { hidden }));
705
+ const outcome = (result: { ok: boolean; reason?: string }) => {
706
+ setError(result.ok ? "" : (BOOKMARK_ERRORS[result.reason ?? ""] ?? ""));
707
+ refresh();
708
+ return result.ok;
709
+ };
710
+ const chosen = list.find((b) => b.name === picked) ?? null;
711
+ return (
712
+ // biome-ignore lint/a11y/noStaticElementInteractions: Escape, as in the toolbar's dialogs
713
+ <div
714
+ role="dialog"
715
+ aria-label="Bookmarks"
716
+ className="foli-link-dialog foli-find-panel foli-bookmarks"
717
+ onKeyDown={(event) => {
718
+ if (event.key !== "Escape") return;
719
+ event.preventDefault();
720
+ onClose(false);
721
+ }}
722
+ >
723
+ <form
724
+ noValidate
725
+ onSubmit={(event) => {
726
+ event.preventDefault();
727
+ if (!readOnly && outcome(insertBookmark(active, name.trim()))) {
728
+ setPicked(name.trim());
729
+ setName("");
730
+ }
731
+ }}
732
+ >
733
+ <label htmlFor={`${id}-name`}>Bookmark name</label>
734
+ <input
735
+ ref={input}
736
+ id={`${id}-name`}
737
+ type="text"
738
+ value={name}
739
+ aria-invalid={error ? true : undefined}
740
+ onChange={(event) => {
741
+ setName(event.target.value);
742
+ setError("");
743
+ }}
744
+ />
745
+ <label htmlFor={`${id}-list`}>Bookmarks</label>
746
+ <select
747
+ id={`${id}-list`}
748
+ size={6}
749
+ value={picked}
750
+ onChange={(event) => {
751
+ setPicked(event.target.value);
752
+ setName(event.target.value);
753
+ setError("");
754
+ }}
755
+ >
756
+ {list.map((bookmark) => (
757
+ <option key={bookmark.name} value={bookmark.name}>
758
+ {bookmark.name}
759
+ {bookmark.text ? `: ${bookmark.text.slice(0, 40)}` : ""}
760
+ </option>
761
+ ))}
762
+ </select>
763
+ <label className="foli-find-option">
764
+ <input
765
+ type="checkbox"
766
+ checked={hidden}
767
+ onChange={(event) => setHidden(event.target.checked)}
768
+ />
769
+ Hidden bookmarks
770
+ </label>
771
+ {!readOnly && <button type="submit">Add</button>}
772
+ <button
773
+ type="button"
774
+ disabled={!chosen}
775
+ onClick={() => {
776
+ if (chosen && goTo(body, chosen, { focus: true })) onClose(true);
777
+ else setError("No page shows that bookmark.");
778
+ }}
779
+ >
780
+ Go to
781
+ </button>
782
+ {!readOnly && (
783
+ <>
784
+ <button
785
+ type="button"
786
+ disabled={!chosen}
787
+ onClick={() => {
788
+ if (chosen && outcome(renameBookmark(body, chosen.name, name.trim())))
789
+ setPicked(name.trim());
790
+ }}
791
+ >
792
+ Rename
793
+ </button>
794
+ <button
795
+ type="button"
796
+ disabled={!chosen}
797
+ onClick={() => {
798
+ if (chosen) deleteBookmark(body, chosen.name);
799
+ setPicked("");
800
+ setName("");
801
+ refresh();
802
+ }}
803
+ >
804
+ Delete
805
+ </button>
806
+ </>
807
+ )}
808
+ <button type="button" onClick={() => onClose(false)}>
809
+ Close
810
+ </button>
811
+ {error && (
812
+ <p className="foli-link-error" role="alert">
813
+ {error}
814
+ </p>
815
+ )}
816
+ </form>
817
+ </div>
818
+ );
819
+ }
820
+
821
+ /** The headings of the document; a press goes there. Up and Down move between them. */
822
+ function OutlinePanel({ body, onClose }: { body: Editor; onClose(): void }) {
823
+ const [entries, setEntries] = useState<OutlineEntry[]>([]);
824
+ const list = useRef<HTMLOListElement>(null);
825
+ const caret = useEditorState((state) => state.selection.from, { editor: body });
826
+ useEffect(() => {
827
+ const read = () => setEntries(documentOutline(body.state, body.storyView?.fieldLayout ?? null));
828
+ read();
829
+ let timer: ReturnType<typeof setTimeout> | undefined;
830
+ let doc = body.state.doc;
831
+ const unsubscribe = body.subscribe((state) => {
832
+ if (state.doc === doc) return;
833
+ doc = state.doc;
834
+ clearTimeout(timer);
835
+ // After the pages have settled: the entries show their numbers.
836
+ timer = setTimeout(read, 150);
837
+ });
838
+ return () => {
839
+ clearTimeout(timer);
840
+ unsubscribe();
841
+ };
842
+ }, [body]);
843
+ let current = -1;
844
+ entries.forEach((entry, i) => {
845
+ if (entry.pos < caret) current = i;
846
+ });
847
+ const onKeyDown = (event: KeyboardEvent) => {
848
+ const step = event.key === "ArrowDown" ? 1 : event.key === "ArrowUp" ? -1 : 0;
849
+ if (event.key === "Escape") onClose();
850
+ else if (step) {
851
+ const buttons = [...(list.current?.querySelectorAll("button") ?? [])];
852
+ const at = buttons.indexOf(document.activeElement as HTMLButtonElement);
853
+ buttons[Math.max(0, Math.min(at + step, buttons.length - 1))]?.focus();
854
+ } else return;
855
+ event.preventDefault();
856
+ };
857
+ return (
858
+ // biome-ignore lint/a11y/noNoninteractiveElementInteractions: the panel's keys
859
+ <nav aria-label="Document outline" className="foli-outline" onKeyDown={onKeyDown}>
860
+ <div className="foli-outline-head">
861
+ <h2>Outline</h2>
862
+ <button type="button" onClick={onClose}>
863
+ Close
864
+ </button>
865
+ </div>
866
+ {entries.length ? (
867
+ <ol ref={list}>
868
+ {entries.map((entry, i) => (
869
+ <li key={entry.pos} style={{ paddingInlineStart: `${(entry.level - 1) * 12}px` }}>
870
+ <button
871
+ type="button"
872
+ aria-current={i === current ? "location" : undefined}
873
+ onClick={() =>
874
+ goTo(
875
+ body,
876
+ { story: null, from: entry.pos + 1, to: entry.pos + 1 },
877
+ { focus: true },
878
+ )
879
+ }
880
+ >
881
+ <span>
882
+ {entry.number ? `${entry.number} ` : ""}
883
+ {entry.text}
884
+ </span>
885
+ {entry.page && <span className="foli-outline-page">{entry.page}</span>}
886
+ </button>
887
+ </li>
888
+ ))}
889
+ </ol>
890
+ ) : (
891
+ <p>No headings.</p>
892
+ )}
893
+ </nav>
894
+ );
895
+ }