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