@fluidframework/react 2.90.0-378676 → 2.91.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.
Files changed (112) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +2 -0
  3. package/api-report/react.alpha.api.md +8 -8
  4. package/lib/index.d.ts +2 -0
  5. package/lib/index.d.ts.map +1 -1
  6. package/lib/index.js +2 -0
  7. package/lib/index.js.map +1 -1
  8. package/lib/propNode.js.map +1 -1
  9. package/lib/reactSharedTreeView.d.ts +6 -6
  10. package/lib/reactSharedTreeView.d.ts.map +1 -1
  11. package/lib/reactSharedTreeView.js +16 -18
  12. package/lib/reactSharedTreeView.js.map +1 -1
  13. package/lib/test/mochaHooks.js +13 -0
  14. package/lib/test/mochaHooks.js.map +1 -0
  15. package/lib/test/reactSharedTreeView.spec.js +3 -3
  16. package/lib/test/reactSharedTreeView.spec.js.map +1 -1
  17. package/lib/test/text/plainUtils.test.js +75 -0
  18. package/lib/test/text/plainUtils.test.js.map +1 -0
  19. package/lib/test/text/textEditor.test.js +760 -0
  20. package/lib/test/text/textEditor.test.js.map +1 -0
  21. package/lib/test/undoRedo.test.js +62 -0
  22. package/lib/test/undoRedo.test.js.map +1 -0
  23. package/lib/test/useObservation.spec.js +8 -9
  24. package/lib/test/useObservation.spec.js.map +1 -1
  25. package/lib/test/useTree.spec.js +15 -16
  26. package/lib/test/useTree.spec.js.map +1 -1
  27. package/lib/text/formatted/index.d.ts +6 -0
  28. package/lib/text/formatted/index.d.ts.map +1 -0
  29. package/lib/text/formatted/index.js +6 -0
  30. package/lib/text/formatted/index.js.map +1 -0
  31. package/lib/text/formatted/quillFormattedView.d.ts +66 -0
  32. package/lib/text/formatted/quillFormattedView.d.ts.map +1 -0
  33. package/lib/text/formatted/quillFormattedView.js +520 -0
  34. package/lib/text/formatted/quillFormattedView.js.map +1 -0
  35. package/lib/text/index.d.ts +7 -0
  36. package/lib/text/index.d.ts.map +1 -0
  37. package/lib/text/index.js +7 -0
  38. package/lib/text/index.js.map +1 -0
  39. package/lib/text/plain/index.d.ts +7 -0
  40. package/lib/text/plain/index.d.ts.map +1 -0
  41. package/lib/text/plain/index.js +7 -0
  42. package/lib/text/plain/index.js.map +1 -0
  43. package/lib/text/plain/plainTextView.d.ts +14 -0
  44. package/lib/text/plain/plainTextView.d.ts.map +1 -0
  45. package/lib/text/plain/plainTextView.js +70 -0
  46. package/lib/text/plain/plainTextView.js.map +1 -0
  47. package/lib/text/plain/plainUtils.d.ts +23 -0
  48. package/lib/text/plain/plainUtils.d.ts.map +1 -0
  49. package/lib/text/plain/plainUtils.js +51 -0
  50. package/lib/text/plain/plainUtils.js.map +1 -0
  51. package/lib/text/plain/quillView.d.ts +22 -0
  52. package/lib/text/plain/quillView.d.ts.map +1 -0
  53. package/lib/text/plain/quillView.js +106 -0
  54. package/lib/text/plain/quillView.js.map +1 -0
  55. package/lib/undoRedo.d.ts +51 -0
  56. package/lib/undoRedo.d.ts.map +1 -0
  57. package/lib/undoRedo.js +76 -0
  58. package/lib/undoRedo.js.map +1 -0
  59. package/lib/useObservation.js +6 -6
  60. package/lib/useObservation.js.map +1 -1
  61. package/lib/useTree.d.ts +7 -7
  62. package/lib/useTree.d.ts.map +1 -1
  63. package/lib/useTree.js +6 -6
  64. package/lib/useTree.js.map +1 -1
  65. package/package.json +28 -46
  66. package/react.test-files.tar +0 -0
  67. package/src/index.ts +10 -0
  68. package/src/propNode.ts +1 -1
  69. package/src/reactSharedTreeView.tsx +11 -13
  70. package/src/text/formatted/index.ts +11 -0
  71. package/src/text/formatted/quillFormattedView.tsx +627 -0
  72. package/src/text/index.ts +15 -0
  73. package/src/text/plain/index.ts +7 -0
  74. package/src/text/plain/plainTextView.tsx +110 -0
  75. package/src/text/plain/plainUtils.ts +68 -0
  76. package/src/text/plain/quillView.tsx +149 -0
  77. package/src/undoRedo.ts +117 -0
  78. package/src/useObservation.ts +6 -6
  79. package/src/useTree.ts +19 -12
  80. package/tsconfig.json +6 -0
  81. package/api-extractor/api-extractor-lint-alpha.cjs.json +0 -5
  82. package/api-extractor/api-extractor-lint-beta.cjs.json +0 -5
  83. package/api-extractor/api-extractor-lint-public.cjs.json +0 -5
  84. package/dist/alpha.d.ts +0 -45
  85. package/dist/beta.d.ts +0 -15
  86. package/dist/index.d.ts +0 -16
  87. package/dist/index.d.ts.map +0 -1
  88. package/dist/index.js +0 -26
  89. package/dist/index.js.map +0 -1
  90. package/dist/package.json +0 -4
  91. package/dist/propNode.d.ts +0 -114
  92. package/dist/propNode.d.ts.map +0 -1
  93. package/dist/propNode.js +0 -43
  94. package/dist/propNode.js.map +0 -1
  95. package/dist/public.d.ts +0 -15
  96. package/dist/reactSharedTreeView.d.ts +0 -119
  97. package/dist/reactSharedTreeView.d.ts.map +0 -1
  98. package/dist/reactSharedTreeView.js +0 -206
  99. package/dist/reactSharedTreeView.js.map +0 -1
  100. package/dist/simpleIdentifier.d.ts +0 -19
  101. package/dist/simpleIdentifier.d.ts.map +0 -1
  102. package/dist/simpleIdentifier.js +0 -33
  103. package/dist/simpleIdentifier.js.map +0 -1
  104. package/dist/useObservation.d.ts +0 -83
  105. package/dist/useObservation.d.ts.map +0 -1
  106. package/dist/useObservation.js +0 -295
  107. package/dist/useObservation.js.map +0 -1
  108. package/dist/useTree.d.ts +0 -80
  109. package/dist/useTree.d.ts.map +0 -1
  110. package/dist/useTree.js +0 -137
  111. package/dist/useTree.js.map +0 -1
  112. package/tsconfig.cjs.json +0 -7
