@folijs/react 0.2.0 → 0.4.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@folijs/react",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "React components for the Foli document editor.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -29,8 +29,8 @@
29
29
  "!src/**/*.test.*"
30
30
  ],
31
31
  "dependencies": {
32
- "@folijs/core": "^0.2.0",
33
- "@folijs/view": "^0.2.0"
32
+ "@folijs/core": "^0.4.0",
33
+ "@folijs/view": "^0.4.0"
34
34
  },
35
35
  "peerDependencies": {
36
36
  "react": "^18.2.0 || ^19.0.0",
@@ -0,0 +1,499 @@
1
+ import {
2
+ type CommentJSON,
3
+ commentAnchors,
4
+ deleteComment,
5
+ type Editor,
6
+ type EditorState,
7
+ editComment,
8
+ type NodeJSON,
9
+ replyToComment,
10
+ resolveComment,
11
+ wordContext,
12
+ } from "@folijs/core";
13
+ import { type FormEvent, type KeyboardEvent, useEffect, useId, useRef, useState } from "react";
14
+ import { useEditorOrContext, useEditorState, useIsomorphicLayoutEffect } from "./editor.js";
15
+
16
+ export interface FoliCommentsProps {
17
+ /** Default: the editor of the nearest `FoliEditorProvider`. */
18
+ editor?: Editor | undefined;
19
+ /** Comments can be read, not changed (pass it with a `readOnly` canvas). */
20
+ readOnly?: boolean | undefined;
21
+ /** Accessible name of the pane (default "Comments"). */
22
+ label?: string | undefined;
23
+ className?: string | undefined;
24
+ /** Not shown (still following the editor: a comment made meanwhile opens for writing). */
25
+ hidden?: boolean | undefined;
26
+ }
27
+
28
+ /** A comment and its replies, where its range starts in the document. */
29
+ interface Thread {
30
+ comment: CommentJSON;
31
+ replies: CommentJSON[];
32
+ /** Where its range starts (or its reference is), for order and alignment. */
33
+ pos: number;
34
+ /** Where its range ends. */
35
+ end: number;
36
+ }
37
+
38
+ const EMPTY: readonly CommentJSON[] = [];
39
+
40
+ /** The comments of the editor's document, as threads in document order. */
41
+ function threadsOf(state: EditorState, comments: readonly CommentJSON[]): Thread[] {
42
+ const anchors = commentAnchors(state.doc);
43
+ const byId = new Map(comments.map((c) => [c.id, c]));
44
+ const rootOf = (c: CommentJSON) => {
45
+ let root = c;
46
+ const seen = new Set<number>();
47
+ while (root.parent !== undefined && byId.has(root.parent) && !seen.has(root.id)) {
48
+ seen.add(root.id);
49
+ root = byId.get(root.parent) as CommentJSON;
50
+ }
51
+ return root;
52
+ };
53
+ const threads = new Map<number, Thread>();
54
+ for (const c of comments) {
55
+ const root = rootOf(c);
56
+ let thread = threads.get(root.id);
57
+ if (!thread) {
58
+ const a = anchors.get(root.id);
59
+ const pos = a?.start ?? a?.reference ?? Number.MAX_SAFE_INTEGER;
60
+ thread = { comment: root, replies: [], pos, end: a?.end ?? a?.reference ?? pos };
61
+ threads.set(root.id, thread);
62
+ }
63
+ if (c !== root) thread.replies.push(c);
64
+ }
65
+ return [...threads.values()].sort((a, b) => a.pos - b.pos || a.comment.id - b.comment.id);
66
+ }
67
+
68
+ /** A paragraph's text as shown: tabs and line breaks kept. */
69
+ const paragraphText = (p: NodeJSON) =>
70
+ (p.content ?? [])
71
+ .map((n) =>
72
+ n.type === "text"
73
+ ? (n.text ?? "")
74
+ : n.type === "tab"
75
+ ? "\t"
76
+ : n.type === "hardBreak"
77
+ ? "\n"
78
+ : "",
79
+ )
80
+ .join("");
81
+
82
+ /** A comment's text: its paragraphs' text, a line each. */
83
+ const textOf = (c: CommentJSON) => c.content.map(paragraphText).join("\n");
84
+
85
+ /**
86
+ * Whether the pane edits a comment as text without losing anything: paragraphs of unformatted
87
+ * text, all in one paragraph style or none (Word gives its comments the CommentText style).
88
+ */
89
+ function plain(c: CommentJSON): boolean {
90
+ const styles = new Set(c.content.map((p) => (p.attrs as { style?: unknown } | undefined)?.style));
91
+ return (
92
+ styles.size <= 1 &&
93
+ c.content.every(
94
+ (p) =>
95
+ p.type === "paragraph" &&
96
+ Object.keys(p.attrs ?? {}).every((key) => key === "style") &&
97
+ (p.content ?? []).every((n) => n.type === "text" && !n.marks?.length),
98
+ )
99
+ );
100
+ }
101
+
102
+ /** `text` as `c`'s content: a paragraph per line, in `c`'s paragraph style. */
103
+ function contentLike(c: CommentJSON, text: string): NodeJSON[] {
104
+ const style = (c.content[0]?.attrs as { style?: string } | undefined)?.style;
105
+ return text.split(/\r\n|\r|\n/).map((line) => ({
106
+ type: "paragraph",
107
+ ...(style ? { attrs: { style } } : {}),
108
+ ...(line ? { content: [{ type: "text", text: line }] } : {}),
109
+ }));
110
+ }
111
+
112
+ const isEmpty = (c: CommentJSON) => textOf(c).trim() === "";
113
+
114
+ /** The nearest ancestor of the pane that holds the editor's pages. */
115
+ function pagesAround(pane: HTMLElement): HTMLElement | null {
116
+ let element = pane.parentElement;
117
+ while (element && !element.querySelector(".foli-page")) element = element.parentElement;
118
+ return element;
119
+ }
120
+
121
+ const dateOf = (date: string | undefined) => (date ? date.slice(0, 10) : "");
122
+ const nameOf = (c: CommentJSON) => c.author || "an unknown author";
123
+
124
+ /**
125
+ * The comments pane: the document's comment threads beside the pages, each next to its text,
126
+ * moved down when they would overlap. Focusing a thread marks its text in the document; a
127
+ * caret in commented text marks its thread. Reply, edit (plain text), resolve, reopen and
128
+ * delete; a comment made empty while the pane shows (the toolbar's "New comment") opens for
129
+ * writing, and goes when cancelled empty. Render it beside the pages (`FoliEditor` does): it
130
+ * finds the comments' text in the nearest ancestor holding them.
131
+ */
132
+ export function FoliComments({
133
+ editor: editorProp,
134
+ readOnly = false,
135
+ label = "Comments",
136
+ className,
137
+ hidden = false,
138
+ }: FoliCommentsProps) {
139
+ const editor = useEditorOrContext(editorProp, "FoliComments");
140
+ const comments = useEditorState((state) => wordContext(state)?.envelope.comments ?? EMPTY, {
141
+ editor,
142
+ });
143
+ const documentId = useEditorState((state) => wordContext(state)?.id ?? "", { editor });
144
+ const doc = useEditorState((state) => state.doc, { editor });
145
+ const head = useEditorState((state) => state.selection.head, { editor });
146
+ const threads = threadsOf(editor.state, comments);
147
+ const pane = useRef<HTMLElement>(null);
148
+ const [tops, setTops] = useState<number[]>([]);
149
+ const [height, setHeight] = useState(0);
150
+ const [writing, setWriting] = useState<{ id: number; reply: boolean } | null>(null);
151
+ const [focused, setFocused] = useState<number | null>(null);
152
+ /** The comments the pane has seen, per document: only ones made later open for writing. */
153
+ const known = useRef<{
154
+ document: string;
155
+ objects: WeakSet<CommentJSON>;
156
+ ids: Set<number>;
157
+ } | null>(null);
158
+ /** The comments the pane opened for writing: cancelled while empty, they go. */
159
+ const created = useRef(new Set<number>());
160
+ /** After a change, the element to focus (the next thread, the button that opened a form). */
161
+ const refocus = useRef<(() => void) | null>(null);
162
+
163
+ useEffect(() => {
164
+ const seen = known.current;
165
+ const same = seen?.document === documentId;
166
+ const objects = same ? seen.objects : new WeakSet<CommentJSON>();
167
+ known.current = { document: documentId, objects, ids: new Set(comments.map((c) => c.id)) };
168
+ // New: an id that was not there, and an object never seen (not one undo brought back).
169
+ const fresh = same ? comments.find((c) => !seen.ids.has(c.id) && !objects.has(c)) : undefined;
170
+ for (const c of comments) objects.add(c);
171
+ // The first render, or another document: what is there was not made here, and nothing
172
+ // open for writing belongs to it.
173
+ if (!same) {
174
+ if (seen) {
175
+ created.current.clear();
176
+ setWriting(null);
177
+ }
178
+ return;
179
+ }
180
+ // A comment that comes back (undo) is the very object seen before: not new.
181
+ if (fresh && !readOnly && isEmpty(fresh) && plain(fresh)) {
182
+ created.current.add(fresh.id);
183
+ setWriting({ id: fresh.id, reply: false });
184
+ }
185
+ }, [comments, documentId, readOnly]);
186
+
187
+ // Each thread next to its text, pushed down below the one before.
188
+ const measure = () => {
189
+ const root = pane.current;
190
+ const container = root && pagesAround(root);
191
+ if (!root || !container) return;
192
+ const paneTop = root.getBoundingClientRect().top;
193
+ // The first text of each comment, in one pass.
194
+ const anchors = new Map<string, HTMLElement>();
195
+ for (const element of container.querySelectorAll<HTMLElement>(
196
+ "[data-foli-comments], [data-foli-comment-reference]",
197
+ )) {
198
+ const ids = (element.dataset.foliComments ?? element.dataset.foliCommentReference ?? "")
199
+ .split(" ")
200
+ .filter(Boolean);
201
+ for (const id of ids) if (!anchors.has(id)) anchors.set(id, element);
202
+ }
203
+ const items = [...root.querySelectorAll<HTMLElement>(":scope > .foli-comment-thread")];
204
+ const next: number[] = [];
205
+ let bottom = 0;
206
+ threads.forEach((thread, i) => {
207
+ const anchor = anchors.get(String(thread.comment.id));
208
+ const wanted = anchor ? anchor.getBoundingClientRect().top - paneTop : bottom;
209
+ const top = Math.max(wanted, bottom);
210
+ next.push(top);
211
+ bottom = top + (items[i]?.offsetHeight ?? 0) + 8;
212
+ });
213
+ setTops((old) =>
214
+ old.length === next.length && old.every((t, i) => Math.abs(t - (next[i] as number)) < 0.5)
215
+ ? old
216
+ : next,
217
+ );
218
+ setHeight(bottom);
219
+ };
220
+ const measureRef = useRef(measure);
221
+ measureRef.current = measure;
222
+ // biome-ignore lint/correctness/useExhaustiveDependencies: measured after every change of what it shows.
223
+ useIsomorphicLayoutEffect(measure, [doc, comments, writing, threads.length]);
224
+ useEffect(() => {
225
+ const container = pane.current && pagesAround(pane.current);
226
+ if (!container || typeof ResizeObserver === "undefined") return;
227
+ const observer = new ResizeObserver(() => measureRef.current());
228
+ observer.observe(container);
229
+ return () => observer.disconnect();
230
+ }, []);
231
+ // Focus where the last action left it (after React drew the change).
232
+ useEffect(() => {
233
+ const focus = refocus.current;
234
+ refocus.current = null;
235
+ focus?.();
236
+ });
237
+
238
+ // The focused thread's text marked in the document (again after the view redraws it).
239
+ // biome-ignore lint/correctness/useExhaustiveDependencies: `doc` changes mean redrawn text to mark.
240
+ useEffect(() => {
241
+ const container = pane.current && pagesAround(pane.current);
242
+ if (!container || focused === null) return;
243
+ const marked = [
244
+ ...container.querySelectorAll<HTMLElement>(`[data-foli-comments~="${focused}"]`),
245
+ ];
246
+ for (const element of marked) element.classList.add("foli-comment-active");
247
+ return () => {
248
+ for (const element of marked) element.classList.remove("foli-comment-active");
249
+ };
250
+ }, [focused, doc]);
251
+
252
+ const run = (command: Parameters<Editor["run"]>[0]) => editor.run(command);
253
+ /** Focus the thread of `id` (its first button), else the pane, else the document. */
254
+ const focusThread = (id: number | undefined) => {
255
+ refocus.current = () => {
256
+ const root = pane.current;
257
+ const thread =
258
+ id === undefined ? null : root?.querySelector<HTMLElement>(`[data-thread="${id}"]`);
259
+ const document = root && pagesAround(root)?.querySelector<HTMLElement>('[role="textbox"]');
260
+ (
261
+ thread?.querySelector<HTMLElement>("button") ??
262
+ thread ??
263
+ (root?.hidden ? document : root)
264
+ )?.focus();
265
+ };
266
+ };
267
+
268
+ return (
269
+ <aside
270
+ ref={pane}
271
+ tabIndex={-1}
272
+ className={`foli-comments${className ? ` ${className}` : ""}`}
273
+ aria-label={label}
274
+ hidden={hidden}
275
+ style={height ? { minHeight: height } : undefined}
276
+ >
277
+ {threads.length === 0 && <p className="foli-comments-empty">No comments</p>}
278
+ {threads.map((thread, i) => {
279
+ const { comment } = thread;
280
+ const active = head >= thread.pos && head <= thread.end + 1;
281
+ const after = threads[i + 1] ?? threads[i - 1];
282
+ const canReply = !readOnly && editor.can(replyToComment(comment.id, "x"));
283
+ return (
284
+ <article
285
+ key={comment.id}
286
+ data-thread={comment.id}
287
+ tabIndex={-1}
288
+ className="foli-comment-thread"
289
+ data-active={active || undefined}
290
+ data-done={comment.done || undefined}
291
+ style={{ top: tops[i] ?? 0 }}
292
+ aria-label={`Comment by ${nameOf(comment)}${comment.done ? ", resolved" : ""}`}
293
+ onFocus={() => setFocused(comment.id)}
294
+ onBlur={(e) => {
295
+ if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setFocused(null);
296
+ }}
297
+ >
298
+ {[comment, ...thread.replies].map((c) => (
299
+ <CommentView
300
+ key={c.id}
301
+ comment={c}
302
+ root={c === comment}
303
+ readOnly={readOnly}
304
+ canReply={canReply}
305
+ canDelete={!readOnly && editor.can(deleteComment(c.id))}
306
+ editing={writing?.id === c.id && !writing.reply}
307
+ onEdit={() => setWriting({ id: c.id, reply: false })}
308
+ onReply={() => setWriting({ id: comment.id, reply: true })}
309
+ onResolve={() => {
310
+ run(resolveComment(comment.id, !comment.done));
311
+ focusThread(comment.id);
312
+ }}
313
+ onDelete={() => {
314
+ run(deleteComment(c.id));
315
+ focusThread(c === comment ? after?.comment.id : comment.id);
316
+ }}
317
+ onSave={(text) => {
318
+ if (!run(editComment(c.id, contentLike(c, text)))) return false;
319
+ created.current.delete(c.id);
320
+ setWriting(null);
321
+ focusThread(comment.id);
322
+ return true;
323
+ }}
324
+ onCancel={() => {
325
+ // A comment made here and left empty goes.
326
+ const gone = created.current.has(c.id) && isEmpty(c);
327
+ created.current.delete(c.id);
328
+ if (gone) run(deleteComment(c.id));
329
+ setWriting(null);
330
+ focusThread(gone ? after?.comment.id : comment.id);
331
+ }}
332
+ />
333
+ ))}
334
+ {writing?.reply && writing.id === comment.id && (
335
+ <CommentForm
336
+ label="Reply"
337
+ initial=""
338
+ onSave={(text) => {
339
+ if (text.trim() && !run(replyToComment(comment.id, text))) return false;
340
+ setWriting(null);
341
+ focusThread(comment.id);
342
+ return true;
343
+ }}
344
+ onCancel={() => {
345
+ setWriting(null);
346
+ focusThread(comment.id);
347
+ }}
348
+ />
349
+ )}
350
+ </article>
351
+ );
352
+ })}
353
+ </aside>
354
+ );
355
+ }
356
+
357
+ function CommentView({
358
+ comment,
359
+ root,
360
+ readOnly,
361
+ canReply,
362
+ canDelete,
363
+ editing,
364
+ onEdit,
365
+ onReply,
366
+ onResolve,
367
+ onDelete,
368
+ onSave,
369
+ onCancel,
370
+ }: {
371
+ comment: CommentJSON;
372
+ root: boolean;
373
+ readOnly: boolean;
374
+ canReply: boolean;
375
+ canDelete: boolean;
376
+ editing: boolean;
377
+ onEdit(): void;
378
+ onReply(): void;
379
+ onResolve(): void;
380
+ onDelete(): void;
381
+ onSave(text: string): boolean;
382
+ onCancel(): void;
383
+ }) {
384
+ const author = comment.author || "Unknown author";
385
+ const what = root ? "comment" : "reply";
386
+ return (
387
+ <div className="foli-comment">
388
+ <p className="foli-comment-meta">
389
+ <strong>{author}</strong> <span>{dateOf(comment.date)}</span>
390
+ </p>
391
+ {editing ? (
392
+ <CommentForm
393
+ label="Comment"
394
+ initial={textOf(comment)}
395
+ onSave={onSave}
396
+ onCancel={onCancel}
397
+ />
398
+ ) : (
399
+ <div className="foli-comment-text">
400
+ {comment.content.map((p, i) => (
401
+ // biome-ignore lint/suspicious/noArrayIndexKey: paragraphs have no identity.
402
+ <p key={i}>{paragraphText(p)}</p>
403
+ ))}
404
+ </div>
405
+ )}
406
+ {!readOnly && !editing && (
407
+ <div className="foli-comment-actions">
408
+ {root && canReply && (
409
+ <button type="button" onClick={onReply}>
410
+ Reply
411
+ </button>
412
+ )}
413
+ {plain(comment) && (
414
+ <button
415
+ type="button"
416
+ onClick={onEdit}
417
+ aria-label={`Edit ${what} by ${nameOf(comment)}`}
418
+ >
419
+ Edit
420
+ </button>
421
+ )}
422
+ {root && (
423
+ <button type="button" onClick={onResolve}>
424
+ {comment.done ? "Reopen" : "Resolve"}
425
+ </button>
426
+ )}
427
+ {canDelete && (
428
+ <button
429
+ type="button"
430
+ onClick={onDelete}
431
+ aria-label={`Delete ${what} by ${nameOf(comment)}`}
432
+ >
433
+ Delete
434
+ </button>
435
+ )}
436
+ </div>
437
+ )}
438
+ </div>
439
+ );
440
+ }
441
+
442
+ function CommentForm({
443
+ label,
444
+ initial,
445
+ onSave,
446
+ onCancel,
447
+ }: {
448
+ label: string;
449
+ initial: string;
450
+ /** False when it could not be saved: the form stays open. */
451
+ onSave(text: string): boolean;
452
+ onCancel(): void;
453
+ }) {
454
+ const id = useId();
455
+ const [text, setText] = useState(initial);
456
+ const [failed, setFailed] = useState(false);
457
+ const field = useRef<HTMLTextAreaElement>(null);
458
+ useEffect(() => field.current?.focus(), []);
459
+ const save = () => setFailed(!onSave(text));
460
+ const submit = (e: FormEvent) => {
461
+ e.preventDefault();
462
+ save();
463
+ };
464
+ const keys = (e: KeyboardEvent<HTMLTextAreaElement>) => {
465
+ if (e.key === "Escape") {
466
+ e.preventDefault();
467
+ onCancel();
468
+ } else if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
469
+ e.preventDefault();
470
+ save();
471
+ }
472
+ };
473
+ return (
474
+ <form className="foli-comment-form" onSubmit={submit}>
475
+ <label htmlFor={id}>{label}</label>
476
+ <textarea
477
+ id={id}
478
+ ref={field}
479
+ value={text}
480
+ rows={3}
481
+ onChange={(e) => setText(e.target.value)}
482
+ onKeyDown={keys}
483
+ aria-invalid={failed || undefined}
484
+ aria-describedby={failed ? `${id}-error` : undefined}
485
+ />
486
+ {failed && (
487
+ <p id={`${id}-error`} className="foli-comment-error" role="alert">
488
+ Could not be saved here.
489
+ </p>
490
+ )}
491
+ <div className="foli-comment-actions">
492
+ <button type="submit">Save</button>
493
+ <button type="button" onClick={onCancel}>
494
+ Cancel
495
+ </button>
496
+ </div>
497
+ </form>
498
+ );
499
+ }
@@ -1,14 +1,21 @@
1
1
  import {
2
- createDocument,
3
- type DocJSON,
4
2
  type Editor,
3
+ type EditorDocument,
5
4
  type FoliDocument,
6
5
  type Plugin,
6
+ type ReviewView,
7
7
  type Transaction,
8
+ wordContext,
8
9
  } from "@folijs/core";
