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