@@ -0,0 +1,627 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import { assert } from "@fluidframework/core-utils/internal";
7
+ import { Tree, TreeAlpha, FormattedTextAsTree } from "@fluidframework/tree/internal";
8
+ export { FormattedTextAsTree } from "@fluidframework/tree/internal";
9
+ import Quill, { type EmitterSource } from "quill";
10
+ import DeltaPackage from "quill-delta";
11
+ import {
12
+ forwardRef,
13
+ useEffect,
14
+ useImperativeHandle,
15
+ useReducer,
16
+ useRef,
17
+ useState,
18
+ } from "react";
19
+ import * as ReactDOM from "react-dom";
20
+
21
+ import { type PropTreeNode, unwrapPropTreeNode } from "../../propNode.js";
22
+ import type { UndoRedo } from "../../undoRedo.js";
23
+
24
+ // Workaround for quill-delta's export style not working well with node16 module resolution.
25
+ type Delta = DeltaPackage.default;
26
+ type QuillDeltaOp = DeltaPackage.Op;
27
+ const Delta = DeltaPackage.default;
28
+
29
+ /**
30
+ * Props for the FormattedMainView component.
31
+ * @input @internal
32
+ */
33
+ export interface FormattedMainViewProps {
34
+ readonly root: PropTreeNode<FormattedTextAsTree.Tree>;
35
+ /** Optional undo/redo stack for the editor. */
36
+ readonly undoRedo?: UndoRedo;
37
+ }
38
+
39
+ /**
40
+ * Ref handle exposing undo/redo methods for the formatted editor.
41
+ * @input @internal
42
+ */
43
+ export type FormattedEditorHandle = Pick<UndoRedo, "undo" | "redo">;
44
+
45
+ /**
46
+ * A React component for formatted text editing.
47
+ * @remarks
48
+ * Uses {@link @fluidframework/tree#FormattedTextAsTree.Tree} for the data-model and Quill for the rich text editor UI.
49
+ * @internal
50
+ */
51
+ export const FormattedMainView = forwardRef<FormattedEditorHandle, FormattedMainViewProps>(
52
+ ({ root, undoRedo }, ref) => {
53
+ return <FormattedTextEditorView root={root} undoRedo={undoRedo} ref={ref} />;
54
+ },
55
+ );
56
+ FormattedMainView.displayName = "FormattedMainView";
57
+
58
+ /** Quill size names mapped to pixel values for tree storage. */
59
+ const sizeMap = { small: 10, large: 18, huge: 24 } as const;
60
+ /** Reverse mapping: pixel values back to Quill size names for display. */
61
+ const sizeReverse = { 10: "small", 18: "large", 24: "huge" } as const;
62
+ /** Set of recognized font families for Quill. */
63
+ const fontSet = new Set<string>(["monospace", "serif", "sans-serif", "Arial"]);
64
+ /** Default formatting values when no explicit format is specified. */
65
+ const defaultSize = 12;
66
+ /** Default font when no explicit font is specified. */
67
+ const defaultFont = "Arial";
68
+ /** default heading for when an unsupported header is supplied */
69
+ const defaultHeading = "h5";
70
+ /** The string literal values accepted by LineTag. */
71
+ type LineTagValue = Parameters<typeof FormattedTextAsTree.LineTag>[0];
72
+ /** Quill header numbers → LineTag values. */
73
+ const headerToLineTag = {
74
+ 1: "h1",
75
+ 2: "h2",
76
+ 3: "h3",
77
+ 4: "h4",
78
+ 5: "h5",
79
+ } as const satisfies Readonly<Record<number, LineTagValue>>;
80
+ /** LineTag values → Quill attributes. Used by buildDeltaFromTree (tree → Quill). */
81
+ const lineTagToQuillAttributes = {
82
+ h1: { header: 1 },
83
+ h2: { header: 2 },
84
+ h3: { header: 3 },
85
+ h4: { header: 4 },
86
+ h5: { header: 5 },
87
+ li: { list: "bullet" },
88
+ } as const satisfies Readonly<Record<LineTagValue, Record<string, unknown>>>;
89
+ /**
90
+ * Parse CSS font-size from a pasted HTML element's inline style.
91
+ * Returns a Quill size name if the pixel value matches a supported size, undefined otherwise.
92
+ * 12px is the default size and returns undefined (no Quill attribute needed).
93
+ */
94
+ export function parseCssFontSize(node: HTMLElement): string | undefined {
95
+ const style = node.style.fontSize;
96
+ if (!style) return undefined;
97
+
98
+ // check if pixel value is in <size>px format
99
+ if (style.endsWith("px")) {
100
+ // Parse pixel value (e.g., "18px" -> 18)
101
+ const parsed = Number.parseFloat(style);
102
+ if (Number.isNaN(parsed)) return undefined;
103
+
104
+ // Round to nearest integer and look up Quill size name
105
+ const rounded = Math.round(parsed);
106
+ if (rounded in sizeReverse) {
107
+ return sizeReverse[rounded as keyof typeof sizeReverse];
108
+ }
109
+ }
110
+ return undefined;
111
+ }
112
+
113
+ /**
114
+ * Parse CSS font-family from a pasted HTML element's inline style.
115
+ * Tries fonts in priority order (first to last per CSS spec) and returns
116
+ * the first recognized Quill font value.
117
+ */
118
+ export function parseCssFontFamily(node: HTMLElement): string | undefined {
119
+ const style = node.style.fontFamily;
120
+ if (style === "") return undefined;
121
+
122
+ // Splitting on "," does not handle commas inside quoted font names, and escape
123
+ // sequences within font names are not supported. This is fine since none of the
124
+ // font names we match against contain commas or escapes.
125
+ const fonts = style.split(",");
126
+ for (const raw of fonts) {
127
+ // Trim whitespace and leading and trailing quotes
128
+ const font = raw.trim().replace(/^["']/, "").replace(/["']$/, "");
129
+ // check if font is in our supported font set
130
+ if (fontSet.has(font)) {
131
+ return font;
132
+ }
133
+ }
134
+ // No recognized font family found; fall back to default (Arial)
135
+ return undefined;
136
+ }
137
+
138
+ /**
139
+ * Clipboard matcher that preserves recognized font-size and font-family
140
+ * from pasted HTML elements. Applies each format independently via
141
+ * compose/retain so new attributes can be added without risk of an
142
+ * early return skipping them.
143
+ * @see https://quilljs.com/docs/modules/clipboard#addmatcher
144
+ */
145
+ export function clipboardFormatMatcher(node: Node, delta: Delta): Delta {
146
+ if (!(node instanceof HTMLElement)) return delta;
147
+
148
+ const size = parseCssFontSize(node);
149
+ const font = parseCssFontFamily(node);
150
+
151
+ let result = delta;
152
+ if (size !== undefined) {
153
+ result = result.compose(new Delta().retain(result.length(), { size }));
154
+ }
155
+ if (font !== undefined) {
156
+ result = result.compose(new Delta().retain(result.length(), { font }));
157
+ }
158
+ return result;
159
+ }
160
+
161
+ /**
162
+ * Parse a size value from Quill into a numeric pixel value.
163
+ * Handles Quill's named sizes (small, large, huge), numeric values, and pixel strings.
164
+ */
165
+ function parseSize(size: unknown): number {
166
+ if (typeof size === "number") return size;
167
+ if (size === "small" || size === "large" || size === "huge") {
168
+ return sizeMap[size];
169
+ }
170
+ if (typeof size === "string") {
171
+ const parsed = Number.parseInt(size, 10);
172
+ if (!Number.isNaN(parsed)) {
173
+ return parsed;
174
+ }
175
+ }
176
+ return defaultSize;
177
+ }
178
+
179
+ /** Extract a LineTag from Quill attributes, or undefined if none present. Quill only supports one LineTag at a time. */
180
+ export function parseLineTag(
181
+ attributes?: Record<string, unknown>,
182
+ ): FormattedTextAsTree.LineTag | undefined {
183
+ if (!attributes) return undefined;
184
+ // Quill should never send both header and list attributes simultaneously.
185
+ assert(
186
+ !(typeof attributes.header === "number" && typeof attributes.list === "string"),
187
+ 0xce2 /* expected at most one line tag (header or list), but received both */,
188
+ );
189
+ if (typeof attributes.header === "number") {
190
+ const tag: LineTagValue =
191
+ headerToLineTag[attributes.header as keyof typeof headerToLineTag] ?? defaultHeading;
192
+ return FormattedTextAsTree.LineTag(tag);
193
+ }
194
+ if (attributes.list === "bullet") {
195
+ return FormattedTextAsTree.LineTag("li");
196
+ }
197
+ return undefined;
198
+ }
199
+
200
+ /** Create a StringAtom containing a StringLineAtom with the given line tag. */
201
+ function createLineAtom(lineTag: FormattedTextAsTree.LineTag): FormattedTextAsTree.StringAtom {
202
+ return new FormattedTextAsTree.StringAtom({
203
+ content: new FormattedTextAsTree.StringLineAtom({
204
+ tag: lineTag,
205
+ }),
206
+ format: new FormattedTextAsTree.CharacterFormat(quillAttributesToFormat()),
207
+ });
208
+ }
209
+
210
+ /**
211
+ * Convert Quill attributes to a complete CharacterFormat object.
212
+ * Used when inserting new characters - all format properties must have values.
213
+ * Missing attributes default to false/default values.
214
+ */
215
+ function quillAttributesToFormat(attributes?: Record<string, unknown>): {
216
+ bold: boolean;
217
+ italic: boolean;
218
+ underline: boolean;
219
+ size: number;
220
+ font: string;
221
+ } {
222
+ return {
223
+ bold: attributes?.bold === true,
224
+ italic: attributes?.italic === true,
225
+ underline: attributes?.underline === true,
226
+ size: parseSize(attributes?.size),
227
+ font: typeof attributes?.font === "string" ? attributes.font : defaultFont,
228
+ };
229
+ }
230
+
231
+ /**
232
+ * Convert Quill attributes to a partial CharacterFormat object.
233
+ * Used when applying formatting to existing text via retain operations.
234
+ * Only includes properties that were explicitly set in the Quill attributes,
235
+ * allowing selective format updates without overwriting unrelated properties.
236
+ */
237
+ function quillAttributesToPartial(
238
+ attributes?: Record<string, unknown>,
239
+ ): Partial<FormattedTextAsTree.CharacterFormat> {
240
+ if (!attributes) return {};
241
+ const format: Partial<FormattedTextAsTree.CharacterFormat> = {};
242
+ // Only include attributes that are explicitly present in the Quill delta
243
+ if ("bold" in attributes) format.bold = attributes.bold === true;
244
+ if ("italic" in attributes) format.italic = attributes.italic === true;
245
+ if ("underline" in attributes) format.underline = attributes.underline === true;
246
+ if ("size" in attributes) format.size = parseSize(attributes.size);
247
+ if ("font" in attributes)
248
+ format.font = typeof attributes.font === "string" ? attributes.font : defaultFont;
249
+ return format;
250
+ }
251
+
252
+ /**
253
+ * Convert a CharacterFormat from the tree to Quill attributes.
254
+ * Used when building Quill deltas from tree content to sync external changes.
255
+ * Only includes non-default values to keep deltas minimal.
256
+ */
257
+ function formatToQuillAttributes(
258
+ format: FormattedTextAsTree.CharacterFormat,
259
+ ): Record<string, unknown> {
260
+ const attributes: Record<string, unknown> = {};
261
+ // Only include non-default formatting to keep Quill deltas minimal
262
+ if (format.bold) attributes.bold = true;
263
+ if (format.italic) attributes.italic = true;
264
+ if (format.underline) attributes.underline = true;
265
+ if (format.size !== defaultSize) {
266
+ // Convert pixel value back to Quill size name if possible
267
+ attributes.size =
268
+ format.size in sizeReverse
269
+ ? sizeReverse[format.size as keyof typeof sizeReverse]
270
+ : `${format.size}px`;
271
+ }
272
+ if (format.font !== defaultFont) attributes.font = format.font;
273
+ return attributes;
274
+ }
275
+
276
+ /**
277
+ * Build a Quill Delta representing the full tree content.
278
+ * Iterates through formatted characters and groups consecutive characters
279
+ * with identical formatting into single insert operations for efficiency.
280
+ *
281
+ * @remarks
282
+ * This is used to sync Quill's display when the tree changes externally
283
+ * (e.g., from a remote collaborator's edit).
284
+ */
285
+ export function buildDeltaFromTree(root: FormattedTextAsTree.Tree): QuillDeltaOp[] {
286
+ const ops: QuillDeltaOp[] = [];
287
+ // Accumulator for current run of identically-formatted text
288
+ let text = "";
289
+ let previousAttributes: Record<string, unknown> = {};
290
+ // JSON key for current attributes, used for equality comparison
291
+ // TODO:Performance: implement faster equality check.
292
+ let key = "";
293
+
294
+ // Helper to push accumulated text as an insert operation
295
+ const pushRun = (): void => {
296
+ if (!text) return;
297
+ const op: QuillDeltaOp = { insert: text };
298
+ if (Object.keys(previousAttributes).length > 0) op.attributes = previousAttributes;
299
+ ops.push(op);
300
+ };
301
+
302
+ // Iterate through each formatted character in the tree
303
+ // TODO:Performance: Optimize this loop by adding an API to get runs to FormattedTextAsTree.Tree, and implementing that using cursors.
304
+ // Something like `getUniformRun(startIndex, maxLength): number` and `substring(startIndex, length): string`.
305
+ for (const atom of root.charactersWithFormatting()) {
306
+ const currentAttributes = formatToQuillAttributes(atom.format);
307
+
308
+ if (atom.content instanceof FormattedTextAsTree.StringLineAtom) {
309
+ // Merge line-specific attributes (header/list) into the format
310
+ const lineTag = atom.content.tag.value;
311
+ Object.assign(currentAttributes, lineTagToQuillAttributes[lineTag]);
312
+
313
+ // Line atoms always break the current run and emit a newline
314
+ pushRun();
315
+ text = "";
316
+ key = "";
317
+ const op: QuillDeltaOp = { insert: "\n" };
318
+ if (Object.keys(currentAttributes).length > 0) op.attributes = currentAttributes;
319
+ ops.push(op);
320
+ } else {
321
+ const stringifiedAttributes = JSON.stringify(currentAttributes);
322
+ if (stringifiedAttributes === key) {
323
+ // Same formatting as previous character - extend run
324
+ text += atom.content.content;
325
+ } else {
326
+ // Different formatting - push previous run and start a new one
327
+ pushRun();
328
+ text = atom.content.content;
329
+ previousAttributes = currentAttributes;
330
+ key = stringifiedAttributes;
331
+ }
332
+ }
333
+ }
334
+
335
+ // Push any remaining accumulated text
336
+ pushRun();
337
+
338
+ // Quill expects documents to end with a newline
339
+ // eslint-disable-next-line unicorn/prefer-at -- .at() not available in target
340
+ const last = ops[ops.length - 1];
341
+ if (typeof last?.insert !== "string" || !last.insert.endsWith("\n")) {
342
+ ops.push({ insert: "\n" });
343
+ }
344
+ return ops;
345
+ }
346
+
347
+ /**
348
+ * The formatted text editor view component with Quill integration.
349
+ * Uses FormattedTextAsTree for collaborative rich text storage with formatting.
350
+ *
351
+ * @remarks
352
+ * This component uses event-based synchronization via Tree.on("treeChanged")
353
+ * to efficiently handle external changes without expensive render-time operations.
354
+ * Unlike the plain text version, this component uses Quill's delta operations
355
+ * to make targeted edits (insert at index, delete range, format range) rather
356
+ * than replacing all content on each change.
357
+ */
358
+ const FormattedTextEditorView = forwardRef<
359
+ FormattedEditorHandle,
360
+ {
361
+ root: PropTreeNode<FormattedTextAsTree.Tree>;
362
+ undoRedo?: UndoRedo;
363
+ }
364
+ >(({ root: propRoot, undoRedo }, ref) => {
365
+ // Unwrap the PropTreeNode to get the actual tree node
366
+ const root = unwrapPropTreeNode(propRoot);
367
+ // DOM element where Quill will mount its editor
368
+ const editorRef = useRef<HTMLDivElement>(null);
369
+ // Quill instance, persisted across renders to avoid re-initialization
370
+ const quillRef = useRef<Quill | null>(null);
371
+ // Guards against update loops between Quill and the tree
372
+ const isUpdating = useRef(false);
373
+ // Container element for undo/redo button portal
374
+ const [undoRedoContainer, setUndoRedoContainer] = useState<HTMLElement | undefined>(
375
+ undefined,
376
+ );
377
+ // Force re-render when undo/redo state changes
378
+ const [, forceUpdate] = useReducer((x: number) => x + 1, 0);
379
+
380
+ // Expose undo/redo methods via ref
381
+ useImperativeHandle(ref, () => ({
382
+ undo: () => undoRedo?.undo(),
383
+ redo: () => undoRedo?.redo(),
384
+ }));
385
+
386
+ // Initialize Quill editor with formatting toolbar using Quill provided CSS
387
+ useEffect(() => {
388
+ if (!editorRef.current || quillRef.current) return;
389
+ const quill = new Quill(editorRef.current, {
390
+ theme: "snow",
391
+ placeholder: "Start typing with formatting...",
392
+ modules: {
393
+ history: false, // Disable Quill's built-in undo/redo
394
+ toolbar: [
395
+ ["bold", "italic", "underline"],
396
+ [{ size: ["small", false, "large", "huge"] }],
397
+ [{ font: [] }],
398
+ [{ header: [1, 2, 3, 4, 5, false] }],
399
+ [{ list: "bullet" }],
400
+ ["clean"],
401
+ ],
402
+ clipboard: [Node.ELEMENT_NODE, clipboardFormatMatcher],
403
+ },
404
+ });
405
+
406
+ // Set initial content from tree
407
+ quill.setContents(buildDeltaFromTree(root));
408
+
409
+ // Listen to local Quill changes and apply them to the tree.
410
+ // We process delta operations to make targeted edits, preserving collaboration integrity.
411
+ // Note: Quill uses UTF-16 code units for positions, but the tree uses Unicode codepoints.
412
+ // We must convert between them to handle emoji and other non-BMP characters correctly.
413
+ //
414
+ // The typing here is very fragile: if no parameter types are given,
415
+ // the inference for this event is strongly typed, but the types are wrong (The wrong "Delta" type is provided).
416
+ // This is likely related to the node16 module resolution issues with quill-delta.
417
+ // If we break that inference by adding types, `any` is inferred for all of them, so incorrect types here would still compile.
418
+ quill.on("text-change", (delta: Delta, _oldDelta: Delta, source: EmitterSource) => {
419
+ if (source !== "user" || isUpdating.current) return;
420
+ isUpdating.current = true;
421
+
422
+ // Wrap all tree mutations in a transaction so they undo/redo as one atomic unit.
423
+ // If the node is not part of a branch (e.g. unhydrated), apply edits directly.
424
+ const branch = TreeAlpha.branch(root);
425
+ const applyDelta = (): void => {
426
+ // Helper to count Unicode codepoints in a string
427
+ const codepointCount = (s: string): number => [...s].length;
428
+
429
+ // Get current content for UTF-16 to codepoint position mapping
430
+ // We update this as we process operations to keep positions accurate
431
+ let content = root.fullString();
432
+ let utf16Pos = 0; // Position in UTF-16 code units (Quill's view)
433
+ let cpPos = 0; // Position in codepoints (tree's view)
434
+
435
+ for (const op of delta.ops) {
436
+ if (op.retain !== undefined) {
437
+ // The docs for retain imply this is always a number, but the type definitions allow a record here.
438
+ // It is unknown why the type definitions allow a record as they have no doc comments.
439
+ // For now this assert seems to be passing, so we just assume its always a number.
440
+ assert(
441
+ typeof op.retain === "number",
442
+ 0xcdf /* Expected retain count to be a number */,
443
+ );
444
+ // Convert UTF-16 retain count to codepoint count
445
+ const retainedStr = content.slice(utf16Pos, utf16Pos + op.retain);
446
+ const cpCount = codepointCount(retainedStr);
447
+
448
+ if (op.attributes) {
449
+ const lineTag = parseLineTag(op.attributes);
450
+ // Case 1: Applying line formatting (header/list) to an existing newline in the document.
451
+ if (lineTag !== undefined && content[utf16Pos] === "\n") {
452
+ // Swap existing newline atom to StringLineAtom
453
+ root.removeRange(cpPos, cpPos + 1);
454
+ root.insertWithFormattingAt(cpPos, [createLineAtom(lineTag)]);
455
+ // Case 2: Applying line formatting past the end of content. Quill's implicit trailing newline.
456
+ } else if (lineTag !== undefined && utf16Pos >= content.length) {
457
+ // Quill's implicit trailing newline — insert a new line atom
458
+ root.insertWithFormattingAt(cpPos, [createLineAtom(lineTag)]);
459
+ content += "\n";
460
+ // Case 3: clearing line formatting. Deletes StringLineAtom and inserts a plain
461
+ // StringTextAtom("\n") in its place.
462
+ } else if (
463
+ lineTag === undefined &&
464
+ content[utf16Pos] === "\n" &&
465
+ root.charactersWithFormatting()[cpPos]?.content instanceof
466
+ FormattedTextAsTree.StringLineAtom
467
+ ) {
468
+ // Quill is clearing line formatting (e.g. { retain: 1, attributes: { header: null } }).
469
+ // StringLineAtom and StringTextAtom are distinct schema types in the tree,
470
+ // so we can't convert between them via formatRange — we must delete the
471
+ // StringLineAtom and insert a plain StringTextAtom("\n") in its place.
472
+ root.removeRange(cpPos, cpPos + 1);
473
+ root.insertAt(cpPos, "\n");
474
+ // Case 4: Normal character formatting (bold, italic, size, etc...)
475
+ } else {
476
+ root.formatRange(
477
+ cpPos,
478
+ cpPos + cpCount,
479
+ quillAttributesToPartial(op.attributes),
480
+ );
481
+ }
482
+ }
483
+ utf16Pos += op.retain;
484
+ cpPos += cpCount;
485
+ } else if (op.delete !== undefined) {
486
+ // Convert UTF-16 delete count to codepoint count
487
+ const deletedStr = content.slice(utf16Pos, utf16Pos + op.delete);
488
+ const cpCount = codepointCount(deletedStr);
489
+
490
+ root.removeRange(cpPos, cpPos + cpCount);
491
+ // Update content to reflect deletion for future position calculations
492
+ content = content.slice(0, utf16Pos) + content.slice(utf16Pos + op.delete);
493
+ // Don't advance positions - next op starts at same position
494
+ } else if (typeof op.insert === "string") {
495
+ const lineTag = parseLineTag(op.attributes);
496
+ if (lineTag !== undefined && op.insert === "\n") {
497
+ root.insertWithFormattingAt(cpPos, [createLineAtom(lineTag)]);
498
+ } else {
499
+ // Insert: add new text with formatting at current position
500
+ root.defaultFormat = new FormattedTextAsTree.CharacterFormat(
501
+ quillAttributesToFormat(op.attributes),
502
+ );
503
+ root.insertAt(cpPos, op.insert);
504
+ }
505
+ // Update content to reflect insertion
506
+ content = content.slice(0, utf16Pos) + op.insert + content.slice(utf16Pos);
507
+ // Advance by inserted content length
508
+ utf16Pos += op.insert.length;
509
+ cpPos += codepointCount(op.insert);
510
+ }
511
+ }
512
+ };
513
+ if (branch === undefined) {
514
+ applyDelta();
515
+ } else {
516
+ branch.runTransaction(applyDelta);
517
+ }
518
+
519
+ isUpdating.current = false;
520
+ });
521
+
522
+ quillRef.current = quill;
523
+
524
+ // Create container for React-controlled undo/redo buttons and prepend to toolbar
525
+ const toolbar = editorRef.current.previousElementSibling as HTMLElement;
526
+ const container = document.createElement("span");
527
+ container.className = "ql-formats";
528
+ toolbar.prepend(container);
529
+ setUndoRedoContainer(container);
530
+ // In React strict mode, effects run twice. The `!quillRef.current` check above
531
+ // makes the second call a no-op, preventing double-initialization of Quill.
532
+ // eslint-disable-next-line react-hooks/exhaustive-deps
533
+ }, []);
534
+
535
+ // Sync Quill when tree changes externally (e.g., from remote collaborators).
536
+ // Uses event subscription instead of render-time observation for efficiency.
537
+ useEffect(() => {
538
+ return Tree.on(root, "treeChanged", () => {
539
+ // Skip if we caused the tree change ourselves via the text-change handler
540
+ if (!quillRef.current || isUpdating.current) return;
541
+
542
+ // TODO:Performance: Once SharedTree has better ArrayNode change events,
543
+ // use those events to construct a delta, instead of rebuilding a new delta then diffing every edit.
544
+ // After doing the optimization, keep this diffing logic as a way to test for de-sync between the tree and Quill:
545
+ // Use it in tests and possibly occasionally in debug builds.
546
+ const treeDelta = buildDeltaFromTree(root);
547
+
548
+ // eslint doesn't seem to be resolving the types correctly here.
549
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
550
+ const quillDelta: Delta = quillRef.current.getContents();
551
+
552
+ // Compute diff between current Quill state and tree state
553
+ const diff = new Delta(quillDelta).diff(new Delta(treeDelta));
554
+
555
+ // Only update if there are actual differences
556
+ if (diff.ops.length > 0) {
557
+ isUpdating.current = true;
558
+
559
+ // Apply only the diff for surgical updates (better cursor preservation)
560
+ quillRef.current.updateContents(diff.ops);
561
+
562
+ isUpdating.current = false;
563
+ }
564
+ });
565
+ }, [root]);
566
+
567
+ // Subscribe to undo/redo state changes to update button disabled state
568
+ useEffect(() => {
569
+ if (!undoRedo) return;
570
+ return undoRedo.onStateChange(() => {
571
+ forceUpdate();
572
+ });
573
+ }, [undoRedo]);
574
+
575
+ // Render undo/redo buttons via portal into Quill toolbar
576
+ const undoRedoButtons = undoRedoContainer
577
+ ? ReactDOM.createPortal(
578
+ <>
579
+ <button
580
+ type="button"
581
+ className="ql-undo"
582
+ disabled={undoRedo?.canUndo() !== true}
583
+ onClick={() => undoRedo?.undo()}
584
+ />
585
+ <button
586
+ type="button"
587
+ className="ql-redo"
588
+ disabled={undoRedo?.canRedo() !== true}
589
+ onClick={() => undoRedo?.redo()}
590
+ />
591
+ </>,
592
+ undoRedoContainer,
593
+ )
594
+ : undefined;
595
+
596
+ return (
597
+ <div style={{ height: "100%", display: "flex", flexDirection: "column" }}>
598
+ <style>{`
599
+ .ql-container { height: 100%; font-size: 14px; }
600
+ .ql-editor { height: 100%; outline: none; }
601
+ .ql-editor.ql-blank::before { color: #999; font-style: italic; }
602
+ .ql-toolbar { border-radius: 4px 4px 0 0; background: #f8f9fa; }
603
+ .ql-container.ql-snow { border-radius: 0 0 4px 4px; }
604
+ .ql-undo, .ql-redo { width: 28px !important; }
605
+ .ql-undo::after { content: "↶"; font-size: 18px; }
606
+ .ql-redo::after { content: "↷"; font-size: 18px; }
607
+ .ql-undo:disabled, .ql-redo:disabled { opacity: 0.3; cursor: not-allowed; }
608
+ /* custom css altering Quill's default bullet point alignment */
609
+ /* vertically center bullets in list items, since Quill's bullet has no inherent height */
610
+ li[data-list="bullet"] { display: flex; align-items: center; }
611
+ li[data-list="bullet"] .ql-ui { align-self: center; }
612
+ `}</style>
613
+ <h2 style={{ margin: "10px 0" }}>Collaborative Formatted Text Editor</h2>
614
+ <div
615
+ ref={editorRef}
616
+ style={{
617
+ flex: 1,
618
+ minHeight: "300px",
619
+ border: "1px solid #ccc",
620
+ borderRadius: "4px",
621
+ }}
622
+ />
623
+ {undoRedoButtons}
624
+ </div>
625
+ );
626
+ });
627
+ FormattedTextEditorView.displayName = "FormattedTextEditorView";
@@ -0,0 +1,15 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ export {
7
+ FormattedMainView,
8
+ type FormattedMainViewProps,
9
+ type FormattedEditorHandle,
10
+ } from "./formatted/index.js";
11
+ export {
12
+ PlainTextMainView,
13
+ QuillMainView as PlainQuillView,
14
+ type MainViewProps as PlainMainViewProps,
15
+ } from "./plain/index.js";
@@ -0,0 +1,7 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ export { MainView as PlainTextMainView } from "./plainTextView.js";
7
+ export { MainView as QuillMainView, type MainViewProps } from "./quillView.js";