9
10
  import { forwardRef, type ReactNode, useImperativeHandle, useRef } from "react";
10
- import { FoliEditorProvider, useFoliEditor, useIsomorphicLayoutEffect } from "./editor.js";
11
+ import {
12
+ FoliEditorProvider,
13
+ useEditorState,
14
+ useFoliEditor,
15
+ useIsomorphicLayoutEffect,
16
+ } from "./editor.js";
11
17
  import { FoliCanvas, type FoliCanvasHandle, type FoliCanvasProps } from "./FoliCanvas.js";
18
+ import { FoliComments } from "./FoliComments.js";
12
19
  import { FoliToolbar } from "./FoliToolbar.js";
13
20
 
14
21
  /**
@@ -21,16 +28,25 @@ export interface FoliChange {
21
28
  readonly transactions: readonly Transaction[];
22
29
  /**
23
30
  * The whole document right after this change, serialized on first read (keep reads out of
24
- * the hot path of typing: a debounced save reads only the last change's).
31
+ * the hot path of typing: a debounced save reads only the last change's). Schema v3.
25
32
  */
26
33
  readonly document: FoliDocument;
27
34
  }
28
35
 
29
36
  export interface FoliEditorProps extends Omit<FoliCanvasProps, "editor"> {
30
- /** Read once on mount. To load another document later: `editor.setDocument()` or a new `key`. */
31
- initialContent?: FoliDocument | undefined;
37
+ /**
38
+ * Read once on mount: a document of any version (0.1.0 and 0.2.0 documents are migrated to
39
+ * schema v3). To load another document later: `editor.setDocument()` or a new `key`.
40
+ */
41
+ initialContent?: EditorDocument | undefined;
32
42
  /** Read once on mount. */
33
43
  plugins?: readonly Plugin[] | undefined;
44
+ /** Read once on mount: who edits (tracked changes are made in this name). */
45
+ author?: string | undefined;
46
+ /** Read once on mount: record edits as tracked changes (the toolbar turns it on and off). */
47
+ trackChanges?: boolean | undefined;
48
+ /** Read once on mount: how tracked changes show (the toolbar changes it). */
49
+ reviewView?: ReviewView | undefined;
34
50
  /**
35
51
  * Called after every change to the document's content made through transactions (typing,
36
52
  * commands, undo). Not for selection changes, and not for `editor.setDocument()`, whose
@@ -39,6 +55,11 @@ export interface FoliEditorProps extends Omit<FoliCanvasProps, "editor"> {
39
55
  onChange?: ((change: FoliChange) => void) | undefined;
40
56
  /** Show the default `FoliToolbar` above the pages (default true). */
41
57
  toolbar?: boolean | undefined;
58
+ /**
59
+ * Show the comments pane (`FoliComments`) beside the pages: `"auto"` (the default) while the
60
+ * document has comments, `true` always, `false` never.
61
+ */
62
+ comments?: boolean | "auto" | undefined;
42
63
  /** Rendered between the toolbar and the pages, inside the editor's context. */
43
64
  children?: ReactNode | undefined;
44
65
  }
@@ -54,10 +75,25 @@ export interface FoliEditorHandle extends FoliCanvasHandle {
54
75
  * through `onChange`, a parent reaches it through a `ref`.
55
76
  */
56
77
  export const FoliEditor = forwardRef<FoliEditorHandle, FoliEditorProps>(function FoliEditor(
57
- { initialContent, plugins, onChange, toolbar = true, children, ...canvas },
78
+ {
79
+ initialContent,
80
+ plugins,
81
+ author,
82
+ trackChanges,
83
+ reviewView,
84
+ onChange,
85
+ toolbar = true,
86
+ comments = "auto",
87
+ children,
88
+ ...canvas
89
+ },
58
90
  ref,
59
91
  ) {
60
- const editor = useFoliEditor({ initialContent, plugins });
92
+ const editor = useFoliEditor({ initialContent, plugins, author, trackChanges, reviewView });
93
+ const hasComments = useEditorState(
94
+ (state) => (wordContext(state)?.envelope.comments.length ?? 0) > 0,
95
+ { editor },
96
+ );
61
97
  const onChangeRef = useRef(onChange);
62
98
  const canvasRef = useRef<FoliCanvasHandle>(null);
63
99
 
@@ -73,13 +109,15 @@ export const FoliEditor = forwardRef<FoliEditorHandle, FoliEditorProps>(function
73
109
  const listener = onChangeRef.current;
74
110
  if (!listener || !transactions.some((tr) => tr.docChanged)) return;
75
111
  // The state is immutable: keeping it makes a later read give this change's document.
76
- const { settings } = editor;
77
112
  let document: FoliDocument | undefined;
78
113
  listener({
79
114
  editor,
80
115
  transactions,
81
116
  get document() {
82
- document ??= createDocument(state.doc.toJSON() as DocJSON, settings);
117
+ document ??= {
118
+ ...(structuredClone(wordContext(state)?.envelope) as Omit<FoliDocument, "content">),
119
+ content: state.doc.toJSON(),
120
+ };
83
121
  return document;
84
122
  },
85
123
  });
@@ -93,11 +131,22 @@ export const FoliEditor = forwardRef<FoliEditorHandle, FoliEditorProps>(function
93
131
  <FoliToolbar
94
132
  editor={editor}
95
133
  disabled={canvas.readOnly}
134
+ comments={comments !== false}
96
135
  onClickCommand={() => canvasRef.current?.focus()}
97
136
  />
98
137
  )}
99
138
  {children}
100
- <FoliCanvas ref={canvasRef} editor={editor} {...canvas} />
139
+ <div className="foli-editor-body">
140
+ <FoliCanvas ref={canvasRef} editor={editor} {...canvas} />
141
+ {/* "auto": mounted while hidden, so a comment made from the toolbar opens for writing. */}
142
+ {comments !== false && (
143
+ <FoliComments
144
+ editor={editor}
145
+ readOnly={canvas.readOnly}
146
+ hidden={comments === "auto" && !hasComments}
147
+ />
148
+ )}
149
+ </div>
101
150
  </FoliEditorProvider>
102
151
  );
103
152
  });